@parcha/agentrun-serve 0.1.0-beta.51 → 0.1.0-beta.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +94 -13
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +10 -4
  8. package/dist/api-only.d.ts +4 -2
  9. package/dist/api-only.js +5 -3
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/computer-setting.d.ts +8 -0
  13. package/dist/computer-setting.js +11 -0
  14. package/dist/computers.d.ts +6 -2
  15. package/dist/computers.js +2 -2
  16. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  17. package/dist/console/assets/index-DlQepP2J.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/fal-price.d.ts +76 -0
  20. package/dist/fal-price.js +368 -0
  21. package/dist/learn/commit.d.ts +5 -0
  22. package/dist/learn/commit.js +4 -1
  23. package/dist/learn/compile.d.ts +13 -5
  24. package/dist/learn/compile.js +24 -7
  25. package/dist/learn/delete.d.ts +12 -6
  26. package/dist/learn/delete.js +17 -11
  27. package/dist/learn/folder.d.ts +11 -0
  28. package/dist/learn/folder.js +20 -3
  29. package/dist/learn/learning-of.d.ts +8 -0
  30. package/dist/learn/learning-of.js +8 -0
  31. package/dist/learn/learning.sh +14 -1
  32. package/dist/learn/promote.d.ts +51 -7
  33. package/dist/learn/promote.js +51 -8
  34. package/dist/learning-reset.d.ts +18 -0
  35. package/dist/learning-reset.js +115 -0
  36. package/dist/learning-routes.d.ts +1 -1
  37. package/dist/learning-words.d.ts +5 -0
  38. package/dist/learning-words.js +5 -0
  39. package/dist/learning.d.ts +8 -6
  40. package/dist/learning.js +5 -4
  41. package/dist/llms.txt +1 -0
  42. package/dist/mcp-gateway.d.ts +39 -2
  43. package/dist/mcp-gateway.js +41 -10
  44. package/dist/mcp-pin-first.js +1 -1
  45. package/dist/mcp-servers-store.d.ts +1 -0
  46. package/dist/mcp-servers-store.js +2 -1
  47. package/dist/media-duration.d.ts +2 -0
  48. package/dist/media-duration.js +136 -0
  49. package/dist/openapi.js +45 -12
  50. package/dist/provider.d.ts +8 -0
  51. package/dist/provider.js +14 -2
  52. package/dist/refusal-words.d.ts +0 -3
  53. package/dist/refusal-words.js +0 -3
  54. package/dist/request-metadata.d.ts +20 -0
  55. package/dist/request-metadata.js +24 -0
  56. package/dist/run-launch.d.ts +13 -4
  57. package/dist/run-launch.js +14 -3
  58. package/dist/run-learning-served.d.ts +2 -2
  59. package/dist/run-usage.d.ts +48 -4
  60. package/dist/run-usage.js +156 -39
  61. package/dist/run-view.d.ts +1 -1
  62. package/dist/run-view.js +3 -7
  63. package/dist/runner/adapter-loop.d.ts +3 -1
  64. package/dist/runner/adapter-loop.js +12 -9
  65. package/dist/runner/adapter-run-spec.d.ts +1 -1
  66. package/dist/runner/adapter-run-spec.js +13 -13
  67. package/dist/runner/audit.d.ts +8 -3
  68. package/dist/runner/audit.js +21 -6
  69. package/dist/runner/claim-secrets.d.ts +2 -1
  70. package/dist/runner/claim-secrets.js +5 -3
  71. package/dist/runner/cli-run-spec.d.ts +1 -1
  72. package/dist/runner/cli-run-spec.js +12 -11
  73. package/dist/runner/conformance/harness.js +4 -2
  74. package/dist/runner/dispatch.js +4 -2
  75. package/dist/runner/harness-loops.js +5 -2
  76. package/dist/runner/journal-kinds.d.ts +3 -0
  77. package/dist/runner/learning-end.d.ts +2 -1
  78. package/dist/runner/learning-end.js +47 -22
  79. package/dist/runner/mcp-claim.js +1 -1
  80. package/dist/runner/mcp-run.d.ts +9 -0
  81. package/dist/runner/mcp-run.js +16 -1
  82. package/dist/runner/model-route.js +7 -4
  83. package/dist/runner/promotion.d.ts +40 -21
  84. package/dist/runner/promotion.js +130 -59
  85. package/dist/runner/run-child-host.js +6 -4
  86. package/dist/runner/runner.js +15 -3
  87. package/dist/runner/sdk-loop.d.ts +2 -2
  88. package/dist/runner/sdk-loop.js +3 -3
  89. package/dist/runner/store-port.d.ts +3 -0
  90. package/dist/runner/workflow-spec.js +3 -3
  91. package/dist/runs-over-store.d.ts +5 -2
  92. package/dist/runs-over-store.js +14 -7
  93. package/dist/sdk/check.d.ts +6 -5
  94. package/dist/sdk/check.js +17 -16
  95. package/dist/sdk/runs.js +81 -65
  96. package/dist/server.js +84 -20
  97. package/dist/store/agent-body.d.ts +4 -0
  98. package/dist/store/agent-body.js +4 -1
  99. package/dist/store/index.d.ts +1 -1
  100. package/dist/store/journal/storage.d.ts +2 -0
  101. package/dist/store/journal/storage.js +2 -1
  102. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  103. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  104. package/dist/store/schema.d.ts +14 -1
  105. package/dist/store/schema.js +42 -4
  106. package/dist/store/sqlite/run-launch.d.ts +22 -0
  107. package/dist/store/sqlite/run-launch.js +72 -7
  108. package/dist/store/sqlite/run-patch.d.ts +2 -1
  109. package/dist/store/sqlite/run-patch.js +4 -3
  110. package/dist/store/sqlite/store.js +141 -29
  111. package/dist/store/store-schema.js +2 -2
  112. package/dist/store/store.d.ts +67 -4
  113. package/dist/store-reads/learning.d.ts +12 -8
  114. package/dist/store-reads/learning.js +33 -24
  115. package/dist/store-reads/loop.d.ts +4 -3
  116. package/dist/store-reads/loop.js +7 -5
  117. package/dist/template-eval.js +4 -4
  118. package/dist/templates.d.ts +3 -0
  119. package/dist/templates.js +7 -5
  120. package/dist/timeline/labels.js +1 -1
  121. package/dist/tools.js +1 -1
  122. package/dist/uploads-archil.js +2 -1
  123. package/dist/uploads.d.ts +0 -3
  124. package/dist/uploads.js +2 -11
  125. package/dist/validate.js +5 -1
  126. package/dist/web-save.d.ts +3 -0
  127. package/dist/web-save.js +17 -2
  128. package/dist/workspace/archil-exec.js +1 -1
  129. package/dist/workspace/archil.js +1 -1
  130. package/dist/workspace/revision-skills.js +24 -11
  131. package/dist/workspace/synced-folder.d.ts +3 -3
  132. package/dist/workspace/synced-folder.js +7 -6
  133. package/package.json +10 -10
  134. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  135. package/dist/console/assets/index-sVftE9Ht.css +0 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,44 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.52 (2026-11-21)
