Write a script
A script exports a default function that receives input. Its return value becomes the run’s output.
Before running this page, complete quickstart steps 1–3 in the same Bash session: set PRAXIS_API_URL and PRAXIS_API_KEY, define SOURCE and run it, then define and run read_result. The helper checks for answer 42, as expected by the arithmetic examples here.
Entry point and schemas
Save this as script.ts:
export default async (input: { n: number }): Promise<{ answer: number }> => { console.log("Adding one", input.n); return { answer: input.n + 1 };};The input schema comes from parameter types. The output schema comes from an explicit return type, with Promise unwrapped. Supported forms include primitives, objects, arrays, unions and resolvable local type aliases. Unsupported types produce an empty schema and a warning. An empty schema does not validate your fields. Do not rely on a return expression to infer output constraints when the return annotation is missing.
Validate the definition to inspect the generated schemas before publishing:
curl --fail-with-body -sS "$PRAXIS_API_URL/automation/v1/validate" \ -H "Authorization: Bearer $PRAXIS_API_KEY" \ -H 'Content-Type: application/json' \ --data "$(jq -n --rawfile source script.ts '{kind:"script",source:$source}')" \ | jq -e '.valid == true and .input_schema.properties.n.type == "number" and .output_schema.properties.answer.type == "number"'Expected: true and exit code 0. Inspect errors and warnings in the full validation response when a type cannot be inferred.
Execution and logs
RUN=$(curl --fail-with-body -sS "$PRAXIS_API_URL/automation/v1/runs" \ -H "Authorization: Bearer $PRAXIS_API_KEY" \ -H 'Content-Type: application/json' \ --data "$(jq -n --rawfile source script.ts \ '{source:$source,language:"ts",input:{n:41},wait:60}')")RUN_ID=$(jq -er '.id' <<< "$RUN")read_result "$RUN_ID"curl --fail-with-body -sS "$PRAXIS_API_URL/automation/v1/runs/$RUN_ID/logs" \ -H "Authorization: Bearer $PRAXIS_API_KEY"Expected: the result assertion prints true; the log response includes Adding one 41. console.log/info/debug produce info entries; console.warn and console.error retain their levels. Logs are separate from output: use return for data the caller needs. Read logs, or subscribe with Accept: text/event-stream.
Preset bindings: praxis, call, invoke
The runtime presets praxis, call, invoke, console and codemode in the script module. Use them directly: no import is needed, and they are not on globalThis either — inside a script globalThis.praxis is undefined.
Their shapes differ, so do not confuse them:
praxisis an object: the platform SDK. Call platform APIs aspraxis.<domain>.<resource>.<method>(...), with methods taking the reference pages’path,queryandbodyoptions, for examplepraxis.automation.runs.create({body:{target,input}})orpraxis.model.ocr.create(...). The initiator’s permissions still govern access.- An Action ID is a string: it is the argument you pass to
call(), for examplecall("ocr", { ... }). It is not a function name, sopraxis.ocr(...)does not exist and fails at runtime with the correct form.
Its SDK entry points are listed below:
| Entry point | Reference |
|---|---|
praxis.agent | Agent |
praxis.model | Model |
praxis.file | File |
praxis.sandbox | Sandbox |
praxis.search | Search |
praxis.database | Database |
praxis.automation | Automation |
praxis.organization | Organization |
praxis.application | Application |
praxis.browser | Browser |
praxis.knowledge | Knowledge |
praxis.media | Media |
praxis.vault | Vault |
praxis.canvas | Canvas |
praxis.content | Content |
praxis.crm | CRM |
praxis.customer | Customer |
praxis.cut | Cut |
praxis.ontology | Ontology |
praxis.meta | Meta |
Scripts cannot access external networks directly. Use platform capabilities and await calls to receive their results and handle failures.
For how the three calls relate, see Calling Automation from codemode.
Call a built-in action
call("namespace/name", input) takes an Action reference and an input object and returns the Action’s output. Built-in Actions use a bare short name (for example ocr); Actions you create use namespace/name (for example shop/refund). It is one step of the current run: it has its own input and output and takes one row in the call ledger; it does not create a child run. A call always uses the Action’s current revision; @version is not supported yet, and the namespace::name form is no longer accepted.
A failed call throws an error carrying code, message, hint, the call-ledger position seq, request_id, and errors, which lists the offending fields (each entry has pointer and detail, often hint). String(e) is only the summary; read e.errors for the field list. INPUT_INVALID uses it to name the field that breaks the Action’s input contract. The input contract is in the response of get an action at current_revision.input_schema, not at the top level. Several calls can run concurrently with Promise.all. praxis.* is the platform SDK only: praxis.ocr(...) does not exist and fails at runtime with a hint to use call.
Save this as chat.ts. It calls the built-in Action chat. The model is built into the action and maintained by its author; callers do not select a model. The same applies to ocr, image and embed. The legacy model field is deprecated and ignored. This call incurs model usage charges:
export default async (input: { prompt: string }) => { return await call("chat", { messages: [{ role: "user", content: input.prompt }], stream: false, });};RUN=$(curl --fail-with-body -sS "$PRAXIS_API_URL/automation/v1/runs" \ -H "Authorization: Bearer $PRAXIS_API_KEY" \ -H 'Content-Type: application/json' \ --data "$(jq -n --rawfile source chat.ts \ '{source:$source,language:"ts",input:{prompt:"Say hello in one sentence."},wait:60}')")RUN_ID=$(jq -er '.id' <<< "$RUN")curl --fail-with-body -sS "$PRAXIS_API_URL/automation/v1/runs/$RUN_ID" \ -H "Authorization: Bearer $PRAXIS_API_KEY" | jq '{id,status,output,error}'Expected: terminal status completed, model output in output, and null error. If still pending or running, repeat the final GET until terminal. For faulted, inspect the error; HTTP success alone does not prove a successful model call. For the complete input and output contract of chat, get the action and read current_revision.input_schema and current_revision.output_schema.
Call your own action
This example creates an action, then calls its full name. The generated script contains a literal reference so it can be checked before publication.
ACTION_NAME="add-one-$(date +%s)-$RANDOM"curl --fail-with-body -sS "$PRAXIS_API_URL/automation/v1/actions" \ -H "Authorization: Bearer $PRAXIS_API_KEY" \ -H 'Content-Type: application/json' \ --data "$(jq -n --arg name "$ACTION_NAME" '{ namespace:"docs-samples",name:$name, input_schema:{type:"object",properties:{n:{type:"number"}},required:["n"],additionalProperties:false}, output_schema:{type:"object",properties:{answer:{type:"number"}},required:["answer"],additionalProperties:false}, implementation:{kind:"code",language:"ts",source:"export default async (input: { n: number }) => ({ answer: input.n + 1 });"} }')" | jq -e '.id | startswith("act_")'SOURCE="export default async (input: { n: number }) => await call(\"docs-samples/$ACTION_NAME\", input);"RUN=$(curl --fail-with-body -sS "$PRAXIS_API_URL/automation/v1/runs" \ -H "Authorization: Bearer $PRAXIS_API_KEY" \ -H 'Content-Type: application/json' \ --data "$(jq -n --arg source "$SOURCE" \ '{source:$source,language:"ts",input:{n:41},wait:60}')")RUN_ID=$(jq -er '.id' <<< "$RUN")read_result "$RUN_ID"Expected: both creation and result checks print true, with answer 42. Archive the action when finished. Actions are reusable. The code of your own Action has no praxis or invoke, and call there takes a string literal and reaches built-in Actions only; it cannot call another of your Actions, a script, a workflow or an agent. Orchestrate in a script or workflow instead.
To catch a call error and read its field list (with input {"n":"x"}, problems lists the fields that break the contract). call accepts only a literal string, so replace add-one in the example with the full Action name created in the previous step (the value of $ACTION_NAME):
export default async (input: { n: number }): Promise<{ answer?: number; problems?: string[] }> => { try { return await call("docs-samples/add-one", { n: input.n }); } catch (e: any) { // String(e) is only the summary; the field list is in e.errors[]. console.error(e.code, e.hint, e.requestId); return { problems: e.errors.map((x: { pointer: string; detail: string }) => `${x.pointer}: ${x.detail}`) }; }};Call another script or workflow
invoke("namespace/name@version", input) starts another published script or workflow as a child run, waits for it to finish and returns the child’s output; leave out @version for the latest. Unlike call, which is one step inside the current run and creates no child run, invoke creates a child run with its own ID, status and logs, and the call record points to it through child_run_id.
export default async (input: { urls: string[] }) => { // Use Promise.all to run several invokes at once; child runs start through a queue. const pages = await Promise.all(input.urls.map(url => invoke("team/fetch-page", { url }))); return { pages };};- The wait is capped:
invokewaits synchronously, bounded by the parent run’sdeadline. At the cap it throwsINVOKE_TIMEOUTwith the child run ID in the message; the child is not cancelled, so you can read its result separately. A workflowrun:step saves compute while it waits but is bounded by the same parentdeadlineand does not shorten the wait; to stop waiting altogether, create the run and read its result on the next round. - A limit for one call: a third argument
{ timeoutMs }lets this oneinvokewait at most that long — for a watcher on its own few-minute cadence, which must never be held to its deadline by one child (invoke("ops/alert-intake@1.9.6", { alerts }, { timeoutMs: 90000 })). It throws the sameINVOKE_TIMEOUT, titled with this invoke’stimeout_ms, and still leaves the child running. It only tightens: a value longer than the parent’s remaining time falls back to the parentdeadlineand never extends it. Catch it and the run can end the round as skipped and start the next one; leave it uncaught and the run faults, as with any other failedinvoke. - Failures: a child that fails, is cancelled or cannot be created makes
invokethrow;codeis the child’s error code andmessagecarries the child run ID. A missing or archived target fails immediately and nothing is queued. - Cancel and timeout: when the parent run is cancelled or fails, children it is still waiting on are cancelled with it.
- Finding child runs: list runs filtered by
parent_run_idfor each child’s ID, target, status and duration. - Limits: at most 1,000 child runs per run, 100 active at once (the rest queue), nesting up to 10 levels, and a run cannot invoke itself.
A script cannot start a detached child with invoke; to start a run without waiting, call create run.
Output and time budgets
Return JSON-serializable data. Do not return undefined, BigInt or circular references. UTF-8 encoded JSON output must fit within 1 MiB; larger output faults the run. Write large results to a file and return its ID.
The default script wall-clock limit is 30 minutes. CPU time is capped at 30 seconds and further bounded by the remaining deadline. Waiting for a platform call differs from executing pure computation; increasing wait time does not fix an infinite loop. See limits and errors for the full limits.
Write large output to a file
Save content with the built-in Action write-file, which returns the file’s id and size; later steps or the caller read the file by that ID. write-file requires filename, purpose, contentType and Base64 contentBase64:
export default async (input: { rows: number }): Promise<{ file_id: string; size: number }> => { const lines: string[] = []; for (let i = 0; i < input.rows; i++) lines.push(`row ${i}`); const bytes = new TextEncoder().encode(lines.join("\n")); let binary = ""; for (const byte of bytes) binary += String.fromCharCode(byte); const saved = await call("write-file", { filename: "report.txt", purpose: "user_data", contentType: "text/plain", contentBase64: btoa(binary), }); return { file_id: saved.id, size: saved.size };};To run commands in a sandbox, use run-sandbox. It returns at most 32 KiB of standard output and truncates the rest. Have the command write large results to files and pass outputs: [{ path: "/tmp/result.json", filename: "result.json" }]; after the command exits successfully, the Action saves those files as managed files.
Read a secret from a bound vault
A script reads a secret by name with await vaults.<alias>.<NAME>: one value per read, fetched only when used.
- Bind a vault to the script under an alias:
PUT /automation/v1/scripts/{namespace}/{name}/vaults/{alias}with body{"vault":"vlt_..."}(SDK:praxis.automation.scripts.vaults.set). The alias matches^[a-z][a-z0-9-]{0,39}$. - Read it in the script:
export default async (): Promise<{ ok: boolean }> => { const id = await vaults.deploy.ALIYUN_ACCOUNT_ID; await call("team/deploy-to-cloud", { accountId: id }); return { ok: true };};- A binding belongs to the script definition. It is not inherited from a parent run, another script, a workflow or a version; bind again for each script.
process.envholds no secrets. The environment is always empty, soprocess.env.Xisundefined. Read secrets only this way.- Masking. A value you read shows as
***in logs, call records, and the runoutputanderror. Masking covers the values this run read; do not re-encode a secret into other text and print it. - Errors (the thrown error carries
codeandhint):
| code | Meaning | Fix |
|---|---|---|
VAULT_ALIAS_NOT_BOUND | This script has no binding for the alias | Bind it with vaults.set on this script, using the alias the code uses. |
SECRET_NOT_FOUND | The bound vault has no secret with that name | Check the secret name (case-sensitive) and which vault is bound. |
SERVICE_UNAVAILABLE | The vault service is unavailable | Retry with a new run later. |
Workflows bind a vault the same way (PUT /automation/v1/workflows/{namespace}/{name}/vaults/{alias}) and then reference it in a step as ${ $vaults.alias.NAME }.
Keep a script replayable
When an executor is lost, the platform executes the script again from the start, and recorded calls return their original results (see Recovery and replay). For that, every execution of the script must make the same calls with the same inputs:
- Keep
Date.now(),new Date(),Math.random()andcrypto.randomUUID()out of call inputs, such as a timestamp in a request body that writes a row. Take the value from the run input or from a call result. - Do not branch on these values.
- Calls started together are matched to records by what they are, not by the order they are sent in, so they replay whatever order their results come back in. A new write made before every recorded write has been made again is refused, and the run fails with
REPLAY_DIVERGEDrather than risk making one write twice.
Diagnosing errors
| Code | Original message | Action |
|---|---|---|
SCRIPT_ERROR | 脚本执行出错 | Inspect the original exception and user-code locations in detail, fix the script and start a new run. |
CPU_LIMIT_EXCEEDED | 脚本 CPU 时间超出上限 | Remove infinite loops and reduce computation per batch. |
PAYLOAD_TOO_LARGE | Payload exceeds 1 MiB | Reduce JSON output and return a storage reference. |
INPUT_INVALID | Value must be JSON serializable | Return an explicit JSON value such as an object or null. |
REPLAY_DIVERGED | Re-execution …, naming the call’s number and target | The new execution made a different call. Find the call detail names, remove the time or random value from its input or from a branch before it, then create a new run. |
EFFECT_OUTCOME_UNKNOWN | EFFECT_OUTCOME_UNKNOWN | The executor was lost after a write was sent, so whether it took effect is unknown. Check its effect before doing it again. |
Execution failures appear in Run.error. Rejected create requests return an HTTP problem response. Handle these separately.