13. Funzioni built-in
Questo capitolo è il catalogo della stdlib: conversioni, math, stringhe, file, JSON, date e helper di errore. I how-to di I/O, prompt, job, JWT e UI stanno in quei capitoli; questa pagina tiene le firme e un indice numerato.
io.print(math.sqrt(16));
io.print(str.upper("malda"));
io.print(toIntOr("", 1));
13.0 Mappa del capitolo
- 13.1 Conversioni di tipo
- 13.2 Namespace della stdlib e alias piatti
- 13.3 Funzioni matematiche
- 13.4 Funzioni sulle stringhe
- 13.5 Ambiente e host (
webSearch,webFetch) - 13.6 Utility sugli array
- 13.7 JSON,
validate,evalPrompt— 13.7.2 Indice pipeline AI - 13.8 File system — 13.9 Git — 13.10 Comandi — 13.11 Esecuzione MALDA
- 13.12 Spectre.Console — 13.13 Date/ora — 13.14 Random — 13.15 Controlli di tipo
- 13.16 Encoding — 13.17 Hash — 13.18 Range — 13.19 Errori,
result/option,cap - 13.20–13.24 Indici verso agenti, workflow e UI
- 13.25 Password, JWT e
req.auth— 13.26 Job in background — 13.27 Pacchetti opzionali
13.1 Conversioni di tipo
var num = int("123"); // Convert string to integer
var floatVal = float("3.14"); // Convert string to float
var str = string(42); // Convert number to string
13.1.1 Helper di conversione intera sicura
Usa questi helper quando l'input può essere vuoto, null o malformato.
var page = toIntOr(query.page, 1); // Fallback when null/empty/unparseable
var limit = toIntOr(query.limit, 50); // Always returns integer
var ownerId = toIntOrNull(query.ownerId); // Returns null when missing/unparseable
toIntOr(value, fallback)- restituisce l'intero analizzato quando possibile, altrimentifallback.toIntOrNull(value)- restituisce l'intero analizzato onullquando il valore è null/vuoto/non analizzabile.- Entrambe le funzioni accettano valori interi, float, boolean e stringhe numeriche.
13.2 Namespace della stdlib e alias piatti
La maggior parte della libreria standard è raggiungibile in due forme: una chiamata namespaced tramite un oggetto modulo, e un globale piatto con lo stesso nome. Entrambe risolvono la stessa implementazione e si comportano in modo identico a runtime.
print(math.sqrt(16)); // namespaced
print(sqrt(16)); // flat alias, same result
print(str.join(str.split("a,b", ","), "|")); // a|b
print(io.readFile("config.json"));
Gli oggetti modulo
| Modulo | Copre |
|---|---|
math | Arrotondamento, trigonometria, aggregati, helper random, math per LLM, algebra lineare e le costanti math.PI, math.E, math.TAU, math.INF, math.NaN |
nn | Attivazioni per reti neurali, derivate locali, dense / denseBackward e i gradienti mseGrad / softmaxGrad. Firme e modello del layer sono in 14. Reti neurali. Nessun alias piatto |
buf | Buffer numerici a dimensione fissa (float64, float32, int32, bytes, from, toArray, kind, slice, fill) e dati binari (readAt, writeAt, fromUtf8, toUtf8, fromBase64, toBase64) — vedi 6.7. Nessun alias piatto |
str | Maiuscole/minuscole, trimming, split e join, padding, helper regex, similarità, base64, md5 / sha256 |
io | print, input, helper per file e path, glob, grep, variabili d'ambiente, helper git |
pdf | extractText — legge il testo da un file PDF (livello di testo digitale; nessun OCR) |
doc | extractText — legge il testo da un Word .docx (Open XML; non il .doc legacy) |
result | ok, err, map, unwrapOr, isOk, isErr — vedi 13.19.1 |
option | some, none, map, unwrapOr, isSome, isNone — vedi 13.19.1 |
Math (M maiuscola) è un alias deprecato per lo stesso oggetto di math.
Quali nomi piatti sono deprecati
Solo i nomi piatti che hanno una controparte math., str. o io. sono considerati alias deprecati. Chiamarne uno produce un warning nell'IDE e nel language server dalla sorgente malda-style, nella forma Prefer 'io.print(...)' instead of 'print(...)' (deprecated flat alias). Il warning è solo un avviso: a runtime non viene rimosso nulla e i transpiler accettano entrambe le forme.
I nomi interessati, che rispecchiano MaldaLang/BuiltIns/StdLibNamespaces.cs:
- math:
abs,sum,average,max,min,pow,sqrt,floor,ceil,round,trunc,sign,exp,log,log10,log2,sin,cos,tan,asin,acos,atan,atan2,hypot,clamp,degToRad,radToDeg,zeros,rsqrt,randn,argmax,argmin,logSumExp,softmax,dot,matmul,transpose,sigmoid,tanh,randomChoiceWeighted,seed,random,randomInt,randomFloat,anneal - str:
length,upper,lower,trim,text,trimText,substring,indexOf,replace,split,normalizeText,tokenize,tokenOverlap,similarity,extractNumbers,regexMatch,regexReplace,regexFind,startsWith,endsWith,padStart,padEnd,includes,join,repeat,base64Encode,base64Decode,md5,sha256 - io:
print,input,readFile,writeFile,copyFile,readFileBase64,writeFileBase64,readPng,writePng,readTextFileLines,deleteFile,hasFile,hasDirectory,ensureDir,listDirectory,hasEmbeddedFolder,embeddedFolderRoot,glob,grep,replaceInFile,pathExists,pathJoin,pathNormalize,pathGetExtension,isPathUnder,getEnv,getEnvOr,hasEnv,getFileName,getDirectoryName,gitStatus,gitAdd,gitCommit,gitDiff,gitLog,gitBranch,gitCheckout,gitPull,gitPush
Ogni altro built-in in questo capitolo — sleep, runCommand, parseJson, gli helper di agenti e workflow, e così via — non ha una controparte di modulo e non ha deprecazione associata.
Examples/ usano la forma piatta (print(...), sqrt(...)) perché è più breve ed è quella del codice MALDA esistente. Leggile come equivalenti alla forma namespaced. Nel codice nuovo, preferisci la forma namespaced se vuoi che l'editor resti senza warning.
13.3 Funzioni matematiche
La forma preferita è math.*. I nomi piatti e Math.* sono alias deprecati (vedi 13.2).
Interprete, transpile C# e JavaScript eseguono tutti math.*. Vedi la matrice delle capacità dei backend.
print(math.abs(-5));
print(math.pow(2, 3));
| Argomenti | Ritorno | Note |
|---|---|---|
math.abs(x) | ||
| 1 argument | — | |
math.acos(x) | ||
| 1 argument | — | |
math.anneal(initial, cost, neighbor, options?) | ||
| 3-4 arguments: (initial, cost, neighbor, options?) | { state, cost, steps } | Metropolis search; cost/neighbor are unary lambdas (cooling may be a number or unary lambda); options: steps/temp/cooling/schedule/maximize/copy; uses math.random so math.seed pins it; WF1001 outside a workflow step |
math.argmax(array) | ||
| 1 argument: (array) | — | |
math.argmin(array) | ||
| 1 argument: (array) | — | |
math.asin(x) | ||
| 1 argument | — | |
math.atan(x) | ||
| 1 argument | — | |
math.atan2(a, b) | ||
| 2 arguments | — | |
math.average(array) | ||
| 1 argument: (array) | — | |
math.ceil(x) | ||
| 1 argument | — | returns a float even when whole-valued; integer sinks coerce whole floats; wrap with int() if you need an Integer-tagged value |
math.clamp(x, lo, hi) | ||
| 3 arguments | — | |
math.cos(x) | ||
| 1 argument | — | |
math.degToRad(x) | ||
| 1 argument | — | |
math.dot(a, b) | ||
| 2 arguments: (a, b) | float | vettori 1D, stessa lunghezza |
math.exp(x) | ||
| 1 argument | — | |
math.floor(x) | ||
| 1 argument | — | returns a float even when whole-valued (print shows 1, not 1.0); integer sinks coerce whole floats, so str.repeat("-", math.floor(n)) works; fractional floats still fail |
math.hypot(a, b) | ||
| 2 arguments | — | |
math.log(x) | ||
| 1 argument | — | |
math.log10(x) | ||
| 1 argument | — | |
math.log2(x) | ||
| 1 argument | — | |
math.logSumExp(array) | ||
| 1 argument: (array) | — | |
math.max(a, b) | ||
| 2 arguments or 1 array | — | |
math.matmul(a, b) | ||
| 2 arguments: (a, b) | array | 2D@2D, 2D@1D o 1D@2D |
math.min(a, b) | ||
| 2 arguments or 1 array | — | |
math.pow(a, b) | ||
| 2 arguments | — | |
math.radToDeg(x) | ||
| 1 argument | — | |
math.randn(std?, mean?) | ||
| 0-2 arguments: (std?, mean?) | — | |
math.random() | ||
| 0 arguments | — | float in [0.0, 1.0) |
math.randomChoiceWeighted(weights) | ||
| 1 argument: (weights) | — | |
math.randomFloat(min, max) | ||
| 2 arguments: (min, max) | — | min included, max excluded |
math.randomInt(min, max) | ||
| 2 arguments: (min, max) | — | min and max are BOTH included, unlike half-open ranges elsewhere; math.seed(n) pins the sequence |
math.round(x) | ||
| 1 argument | — | returns a float even when whole-valued; integer sinks coerce whole floats; wrap with int() if you need an Integer-tagged value |
math.rsqrt(x) | ||
| 1 argument | — | |
math.seed(x) | ||
| 1 argument | null | resets the one generator shared by random, randomInt, randomFloat, randn, randomChoiceWeighted and anneal |
math.sigmoid(x) | ||
| 1 argument: (x) | — | scalare o elementwise 1D/2D |
math.sign(x) | ||
| 1 argument | — | |
math.sin(x) | ||
| 1 argument | — | |
math.softmax(array, temperature?) | ||
| 1-2 arguments: (array, temperature?) | — | |
math.sqrt(x) | ||
| 1 argument | — | returns a float even when whole-valued (sqrt(4) is 2.0); integer sinks coerce whole floats; wrap with int() if you need an Integer-tagged value |
math.sum(array) | ||
| 1 argument: (array) | — | |
math.tan(x) | ||
| 1 argument | — | |
math.tanh(x) | ||
| 1 argument: (x) | — | scalare o elementwise 1D/2D |
math.transpose(matrix) | ||
| 1 argument: (matrix) | array | matrice 2D nidificata |
math.trunc(x) | ||
| 1 argument | — | |
math.zeros(n, cols?) | ||
| 1-2 arguments: (n, cols?) | array | 1D math.zeros(n) or 2D math.zeros(rows, cols); each 2D row is a new array; cells are 0.0 |
math.max e math.min accettano (a, b) o un array numerico non vuoto. Gli aggregati sono anche metodi: values.sum(), values.average(), values.min(), values.max(). La trigonometria è in radianti; un input fuori dominio è NaN, non un errore. math.round usa l'arrotondamento del banchiere.
math.zeros(n) / math.zeros(rows, cols)
Costruisce un vettore 1D o un array nidificato 2D riempito di 0.0. La forma a due argomenti alloca una riga nuova per riga, così scrivere m[0][0] non cambia le altre. Le dimensioni devono essere interi >= 0. Le dimensioni vuote sono ammesse: math.zeros(0) è [], e math.zeros(2, 0) è due righe vuote.
var w = math.zeros(2); // [0, 0]
var g = math.zeros(3, 4); // 3 rows, 4 columns
g[0][0] = 1.0; // other rows stay zero
Helper per reti neurali
L'algebra lineare del percorso offline AI_Theory resta su math. Le dimensioni interne di math.matmul devono coincidere. Attivazioni, derivate locali, un layer denso e la tabella delle firme sono in 14. Reti neurali.
print(math.dot([1.0, 2.0], [3.0, 1.0]));
13.3.1 Helper math orientati agli LLM (riferimento)
Vedi math.seed fino a math.anneal nella tabella. Conteggi o tipi non validi, array vuoti, temperatura softmax non positiva o peso totale zero lanciano. math.seed fissa math.random, math.randomInt, math.randomFloat, math.randn, math.randomChoiceWeighted e math.anneal.
13.3.2 Simulated annealing
math.anneal(initial, cost, neighbor, options?) esegue simulated annealing Metropolis. cost e neighbor sono lambda unarie (o funzioni con nome): cost restituisce un numero finito da minimizzare, neighbor restituisce uno stato candidato. options opzionale:
steps— numero di iterazioni (default1000)temp/temperature— temperatura iniziale (default1.0)cooling— fattore geometrico (default0.995) oppure una lambda unariat => nextTempschedule— uguale a uncoolingfunzionemaximize—trueper massimizzare il cost (defaultfalse)copy— clona array/dict prima di ogni neighbor e quando salva il migliore (defaulttrue)
Restituisce { state, cost, steps }. L'accettazione usa math.random(), quindi math.seed(n) rende un'esecuzione riproducibile. Come gli altri helper RNG, anneal è WF1001 fuori da uno step di workflow.
math.seed(1);
var result = math.anneal(0.0, x => x * x, x => x, { steps: 5 });
print(result.cost == 0.0);
print(result.steps);
math.seed(7);
var result = math.anneal(
10.0,
x => (x - 3.0) * (x - 3.0),
x => x + math.randomFloat(-1.0, 1.0),
{ steps: 800, temp: 2.0, cooling: t => t * 0.995 }
);
print(result.state);
print(result.cost);
13.4 Funzioni sulle stringhe
La forma preferita è str.*. Gli stessi nomi funzionano anche come metodi su un valore stringa ("hello".upper()). I globali piatti sono alias deprecati (vedi 13.2).
Interprete, transpile C# e JavaScript eseguono tutti str.*. Vedi la matrice delle capacità dei backend.
print(str.lower("HELLO"));
print(str.startsWith("Hello", "He"));
| Argomenti | Ritorno | Note |
|---|---|---|
str.base64Decode(x) | ||
| 1 argument | — | |
str.base64Encode(x) | ||
| 1 argument | — | |
str.endsWith(str, suffix) | ||
| 2 arguments: (str, suffix) | — | |
str.extractNumbers(x) | ||
| 1 argument | — | |
str.includes(target, value) | ||
| 2 argomenti: (string | array, value) | — | Ricerca sottostringa su stringhe, presenza elemento su array |
str.indexOf(string, string) | ||
| (string, string) | — | |
str.join(array, separator?) | ||
| 1-2 arguments: (array, separator?) | — | |
str.length(x) | ||
| 1 argument | — | accepts a string or an array |
str.lower(x) | ||
| 1 argument | — | |
str.md5(x) | ||
| 1 argument | — | |
str.normalizeText(string, options?) | ||
| (string, options?) | — | |
str.padEnd(str, length, padChar?) | ||
| 2-3 arguments: (str, length, padChar?) | — | |
str.padStart(str, length, padChar?) | ||
| 2-3 arguments: (str, length, padChar?) | — | |
str.regexFind(string, string) | ||
| (string, string) | — | |
str.regexMatch(string, string) | ||
| (string, string) | — | |
str.regexReplace(string, string, string) | ||
| (string, string, string) | — | |
str.repeat(str, count) | ||
| 2 arguments: (str, count) | — | count must be an integer or a whole-valued float; fractional floats are rejected |
str.replace(string, string, string) | ||
| (string, string, string) | — | |
str.sha256(x) | ||
| 1 argument | — | |
str.similarity(string, string, method?, options?) | ||
| (string, string, method?, options?) | — | |
str.split(string, string?, bool?) | ||
| (string, string?, bool?) | — | |
str.startsWith(str, prefix) | ||
| 2 arguments: (str, prefix) | — | |
str.substring(string, int, int) | ||
| (string, int, int) | — | |
str.text(value) | ||
| 1 argument: (value) | string (never null) | null → empty string (unlike string(null) → "null"); use at env/JSON/CLI boundaries |
str.tokenize(string, options?) | ||
| (string, options?) | — | |
str.tokenOverlap(string, string, options?) | ||
| (string, string, options?) | — | |
str.trim(x) | ||
| 1 argument | — | |
str.trimText(value) | ||
| 1 argument: (value) | string (never null) | null-safe trim: str.trim(str.text(value)) |
str.upper(x) | ||
| 1 argument | — | |
str.substring(text, startIndex, length) — il terzo argomento è un conteggio, non un indice di fine. str.text(value) mappa null su "" (a differenza di string(null) → "null"). str.trimText(value) è str.trim(str.text(value)). Usali ai confini env / JSON / CLI. str.repeat rifiuta un conteggio frazionario.
Metodi stringa in stile extension
Le funzioni length, upper, lower, trim, substring, indexOf, replace, split, startsWith, endsWith, padStart, padEnd e repeat si possono chiamare anche come metodi su qualsiasi valore stringa. Il ricevente è il primo argomento.
print("hello".upper()); // HELLO
print("HELLO".lower()); // hello
var s = "Hello";
print(s.substring(0, 3)); // Hel
print("abc".repeat(2)); // abcabc
var f = "world".upper; // method as value
print(f()); // WORLD
Un membro non supportato su una stringa (es. s.foo()) è un errore di runtime. Gli helper di path (io.pathJoin, io.isPathUnder, …) sono in 13.8. Gli helper di ~/.malda sono in 13.5.
13.5 Ambiente e host
How-to e il footgun getEnv / str.trim: 12.5 Ambiente e host. Solo host (interprete e transpile C#); JavaScript non legge l'ambiente di processo e non chiama Brave / webFetch. Vedi la matrice delle capacità dei backend.
| Argomenti | Ritorno | Note |
|---|---|---|
getAssistantMemory(path?) | ||
| 0-1 arguments: (path?) | — | |
getCommandLineArgs() | ||
| 0 arguments | — | |
io.getEnv(x) | ||
| 1 argument | string, or null when the variable is not set | unlike io.input (which returns empty string at EOF), missing variables yield null — prefer io.getEnvOr or str.trimText before string sinks |
io.getEnvOr(name, default?) | ||
| 1-2 arguments: (name, default?) | string (never null) | never null; missing variables yield default (empty string when omitted) — preferred before str.trim |
getHostPlatform() | ||
| 0 arguments | — | |
getMaldaConfig() | ||
| 0 arguments | — | |
getMaldaHome() | ||
| 0 arguments | — | |
getProgramDirectory() | ||
| 0 arguments | — | |
getSkillNames() | ||
| 0 arguments | — | |
io.hasEnv(x) | ||
| 1 argument | — | |
httpAuthToken | ||
| request and optional options object | — | |
httpBearerToken(request) | ||
| 1 argument: (request) | — | |
httpCookieToken | ||
| request, cookieName, optional cookieSecret | — | |
loadSkill(name) | ||
| 1 argument: (name) | — | |
loadSkillsFromDir(skillsPath?) | ||
| 0-1 arguments: (skillsPath?) | — | |
webFetch(urlOrToken, pathOrMaxBytes?, maxBytes?, timeoutMs?) | ||
| 1-4 arguments: (urlOrToken, pathOrMaxBytes?, maxBytes?, timeoutMs?) | — | |
webSearch(query, apiKey?) | ||
| at least 1 string argument: (query, apiKey?) | — | |
13.5.1 Informazioni sull'host
I built-in senza argomenti descrivono la macchina e l'invocazione sotto cui gira il programma. Passare un qualsiasi argomento solleva un errore.
var host = getHostPlatform();
print(host.os); // Operating system identifier
print(host.arch); // Process architecture
print(host.pathSeparator); // "\" on Windows, "/" elsewhere
print(host.description); // Full OS description string
var args = getCommandLineArgs();
// Arguments passed to the program, excluding the program name itself
if (args.length > 0) {
print("first argument: " + args[0]);
}
// Folder of the .malda script (interpreter) or of the compiled .exe (transpile)
var programDir = getProgramDirectory();
var modelPath = io.pathJoin(programDir, "bge-m3-Q4_K_M.gguf");
getHostPlatform() restituisce un oggetto con i quattro campi mostrati sopra. getCommandLineArgs() restituisce un array di stringhe ed è il modo per leggere gli argomenti CLI da un programma MALDA, sia in esecuzioni interpretate sia transpile. getProgramDirectory() restituisce la directory assoluta del file sorgente .malda in esecuzione sotto l'interprete, oppure AppContext.BaseDirectory (la cartella che contiene l'eseguibile compilato) dopo malda compile.
13.5.2 Ricerca web (Brave Search API)
webSearch(query, apiKey?) — Esegue una ricerca web usando la Brave Search API. query è la stringa di ricerca. apiKey è opzionale; se omessa, la chiave viene presa (in ordine) dall'argomento apiKey, dalla variabile d'ambiente BRAVE_SEARCH_API_KEY o da tools.web.search.apiKey in ~/.malda/config.json (vedi Assistente personale e CLI). Restituisce un oggetto: { ok: true, results: [{ title, url, description }, ...], moreResultsAvailable: bool } in caso di successo, oppure { ok: false, error: "message" } in caso di fallimento.
var r = webSearch("MALDA programming language"); // Uses BRAVE_SEARCH_API_KEY or config
var r2 = webSearch("weather London", "your-brave-api-key"); // Explicit key
if (r.ok) { for (var i = 0; i < r.results.length; i++) print(r.results[i].title); }
13.5.3 Helper per token di autenticazione HTTP
Questi helper estraggono token da oggetti simili a request usati dagli handler di HttpServer.
var bearer = httpBearerToken(req); // Reads Authorization: Bearer <token>
var cookie = httpCookieToken(req, "app_session", "cookie-secret"); // Signed cookie token
var token = httpAuthToken(req, {
"allowBearer": true,
"allowCookie": true,
"allowBody": true,
"cookieName": "app_session",
"cookieSecret": "cookie-secret",
"bodyKey": "auth"
});
httpBearerToken(request)- restituisce la stringa del token bearer o la stringa vuota.httpCookieToken(request, cookieName, cookieSecret?)- restituisce il token del cookie decodificato (o il valore del cookie sicuro verificato quando è fornito il secret), altrimenti la stringa vuota.httpAuthToken(request, options?)- prova bearer/cookie/body in ordine e restituisce il primo token non vuoto.
Collega questi helper agli handler con req.auth — vedi 13.25 e 29.6.2.
13.5.4 webFetch(url, maxBytes?, timeoutMs?)
Catalogo delle firme per recuperare un URL http:// o https:// sullo stesso percorso host di httpGet. How-to, limiti e forma del risultato: 12.9 Recupero di URL. Chiamate REST tipizzate: 30. Client REST Web. La factory per agenti è createWebFetchTool.
13.6 Funzioni di utilità sugli array
math.sum / math.average / math.min / math.max sono in 13.3 e funzionano anche come metodi di array. Le righe sotto sono gli helper solo-array. Interprete, transpile C# e JavaScript li eseguono tutti.
print(str.join(reverse([1, 2, 3, 4, 5]), ", "));
print(includes([1, 2, 3], 3));
| Argomenti | Ritorno | Note |
|---|---|---|
str.includes(target, value) | ||
| 2 argomenti: (string | array, value) | — | Ricerca sottostringa su stringhe, presenza elemento su array |
str.join(array, separator?) | ||
| 1-2 arguments: (array, separator?) | — | |
reverse(x) | ||
| 1 argument | — | |
sort(array, compareFn?) | ||
| 1-2 arguments: (array, compareFn?) | — | |
toCsv(rows, columns?, options?) | ||
| 1-3 arguments: (rows, columns?, options?) | — | |
13.6.1 Helper di esportazione CSV
var rows = [
{"name": "Alice", "score": 95},
{"name": "Bob", "score": 88}
];
var csv1 = toCsv(rows, ["name", "score"]); // With explicit column order
var csv2 = toCsv(rows); // Infer columns from first row
var csv3 = toCsv(rows, ["name", "score"], {
"delimiter": ";",
"includeHeader": true,
"quoteAll": false,
"newline": "\n"
});
toCsv(rows, columns?, options?) converte un array di righe in testo CSV. Esegue l'escape delle virgolette e racchiude le celle quando serve (delimitatore/newline/virgolette). Utile per report e endpoint di esportazione dati.
13.7 Funzioni JSON
Catalogo degli helper JSON / schema. toJSON, parseJSON, validate e asVariant girano su interprete, transpile C# e JavaScript. evalPrompt è solo host (prompt). Vedi la matrice delle capacità dei backend.
| Argomenti | Ritorno | Note |
|---|---|---|
asVariant(typeName, value) | ||
| 2 arguments: (typeName, value) | variant | throws if typeName is not a sum type or the tagged JSON is invalid; already-a-variant is idempotent; validate() does not coerce |
evalPrompt(prompt, fixture, typeName?) | ||
| 2-3 arguments: (prompt, fixture, typeName?) | { ok, data } | { ok: false, error } | no LLM; same extract/validate/coerce path as await; {ok,data} or {ok:false,error}; data is a variant for sum types; instance.eval(fixture) is the same helper |
parseJson(value, schemaRef) and optional options object. For a plain JSON reader use parseJSON(text) | ||
| 2 arguments (value, schemaRef) and optional options object. For a plain JSON reader use parseJSON(text) | — | schema-validating parser for LLM output, NOT a plain JSON reader |
parseJSON(the JSON string). For schema-validated LLM JSON use parseJson(value, schemaRef) | ||
| 1 argument (the JSON string). For schema-validated LLM JSON use parseJson(value, schemaRef) | — | plain JSON text to a value; note that parseJson with a lowercase s is a different built-in |
toJSON(x) | ||
| 1 argument | — | |
validate(schema, value) | ||
| 2 arguments: (schema, value) | — | |
var jsonStr = toJSON(obj); // Convert object to JSON string
var obj = parseJSON('{"name":"Alice","age":30}'); // Parse JSON string to object
toJSON scrive dict, array e i campi di istanza pubblici di una classe (incluso un costruttore primario). I metodi e i campi private vengono omessi. Un ciclo solleva un'eccezione. parseJSON restituisce sempre un dict — non ricostruisce la classe. Crea una nuova istanza se ti servono di nuovo i metodi.
class Point(x, y);
var d = parseJSON(toJSON(new Point(3, 4)));
print(d.x);
print(d.y);
parseJSON analizza JSON arbitrario in valori MALDA. parseJson(jsonString, schemaName) analizza JSON e lo valida rispetto a una dichiarazione schema registrata, sollevando un'eccezione in caso di mancata corrispondenza.
schema Answer {
text: string;
sources: string[];
}
var parsed = parseJson('{"text":"ok","sources":["a.md"]}', "Answer");
print(parsed.text); // ok
print(parsed.sources[0]); // a.md
I tipi di campo array usano la sintassi type[] (es. string[], int[] o OtherSchema[]). I tipi di campo possono anche nominare un altro schema dichiarato (le forme oggetto nidificate vengono espanse per la validazione e i prompt tipizzati) o un sum type dichiarato (JSON oneOf con tag). I campi opzionali aggiungono ? dopo il tipo. Nomi di tipo di campo sconosciuti e riferimenti ciclici allo schema sollevano un errore quando lo schema viene risolto.
13.7.1 validate(schema, value)
Controlla un valore che hai già rispetto a uno schema, senza analizzare JSON. A differenza di parseJson, un fallimento di validazione non è un'eccezione: il risultato è sempre un oggetto che riporta l'esito.
- In caso di successo:
{ ok: true, data: value } - In caso di fallimento:
{ ok: false, error: "message" }
Il primo argomento è il nome di uno schema o sum type registrato, oppure un oggetto schema in linea. Un nome sconosciuto solleva Unknown schema 'Name'. In caso di successo, data è il valore originale — un dict con tag resta un dict (non viene coercizzato a variant). Usa asVariant("Intent", dict) o await prompt … -> Intent quando ti serve un variant per match. La factory per agenti è createValidateJsonTool (nessuna directory di lavoro; sicuro in parallelo); restituisce lo stesso oggetto { ok, data } / { ok: false, error }.
schema Answer {
text: string;
sources: string[];
}
var candidate = dict { "text": "ok", "sources": ["a.md"] };
var checked = validate("Answer", candidate);
if (checked.ok) {
print(checked.data.text); // ok
} else {
print("invalid: " + checked.error);
}
type Intent = Search(query) | Buy(sku, qty);
var tagged = dict { "tag": "Buy", "sku": "SKU-9", "qty": 2 };
var checkedIntent = validate("Intent", tagged);
if (checkedIntent.ok) {
print(checkedIntent.data.tag);
}
type Intent = Search(query: string) | Buy(sku: string, qty: int);
var tagged = dict { "tag": "Buy", "sku": "SKU-9", "qty": "x" };
var checkedTyped = validate("Intent", tagged);
print(checkedTyped.ok);
memory.validate() su un'istanza GraphMemory, che controlla l'integrità del grafo piuttosto che uno schema. Condividono il nome ma non sono correlati.
13.7.1.1 asVariant(typeName, value)
Trasforma un dict tagged in una variante di sum type così match può associare i costruttori. validate("Intent", dict) non lo fa mai. Una variante già costruita viene restituita così com'è se il tag appartiene al tipo. Un mismatch (nome sconosciuto, schema oggetto, tag errato, payload tipizzato che fallisce lo JSON Schema) solleva un'eccezione — a differenza di validate.
type Intent = Search(query: string) | Buy(sku: string, qty: int) | Help();
var tagged = dict { "tag": "Buy", "sku": "SKU-9", "qty": 2 };
var checked = validate("Intent", tagged);
var label = match asVariant("Intent", checked.data) {
case Search(q): "search " + q;
case Buy(sku, qty): "buy " + sku + " x " + qty;
case Help(): "help";
};
print(label);
Vedi Examples/Basics/as_variant.malda e docs/llm/few-shot/25_as_variant.malda.
13.7.1.2 evalPrompt(prompt, fixture, typeName?)
Harness offline su un PromptInstance: fixture in, valore coercizzato out. Non chiama un LLM, non consuma @budget e non esegue il round gather. La fixture è un dict/oggetto oppure una stringa JSON in forma LLM (fence markdown e un { … } circostante si estraggono come con await). La forma del risultato è quella di validate:
- In caso di successo:
{ ok: true, data }—dataè ciò che avrebbe restituitoawait prompt … -> Type(oggetto per uno schema, variant per un sum type, valore programma perprogram(Api)). - In caso di fallimento extract / parse / schema:
{ ok: false, error }. Nessun ciclo di repair.
Il tipo arriva da -> Type dichiarato sull’istanza (instance.returnType), anche per i prompt Mode C con gather: che non hanno ancora response_format. typeName opzionale sovrascrive. instance.eval(fixture, typeName?) è lo stesso helper. Compatibile con la pipe: p |> evalPrompt(fixture).
schema Card {
name: string;
}
prompt extract(raw) -> Card {
user: raw;
}
var p = extract("Ada Lovelace");
var checked = evalPrompt(p, dict { "name": "Ada" });
if (checked.ok) {
print(checked.data.name);
}
type Intent = Search(query: string) | Buy(sku: string, qty: int) | Help();
prompt parseUtterance(text) -> Intent {
user: text;
}
var checked = evalPrompt(parseUtterance("buy"), dict { "tag": "Buy", "sku": "SKU-9", "qty": 2 });
var label = match checked.data {
case Search(q): "search " + q;
case Buy(sku, qty): "buy " + sku + " x " + qty;
case Help(): "help";
};
print(label);
Vedi Examples/Prompts/eval_prompt.malda e docs/llm/few-shot/27_eval_prompt.malda.
13.7.2 Funzioni per pipeline AI
How-to, pipe lavorate e tabella delle firme: 10.9.1 Helper di pipeline AI. Indice vettoriale + asRetriever: 16. VectorDB. Fixture offline: 13.7.1.2 evalPrompt.
Nomi in catalogo: loadDocuments, splitDocuments, indexInto, formatRetrievedDocs, composePipe, parallelRun, mergeRetrievedDocs, withExamples, evalPrompt, runPrompt, parseJson.
13.8 Funzioni del file system
How-to, stili di fallimento, intervalli di righe, token di capability e note sui backend: 12. Input/Output. Questa sezione è il catalogo delle firme. L'I/O su file è solo host (interprete e transpile C#); JavaScript ha io.print / io.input / JSON, non i file su disco. Vedi la matrice delle capacità dei backend.
| Argomenti | Ritorno | Note |
|---|---|---|
io.copyFile(src, dest) | ||
| 2 arguments: (src, dest) | boolean | binary-safe overwrite; returns false on I/O failure; rejects embed: src and dest; does not create parent directories |
io.deleteFile(x) | ||
| 1 argument | — | |
editFile(string, array) | ||
| (string, array) | — | |
io.embeddedFolderRoot(alias) | ||
| 1 argument: (alias) | — | |
io.ensureDir(x) | ||
| 1 argument | — | |
extractDocxText(path) | ||
| 1 argument: (path) | — | |
extractPdfText(path, password?) | ||
| 1-2 arguments: (path, password?) | — | |
io.getDirectoryName(x) | ||
| 1 argument | — | |
io.getFileName(x) | ||
| 1 argument | — | |
io.glob(pattern, dirPath?, ...) | ||
| at least 1 argument: (pattern, dirPath?, ...) | — | |
io.grep(pattern, filePath, ...) | ||
| at least 2 arguments: (pattern, filePath, ...) | — | |
io.hasDirectory(x) | ||
| 1 argument | — | |
io.hasEmbeddedFolder(alias) | ||
| 1 argument: (alias) | — | |
io.hasFile(x) | ||
| 1 argument | — | |
insertAtLine(filePath, lineNumber, content, ...) | ||
| at least 3 arguments: (filePath, lineNumber, content, ...) | — | |
io.isPathUnder(root, path) | ||
| 2 arguments: (root, path) | — | |
io.listDirectory(x) | ||
| 1 argument | — | |
io.pathExists(x) | ||
| 1 argument | — | |
io.pathGetExtension(x) | ||
| 1 argument | — | |
io.pathJoin | ||
| at least 1 argument | — | |
io.pathNormalize(x) | ||
| 1 argument | — | |
io.readFile(string, int?, int?) | ||
| (string, int?, int?) | — | |
io.readFileBase64(x) | ||
| 1 argument | — | |
io.readTextFileLines(x) | ||
| 1 argument | — | |
io.replaceInFile(string, string, string, int?) | ||
| (string, string, string, int?) | — | |
io.writeFile(a, b) | ||
| 2 arguments | — | |
io.writeFileBase64(path, base64Content) | ||
| (path, base64Content) | — | |
io.writePng(path, width, height, pixels) | ||
| (path, width, height, pixels) | — | |
io.readPng(path) | ||
| 1 argument | — | |
13.8.0 Cartelle embedded (embed:)
Compila con malda compile … --embed-folder <dir[=alias]> per impacchettare una directory nell'eseguibile come risorse dell'assembly. A runtime, leggi quei file con lo scheme virtuale embed:<alias>/<relative> — nulla viene estratto su disco. Le scritture (writeFile, ensureDir, …) rifiutano i path embed:.
if (io.hasEmbeddedFolder("secondbrain")) {
var root = io.embeddedFolderRoot("secondbrain"); // "embed:secondbrain"
var catalog = io.readFile(io.pathJoin(root, "brain.json"));
var entries = io.listDirectory(root);
}
hasEmbeddedFolder(alias) restituisce se quell'alias è stato embedded. embeddedFolderRoot(alias) restituisce embed:<alias>, oppure null quando l'alias manca. I tool degli agenti come createReadFileTool, createGrepTool e createListDirectoryTool accettano una working directory embed:<alias>.
replaceInFile("file.txt", "old", "new", 3); // Replace text in file (single replacement)
var edits = [{"oldText": "old1", "newText": "new1"}, {"oldText": "old2", "newText": "new2"}];
var result = editFile("file.txt", edits); // Apply multiple edits to file
13.8.1 Linee, binario, eliminazione e testo PDF
| Restituisce | Comportamento |
|---|---|
pdf.extractText(path, password?) | |
| string | Estrae il testo da un PDF usando PdfPig (ContentOrderTextExtractor). password opzionale per i file cifrati. Solleva un'eccezione quando il path manca o il PDF non può essere aperto. Solo testo digitale — i PDF scansionati/immagine richiedono OCR altrove. Preferisci la forma namespaced; il nome CallBuiltIn è extractPdfText. |
doc.extractText(path) | |
| string | Estrae il testo dei paragrafi del corpo da un Word .docx usando l'Open XML SDK. Solleva un'eccezione quando il path manca, il file non è .docx o il package non può essere aperto. Il .doc binario legacy non è supportato. Preferisci la forma namespaced; il nome CallBuiltIn è extractDocxText. |
readTextFileLines(path) | |
array di stringhe, oppure null | Legge il file come UTF-8 e lo divide in righe. Restituisce null quando il file manca o non può essere letto. |
deleteFile(path) | |
| boolean | Elimina il file. Restituisce true quando il file è stato eliminato o era già assente; false su un path vuoto o un fallimento I/O. |
copyFile(src, dest) | |
| boolean | Copia il file come byte (sovrascrive dest). Restituisce false in caso di fallimento I/O. Rifiuta origine e destinazione embed:. Non crea le cartelle padre. Preferisci io.copyFile. |
insertAtLine(path, lineNumber, content, insertAfter?) | |
| boolean | Inserisce content (che può coprire più righe) a una riga con indice a base 1. Restituisce false se il file non esiste. |
readFileBase64(path) | |
string, oppure null | Legge il file come byte e restituisce base64. Restituisce null quando il file manca. |
writeFileBase64(path, base64Content) | |
| boolean | Decodifica il base64 e scrive i byte. Restituisce false quando l'input non è base64 valido o la scrittura fallisce. |
io.writePng(path, width, height, pixels) | |
| boolean | Scrive un PNG RGBA a 8 bit. pixels è un array piatto di lunghezza width * height * 4 (R, G, B, A). I canali sono arrotondati all'intero più vicino e bloccati tra 0 e 255. Restituisce false su fallimento I/O. Rifiuta i path embed:. Lancia se la dimensione non è positiva, se l'immagine supera i 16 megapixel, se la lunghezza dell'array non coincide, o se un canale non è un numero. |
io.readPng(path) | |
oggetto, oppure null | Legge un PNG a 8 bit non interlacciato (scala di grigi, grigio+alfa, RGB o RGBA) e restituisce { width, height, pixels } con un array RGBA piatto. Restituisce null se il file manca o non è un PNG decodificabile di quel tipo. Le immagini indicizzate, a 16 bit e interlacciate restituiscono null. |
var lines = readTextFileLines("notes.txt");
if (lines != null) {
print("line count: " + lines.length);
}
insertAtLine("notes.txt", 1, "# Header"); // Insert before line 1
insertAtLine("notes.txt", 3, "appended", true); // Insert after line 3
var encoded = readFileBase64("logo.png");
writeFileBase64("logo-copy.png", encoded);
var px = [255, 0, 0, 255];
io.writePng("pixel.png", 1, 1, px);
var image = io.readPng("pixel.png");
deleteFile("scratch.txt");
var pdfText = pdf.extractText("manual.pdf");
// var unlocked = pdf.extractText("secret.pdf", "password");
var docText = doc.extractText("brief.docx");
Per insertAtLine, un lineNumber di 0 o inferiore inserisce all'inizio del file, e un valore oltre l'ultima riga accoda in fondo. insertAfter ha default false, cioè il contenuto viene inserito prima della riga data.
readTextFileLines, deleteFile, insertAtLine, gli helper base64 e io.readPng / io.writePng segnalano i fallimenti ordinari tramite il valore di ritorno (false o null) anziché sollevando un'eccezione. Sollevano un errore solo se chiamati con il numero sbagliato di argomenti o con tipi di argomenti sbagliati (io.writePng lancia anche quando il buffer di pixel non coincide con width e height). Controlla il risultato invece di affidarti a try/catch. pdf.extractText e doc.extractText sollevano un'eccezione su file mancanti e fallimenti di analisi.
insertAtLine è solo interprete: non è disponibile negli eseguibili transpile. Gli altri helper sui file, io.writePng / io.readPng, pdf.extractText / extractPdfText e doc.extractText / extractDocxText sono supportati dal transpiler C#. Il backend JavaScript non implementa io.writePng né io.readPng.
13.8.2 Ricerca nei file: glob e grep
glob trova i path per pattern e grep cerca nel contenuto dei file. Entrambi prendono prima un argomento obbligatorio e poi una serie di argomenti opzionali posizionali.
glob(pattern, dirPath?, maxResults?, includeDirectories?, excludeDirs?, workingDirectory?)
dirPathha default".",maxResults200(limitato a 500),includeDirectoriesfalsee i due argomenti stringa rimanenti"".- In caso di successo restituisce un oggetto
{ items, count, truncated }, dove ogni item è{ name, type, path }etruncatedindica se il risultato ha raggiuntomaxResults. globegrepricorsivi non seguono junction di directory né link simbolici. Il link stesso può comunque comparire in unlistDirectorydi un solo livello.
var found = glob("**/*.malda", "Examples");
print(found.count);
print(found.truncated);
var first = found.items[0];
print(first.path + " (" + first.type + ")");
grep(pattern, filePath, useRegex?, caseInsensitive?, includeLineNumbers?, contextLines?, countOnly?, recursive?, workingDirectory?)
- Default:
useRegexfalse,caseInsensitivefalse,includeLineNumberstrue,contextLines3,countOnlyfalse,recursivetrue. - Di norma restituisce un array di match con forma
{ filePath, content, lineNumber, contextBefore, contextAfter }. ConcountOnlyimpostato restituisce invece{ count, filesSearched }. - I file che non possono essere letti vengono saltati in silenzio.
var matches = grep("function ", "Examples");
for (var m in matches) {
print(m.filePath + ":" + m.lineNumber + " " + m.content);
}
var summary = grep("TODO", "Examples", false, true, true, 0, true);
print(summary.count + " hits in " + summary.filesSearched + " files");
glob e grep restituiscono un messaggio di errore invece del risultato normale. Proteggi con typeOf(result) == "string" prima di trattare il valore come una collezione.
var result = grep("needle", "does-not-exist");
if (typeOf(result) == "string") {
print("search failed: " + result);
}
13.9 Funzioni Git
var status = gitStatus("."); // Get repository status
gitAdd(".", "."); // Stage files
gitCommit(".", "Fix bug"); // Create commit
var commits = gitLog(".", 10); // Get last 10 commits
var diff = gitDiff(".", null, false); // Get unstaged diff
var branches = gitBranch(".", "list"); // List all branches
gitBranch(".", "create", "feature-x"); // Create new branch
// Note: Branch deletion is disabled for safety
gitCheckout(".", "main", false); // Switch to branch
gitPush(".", "origin", "main"); // Push to remote
gitPull(".", "origin", "main"); // Pull from remote
13.10 Funzioni di esecuzione comandi
// Execute shell commands
var result = runCommand("dotnet", ["build"], ".", 30000); // Run dotnet build with 30s timeout
// Returns: {exitCode: 0, stdout: "...", stderr: ""}
var result = runCommand("npm", ["test"]); // Run npm test (no timeout)
var result = runCommand("python", ["script.py"], "./scripts"); // Run with custom working directory
// Result object structure:
// - exitCode (integer): Process exit code (0 typically indicates success)
// - stdout (string): Standard output from the command
// - stderr (string): Standard error output from the command
13.11 Funzioni di esecuzione MALDA
// Execute MALDA code from file or string
var result = runMALDA("example.malda"); // Execute from file
var result = runMALDA("print('Hello');"); // Execute from string
var result = runMALDA("example.malda", "input data"); // Execute with stdin input
// Result object structure:
// - success (boolean): true if execution completed without errors
// - output (string): Standard output from the program
// - error (string): Parse error message if any, empty string otherwise
// - runtimeError (string, optional): Runtime error message if any
// Compile a .malda program to an executable (optional embed folder = CLI --embed-folder)
var packed = compileMALDA("app.malda", "dist/app.exe", "transpile", "secondbrain");
// embedFolder may be "path" or "path=alias"; result: { success, outputPath, error, errors }
// mode is interpreter (default), transpile (C#), or js (browser). game.*/dom.*/three.* need js.
var gameJs = compileMALDA("game.malda", "game.js", "js");
13.11.1 getSymbols(sourceOrFilePath)
Analizza codice MALDA ed estrae informazioni strutturate sui simboli (classi, funzioni, actor, prompt) con numeri di riga e firme. Accetta un argomento stringa: un path a un file .malda oppure codice sorgente MALDA. Se la stringa sembra un path di file (contiene separatori di path o termina con .malda) e il file esiste, il file viene letto e il suo contenuto analizzato; altrimenti l'argomento è trattato come codice sorgente. Il path traversal (.., ~) è rifiutato. Restituisce un oggetto con classes, functions, actors, prompts, imports e parseErrors (tutti array). Ogni class/actor ha name, line, column, members; ogni funzione ha name, line, column, parameters, signature; ogni prompt ha name, line, column, parameters, returnType?, signature. Ogni import ha file?, resolvedPath?, package?, alias?; i moduli non risolti non sono segnalati qui (usa checkMalda, il cui warning malda-import nomina il path mancante). Gli errori di parse hanno line, column, message.
var sym = getSymbols("Examples/OOP/classes_objects.malda"); // From file
var sym2 = getSymbols("function f() { } class C { }"); // From source
// sym.classes, sym.functions, sym.actors, sym.prompts, sym.imports, sym.parseErrors
13.11.2 getParseErrors(sourceOrFilePath)
Analizza codice MALDA e restituisce solo gli errori di parse (nessuna esecuzione). Accetta lo stesso argomento di getSymbols: path di file o stringa sorgente. La risoluzione del path e i controlli di sicurezza sono gli stessi. Restituisce { parseErrors: [{ line, column, message }, ...] }. Usala per validare la sintassi senza eseguire o compilare.
var errs = getParseErrors("var x = ;"); // Invalid: empty rhs
// errs.parseErrors is non-empty with line, column, message
var ok = getParseErrors("var x = 1;"); // Valid: parseErrors is []
13.11.3 checkMalda(sourceOrFilePath, typeMode?, workingDir?)
Diagnostica codice MALDA con le stesse diagnostiche LanguageService di malda check --json (parser, tipi, nomi schema/sum-type, interpolazione). Non esegue il programma. Accetta un path di file o sorgente inline (stessa euristica di getParseErrors). typeMode opzionale: default (IDE: i mismatch di tipo sono errori), strict (suite CLI completa) o lenient (mismatch di tipo come warning). Restituisce { ok, executed: false, file, errorCount, warningCount, infoCount, error?, diagnostics }. Ogni diagnostica ha severity, code, message, file?, line, column (1-based), length, hint?, suggestedFix?. La factory per agenti è createCheckMaldaTool.
var report = checkMalda("var x = 1;");
print(report.ok); // true
var typed = checkMalda("var n: int = \"abc\";", "lenient");
print(typed.ok); // true (mismatch is a warning)
runCommand include controlli di sicurezza completi:
- I comandi pericolosi sono bloccati (es.
rm,del,format,shutdown,powershell,cmd, ecc.) - La working directory è validata e normalizzata per prevenire il path traversal
- Timeout massimo di 1 ora (3.600.000 ms) per evitare attese indefinite
- I path dei comandi sono validati per i path assoluti
- I tentativi di path traversal (
..,~) sono rilevati e bloccati
13.12 Integrazione Spectre.Console
MALDA espone un oggetto globale AnsiConsole che incapsula la libreria .NET Spectre.Console e fornisce output di console ricco:
// Markup (colors, bold, links, etc.)
AnsiConsole.markupLine("[green]Hello[/] [bold red]Spectre.Console[/]!"); // Appends a newline
AnsiConsole.markup("[dim]no newline, [/]"); // Stays on the same line
AnsiConsole.markupLine("[cyan]rest of the line[/]");
// Tables
var rows = [
{"Name": "Alice", "Score": 95},
{"Name": "Bob", "Score": 88}
];
AnsiConsole.table(rows, "Scores");
// Panels (body and title accept markup)
AnsiConsole.panel("[bold]Important[/] message", "Info", "rounded");
// Trees
var treeData = {
"root": "Project",
"children": [
{"label": "src"},
{"label": "tests"}
]
};
AnsiConsole.tree("Project", treeData);
// Status
AnsiConsole.status("Processing...", () => {
// Long-running work here
});
// Prompt (configuration object)
AnsiConsole.prompt({
"type": "text",
"message": "Enter your name"
});
// Progress - New callback-based syntax (recommended)
AnsiConsole.progress((ctx) => {
ctx.addTask("Loading World Map", 100);
while (!ctx.isFinished()) {
ctx.increment("Loading World Map", 1.5);
sleep(50);
}
});
// Progress - Object-based syntax (legacy)
AnsiConsole.progress({
"tasks": [
{"name": "Task 1", "maxValue": 100}
],
"action": (progressObj) => {
var current = 0;
while (current < 100) {
current = current + 10;
// Update progress by setting the value
progressObj["Task 1"] = current;
sleep(50);
}
}
});
AnsiConsole.markupLine(text)scrive il testo e accoda un newline. È la chiamata giusta per una riga di output autonoma.AnsiConsole.markup(text)scrive il testo senza newline finale, così le chiamate consecutive restano sulla stessa riga. Usala per comporre una riga da più frammenti stilizzati, poi chiudi la riga conmarkupLine.- Entrambe analizzano i tag di markup come
[bold],[green]e[/]. Per stampare una parentesi quadra letterale, raddoppiala:[[e]]. AnsiConsole.panel(body, title?, border?)analizza il markup sia nel body sia nel title. Il contenuto che non è markup valido — JSON arbitrario, codice o testo di errore con parentesi quadre — viene reso letteralmente invece di sollevare un errore.
- Sintassi a callback: Passa una funzione che riceve un oggetto context con i metodi:
ctx.addTask(name, maxValue)- Aggiunge un task di progressoctx.increment(taskName, value)- Incrementa il progresso di un task del valore datoctx.isFinished()- Controlla se tutti i task sono finiti
- Sintassi a oggetto: Passa un oggetto con un array
taskse un callbackaction. Il callback riceve un oggetto progresso in cui puoi leggere e aggiornare i valori impostando le proprietà:progressObj["Task Name"] = value
- Interprete da riga di comando: Quando esegui
maldain un terminale reale, MALDA configura UTF-8 e abilita le sequenze di escape ANSI sulle console Windows supportate, così il markup Spectre.Console viene reso con colori e stile completi. - Eseguibili transpile: Gli eseguibili C# generati abilitano le sequenze di escape ANSI all'avvio su Windows, così le chiamate
AnsiConsole.*vengono rese correttamente nei terminali compatibili. - Desktop IDE: Il pannello di output dell'IDE è testo semplice. Al primo uso di
AnsiConsole, MALDA apre automaticamente una finestra di console separata e instrada l'output sia al pannello IDE (testo semplice) sia alla console (rendering ricco Spectre.Console).
13.13 Funzioni data e ora
var timestamp = now(); // Get current timestamp in milliseconds (Unix epoch)
var formatted = formatDate(timestamp, "yyyy-MM-dd HH:mm:ss"); // Format timestamp (default: "yyyy-MM-dd HH:mm:ss")
var parsed = parseDate("2026-01-26 10:30:00"); // Parse date string to timestamp
var tomorrow = addDays(timestamp, 1); // Add days to timestamp
var inHours = addHours(timestamp, 2); // Add hours to timestamp
- I timestamp sono in millisecondi dall'epoca Unix (1 gennaio 1970 UTC)
formatDateusa le stringhe di formato data .NET standard (es. "yyyy-MM-dd", "HH:mm:ss", "dd/MM/yyyy")parseDateaccetta formati data comuni e li converte in timestamp
13.14 Funzioni per numeri casuali
var rand = math.random(); // Random float between 0.0 and 1.0
var randInt = math.randomInt(1, 10); // Random integer, 1 and 10 both included
var randFloat = math.randomFloat(0.0, 100.0); // Random float between 0.0 and 100.0
math.seed(7); // Pin the sequence for reproducible runs
var pinned = math.randomInt(1, 100); // Always 39 after seed(7)
randomInt(min, max)include entrambi gli estremi, a differenza degli intervalli semiaperti comuni in altri linguaggi.math.seed(n)reimposta il generatore condiviso dietrorandom,randomInt,randomFloat,randn,randomChoiceWeightedeanneal. Imposta il seed in cima a un programma per rendere un'esecuzione deterministica, che è ciò che rende testabile un programma casuale.- Le forme piatte
randomInt(1, 10)eMath.randomInt(1, 10)continuano a funzionare, ma il language server le segnala entrambe come alias deprecati. Preferiscimath., come descritto in 13.2 Namespace della stdlib e alias piatti.
13.15 Funzioni di controllo del tipo
var isNum = isNumber(42); // Check if value is a number (integer or float)
var isStr = isString("hello"); // Check if value is a string
var isArr = isArray([1, 2, 3]); // Check if value is an array
var isObj = isObject({name: "Alice"}); // Check if value is an object
var type = typeOf(42); // Canonical tag ("int", "string", "dict", "object", "variant", "task", "null", ...)
var isInt = isTag(42, "int"); // true; isTag also accepts legacy names like "integer" during deprecation
13.16 Funzioni di encoding e decoding
var encoded = base64Encode("Hello World"); // Base64 encode string
var decoded = base64Decode(encoded); // Base64 decode string
var urlEncoded = urlEncode("Hello World"); // URL encode string (returns "Hello%20World")
var urlDecoded = urlDecode(urlEncoded); // URL decode string
13.17 Funzioni hash
var md5Hash = md5("Hello World"); // Calculate MD5 hash (returns hex string)
var sha256Hash = sha256("Hello World"); // Calculate SHA-256 hash (returns hex string)
- Sia
md5siasha256restituiscono stringhe esadecimali in minuscolo - MD5 produce stringhe hex di 32 caratteri
- SHA-256 produce stringhe hex di 64 caratteri
Hash di password, JWT, CSRF e cookie firmati non sono helper di digest — vedi 13.25.
13.18 Generazione di range
var range1 = range(5); // Generate [0, 1, 2, 3, 4]
var range2 = range(1, 10); // Generate [1, 2, 3, 4, 5, 6, 7, 8, 9]
var range3 = range(0, 10, 2); // Generate [0, 2, 4, 6, 8] (step of 2)
var range4 = range(10, 0, -1); // Generate [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] (negative step)
13.19 Funzioni di gestione errori
exit(0); // Exit program with exit code 0 (success)
exit(1); // Exit program with exit code 1 (error)
error("Something went wrong"); // Throw runtime error with message
assert(x > 0, "x must be positive"); // Assert condition is true, throw error if false
assert(isValid, "Validation failed"); // Assert without custom message
exit(code)termina immediatamente il programma con il codice di uscita specificato (0 = successo, non zero = errore)error(message)solleva un errore a runtime che può essere catturato dai meccanismi di gestione erroriassert(condition, message?)è utile per debug e validazione - solleva un errore se la condizione è falsaassertEq(actual, expected, message?)verifica l'uguaglianza strutturale profonda (primitivi, array, dict, variant) e solleva un errore con confronto expected/got se differisconoassertNeq(actual, unexpected, message?)solleva un errore quandoactualè strutturalmente uguale aunexpectedassertThrows(fn, expectedSubstring?, message?)invocafn(), fallisce se non lancia un'eccezione (o se il messaggio non contieneexpectedSubstring) e restituisce il messaggio catturato
13.19.1 result e option
Preferisci questi moduli quando una funzione deve segnalare successo o assenza senza sollevare eccezioni. Restituiscono variant con tag Ok/Err e Some/None — la stessa forma di una dichiarazione type Result = Ok(value) | Err(message), ma non devi dichiarare il tipo. I nomi dei moduli sono in minuscolo (result, option); un type Result dichiarato dall'utente è un nome diverso.
Usa try/catch per i fallimenti inattesi (vedi 8. Strutture di controllo). Usa result/option per gli esiti attesi nel valore di ritorno.
function parseAge(raw) {
var n = toIntOrNull(raw);
if (n == null) {
return result.err("not an int");
}
return result.ok(n);
}
print(result.unwrapOr(parseAge("12"), 0));
print(result.isErr(parseAge("x")));
var present = option.some("hi");
var missing = option.none();
print(option.unwrapOr(present, "no"));
print(option.isNone(missing));
result.ok(value)/result.err(value)— costruisce un variantOkoErrresult.isOk(r)/result.isErr(r)— test sul tagresult.unwrapOr(r, fallback)— payload diOk, altrimentifallbackresult.map(r, fn)— applicafna un payloadOk; lasciaErrinvariatoresult.andThen(r, fn)— seOk, chiamafn(payload)e restituisce quel Result; seErr, non chiamafn.fndeve restituireOk/Err(usamapper trasformare un payload nudo)option.some(value)/option.none()— costruisce un variantSomeoNoneoption.isSome(o)/option.isNone(o)/option.unwrapOr(o, fallback)/option.map(o, fn)/option.andThen(o, fn)— lo stesso schema per i valori opzionali
function parseAge(raw) {
var n = toIntOrNull(raw);
if (n == null) {
return result.err("not an int");
}
return result.ok(n);
}
function doubleAge(n) {
return result.ok(n * 2);
}
print(result.unwrapOr(parseAge("12") |> result.andThen(doubleAge), 0));
print(result.isErr(parseAge("x") |> result.andThen(doubleAge)));
Non trattare i type hint (var n: int = …) come validazione a runtime. Per i payload a forma JSON usa schema e validate(). Tutorial: errori, Result/Option e validate dello schema.
13.19.2 grounded.wrap
Le citazioni di retrieval (GraphMemory, file, tool) non sono un kind di valore visibile a match. Avvolgi un payload così la provenienza è un dict che puoi leggere:
var g = grounded.wrap("the sky is blue", [
{ "source": "wiki", "id": "p1", "span": "12-40" }
]);
print(g.value);
print(g.sourced);
print(g.citations[0].source);
grounded.wrap(value, citations?)— restituisce{ value, citations, sourced }.sourcedè true quando l'elenco delle citazioni è non vuoto dopo la normalizzazione.- Ogni citazione è
{ source, id?, span? }. Una citazione stringa diventa{ source }. Non esiste un alias piattogrounded(). - ASK opt-in di GraphMemory:
memory.ask(query, maxResults?, options?)(oppurequery(..., { grounded: true })) avvolge gli hit con citazioni dafilePath/source/nodeId.query()semplice restituisce ancora un array. Vedi 20. GraphMemory §20.3.15.
13.19.3 cap.fileRead
Questa sottosezione è il catalogo delle firme. Se non hai ancora usato i token, parti dal how-to in 12.6 Token di capability — perché esistono, l'analogia della chiave, cap.confine e il pattern host-mint per i tool.
Un token è un oggetto host sigillato con kind e path (e name per un tool MCP). JSON e object literal non possono rigenerarne uno. @effects("io") nomina solo l'effetto; non lega un path, un URL, un tool o un argv.
var notes = cap.fileRead("notes.md");
print(notes.kind);
print(cap.is(notes, "fileRead"));
var forged = false;
try {
cap.read({ "kind": "fileRead", "path": "notes.md" });
} catch (e) {
forged = true;
}
print(forged);
cap.fileRead(path)/cap.fileWrite(path)/cap.dirList(path)/cap.httpGet(origin)/cap.mcpCall(server, tool?)/cap.shell(prefix)— emette un token. Non esiste un alias piattocap().cap.read(token, startLine?, endLine?)/cap.write(token, content)/cap.list(token)/cap.fetch(token, urlOrPath?, maxBytes?, timeoutMs?)/cap.invoke(token, server, args?)/cap.run(token, extraArgs?, workingDir?, timeout?)— consuma solo un kind corrispondente. Stringhe e dict{ kind, path }sollevano un'eccezione. Origin / tool /../ extra assoluti sbagliati lanciano prima di HTTP, MCP o dell'avvio del processo.cap.is(value, kind?)— true solo per un token reale. Omettikindper accettare qualsiasi kind di token.cap.confine(token, relative)— stesso kind, path / prefisso URL / tool MCP / prefisso argv più stretto; i valori fuori dal padre sollevano un'eccezione.io.readFile/io.writeFile/io.listDirectory/webFetch/callTool/runCommandaccettano anche un token corrispondente. Le stringhe ordinarie continuano a funzionare per il codice che non è un tool.createWebFetchTool(httpCap?)/createRunCommandTool(workingDir?, shellCap?)legano un token così URL / comandi del modello restano sotto di esso.- Marca gli handler che emettono o consumano token con
@effects("cap")(o elenca sia"io"sia"cap"). JavaScript può emettere /is/confine; il consume è solo host. - Non passare un token attraverso JSON LLM. Emetti la root del workspace sull'host e usa
cap.confinesu un path / URL / tool / extra argv relativo dagli argomenti del tool. Scaffold:malda new agent. - Esempi:
Examples/Tools/capability_tokens.malda,Examples/Tools/capability_http_mcp_shell.malda.
13.19.4 expect
Lancia come assert quando la condizione è falsa. Si usa nei case di suite; malda eval esegue quei case. validate continua a tornare { ok, error }. Vedi 24.1.
expect(checked.ok);
expect(n > 0, "n must be positive");
13.19.5 stream
Produce un array di chunk { text }, oppure parziali schema-aware se si passa un nome di schema registrato. LlamaCpp è bufferizzato, non token live. Itera con for await. Vedi 24.8.
var chunks = stream("hello world from malda");
13.19.6 race / firstOk
race è il primo ramo completato. firstOk è il primo ramo che non è una variante Timeout. all aspetta ogni ramo e mette AgentError.Upstream negli slot falliti. Vedi 24.4.
race(taskA, taskB);
firstOk(taskA, taskB);
13.19.7 trace.span / trace.journal / trace.lastUsage
Journal di run in-process: eventi prompt, tool, cap, hop e step di workflow. .usage su un risultato di prompt è metadata (la chiave propria vince). Vedi 24.3.
trace.span("name", () => { });
var events = trace.journal();
var spend = trace.lastUsage();
13.19.8 AgentError
Sum type built-in attaccato come agentError accanto alla stringa error. I throw restano throw. Mismatch di validate → SchemaMismatch. Vedi 24.7.
AgentError = Refused(reason) | Unparsable(raw, attempts) | SchemaMismatch(schema, error)
| BudgetExceeded(kind, limit) | ToolDenied(tool, reason) | Timeout(ms)
| Upstream(status, body)
13.20 Pianificazione strutturata dei task
decomposeTask, executePlan, createSubmitPlanTool, createUpdatePlanTool e createMarkStepTool vivono in 19. Orchestrazione di agenti (§ 19.13). agents.define / agents.team collegano spec di ruolo a un grafo diretto; executePlan(plan, team) rispetta step.role e gli hop dichiarati, dirama gli hop reject sul verdetto approved del predecessore e accetta plan.think: false per restare offline — vedi § 19.17. team.handoff / team.review / team.reject / team.consult sono hop tipizzati e restano solo validazione se think non è true. runProgram esegue un valore chiuso api / program(ApiName) senza ulteriori chiamate LLM — vedi 10. Prompt (§ 10.8 API chiuse e programmi deterministici).
13.21 Funzioni di creazione tool
Le factory di tool per agenti (createReadFileTool, createWriteFileTool, createReplaceInFileTool, createEditFileTool, createInsertAtLineTool, createGrepTool, createListDirectoryTool, createAskUserTool, createWebSearchTool, createWebFetchTool, createGitStatusTool, createGitAddTool, createGitCommitTool, createGitLogTool, createGitDiffTool, createGitBranchTool, createGitCheckoutTool, createGitPushTool, createGitPullTool, createRunCommandTool, createRunMALDATool, createCompileMALDATool, createGetSymbolsTool, createGetParseErrorsTool, createCheckMaldaTool, createValidateJsonTool, createTestMaldaTool, createSubmitPlanTool, createUpdatePlanTool, createMarkStepTool, createGlobTool, createCreateMcpAgentScriptTool, createDeleteFileTool, createCopyFileTool, createEnsureDirTool) vivono in 19. Orchestrazione di agenti (§ 19.6). createNativeCallback incapsula una funzione MALDA come delegate .NET — vedi 32. Interop .NET.
13.22 Operazioni dei workflow durevoli
Gli helper di runtime, query e controllo (startWorkflow, getWorkflowStatus, getWorkflow, getWorkflowSteps, getWorkflowEvents, getWorkflowMetrics, listWorkflows, listWorkflowDeadLetters, requeueDeadLetter, runWorkflowInstance) vivono in 23. Workflow durevoli.
13.23 Logging del runtime degli agenti
Gli helper diagnostici (enableAgentVerboseLogging, setAgentVerbosePhase, setAgentStatusBanner, reportRalphStatus) vivono in 19. Orchestrazione di agenti (§ 19.5 e 19.19 Ralph Wiggum). Influenzano solo la presentazione e non cambiano mai il risultato di un agente.
13.24 Funzioni Web UI
Gli helper dei componenti server (renderTemplate, componentFragment, componentLiveEmit, componentState*, onAgentProgress, clearAgentProgress, cancelThink) e i controlli ui.* vivono in 26. Componenti server Web UI. Parti da 25. Panoramica Web UI se stai scegliendo un modello UI.
13.25 Password, JWT e autenticazione della richiesta
How-to delle firme HTTP: 29.16 Helper per password, JWT e cookie. Principale della richiesta: 29.6.2 req.auth. Primer: hash delle password, JWT, CSRF.
Nomi in catalogo: hashPassword, verifyPassword, createJwt, verifyJwt, generateCsrfToken, verifyCsrfToken, csrfField, createSecureCookie, readSecureCookie, httpBearerToken, httpCookieToken, httpAuthToken, bindForm, formErrors, pageLayout. Superficie handler: req.auth.authenticateBearerJwt, authenticateCookieJwt, requireRole, requirePermission, setVerifiedSub.
13.26 Job in background
Coda SQLite leggera (enqueueJob, claimJob, completeJob, failJob, getJob, listJobs) — non è un workflow durevole. How-to: 23.11 Coda di job leggera.
13.27 Pacchetti opzionali (non nel core)
Il BuiltInRegistry del core elenca solo i simboli open-source del core. I built-in di dominio possono essere distribuiti in pack separati; caricali con loadNativeModule(...) e distribuisci gli assembly richiesti accanto all'app. Il core non registra automaticamente i globali dei pack.
Vedi anche
- Appendice — Pacchetti opzionali
- Input/Output — console, file, path, ambiente, I/O dell'host; preferisci
io.* - 12.6 Token di capability — how-to per
cap.*(questo capitolo è il catalogo) - 10.9.1 Helper di pipeline AI —
loadDocuments,runPrompt,composePipe - 12.9 Recupero di URL —
webFetch - Componenti server Web UI — UI server-side e API dei componenti
- Orchestrazione di agenti — Tool, piani di task e logging degli agenti
- 23.11 Coda di job leggera —
enqueueJobe compagni - 24. Esecuzioni agentiche —
expect,stream,race/firstOk,trace.*,AgentError - 29.16 Helper per password, JWT e cookie