Learn
Research previewPOST /v1/agents/learn. Turn recorded turns into Simulang code, or repair that code.
Turns what Sai did in one or more turns into a Simulang function you own, async function main(params = { ... }), which your program then runs on a computer through direct control. Given code you already have, the same call repairs it. With maxIterations, it also runs the code on a computer, judges each run and repairs the code until it passes (learn jobs). Learned code walks through the whole loop.
Research preview: the request and response may change.
A Tenant token can call it too, for the Tenant's computers and turns.
Try this first, before the details. With Sai added to your coding agent (Claude Code, Codex or Cursor), ask it:
Use Sai to open TechCrunch, find all AI news published today, write their headlines into Notepad and save the file as techcrunch_headlines.txt, then turn what it did into code I can rerun.Uses
Two fields decide what a call does: turns says where the experience comes from (recorded turns, or else an agent run of taskTemplate), and maxIterations says how far to go (0, the default, writes the code; 1 or more also runs, judges and repairs it).
Two more follow from the same rules: { taskTemplate, inputs } runs the agent and returns its code without running it, and { initialCode, taskTemplate, inputs, maxIterations: 3 } runs, judges and repairs code you already have.
A call that only writes code answers 200 with the code. A call that uses the computer (an agent run, or runs of the code) answers 202 with a learn job to read with GET, because it can take an hour.
Request
curl -s "$SAI_API_URL/v1/agents/learn" \
-H "Authorization: Bearer $SAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"turns": ["turn_vzjz62w7j7jvOilZ6zBL"],
"taskTemplate": "Open {{newsSite}}, find all {{topic}} news published today, write their headlines into Notepad, one per line, and save the file as {{fileName}}"
}'¹ Send turns, taskTemplate or initialCode. To repair, send initialCode with evaluations, guidance or new turns. New turns are the usual input: the code failed on a case, you sent the same template to POST /message with recordTrajectory, Sai solved it, and that turn shows what the code is missing.
² Only for a call that uses the computer; on any other call they are a 400, so a forgotten maxIterations is an error rather than a silent conversion.
evaluations is an array of objects, one per run of initialCode:
{
"inputs": { "newsSite": "TechCrunch", "topic": "AI", "fileName": "techcrunch_headlines.txt" },
"result": {
"error": { "kind": "exception", "message": "Error: Notepad did not open" },
"logs": [
"Found 13 headlines published today: ...",
"Launching Notepad...",
"Task failed: Notepad did not open"
]
},
"passed": false,
"note": "Notepad was already open from an earlier run, and its window stayed minimized in the taskbar."
}The call does the work before it answers. How long depends on the task: a longer run gives longer code to write and check. Set your client's timeout to at least 10 minutes. If your side times out, send the same request with the same idempotency_key, or read the result with GET /v1/agents/learn/{learnId}. A learn job answers 202 at once instead.
Response
{
"learnId": "learn_3Fq9cT1kZ0aJ",
"mode": "convert",
"status": "succeeded",
"title": "Save today's TechCrunch AI headlines to Notepad",
"template": "Open {{newsSite}}, find all {{topic}} news published today, write their headlines into Notepad, one per line, and save the file as {{fileName}}",
"parameters": [
{ "name": "newsSite", "defaultValue": "TechCrunch" },
{ "name": "topic", "defaultValue": "AI" },
{ "name": "fileName", "defaultValue": "techcrunch_headlines.txt" }
],
"code": "async function main(params = { newsSite: \"TechCrunch\", topic: \"AI\", fileName: \"techcrunch_headlines.txt\" }) {\n ...\n}",
"validation": { "errors": [], "warnings": [] },
"sourceTurns": ["turn_vzjz62w7j7jvOilZ6zBL"],
"usage": { "inputTokens": 80670, "outputTokens": 4525 },
"researchPreview": true
}A repeated idempotency_key returns the earlier result plus "idempotent_replay": true.
Run the code
Run it in a control lease with the call to main as the block's last line; the block's result is what main returns. Pass every input: an argument to main replaces its whole default object, so merge your inputs over parameters' defaults.
Learned code reads your account's clock: the timezone your Sai app last reported, or UTC if you have never opened it. A learn job's runs and a control lease both use it, so new Date() gives the same day when you replay the code as when the job tested it.
curl -s "$SAI_API_URL/v1/machines/$MACHINE_ID/control/exec" \
-H "Authorization: Bearer $SAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"code": "<code>\nawait main({\"newsSite\": \"TechCrunch\", \"topic\": \"Fintech\", \"fileName\": \"techcrunch_fintech.txt\"})",
"timeoutMs": 300000
}'Note
<code>is a placeholder: put thecodestring from the learn response in its place, then a newline and the call tomain.
The SDKs do this for you: lease.run(learned, inputs).
Learn jobs
A call that uses the computer is a job. It answers at once:
{ "learnId": "learn_LIEHFGsRU4H3", "mode": "policyIteration", "status": "running" }curl -s "$SAI_API_URL/v1/agents/learn" \
-H "Authorization: Bearer $SAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"taskTemplate": "Open {{newsSite}}, find all {{topic}} news published today, write their headlines into Notepad, one per line, and save the file as {{fileName}}",
"inputs": { "newsSite": "TechCrunch", "topic": "AI", "fileName": "techcrunch_headlines.txt" },
"criteria": "techcrunch_headlines.txt is saved and holds only the headlines of the AI articles TechCrunch published today, one per line, with no text left from earlier runs",
"maxIterations": 3,
"rollouts": 3
}'What the job does:
- Reset, when you sent one, then the agent run, when you sent no
turns. A run that stopped at a question or failed on its own stops the job here (agent_failed, ormachine_unavailable), withagentRunEndsaying why and nothing converted: fix the task, or send itsagentTurnIdasturnsto convert it anyway. A run the account could not pay for stops the job too (insufficient_credit). Any other run goes on, even one that got the task wrong or was cut off atagentRunMinutes: the runs and repairs fix the rest. WithjudgeInitialAgentRun, that run is judged first, and if it fails, the job stops here (agent_failed) with the judgement; send itsagentTurnIdasturnsto start again from it if you disagree with the judge. - Convert the run (or your
turns) into version 1. WithmaxIterations0 the job ends here. - For each version, run the code up to
rolloutstimes in a row, each after the reset, and judge each run on what it returned, its logs, the screen when it ended, and the date and time it started on your account's clock (so "today" in a task means the day the run saw). The first failed run ends that version's runs. - If every run passed, the job ends
succeeded. Otherwise, withcontinueWithAgent, the agent finishes the task from where the code stopped; then the code is repaired with the failed run, its judgement, the agent's turn andguidance, and the next version runs. After the last version, the job endssucceededwithtestResult.status: "failed".
Nobody watches a job, so it approves like a control lease: in the agent run, resets and code runs, commands and clicks that would ask for approval go ahead, and a sign-in, a choice or a connect request fails at once instead of waiting. On your own computer, that is your real screen, mouse and keyboard.
A step that fails for a reason that may pass (a 429 or 5xx, a dropped connection, a judge or model call that gave no answer, the computer not free yet) is tried two more times before the job stops.
Read it with GET /v1/agents/learn/{learnId} every 10 to 30 seconds. The SDKs' wait does this for you:
curl -s "$SAI_API_URL/v1/agents/learn/$LEARN_ID" \
-H "Authorization: Bearer $SAI_API_KEY"{
"learnId": "learn_LIEHFGsRU4H3",
"mode": "policyIteration",
"status": "running",
"progress": { "step": "run", "iteration": 1, "rollout": 2 }
}When status is no longer running, the job has ended:
{
"learnId": "learn_LIEHFGsRU4H3",
"mode": "policyIteration",
"status": "succeeded",
"testResult": {
"status": "passed",
"passedRuns": 3,
"requiredRuns": 3,
"inputs": { "newsSite": "TechCrunch", "topic": "AI", "fileName": "techcrunch_headlines.txt" }
},
"version": 2,
"code": "async function main(params = { newsSite: \"TechCrunch\", topic: \"AI\", fileName: \"techcrunch_headlines.txt\" }) {\n ...\n}",
"agentTurnId": "turn_mklL8pNHaL59",
"iterations": [
{
"index": 1,
"learnId": "learn_lkP4",
"passed": 1,
"runs": 2,
"rollouts": [
{
"index": 1,
"verdict": "passed",
"reset": { "kind": "code", "ok": true, "durationMs": 900 }
},
{
"index": 2,
"verdict": "failed",
"summary": "It returned the second story.",
"continuationTurnId": "turn_ED6M"
}
]
},
{
"index": 2,
"learnId": "learn_OoPe",
"changes": "...",
"passed": 3,
"runs": 3,
"rollouts": ["..."]
}
]
}Read one run, with what it returned and logged and its judgement:
curl -s "$SAI_API_URL/v1/agents/learn/$LEARN_ID/iterations/1/rollouts/2" \
-H "Authorization: Bearer $SAI_API_KEY"Stop a job at once, whatever step it is on. It keeps the last complete results, reads stopped with stopReason: "cancelled" within seconds, and frees the computer:
curl -s -X POST "$SAI_API_URL/v1/agents/learn/$LEARN_ID/cancel" \
-H "Authorization: Bearer $SAI_API_KEY"Note
The runs do the task for real, up to
maxIterations×rolloutstimes, plus the agent run and continuations. Use test inputs or a test account for a task that sends or submits something. The computer is busy for the whole job.
Time limits. Each step has a limit (rolloutMinutes, agentRunMinutes, continuationMinutes, and 5 minutes for reset.code), and the job has maxJobMinutes. Before it starts, the job's worst case (every step at its limit, every version failing on its last run) must fit in maxJobMinutes; otherwise the call is refused with time_limit_too_low and the computed worst case. Reaching maxJobMinutes stops the job at once with stopReason: "time_limit" and the last complete results.
The limits' maxima cannot all be used at once. The worst case is:
[reset + agent run, with an agent run] + 2 for the initial judge + 5 for the conversion (none from initialCode)
+ maxIterations × (rollouts × (reset + rolloutMinutes + 2) + continuationMinutes)
+ (maxIterations − 1) × 5 for the repairswith 15 for a reset task (agentRunMinutes), 5 for reset code, 2 for each judge call and 5 for each conversion or repair. With every default, 5 versions × 3 runs, a reset task, the initial judge and continuations come to 612 minutes, which is why maxJobMinutes defaults to 615. The longest job the API accepts is one whose worst case fits in 690 minutes; 5 versions × 5 runs with all of the above comes to 932 and is refused, so lower rollouts or the step limits for it. The main uses with defaults need far less: 20 minutes for an agent run converted to code, 183 for the full loop from a task with maxIterations: 3.
Every model call a job makes is billed to your account, as the same calls would be when made one by one. If the account runs out of credit at any step, the job stops with insufficient_credit and returns its latest code.
Read a result later
curl -s "$SAI_API_URL/v1/agents/learn/$LEARN_ID" \
-H "Authorization: Bearer $SAI_API_KEY"Returns the same object. A call that stopped mid-way reads as failed with error: "interrupted". A job whose computer stopped answering reads as stopped with stopReason: "interrupted".