6
+
7
+ **Breaking:**
8
+
9
+ - The apply answer (`POST /v2/templates/{template}/apply`) no longer carries `trigger_ids`: read each trigger's `trigger_id` from `triggers`, which lists the same triggers in the same order with their names, kinds and on or off. The TypeScript and Python clients' `ApplyTemplateResponse` drop the field. <!-- changes/apply-drops-trigger-ids.md -->
10
+
11
+ **Changes:**
12
+
13
+ - An agent can limit its own runs' requests on free models: `definition.max_requests`, a whole number, under the server's limit (`AGENTRUN_FREE_MODEL_REQUESTS`, 60 by default), so a run stops at the lower of the two. A dollar cap can't stop a free model, so before, the server's limit was the only bound, for every run on the server alike, and one run looping on a free model could spend a person's whole daily free quota under it. The run that reaches the agent's limit ends `failed` with `spend_cap_reached` in the server limit's words, naming the number it stopped at ("Not sent: this run reached its 20-request limit for free models."). It counts what the server's limit counts, and a paid request never counts. Above 0 sets it, 0 clears it, and an edit that leaves it out keeps it. A template sets it with `budget: { per_run_usd, max_requests }`: the manifest refuses 0 or a fraction, the template list shows it, and the console's template card says "Free-model requests: at most N a run". <!-- changes/agent-max-requests.md -->
14
+ - `GET /v2/computers` says per kind whether a run of it can record its screen on this server, and the console's Recording switch reads that alone. <!-- changes/computers-say-record.md -->
15
+ - Public API addition: each of `kinds[]` carries `record`, `{available: true}` or `{available: false, why}`. A desktop, a phone or a browser is available when this server has `ffmpeg` on its PATH (read at each call, as a save of `computer.record: true` checks it); without it, each says "ffmpeg isn't installed on this server (no ffmpeg command on PATH)". A sandbox and no computer are never available, in their own words. The TypeScript and Python clients' `ListComputersResponse` gain it.
16
+ - The agent editor's Computer step shows the Recording switch for every kind but no computer, from the kind's `record`: where a run can't record here, the switch is off and disabled with the server's words for why (a saved `record: true` can still be turned off). It used to show the switch only for a kind whose `settings` list `record`, and offered it on a server with no ffmpeg until the save was refused. A switch of kind or provider drops `record: true` where the new kind can't record, in the same words.
17
+ - The console filters Composio's actions, the agent editor's Tools step and an app trigger's events by name, slug or description; events list A to Z with their Markdown descriptions rendered; a new trigger marks Agent, Each run is asked and (with no agent default) the cost cap with *. Every list search in the console (agents and connected coding agents, an agent's runs, templates, a run's trace) now keeps a row holding each word typed, in any order. <!-- changes/console-list-filters.md -->
18
+ - A run counts fal's jobs: `run_model`, `submit_job` and `submit_jobs` on a fal MCP server (toolkit `fal`, or `mcp.fal.ai`) are priced before they are sent, at fal's `get_pricing` unit price times the units the job's input states (images, megapixels, characters, seconds, or the length of its input media), held under the run's spend cap and booked as tool cost. A job the cap can't take is refused unsent, as is one whose price can't be known beforehand; with no cap that one runs, booked as an unknown charge. The figure is an estimate at fal's list price. Agents saved before this are metered when their server is at `mcp.fal.ai`; save an agent again to pin a fal server at another address as metered. <!-- changes/fal-spend-metered.md -->
19
+ - `GET /v2/runs/{run_id}/usage` (`runusage/5`) now says which charges were the infrastructure's own redo. A turn is worked again when the claim working it is cut: its runner drained for a deploy (SIGTERM), its runner died, it lost its lease, or the turn was tried again. Each line, browser session and computer interval carries `attempt` (1 for a turn's first, 2 for its first redo, and so on) and `billable`. A turn's charges are split into one line per attempt. `billable` is false only for the model requests a cut attempt sent and never finished, which the attempt that takes the turn over sends again. Answered requests, paid calls, browser and computer time stay billable: the next attempt reuses them. The run also reports `infra_usd`, the sum of the lines that are not billable: 0 for a run with no such request, and null when one has no known cost, which a request cut in flight never does. This is data only: `total` and `cost.usd` still hold every line, and nothing is charged differently. A run from before this read keeps `attempt: null` and `billable: true` on every line. <!-- changes/run-attempts.md -->
20
+
21
+ Each claim writes its turn and attempt in its own transaction to the store's new `run_attempts` table. Postgres gets it from migration `0025_run_attempts.sql`, which is additive (a runner of the earlier version never reads it). A SQLite store gets it at the server's open, and a runner waits for that server. Each row holds `cause`, why the attempt before it was cut: `drain`, `crash`, `lease_lapse` or `retry`. A runner's release writes the cut attempt's own word for `drain` and `retry`. A runner that loses its lease writes `lease_lapse` while it can still reach the store. A lapse with no word reads as `crash`. A claim's `turn` and `attempt` are on `Claim`.
22
+
23
+ Each model request a claim sends to the server's model gateway carries the run, turn and attempt as LiteLLM's spend-logs metadata, in the header `x-litellm-spend-logs-metadata` (`{"agentrun_run_id":…,"agentrun_turn":…,"agentrun_attempt":…}`). That lets a gateway's spend logs be matched to the run's lines call by call. "The server's model gateway" means `AGENT_MODEL_BASE_URL`, or `ANTHROPIC_BASE_URL` on its origin. The header is sent on pi's routes and Claude Code's, never to a vendor's own endpoint. Codex's adapter takes no extra headers, so its requests carry none yet.
24
+ - `web_save` answers a saved audio or video file's length in seconds as `duration_s` (to the millisecond), read from the file's own bytes: mp3, wav, mp4 and m4a. An agent can then fit a cut to a voiceover, or price a job billed by its input's length, without another tool. Any other file, or media whose length its bytes don't give (ogg, webm, a file with no header), answers no `duration_s`. <!-- changes/web-save-duration.md -->
25
+ - A connected SDK agent's learned workflow is promoted only after compile_after checked turns, like a managed agent's, not after one. Each reserved native turn is one row of the check: the agent answers it, the caller's shadow runs the draft, and the server keeps the compared turn on the promotion record (`check.turns`) and waits for the next turn the draft takes. The turn that makes `learning.compile_after` decides once on every turn collected, on the same `agree_min` and `alone_min` bar; a disagreement no longer holds the draft on its own turn, and a turn the backend never completes within an hour is one failed row of the check instead of its decision. <!-- changes/sdk-check-evidence-bar.md -->
26
+ - A synced folder now sees a file rewritten to the same size in the push's own clock tick (a command that lands tens of milliseconds after the claim's push, on a filesystem whose timestamps come from the kernel's coarse clock). Before, such a file kept the size and mtime the baseline listing recorded, and the runner's copy kept the old bytes for good. The claim's push now gives every file `PUSHED_MTIME` (2000-01-01T00:00:00Z) in its tar header, so any later write moves its mtime, and nothing is read back after the push. <!-- changes/sync-sees-push-tick-rewrite.md -->
27
+ computerd's `tar.push` now gives each file its tar header's mtime, as tar and the macOS computerd already did, instead of the time of the extraction. `TarEntry` takes an optional `mtime` for the header, whole seconds from 0 to `MAX_TAR_MTIME` (ustar's 11 octal digits; any other value throws a `RangeError` before the entry is written); without one it is the time the entry is written, as before.
28
+ - In the console, a webhook trigger's once-shown signing secret after a template apply that skipped a trigger (a feed given no feeds, a GitHub or Composio trigger not set up here) is labelled with its own trigger's name, and its warning opens that trigger. Before, the console matched the package's trigger index against the answer's list, which a skipped trigger shifts: the secret carried the skipped trigger's name, and the warning's "Open … (Rotate)" link went to another trigger or to none. The console now finds each trigger by its name. <!-- changes/webhook-secret-name.md -->
29
+ - `DELETE /v2/agents/{agent_id}/learning` resets an agent's learning without deleting the agent: its learning folder whole (corrections, learned workflows, their history and the audit ledger), on this server and on every Archil disk its runs used (`503` while one can't be reached, nothing deleted), then its promotion records and grades. Deleting an agent now also deletes its learning folder on a disk a run's launch named. The agent, its runs and their files stay, and the run list, `GET /stats` and `GET /usage` read the same; the next run takes the agent path with nothing learned. Learning reads only the runs after the reset: they alone count toward `compile_after` and feed a compile, a check's replays and audits. A run whose start read the agent's learning before the reset learns nothing at its end, its learning `dropped` with the new reason `reset`. Learning-only runs in flight (replays, audit shadows) are cancelled first; while a run of the agent's own is still going it answers `409 learning_busy` naming the runs, and nothing is deleted. `204` when done, idempotent (an agent that never learned is `204` too), with the owner's session or the token as deleting an agent takes (any other console session is `403 forbidden`), in the API-only profile as well. The TypeScript and Python clients add `learning.reset(agent_id)`, and the CLI `agentrun learning reset <agent_id>`. <!-- changes/reset-agent-learning.md -->
30
+ - A run on a disk its launch names (`archil_disk`) learns nothing: it starts with no seed, no learned corrections and no learned workflow, and every learning read of the agent's runs (a compile's traces and its `compile_after` count, a check's replays, an audit's draw, the money rule, the cost page's ledger) skips it. Before, such a run read and fed the one learning of its agent, so a self-hoster's customers could see each other's traces in a learned workflow. A later change that lets named disks learn adds a per-disk key to the learning records. <!-- changes/learning-per-disk.md -->
31
+
32
+ Upgrading: runs gain a `disk` column, filled from each run's launch (Postgres migration `0026_run_disk.sql`; SQLite store version 15, which the server applies when it opens the store, and a runner waits for that). A run purged before the upgrade has no launch left, so it reads as the default disk's. A run on the agent's own disk, or on no disk, learns as before.
33
+ - An API-only server (`AGENTRUN_API_ONLY=1`) serves `DELETE /v2/runs/{id}` for a run of an agent an inline run made (`external`): a backend erasing one user's runs of a shared external agent purges each run, where deleting the agent would take every user's runs. The purge is the full server's: `204`, and `204` again once purged; `409 run_not_final` while it or a run made from it is live; every other route of it `410 purged`; its cost kept in every total. A run of an agent made here stays refused there with the profile's `404`, as before. <!-- changes/api-only-run-delete.md -->
34
+ - A run's fal jobs no longer collide with another run's: fal's hosted MCP server (`mcp.fal.ai`) keeps one `submission_key` journal per fal account and refuses a key it has seen with another request, so the same task run twice in a day, which makes the same keys, had its second run refused. The run's gateway now sends fal each `submission_key` of `run_model`, `submit_job`, each request of `submit_jobs` and `get_submission` with a suffix derived from the run, so a retry within one run still reaches fal with the same key and is deduped, and two runs never share one. Replies read back with the agent's own key. A key too long for fal's 128-character limit with the suffix is shortened with a hash of the whole key and marked apart from unshortened keys, so it never becomes another key. A server saved with the toolkit `fal` at another address (an eval's fake) receives the agent's keys unchanged. <!-- changes/fal-run-scoped-key.md -->
35
+ - A `DELETE` of a run or an agent retried after its purge committed and could not write the SQLite scrub marker (the 500 `internal` a full disk answers) now arranges the scrub again: it answers 204 as before, and it also runs the purge's WAL checkpoint again, writing `store.sqlite.scrub` when another connection still holds the log back, so the next start's scrub truncates it. Before, the retry answered 204 and wrote nothing, and the log could keep the purged bytes until some later checkpoint. A `DELETE` of a purged run or agent with the marker already there writes nothing new, and an agent's retried `DELETE` also drops the purge-in-progress mark its failed one left. <!-- changes/purge-retry-marker.md -->
36
+ - On Postgres, a run whose input or text holds an escaped NUL (`\u0000`) or a lone surrogate no longer breaks the store's reads of its launch body, its commands or its journal. The affected reads were an agent's learning starts, the runs made from a run, a run's purge, a reopen, a claim, a trigger's queued message and the start sweep of runs of unknown cost. Postgres keeps such text, but its json functions refuse the whole document over one escape, and a read that scans every launch failed for every run. Outside a transaction, each read retries on that refusal against a copy with those escapes blanked. Inside a transaction, where a refused statement can't be retried, the read uses the copy from the start. Learning starts come back as written: a run's `learning` member is never taken from a blanked copy. <!-- changes/launch-json-unicode.md -->
37
+ - `DELETE /v2/runs/{id}` on a run whose launch named a caller's Archil disk now also deletes the agent's learning folder on that disk, together with the run's own folder. Before, the folder stayed until the agent's learning reset or the agent's delete, and the run's merge diff and its correction line stayed in it after the purge. Nothing reads that folder: a run on a named disk gets no learning seed. <!-- changes/purge-learning-folder.md -->
38
+ - A connected agent's workflow check now holds only after five give-backs in a row, never counts a cancelled turn, and starts the count again when a turn lands. A check held that way is never stopped for good: the agent's next compile revises the workflow and checks the revision afresh. <!-- changes/sdk-check-give-backs-in-a-row.md -->
39
+ - A backend SDK run's compile ask now stops at the agent's own max_requests on a free model, as every other run of the agent does, when that is under the server's AGENTRUN_FREE_MODEL_REQUESTS. <!-- changes/sdk-compile-max-requests.md -->
40
+ - Two files uploaded in one millisecond now list newest first in `GET /v2/files`. Upload ids are minted by the same monotonic UUIDv7 as agent ids, so each sorts after the one before it; before, two ids in one millisecond carried random bits after the time and could list in either order. <!-- changes/uploads-monotonic-id.md -->
41
+ - A run's claim-time lay of its skills no longer depends on the class of a `NOT_FOUND` error to tell that a fresh folder has no `.agents/skills/` yet: it asks `stat`. On beta.50 a Mode 2 run in its own process lost `WorkspaceError`'s class over its channel and failed at its claim with `".agents/skills" is not there` whenever it had a skill (its own, or a desktop or phone computer's); beta.51 registered the class, and the lay now holds without it. A lay that fails says so (`laying the run's skills in .agents/skills/: …`), and an Archil listing or exec of a folder that is not there names the disk's key and the disk. <!-- changes/run-skills-lay-reads-no-error-class.md -->
42
+
5
43
  ## 0.1.0-beta.51 (2026-11-21)
6
44
 
7
45
  **Breaking:**
package/README.md CHANGED
@@ -888,7 +888,9 @@ one computer that it keeps between runs, instead of a fresh one for each run:
888
888
  **A video of each run.** `computer: {"kind": "desktop", "provider": "e2b", "record": true}` records the computer's
889
889
  screen during each of the agent's runs. Off by default; a desktop, a phone or a browser (a sandbox is 422). A browser's is
890
890
  each session's page, one file per session (its computer), from the live view's own screencast of it, which the viewer
891
- shares: frames come as the page changes.
891
+ shares: frames come as the page changes. `GET /v2/computers` says per kind whether its runs can record here, in
892
+ `record` (`{"available": false, "why": "..."}` for a sandbox, for no computer, and for every kind on a server with no
893
+ `ffmpeg` on its PATH), and the console's Recording switch reads it.
892
894
 
893
895
  - **It shows everything on the screen.** That includes what a person types while they have taken over the computer, and
894
896
  any password, key or private page shown on it. Pixels can't be redacted. Turn it on only for an agent whose screen
@@ -1468,7 +1470,7 @@ agent_not_runnable`, with `details.unbound` and `details.missing`).
1468
1470
  | `ask_person` | Ask the person who started the run; the turn ends until a message answers | nothing | no, no |
1469
1471
  | `web_fetch` | Read one web page from a public host through the guarded direct fetch, or through Parallel's extract where Parallel is picked ([search and fetch](#search-and-fetch)), a part at a time: `{url, offset?, max_chars?}` in, a Page out, `{ok, url, status, title, text, chars, truncated?, original_chars?, beyond_read?, offset?, next_offset?, html_chars?, converted?, links, links_omitted?, via, parallel?, refused?, error?}` | nothing (`PARALLEL_API_KEY` for Parallel, one billed extract a page a run) | yes, yes |
1470
1472
  | `web_search` | Search the web, natively where the harness or the model's provider can, else through Parallel where the server holds its key, else keyless through Exa, or through the provider picked ([search and fetch](#search-and-fetch)): `{query, n?}` in, `{provider, query, results: [{url, title, snippet, published?}], text?}` or `{error}` out | nothing (`PARALLEL_API_KEY` for Parallel) | yes, yes |
1471
- | `web_save` | Download one file from a public URL into the run's `work/` and keep it there, for a link that expires (a generated image, audio or video): `{url, path}` in, `path` relative to `work/` and a bare name under `media/`; `{ok: true, path, bytes, content_type, url}` or `{ok: false, url, refused \| error}` out. Never overwrites | nothing | no, no |
1473
+ | `web_save` | Download one file from a public URL into the run's `work/` and keep it there, for a link that expires (a generated image, audio or video): `{url, path}` in, `path` relative to `work/` and a bare name under `media/`; `{ok: true, path, bytes, content_type, duration_s?, url}` or `{ok: false, url, refused \| error}` out, `duration_s` an mp3, wav, mp4 or m4a's length in seconds read from its bytes. Never overwrites | nothing | no, no |
1472
1474
  | `browser` | A hosted browser, Browserbase's or Kernel's, on pi-browser's durable adapter: `snapshot`, `run`, `screenshot`, `browser_read`, `browser_release`, `browser_relaunch`, `browser_downloads` and `browser_upload` (into and from the run's `work/`); Kernel keeps no downloads, so a run on Kernel has no `browser_downloads` | `BROWSERBASE_API_KEY` and `BROWSERBASE_PROJECT_ID`, or `KERNEL_API_KEY` | yes, no |
1473
1475
  | `monid:<provider>/<endpoint>`, `monid:<provider>/*` | One monid endpoint, or every endpoint monid lists for a provider (at most 50), each pinned at the save and run as a tool of its own, paid per call from the monid wallet: `{body?, queryParams?, pathParams?}` in, the run's `output`, `price` and `cost` out ([monid](#monid)) | `MONID_API_KEY` | no, no |
1474
1476
  | `pdf_pages` | A workflow call only: `{path, maxPages?, dpi?}` in, `{name, pageCount, dpi, pages: [{page, image}], text}` out. Draws a document's first pages (3 by default, at 110 dpi) as PNGs under the run's `work/pages/<stem>/<dpi>/` (`<stem>`: the document's path below its directory made one name, with a short hash, so two documents of one file name never share pages), the dpi lowered so a page's long side is at most 1568 px, with its text (`pdftotext`, cut at 20,000 characters). A PNG or JPEG passes through as one page, scaled down to 1568 px. `path` is under `--documents` or the run's `work/`, never outside | `pdftoppm`, `pdftotext` | no, yes |
@@ -1516,8 +1518,9 @@ loop), at most 200 MiB in at most 10 minutes, into the run's Workspace (a bare n
1516
1518
  absolute path and a link are refused, and a path already in use is refused, never overwritten. The file is written once,
1517
1519
  after the whole download, so a failed one leaves nothing. An image, audio or video is saved only when its bytes, the
1518
1520
  declared type and the path's extension agree (`media/card.png`, never `media/card`); any other type only to a path whose
1519
- extension names the declared type. It makes no paid request and is never run again after a crash. Only an agent that
1520
- names `web_save` has it; no workflow node or call node may name it.
1521
+ extension names the declared type. A saved mp3, wav, mp4 or m4a answers its length in seconds, `duration_s`, read from
1522
+ its bytes (`media-duration.ts`); other files answer none. It makes no paid request and is never run again after a crash.
1523
+ Only an agent that names `web_save` has it; no workflow node or call node may name it.
1521
1524
 
1522
1525
  On another harness, every host tool's result reaches the model within the host's bound of 120,000 characters
1523
1526
  (`HOST_RESULT_MAX_CHARS`, `@parcha/agentrun-kernel`): the kernel's tool bridge cuts a longer one, its start with a line
@@ -2959,7 +2962,7 @@ failed, 2 when nothing ran. The runner, the graders and the report are in
2959
2962
  | `GET /agents/{id}/home/files`, and `GET`, `PUT`, `DELETE` on a file's path below it | The files in the agent's home, listed, read, written and deleted ([agent home](#agent-home)). This server's own routes (`x-agentrun-serve: "home/1"`). |
2960
2963
  | `GET /stats` | This server's own route, outside the contract (`x-agentrun-serve: "stats/1"`): the agents, the runs (`total`, `active`, `needs_input`, `failed`, `needs_review`, `status_unknown`), each agent's run count, the cost and what is archived, read from the agent store's aggregates and verified source reports; source completion counters are read when needed to separate overlapping usage. Archived agents and runs are left out of every number but `archived`. A completed or cancelled run counts only in `runs.total`, but for an escalated one (completed, waiting for a person's review), which `needs_review` (`stats/3`) counts; `failed` never does. Each running run is in exactly one of `active` (queued or working) and `needs_input` (`input_required`), both from the runs this server holds, and `status_unknown`: a running run it does not hold, or holds as ended before its end is written. `cost.usd` sums the runs that ended with a cost and is null when none did, never $0, with `basis` (`reported`, `estimate` or `unpriced`: [A run's cost](#a-runs-cost-its-tokens-and-its-basis)), or null beside a null `usd`; `unknown_runs` counts the rest. `analytics` (`stats/2`) sums the runs' metrics over the runs not archived that the `from` and `to` query parameters (RFC 3339 date-times to the millisecond, an impossible one or a finer fraction refused; runs started in [`from`, `to`)) and `agent` pick, each optional, 400 when malformed: `filter` echoes them; `totals` (runs, completed, an escalated run included, `needs_review` (`stats/3`), failed, never an escalated run, `runs_with_metrics`, `runs_with_token_metrics`, tokens and each token kind, requests, unmetered, `cost_usd` and `unknown_cost_runs`), `time` (`wall_ms` over the ended runs, `active_ms` where metrics have it), `by_harness_effort`, `by_day` (UTC), `by_source` (`live` or the import source) and the top 20 `tools`. Token totals sum only runs with every token counter reported, counted by `runs_with_token_metrics`; other runs remain in `runs` but cannot hide the known partial total. If runs exist but none reports a complete count, `tokens` is null; an empty scope is zero. Individual token-kind totals remain null when a measured run reports that counter as unknown. `analytics.usage` combines recorded runs and connected source reports ([Unified token usage](#unified-token-usage)). `learning` (`learning/1`) counts the runs that tried to learn over the same filters, from the store ([Learning](#learning)). The query bounds `analytics` and `learning` alone. |
2961
2964
  | `GET /runs/{id}/graph` | A workflow run drawn, live: its workflow, the DSL's `workflowGraph`, each node's state (a map's items with their labels and the branch each route took for them, a route's branch), every decision with its receipt (answers, evidence, the state the judge saw, image links), every call with its input and output, and the totals (cost, null when any part is unknown). While the run goes it reads the run process's `live.json`, rewritten every 300 ms, never the run's store, which the process holds; once it ended, its store is read lock-free, so a poll never waits on it and never answers `home_busy`. An agentic run has none (`404`). |
2962
- | `GET /runs/{id}/usage` | This server's own (`runusage/1`): what one run cost, line by line: its model requests by model and provider, its paid tool calls by who charged for them, its browser time by provider, its computers' time by provider and resource (`runusage/4`), joining to its `cost.usd` ([A run's cost, line by line](#a-runs-cost-line-by-line)); beside them its browser sessions (`runusage/2`) and the computers it made, each from its create to its proven delete (`runusage/3`). Lines once the run ended; `reason` says why there are none. |
2965
+ | `GET /runs/{id}/usage` | This server's own (`runusage/1`): what one run cost, line by line: its model requests by model and provider, its paid tool calls by who charged for them, its browser time by provider, its computers' time by provider and resource (`runusage/4`), each line by the attempt it was made in and whether that attempt is billable, with `infra_usd` beside them (`runusage/5`), joining to its `cost.usd` ([A run's cost, line by line](#a-runs-cost-line-by-line)); beside them its browser sessions (`runusage/2`) and the computers it made, each from its create to its proven delete (`runusage/3`). Lines once the run ended; `reason` says why there are none. |
2963
2966
  | `GET /runs/{id}/trace` | A run's trace, for a person who debugs it: each model request that answered and each tool call as one span, in the order they started. A span has its `kind` (`model` or `tool`), its `name` (the model, or the tool), when it started and ended, how it ended (`status`), and the span it ran under (`parent_id`: the request that made a call, the call a subagent's request was started by). A model request also has its `tokens` (`input` not read from cache, `cache_read`, `cache_write`, `output`, and `reasoning` where reported), and its `usd`. A tool call also has the head of its arguments and of its output, as its Timeline rows show them, and what was charged under it (`usd`, `charged`, `not_metered`). A call that asked for approval ends as its approval did: `waiting` until it is answered, `refused` on a deny, `interrupted` when it was withdrawn with its run. Nothing is measured again or estimated: `model_requests` says what the run's record keeps. `priced`: each request is a span with its cost. `tokens_only`: a workflow run. Its model nodes' requests carry tokens and no cost, since the run's cost is its booking's; each of its decisions (a judge's, a route's, a verify's request) is a span too (`decision: true`), named by the model its provider answered with and labelled by its node, with its own cost. `not_recorded`: a CLI harness's record keeps no request, so its trace is its tool calls. A computer's own time is its provider's to bill and is in no span. Readable while the run goes; one read serves the run's first 2,000 spans and counts the rest in `dropped`. Its words are cut as the Timeline's are, and a run whose handed sign-in can't be read back is refused (`403`), as its graph is. The console's Dev tools tab reads it. |
2964
2967
  | `POST /runs/{id}/pause`, `POST /runs/{id}/resume` | A workflow run: what is in flight finishes, and no node, model call or decision starts until it is resumed. Its status reads `paused`, and stays so across a server restart. An agentic run is `501`, an ended one `409`. |
2965
2968
  | `POST /workflows/validate` | `{workflow, tools?}`: every issue a save would refuse (`[{path, code, message}]`, the DSL's validation with code not run) and what this host lacks as `warnings`. Writes nothing. A refused save's `422` carries each issue as a field under `definition.workflow`, with its `code`. |
@@ -3085,6 +3088,9 @@ serves these routes alone:
3085
3088
  - an agent's Archil disk (`GET` and `DELETE /agents/{id}/archil`);
3086
3089
  - the [delete of an agent another system owns](#deleting-an-agent-another-system-owns) (`DELETE /agents/{id}`), for
3087
3090
  the backend whose inline runs made it;
3091
+ - the [purge of a run](#purging-a-run-or-an-agent-made-here) (`DELETE /runs/{id}`) of such an agent, for that
3092
+ backend: it erases one user's runs where deleting the agent, which every user's runs share, would take them all. A
3093
+ run of an agent made here is refused, as every address not listed here is;
3088
3094
  - the computer settings' two reads, for a backend to check before it launches: `GET /computers` (each provider, its
3089
3095
  key names and whether each is saved, and whether it is ready) and `GET /workspace/archil` (whether runs' folders are
3090
3096
  on Archil, and whether its account key is saved). Neither answers a key's value. Their writes, tests and key choices
@@ -3092,7 +3098,8 @@ serves these routes alone:
3092
3098
  - what an agent learned, for the backend whose runs it learned from: the loop's compile turns
3093
3099
  (`GET /agents/{id}/learning/loop`), each learned workflow's promotion and what serves
3094
3100
  (`GET /agents/{id}/learning/promotions`), the cost per run (`GET /agents/{id}/learning/cost`) and a run's learning
3095
- (`GET /runs/{id}/learning`), each cut of the host's secrets as the console's reads are;
3101
+ (`GET /runs/{id}/learning`), each cut of the host's secrets as the console's reads are; and its reset
3102
+ (`DELETE /agents/{id}/learning`, the agent and its runs kept), its one learning write served here;
3096
3103
  - a run's hosted machine fetching this server's computerd build (`GET /computers/daemon`), with the token its create
3097
3104
  minted;
3098
3105
  - `GET /capabilities`, `GET /health`, `GET /usage` and `GET /capacity`;
@@ -3490,7 +3497,8 @@ stays in every total.
3490
3497
  patches) and any feedback line it added to `corrections.md`, in the folder's history too. The run's purge removes
3491
3498
  neither; the agent's purge (below) removes the whole folder.
3492
3499
  - It takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token;
3493
- any other console session is `403 forbidden`, no credential `401`.
3500
+ any other console session is `403 forbidden`, no credential `401`. An [API-only](#api-only) server purges a run of
3501
+ an agent another system owns alone; a run of an agent made here is its profile's `404` there.
3494
3502
 
3495
3503
  An agent made here is purged the same way once archived: `DELETE /v2/agents/{id}`. Its revisions' content, name and
3496
3504
  description, learning, triggers, saved sign-ins, own computer, disk and folders go, and each of its runs is purged.
@@ -3907,8 +3915,10 @@ check closed.
3907
3915
  The bridge posts one `workflow_check` event with the reservation's `id` and `digest`, its execution `outcome`
3908
3916
  (`answered`, `handed_back`, `failed` or `skipped_write`), and its answer or reason. It does not choose whether the
3909
3917
  workflow passes. The server compares the answer with the immutable native completion and applies the same
3910
- `agree_min` and `alone_min` promotion policy. This initial SDK check uses **one independent native turn** (`n: 1`),
3911
- not the server-run agent's historical replay set. Agreement is whole-answer equality (JSON values or trimmed text), or equality of the owner's
3918
+ `agree_min` and `alone_min` promotion policy on the same evidence bar: the check decides once, on `compile_after`
3919
+ **independent native turns**, as a server check decides once on that many of the agent's inputs. Each turn is one row,
3920
+ kept on the promotion record (`check.turns`) while the check waits for the next turn the draft takes; the turn that
3921
+ makes `compile_after` decides on all of them. Agreement is whole-answer equality (JSON values or trimmed text), or equality of the owner's
3912
3922
  configured `agree_on` fields; there is no semantic model grader on this path. A paraphrase can therefore be held even
3913
3923
  when a person would consider it equivalent.
3914
3924
 
@@ -3992,6 +4002,15 @@ with the token, an archived agent's too:
3992
4002
  - `GET .../learning/workflows/{name}/revisions` lists a learned workflow's revisions on `main`;
3993
4003
  `GET .../learning/promotions` its promotion records; `GET .../learning/loop` each compile turn; and
3994
4004
  `GET .../learning/cost` the agent's cost per run, run after run.
4005
+ - `DELETE /agents/{agent_id}/learning` resets the agent's learning: its learning folder whole (`corrections.md`, its
4006
+ workflows, their history and the audit ledger), here and on every Archil disk its runs used (`503` while one can't be
4007
+ reached), then its promotion records and grades. The agent and its runs stay,
4008
+ with their files, costs and each run's own learning, so the run list, `GET /stats` and `GET /usage` read the same (a
4009
+ served run keeps its share of its revision's compile and check); a run's learning diff goes with the folder (404);
4010
+ the next run takes the agent path, given nothing learned. It cancels the runs that exist only for learning (replays,
4011
+ audit shadows) and waits for them; while a run of the agent's own is still going it is `409 learning_busy` (each named
4012
+ in `details.runs`), and nothing is deleted. `204`, a second call and an agent that never learned included. The
4013
+ API-only profile serves it too.
3995
4014
  - `GET /runs/{run_id}/learning`: the run's learning whole (its seed, its merge, the corrections it added, the workflow it
3996
4015
  wrote, its compile turn's attempts and the checks' problems), `null` for a run that does not learn.
3997
4016
  `GET /runs/{run_id}/learning/diff`: a merged run's merge commit against its parent, each file's patch as git writes it
@@ -4150,6 +4169,60 @@ were reached. Nothing is priced here, and nothing is rounded to a billing increm
4150
4169
  `browser_sessions`. A run's computers made before this server kept them have none either. The records are kept in the
4151
4170
  store's `computer_intervals` table (keyed by provider and the provider's id), and a purge of the run keeps them.
4152
4171
 
4172
+ ### Attempts: what the infrastructure redid
4173
+
4174
+ A run's turn can be worked more than once. A runner that drains for a deploy hands its runs back mid-turn, a runner that
4175
+ dies leaves its claims to lapse, a runner that can't renew loses its claim, and a turn whose loop ended on its own is
4176
+ tried again. In each case another claim works the same turn again. It resumes from what the cut claim saved: requests
4177
+ already answered and calls already finished are reused, not sent again. What it does send again is each model request
4178
+ the cut claim sent and never finished, cut in flight or cut off by a crash. Those requests are the infrastructure's
4179
+ cost, not the task's.
4180
+
4181
+ The read says which is which (`runusage/5`). It does not change what anything costs: `total` and `cost.usd` still hold
4182
+ every line.
4183
+
4184
+ - Each line, browser session and computer interval has `attempt`: the attempt at its turn it was made in (1 for the
4185
+ turn's first, 2 for its first redo, and so on). A turn's charges are split into one line per attempt.
4186
+ - Each also has `billable`. It is false only for the model requests an attempt never finished when a later attempt
4187
+ worked its turn again. Everything else is billable: answered requests, paid calls, browser and computer time.
4188
+ - `infra_usd` is the sum of the lines that are not billable. It is 0 for a run with no such request. A request cut in
4189
+ flight never got an answer, so its cost is unknown, and `infra_usd` reads null for a run that has one, as `total`
4190
+ does. It is also null with no lines.
4191
+ - A run from before this server kept attempts reads `attempt: null` and `billable: true` on every line.
4192
+
4193
+ The attempts live in the store's `run_attempts` table: one row per claim, written in the claim's own transaction. Each
4194
+ row holds the claim's turn and attempt, and `cause`, which says why the attempt before it was cut:
4195
+
4196
+ | `cause` | What cut the attempt before |
4197
+ | --- | --- |
4198
+ | `drain` | Its runner closed (SIGTERM) and handed the run back. |
4199
+ | `crash` | Its lease ran out and nobody said why (its runner died). |
4200
+ | `lease_lapse` | Its runner was still there but could not renew the claim in time. |
4201
+ | `retry` | Its loop ended interrupted on its own, and the run was released to be tried again. A stopped run whose end was refused is no cut: the claim that retries the end runs no turn, so it starts a new one and redoes nothing. |
4202
+
4203
+ A turn is the work one claim starts afresh: the run's first, a follow-up's, or a resume after a park. A claim is a redo
4204
+ only of the claim it takes over, and only when that claim wrote its row. A runner of an earlier build, running beside
4205
+ this server through an upgrade, writes none. When the claim after it takes over, it starts a new turn, so no earlier
4206
+ recorded turn is read as redone.
4207
+
4208
+ Each part of the usage is matched to its claim this way:
4209
+
4210
+ - **Journal entries:** a claim's entries start at the run's next entry id at the moment it claimed. Anything written
4211
+ before the run's first recorded claim belongs to no attempt and stays billable, unless that claim was the run's first.
4212
+ - **Browser charges:** a charge whose booking a later claim recovered is the attempt's that wrote the charge, matched
4213
+ by its ref.
4214
+ - **Computer time:** a computer's time is split across the claims that held it, by each claim's window on the store's
4215
+ clock. A computer kept across a park is billed by the claim that resumed it. Its `unheld_quantity` is spread over those
4216
+ windows by their share of its life.
4217
+ - **Computer intervals:** each record's own `attempt` is the claim that made the computer.
4218
+
4219
+ Each model request a claim sends to this server's model gateway carries the run, turn and attempt as LiteLLM's
4220
+ spend-logs metadata, in the header `x-litellm-spend-logs-metadata` (LiteLLM v1.110.0 and later). For example:
4221
+ `{"agentrun_run_id":"run_…","agentrun_turn":1,"agentrun_attempt":2}`. A gateway's spend logs can then be matched to the
4222
+ run's lines call by call. "This server's model gateway" means `AGENT_MODEL_BASE_URL`, or `ANTHROPIC_BASE_URL` on its
4223
+ origin. The header is sent on pi's routes and Claude Code's; Codex's adapter takes no extra headers yet. It is never
4224
+ sent to a vendor's own endpoint.
4225
+
4153
4226
  ### Computer time
4154
4227
 
4155
4228
  A computer's time is priced the way providers bill it: by what the computer holds (its vCPUs, its memory, its GPUs, its
@@ -4202,10 +4275,18 @@ what each request still in flight is held at, plus the most this request can cos
4202
4275
  request is not sent and the run pauses ([below](#a-run-paused-at-its-cap)). The cap is a hard stop for everything but
4203
4276
  the charge of a monid call priced by usage, which can pass the estimate it was held at: when it does, the run stops at
4204
4277
  once ([monid](#monid)). An MCP tool counts only at the price saved for it (its server's `prices`); one with none is
4205
- not metered and bills its own account outside the cap. fal's generations are such calls: they bill your fal account at
4206
- fal's price for the model and the output, the fal presets save no price, and the cap does not count them. A template
4207
- that uses fal caps its fal spend itself, with an input such as `max_fal_usd` that it prices its plan against before the
4208
- first paid call. A request costs its input, plus the output it
4278
+ not metered and bills its own account outside the cap. fal is counted: a job sent to a fal server (one saved with the
4279
+ toolkit `fal`, or at `mcp.fal.ai`) through `run_model`, `submit_job` or `submit_jobs` is priced before it is sent, at
4280
+ fal's unit price for its endpoint (the server's own `get_pricing`, read with the run's credential and kept five
4281
+ minutes) times the units the job's input states: its images, their megapixels, its text's characters, the seconds it
4282
+ names, or the length of the audio or video it is given, read from the file first. That price is held under the cap, a
4283
+ job the cap can't take is refused before it is submitted, and the job is booked as the run's tool cost, charged by the
4284
+ server, with the price and the count it came from. It is an estimate at fal's list price, not fal's invoice: fal
4285
+ reports no cost for a job, and a minimum charge, a discount or a rate that depends on a setting `get_pricing` does not
4286
+ list are not in it. A job whose units can't be known before it runs (one billed by compute time or tokens, one that
4287
+ names no size or length, media whose length can't be read, an endpoint with no listed price) is refused under a cap,
4288
+ in words that say why; with no cap it runs, booked as an unknown charge. A price saved for a fal tool takes the place
4289
+ of this. A request costs its input, plus the output it
4209
4290
  is sent with at the output price, plus any fee its tokens do not show (below). Its input is priced at its worst case:
4210
4291
  every input token at the higher of the input and cache-write prices, since the provider may bill any of it as a cache
4211
4292
  write and a cache can miss at any request. So no request passes the cap, a cache miss included: a request costs at most
package/dist/adapters.js CHANGED
@@ -284,7 +284,7 @@ export async function claudeOf(env, needs, load = loadClaude, sdkOf = (version,
284
284
  // The CLI runs Anthropic's own id, which it knows the limits and betas of, and sends it as it is, OpenRouter too
285
285
  // (providerFor's modelId); the key goes as the endpoint takes it, and the run is priced by the catalog entry of
286
286
  // whoever bills it (its priceModel).
287
- const endpoint = provider ? { origin: provider.origin, credential: provider.credential, auth: provider.auth } : { origin: "", credential: () => "" };
287
+ const endpoint = provider ? { origin: provider.origin, credential: provider.credential, auth: provider.auth, ...(provider.headers ? { headers: provider.headers } : {}) } : { origin: "", credential: () => "" };
288
288
  const priced = provider ? { ...needs, model: provider.priceModel } : native;
289
289
  // Its CLI checked off the event loop first (hashed and run as a child), so the server goes on answering: a pass is
290
290
  // kept, and the adapter's own check answers from it. A CLI that fails its pins is the adapter's to report, in its
@@ -1,7 +1,14 @@
1
1
  import { type PurgeKept, type Store } from "./store/index.js";
2
2
  /** The delete of an agent's learning: the server's is the learning module's deleteLearning over the agent's learning
3
- * folder (learn/delete.ts). Idempotent; refuses with LearningInFlight while learning work of the agent is in flight. */
4
- export type DeleteLearning = (store: Store, agentId: string) => Promise<unknown>;
3
+ * folder, and its folder on each Archil disk a launch of its runs named, a purged run's included (learn/delete.ts;
4
+ * server.ts learningDisksOf), and its records. Idempotent; refuses with LearningInFlight while learning work of the
5
+ * agent is in flight. A reset of the agent's learning (learning-reset.ts), whose agent and runs stay, keeps its reset
6
+ * ledger and watermark (`keepResetLedger`) and deletes the folder on the agent's own disk too (`agentDisk`), which the
7
+ * agent's delete removes whole in its step 3. */
8
+ export type DeleteLearning = (store: Store, agentId: string, options?: {
9
+ keepResetLedger?: boolean;
10
+ agentDisk?: boolean;
11
+ }) => Promise<unknown>;
5
12
  /** A point of a delete a test may stop it at (AgentDeleteHost.at). An agent's: after step 1, after step 2, in step 3
6
13
  * between a trigger's removal upstream and its settings', between its settings' and its row's, and in step 3 once its
7
14
  * triggers and the agent's first run are gone (a purge's: after its learning, then the same). A run's: once the runs
@@ -65,6 +72,10 @@ export declare function deleteExternalAgent(host: AgentDeleteHost, agentId: stri
65
72
  export declare function purgeAgent(host: AgentDeleteHost, agentId: string): Promise<void>;
66
73
  /** The setting that marks agent `agentId`'s purge begun and not finished (purgeAgent). */
67
74
  export declare const purgingKey: (agentId: string) => string;
75
+ /** A DELETE of a run, or of agent `agentId`, already purged: 204 with no purge, but what a purge that committed and then
76
+ * threw left undone (its scrub's marker not written, sqlite/store.ts #purged): the scrub arranged again (store
77
+ * purgeScrub), and the agent's purge mark dropped (purgeAgent removes it only after its store purge returns). */
78
+ export declare function purgedAgain(host: AgentDeleteHost, agentId?: string): Promise<void>;
68
79
  /** Purges run `runId` with every run made from it, as the header says. 404 not_found when it is not there; 409
69
80
  * run_not_final, nothing purged, while it or a run made from it is live. A purged run is no work. */
70
81
  export declare function purgeRun(host: AgentDeleteHost, runId: string): Promise<void>;
@@ -32,9 +32,10 @@
32
32
  // a follow-up that would open one of its runs again are refused (store AgentDeleting / AgentArchived, each read in
33
33
  // the transaction that would start the run). Then each of its runs not yet final, its learning runs included, is
34
34
  // cancelled through the cancel path, and waited for until it is final.
35
- // 2. Its learning, by the learning module's deleteLearning (learn/delete.ts: its learning folder's files, then its
36
- // promotions and grades; idempotent; it refuses with LearningInFlight while learning work
37
- // is in flight, which answers 409 learning_busy with the agent left refusing runs).
35
+ // 2. Its learning, by the learning module's deleteLearning (learn/delete.ts: its learning folder's files, here and on
36
+ // each Archil disk a launch of its runs named, a purged run's included, then its promotions and grades; its own
37
+ // disk goes whole in step 3; idempotent; it refuses with LearningInFlight while learning work is in flight, which
38
+ // answers 409 learning_busy with the agent left refusing runs).
38
39
  // 3. Its things: its triggers through the trigger engine (each one's registration upstream first, then its adapter
39
40
  // settings, then its row), its saved sign-ins (each vendor object too), its own computer, its Archil disk; then each
40
41
  // run's folders (on a disk its launch named, the caller's, too: the run's own folder there, never the disk), settings
@@ -127,6 +128,14 @@ export async function purgeAgent(host, agentId) {
127
128
  }
128
129
  /** The setting that marks agent `agentId`'s purge begun and not finished (purgeAgent). */
129
130
  export const purgingKey = (agentId) => `agent.purging.${agentId}`;
131
+ /** A DELETE of a run, or of agent `agentId`, already purged: 204 with no purge, but what a purge that committed and then
132
+ * threw left undone (its scrub's marker not written, sqlite/store.ts #purged): the scrub arranged again (store
133
+ * purgeScrub), and the agent's purge mark dropped (purgeAgent removes it only after its store purge returns). */
134
+ export async function purgedAgain(host, agentId) {
135
+ await host.store.purgeScrub();
136
+ if (agentId !== undefined)
137
+ await host.store.settings.remove(purgingKey(agentId));
138
+ }
130
139
  /** Purges run `runId` with every run made from it, as the header says. 404 not_found when it is not there; 409
131
140
  * run_not_final, nothing purged, while it or a run made from it is live. A purged run is no work. */
132
141
  export async function purgeRun(host, runId) {
@@ -134,7 +143,7 @@ export async function purgeRun(host, runId) {
134
143
  if (!run)
135
144
  throw new ApiError("not_found", `no run ${runId}`);
136
145
  if (run.purgedAt !== null)
137
- return;
146
+ return purgedAgain(host);
138
147
  const made = await madeFromAll(host, runId);
139
148
  const live = await liveOf(host, [run, ...made]);
140
149
  if (live.length)
@@ -168,7 +177,7 @@ async function purgeOneOrRefuse(host, agentId, runId, purged, alone) {
168
177
  // Its answer and input as this process last served them, dropped whatever the purge answered: every route of it is 410
169
178
  // once it committed, so none is read again. A purge can commit and still throw (its checkpoint held back and the
170
179
  // scrub's marker not written, sqlite/store.ts #purged), and no later DELETE comes back here (purgeRun: a purged run is
171
- // no work). One that did not commit loses a cache its next read fills again.
180
+ // only purgedAgain). One that did not commit loses a cache its next read fills again.
172
181
  forgetServed(host.store, runId);
173
182
  }
174
183
  }
@@ -1,6 +1,7 @@
1
1
  import { type AgentRow, type NewRevision, type RevisionPlace, type RevisionRow, type Store, type TemplatePackage } from "./store/index.js";
2
2
  import { type DefinitionBody, type Json } from "./validate.js";
3
- /** A UUIDv7: time-ordered, so a listing by (created_at, id) is stable, and unique per revision and per minted agent. Two
3
+ /** A UUIDv7: time-ordered, so a listing by (created_at, id) is stable, and unique per revision, per minted agent and per
4
+ * upload (uploads.ts lists files by id, newest first). Two
4
5
  * minted in one millisecond keep their order: the 12 bits after the time count them up (RFC 9562's monotonic counter),
5
6
  * and a clock that steps back keeps the last millisecond, so each id sorts after the one before it. Without that, two
6
7
  * edits in one millisecond tie on created_at and their random ids could number the newer revision first. */
@@ -20,6 +21,9 @@ export type AgentEntry = {
20
21
  * apply with agent_id updates it); absent or null for one made otherwise. */
21
22
  template?: TemplatePackage | null;
22
23
  };
24
+ /** Whether another system owns `agent`: an inline run with `external` made it (its `externalRef` set), so the system that
25
+ * sent it sends its deletes, the agent's whole (DELETE /agents/{id}) and, on an API-only server, a run's purge. */
26
+ export declare const ownedElsewhere: (agent: AgentRow) => boolean;
23
27
  /** Refuses a write to an externally owned agent: one that mirrors an agent in another system (its `externalRef` set) is
24
28
  * read-only here — its source is the truth, which writes a new version by running it. Edits, set-current and archive are
25
29
  * refused (403 forbidden); reads work as for any agent. */
@@ -21,7 +21,8 @@ import { skillIssues, skillNames } from "./validate.js";
21
21
  /** The last millisecond a UUIDv7 was minted in, and how many were minted in it. */
22
22
  let mintedMs = -1;
23
23
  let mintedInMs = 0;
24
- /** A UUIDv7: time-ordered, so a listing by (created_at, id) is stable, and unique per revision and per minted agent. Two
24
+ /** A UUIDv7: time-ordered, so a listing by (created_at, id) is stable, and unique per revision, per minted agent and per
25
+ * upload (uploads.ts lists files by id, newest first). Two
25
26
  * minted in one millisecond keep their order: the 12 bits after the time count them up (RFC 9562's monotonic counter),
26
27
  * and a clock that steps back keeps the last millisecond, so each id sorts after the one before it. Without that, two
27
28
  * edits in one millisecond tie on created_at and their random ids could number the newer revision first. */
@@ -51,11 +52,14 @@ function storeError(error) {
51
52
  throw invalid([{ field: "definition", reason: "invalid", message: error.message }]);
52
53
  throw error;
53
54
  }
55
+ /** Whether another system owns `agent`: an inline run with `external` made it (its `externalRef` set), so the system that
56
+ * sent it sends its deletes, the agent's whole (DELETE /agents/{id}) and, on an API-only server, a run's purge. */
57
+ export const ownedElsewhere = (agent) => agent.externalRef !== null;
54
58
  /** Refuses a write to an externally owned agent: one that mirrors an agent in another system (its `externalRef` set) is
55
59
  * read-only here — its source is the truth, which writes a new version by running it. Edits, set-current and archive are
56
60
  * refused (403 forbidden); reads work as for any agent. */
57
61
  export function refuseExternal(agent) {
58
- if (agent.externalRef !== null)
62
+ if (ownedElsewhere(agent))
59
63
  throw new ApiError("forbidden", `The agent ${agent.id} is managed by its source and is read-only here; change it there and run it again.`);
60
64
  }
61
65
  /** The store's one key of an external reference, "<source>:<kind>:<id>": source and kind hold no colon (POST /runs checks
@@ -100,7 +104,7 @@ function revisionInputOf(definition, files) {
100
104
  // pin's arguments sorted) so two revisions that say the same are one body. The store never reimplements it.
101
105
  const set = toolSettingsOf(definition.tool_settings);
102
106
  const common = { skills: files, tools: definition.tools ?? [], ...harness, ...place, ...set };
103
- const capped = typeof definition.max_cost_usd === "number" && definition.max_cost_usd > 0 ? { maxCostUsd: definition.max_cost_usd } : {};
107
+ const capped = { ...(typeof definition.max_cost_usd === "number" && definition.max_cost_usd > 0 ? { maxCostUsd: definition.max_cost_usd } : {}), ...(typeof definition.max_requests === "number" && definition.max_requests > 0 ? { maxRequests: definition.max_requests } : {}) };
104
108
  // A workflow keeps its approvals too ("never": it runs unattended), so its call nodes are checked with them (runnable.ts,
105
109
  // permissionOf with the revision's approvals): a call node on a tool set to ask runs under never, as on main.
106
110
  if (isObject(definition.workflow))
@@ -342,6 +346,8 @@ function editOn(entry, definition, skills, note, fromPackage = false) {
342
346
  // No approvals here: an edit that leaves them out asks (openapi.ts DefinitionInput.approvals),
343
347
  // so no edit makes an agent unattended by saying nothing. The console's edit sends back the approvals it read.
344
348
  ...(definition.max_cost_usd === undefined && currentBody.maxCostUsd !== undefined ? { max_cost_usd: currentBody.maxCostUsd } : {}),
349
+ // So does its limit on each run's free-model requests (0 clears it): leaving a field out never removes a limit.
350
+ ...(definition.max_requests === undefined && currentBody.maxRequests !== undefined ? { max_requests: currentBody.maxRequests } : {}),
345
351
  // Its input's and its structured answer's schemas are the agent's contract with its callers: an edit that leaves
346
352
  // one out keeps it.
347
353
  ...(definition.input_schema === undefined && current.kind === "agentic" && !isObject(definition.workflow) && currentBody.inputSchema !== undefined ? { input_schema: currentBody.inputSchema } : {}),
@@ -386,7 +392,7 @@ export const etagOf = (entry) => `"${entry.revision?.id ?? "none"}"`;
386
392
  /** A revision as a definition, as POST /agents takes one, numbered. */
387
393
  export function definitionOf(agent, revision, version) {
388
394
  const body = revision.body;
389
- const common = body.maxCostUsd !== undefined ? { max_cost_usd: body.maxCostUsd } : {};
395
+ const common = { ...(body.maxCostUsd !== undefined ? { max_cost_usd: body.maxCostUsd } : {}), ...(body.maxRequests !== undefined ? { max_requests: body.maxRequests } : {}) };
390
396
  const kindBody = revision.kind === "agentic"
391
397
  ? { instructions: body.instructions, ...(body.model ? { model: body.model } : {}), ...(body.modelTiers ? { model_tiers: body.modelTiers } : {}), ...(body.thinking ? { thinking: body.thinking } : {}), ...(learningSettingForBody(body) !== undefined ? { learning: learningSettingForBody(body) } : {}), ...(body.inputSchema !== undefined ? { input_schema: body.inputSchema } : {}), ...(body.outputSchema !== undefined ? { output_schema: body.outputSchema } : {}), ...(body.checkout !== undefined ? { checkout: body.checkout } : {}), ...common }
392
398
  : { workflow: body.workflow, ...common };
@@ -4,9 +4,11 @@ export declare const API_ONLY_ENV = "AGENTRUN_API_ONLY";
4
4
  /** The routes (server.ts ROUTES, by name) an API-only server serves. Past a run's own, why each group is here:
5
5
  * - a run's hosted machine fetches computerd with the token its create minted, not the server's;
6
6
  * - the computers list and the Archil settings are read before a launch, naming keys, never a value;
7
- * - an agent its inline runs made has its disk and its delete sent by the backend that made it;
7
+ * - an agent its inline runs made has its disk, its delete and its runs' purges sent by the backend that made it (a run
8
+ * of an agent made here is refused by the purge's route itself, server.ts deleteRun, in this profile's words);
8
9
  * - a run's computer, take-over, hand-back and viewer link go to the backend, which has no owner's session here;
9
- * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's;
10
+ * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's,
11
+ * and resets it (deleteAgentLearning: the agent and its runs kept) when it erases what an agent learned;
10
12
  * - a run's usage lines (what its cost.usd joins, by meter) are a read of that run alone, cut as the run's read is;
11
13
  * - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart. */
12
14
  export declare const API_ONLY_ROUTES: ReadonlySet<string>;
package/dist/api-only.js CHANGED
@@ -3,16 +3,18 @@ export const API_ONLY_ENV = "AGENTRUN_API_ONLY";
3
3
  /** The routes (server.ts ROUTES, by name) an API-only server serves. Past a run's own, why each group is here:
4
4
  * - a run's hosted machine fetches computerd with the token its create minted, not the server's;
5
5
  * - the computers list and the Archil settings are read before a launch, naming keys, never a value;
6
- * - an agent its inline runs made has its disk and its delete sent by the backend that made it;
6
+ * - an agent its inline runs made has its disk, its delete and its runs' purges sent by the backend that made it (a run
7
+ * of an agent made here is refused by the purge's route itself, server.ts deleteRun, in this profile's words);
7
8
  * - a run's computer, take-over, hand-back and viewer link go to the backend, which has no owner's session here;
8
- * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's;
9
+ * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's,
10
+ * and resets it (deleteAgentLearning: the agent and its runs kept) when it erases what an agent learned;
9
11
  * - a run's usage lines (what its cost.usd joins, by meter) are a read of that run alone, cut as the run's read is;
10
12
  * - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart. */
11
13
  export const API_ONLY_ROUTES = new Set([
12
14
  "createRun", "createInlineRun", "getComputerDaemon",
13
15
  "getRunComputer", "takeOverRunComputer", "handBackRunComputer", "createRunComputerViewer",
14
16
  "listComputers", "getWorkspaceArchil",
15
- "getAgentArchil", "deleteAgentArchil", "deleteAgent",
17
+ "getAgentArchil", "deleteAgentArchil", "deleteAgent", "deleteAgentLearning", "deleteRun",
16
18
  "getLearningLoop", "listLearningPromotions", "getLearningCost", "getRunLearning",
17
19
  "getRun", "getRunUsage", "listRuns", "listAllRuns", "getTimeline",
18
20
  "sendMessage", "stopRun", "cancelRun", "raiseRunCap", "gradeRun",
@@ -71,6 +71,7 @@ export declare function createArchilRoutes(options: ArchilRoutesOptions): {
71
71
  }>;
72
72
  checkLaunchDisk: (diskId: string, signal?: AbortSignal) => Promise<void>;
73
73
  removeRunFolder: (agentId: string, runId: string, diskId: string, whose?: "launch" | "agent") => Promise<void>;
74
+ removeLearningFolder: (agentId: string, diskId: string) => Promise<void>;
74
75
  };
75
76
  export type ArchilRoutes = ReturnType<typeof createArchilRoutes>;
76
77
  /** One of the owner's Archil routes at its handler: its answer (sent 200), or an ApiError (sent with its status). An
@@ -30,7 +30,7 @@ import { unknownFields } from "./validate.js";
30
30
  import { ArchilClaimRefused } from "./workspace/archil-claim.js";
31
31
  import { archilDisk } from "./workspace/archil-disk.js";
32
32
  import { deleteDisk, getDisk, listOneDisk } from "./workspace/archil-disks.js";
33
- import { archilWorkspace } from "./workspace/archil.js";
33
+ import { archilWorkspace, spillFolderOf } from "./workspace/archil.js";
34
34
  import { agentDirName } from "./workspace/paths.js";
35
35
  import { WorkspaceError } from "./workspace/workspace.js";
36
36
  import { ARCHIL_API_KEY_ENV, archilApiKey } from "./workspace/archil-key.js";
@@ -285,6 +285,32 @@ export function createArchilRoutes(options) {
285
285
  throw new ApiError("upstream_failed", `${what} is not deleted there yet: ${describe(error).split(key).join("[the key]")}`);
286
286
  }
287
287
  }
288
+ /** Agent `agentId`'s learning folder on disk `diskId` deleted over the disk's file API: agents/<agent>/learning and
289
+ * everything under it (paths.ts learningKey), which a Mode 2 run's end writes on the disk its claim mounted, the
290
+ * agent's own or one its launch named (the caller's: never made, renamed or removed here), and the folder a learning
291
+ * exec spills beside it (workspace/archil.ts spillFolderOf: a write's input text, left by a failed cleanup). Nothing
292
+ * else on the disk is touched: the agent's runs' folders stay. Done again, it does nothing: a folder not there is gone, and so is the
293
+ * folder of a disk Archil says is gone. Archil off, or no account key, is 503 unavailable; a delete Archil refuses
294
+ * (a computer that still holds the folder, Archil not reached) is 424 upstream_failed, what was not deleted left for
295
+ * the next call. */
296
+ async function removeLearningFolder(agentId, diskId) {
297
+ const what = `The agent ${agentId}'s learning folder on the Archil disk ${diskId}`;
298
+ const settings = await loadArchilSettings(store, env);
299
+ if (settings === undefined)
300
+ throw new ApiError("unavailable", `${what} is not deleted yet: Archil is off on this server, so it can't be reached. Turn Archil on again (PUT /v2/workspace/archil)`);
301
+ const key = await keyOr("unavailable", `${what} can't be deleted`);
302
+ const disk = (options.control?.makeDisk ?? archilDisk)({ disk: diskId, region: settings.region, s3BaseUrl: settings.s3Url, key: () => key });
303
+ try {
304
+ const agent = archilWorkspace(disk, `agents/${agentDirName(agentId)}`, { queueMs: 5_000 });
305
+ for (const name of ["learning", spillFolderOf("learning")])
306
+ await agent.remove(name, { recursive: true, force: true });
307
+ }
308
+ catch (error) {
309
+ if (await diskGone(settings, key, diskId))
310
+ return;
311
+ throw new ApiError("upstream_failed", `${what} is not deleted there yet: ${describe(error).split(key).join("[the key]")}`);
312
+ }
313
+ }
288
314
  /** Whether Archil's control plane says disk `diskId` is gone: its read answers that the account has no such disk (404,
289
315
  * getDisk's undefined) or reads it as deleted. Only Archil's word counts: a read that fails (not reached, a 5xx, the key
290
316
  * refused) says nothing, so the disk is taken as still there. */
@@ -297,7 +323,7 @@ export function createArchilRoutes(options) {
297
323
  return false;
298
324
  }
299
325
  }
300
- return { view, save, off, test, agentView, removeAgentDisk, checkLaunchDisk, removeRunFolder };
326
+ return { view, save, off, test, agentView, removeAgentDisk, checkLaunchDisk, removeRunFolder, removeLearningFolder };
301
327
  }
302
328
  /** One of the owner's Archil routes at its handler: its answer (sent 200), or an ApiError (sent with its status). An
303
329
  * agent's route takes the agent as the dispatch read it. */
@@ -45,6 +45,14 @@ export declare const gpuOf: (computer: {
45
45
  }) => GpuSetting | undefined;
46
46
  /** The fields a computer of `kind` may set beside its kind and provider, in OPTIONAL's order: none for kind none. */
47
47
  export declare const kindSettings: (kind: ComputerKind) => string[];
48
+ /** Whether a run of a kind can record its screen on this server (GET /v2/computers' `record`), and why not, in words. */
49
+ export type RecordView = {
50
+ available: boolean;
51
+ why?: string;
52
+ };
53
+ /** Whether a run of `kind` can record its screen here: the kind takes record (OPTIONAL's record.kinds) and ffmpeg is on
54
+ * `path` (recorderMissing, the server's PATH now when absent), as a save of record: true is checked. */
55
+ export declare function recordOf(kind: ComputerKind, path?: string | undefined): RecordView;
48
56
  /** A place as the v2 API names it. */
49
57
  export type PlaceView = {
50
58
  mode: "runner";
@@ -76,6 +76,17 @@ const OPTIONAL = {
76
76
  };
77
77
  /** The fields a computer of `kind` may set beside its kind and provider, in OPTIONAL's order: none for kind none. */
78
78
  export const kindSettings = (kind) => kind === "none" ? [] : Object.entries(OPTIONAL).filter(([, { kinds }]) => kinds === undefined || kinds.includes(kind)).map(([key]) => key);
79
+ /** Whether a run of `kind` can record its screen here: the kind takes record (OPTIONAL's record.kinds) and ffmpeg is on
80
+ * `path` (recorderMissing, the server's PATH now when absent), as a save of record: true is checked. */
81
+ export function recordOf(kind, path = process.env.PATH) {
82
+ const kinds = OPTIONAL.record.kinds;
83
+ if (!kinds.includes(kind)) {
84
+ const recorders = kinds.map((one) => `a ${one}`);
85
+ return { available: false, why: kind === "none" ? "with no computer, there is no screen to record" : `a ${kind} has no screen to record (${recorders.slice(0, -1).join(", ")} or ${recorders.at(-1)} does)` };
86
+ }
87
+ const missing = recorderMissing(path);
88
+ return missing ? { available: false, why: missing } : { available: true };
89
+ }
79
90
  /** The place the setting reads as: sandbox on its provider, else the runner (no computer holds the run's folder). */
80
91
  export const placeOfComputer = (computer) => (computer.kind === "sandbox" ? { mode: "sandbox", box: computer.provider } : { mode: "runner" });
81
92
  /** The setting a place says: runner is no computer, a sandbox place a sandbox on its box. */