@parcha/agentrun-serve 0.1.0-beta.48 → 0.1.0-beta.49

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 (106) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +144 -16
  3. package/dist/agent-delete.d.ts +33 -10
  4. package/dist/agent-delete.js +184 -26
  5. package/dist/agents-store.d.ts +6 -2
  6. package/dist/agents-store.js +18 -5
  7. package/dist/agents.d.ts +8 -1
  8. package/dist/agents.js +14 -4
  9. package/dist/answer-json.d.ts +2 -2
  10. package/dist/answer-json.js +3 -4
  11. package/dist/archil-routes.d.ts +1 -1
  12. package/dist/archil-routes.js +4 -3
  13. package/dist/browser-sessions.d.ts +56 -0
  14. package/dist/browser-sessions.js +117 -0
  15. package/dist/computer-routes.d.ts +4 -15
  16. package/dist/computer-routes.js +6 -10
  17. package/dist/console/assets/index-Bzn4eUYF.js +715 -0
  18. package/dist/console/assets/index-CR2ZGei1.css +1 -0
  19. package/dist/console/index.html +2 -2
  20. package/dist/errors.d.ts +4 -1
  21. package/dist/errors.js +15 -5
  22. package/dist/import.js +4 -3
  23. package/dist/learn/check.d.ts +11 -2
  24. package/dist/learn/check.js +12 -9
  25. package/dist/learn/promote.d.ts +7 -1
  26. package/dist/learn/promote.js +47 -0
  27. package/dist/learn/repick.d.ts +34 -0
  28. package/dist/learn/repick.js +201 -0
  29. package/dist/learned-workflow.d.ts +2 -0
  30. package/dist/learned-workflow.js +18 -1
  31. package/dist/learning-setting.d.ts +13 -0
  32. package/dist/learning-setting.js +23 -1
  33. package/dist/llms.txt +1 -1
  34. package/dist/openapi.js +170 -12
  35. package/dist/paid-calls.d.ts +4 -1
  36. package/dist/paid-calls.js +1 -1
  37. package/dist/run-learning-served.d.ts +1 -1
  38. package/dist/run-usage.d.ts +110 -0
  39. package/dist/run-usage.js +312 -0
  40. package/dist/runner/adapter-loop.js +51 -20
  41. package/dist/runner/conformance/harness.d.ts +2 -0
  42. package/dist/runner/conformance/harness.js +18 -4
  43. package/dist/runner/feedback-round.d.ts +29 -1
  44. package/dist/runner/feedback-round.js +54 -3
  45. package/dist/runner/journal-kinds.d.ts +3 -1
  46. package/dist/runner/learning-end.js +49 -18
  47. package/dist/runner/loop-contract.d.ts +3 -0
  48. package/dist/runner/monid-run.js +2 -2
  49. package/dist/runner/promotion.js +8 -2
  50. package/dist/runner/reflect-hook.js +3 -2
  51. package/dist/runs-over-store.d.ts +3 -2
  52. package/dist/runs-over-store.js +9 -7
  53. package/dist/server.d.ts +3 -3
  54. package/dist/server.js +221 -98
  55. package/dist/store/index.d.ts +2 -2
  56. package/dist/store/index.js +1 -1
  57. package/dist/store/journal/storage.js +1 -1
  58. package/dist/store/open.d.ts +1 -1
  59. package/dist/store/open.js +1 -1
  60. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  61. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  62. package/dist/store/schema.d.ts +15 -1
  63. package/dist/store/schema.js +50 -5
  64. package/dist/store/sqlite/connection.d.ts +4 -1
  65. package/dist/store/sqlite/connection.js +5 -0
  66. package/dist/store/sqlite/run-patch.d.ts +8 -3
  67. package/dist/store/sqlite/run-patch.js +15 -7
  68. package/dist/store/sqlite/store.d.ts +5 -2
  69. package/dist/store/sqlite/store.js +249 -48
  70. package/dist/store/sqlite/worker.d.ts +9 -0
  71. package/dist/store/sqlite/worker.js +18 -1
  72. package/dist/store/store.d.ts +142 -9
  73. package/dist/store/store.js +63 -0
  74. package/dist/store-reads/analytics.js +2 -1
  75. package/dist/store-reads/cap.d.ts +8 -2
  76. package/dist/store-reads/cap.js +27 -3
  77. package/dist/store-reads/learning.d.ts +1 -1
  78. package/dist/store-reads/learning.js +5 -2
  79. package/dist/store-reads/runs.js +2 -0
  80. package/dist/store-reads/stats.js +4 -2
  81. package/dist/store-view.d.ts +7 -0
  82. package/dist/store-view.js +61 -20
  83. package/dist/tools.js +9 -0
  84. package/dist/trigger-targets.d.ts +7 -4
  85. package/dist/trigger-targets.js +6 -6
  86. package/dist/triggers.d.ts +2 -1
  87. package/dist/triggers.js +5 -2
  88. package/dist/validate.d.ts +4 -2
  89. package/dist/validate.js +13 -3
  90. package/dist/viewer-credential.d.ts +3 -4
  91. package/dist/viewer-credential.js +6 -4
  92. package/dist/workspace/computer-for-claim.d.ts +5 -1
  93. package/dist/workspace/computer-for-claim.js +47 -18
  94. package/dist/workspace/computer-intervals.d.ts +20 -0
  95. package/dist/workspace/computer-intervals.js +49 -0
  96. package/dist/workspace/computer-janitor.d.ts +7 -3
  97. package/dist/workspace/computer-janitor.js +14 -6
  98. package/dist/workspace/computer-kept.d.ts +7 -2
  99. package/dist/workspace/computer-kept.js +9 -2
  100. package/dist/workspace/resolve-computer.d.ts +7 -4
  101. package/dist/workspace/resolve-computer.js +21 -32
  102. package/dist/workspace/run-end-computers.d.ts +1 -0
  103. package/dist/workspace/run-end-computers.js +4 -1
  104. package/package.json +10 -10
  105. package/dist/console/assets/index-CTGegcKt.css +0 -1
  106. package/dist/console/assets/index-D1Se6mgG.js +0 -715
package/dist/openapi.js CHANGED
@@ -22,7 +22,7 @@ import { CALL_MS, PROTOCOL_METHODS } from "./computer-channel.js";
22
22
  import { LAUNCH_LOST, SETUP_LOST } from "./files.js";
23
23
  import { HARNESS_ID_PATTERN, HARNESSES } from "./harness.js";
24
24
  import { LEARNING_LABEL, LEARNING_MODES, LEARNING_REASONS, LEARNING_STATES, RUN_LEARNING_USE } from "./learning.js";
25
- import { AUDIT_DEFAULTS, AUDIT_MAX } from "./learning-setting.js";
25
+ import { AUDIT_DEFAULTS, AUDIT_MAX, REPICK_MAX_CHARS_DEFAULT, REPICK_MAX_CHARS_MAX } from "./learning-setting.js";
26
26
  import { AFTER_STATES, CHEAPER_AFTER_RUNS, COST_CSV_COLUMNS, COST_WINDOW, COST_RUNS_DEFAULT, COST_RUNS_MAX, RUN_PATHS } from "./learning-cost.js";
27
27
  import { FEEDBACK_ROUNDS, FEEDBACK_STATUSES } from "./runner/feedback-round.js";
28
28
  import { COMPILE_AFTER_MAX } from "./learning-setting.js";
@@ -225,6 +225,91 @@ const RUN_GRAPH = {
225
225
  },
226
226
  },
227
227
  };
228
+ /** GET /runs/{run_id}/usage's answer (run-usage.ts): one run's cost by line. Its line is not the contract's UsageLine
229
+ * (GET /usage's, a sum over runs by group). */
230
+ const COST_WORDS = {
231
+ so_far_usd: { type: "number", minimum: 0, description: "Beside a null `usd`, or a bound: what is known of it, the charges' own figures alone." },
232
+ unpriced: { type: "integer", minimum: 0, description: "Beside `so_far_usd`: how many of its charges have no known figure, or count at their hold." },
233
+ upper_bound: { const: true, description: "`usd` counts a request a crash or a stop cut at the hold its cap kept for it: the most it can have cost." },
234
+ };
235
+ const RUN_USAGE_LINE = {
236
+ type: "object", additionalProperties: false, required: ["meter", "model", "provider", "charged_by", "quantity", "unit", "basis", "usd"],
237
+ properties: {
238
+ meter: { enum: ["tokens", "tools", "browser_time"], description: "`tokens`: model requests, by model. `tools`: paid tool calls, by who charged for them. `browser_time`: browser session time, by browser provider. A computer's own time is on no line: it is not priced yet, so its cost is not in `total` (each computer the run made is in `computer_intervals`)." },
239
+ model: { type: ["string", "null"], description: "On `tokens`: the model the requests were sent on, as the run's booking names it (a workflow decision's model too). One line per model and route: the same model reached two ways is two lines. Null on the other meters, and when the record names none." },
240
+ provider: { type: ["string", "null"], description: "On `tokens`: the provider the requests went to, named only when this server sent them there itself (the run's own model on a provider's key). Null behind a model gateway, whose upstream this server does not know, and for a model it did not route (a workflow decision's). On `tools`: the vendor that charged for the calls, the same name as `charged_by` (the vendor that charges for a call is its provider). On `browser_time`: the browser provider. Null where the record names none." },
241
+ charged_by: { type: ["string", "null"], description: "On `tools`: who charged for the calls, whose invoice they land on (`monid`, an MCP server's name, `parallel`). Null on the other meters, and when the record names none." },
242
+ quantity: { type: ["number", "null"], minimum: 0, description: "In `unit`, as measured: never rounded to a billing increment, never topped up to a minimum. On `tokens`, the requests' input, cache read, cache write and output tokens as each reported them (a workflow decision's as its receipt does; a request that reported none is in `unmetered_requests`, in no token); on `tools`, the charges booked, one per paid call; on `browser_time`, the seconds this server's clock charged the provider's sessions for, its minimum per session included as the browser charged it. Null when nothing measured it." },
243
+ unit: { enum: ["token", "call", "second"] },
244
+ basis: { enum: ["reported", "estimate", "unpriced"], description: "How `usd` was reached. On `tokens`, as the run's `cost.basis` is, over the line's requests alone: `reported` when every request priced had its gateway's or provider's own figure, `estimate` when any was priced from a price table, `unpriced` when none was priced. On `tools`, `reported` when every charge with a figure is the provider's own (monid's answer says what it charged), `estimate` when any is a price this server holds (an MCP tool's saved price, Parallel's), `unpriced` when none has a figure. On `browser_time`, `estimate` when any charge has a figure (the provider's price per hour on this server's clock, never its invoice), else `unpriced`." },
245
+ usd: { type: ["number", "null"], minimum: 0, description: "The line's cost on this server, as booked, joined by the rule `cost.usd` is (float noise rounded off at 1e-12). Null when a charge of it is unknown: never $0 for unknown." },
246
+ ...COST_WORDS,
247
+ requests: { type: "integer", minimum: 0, description: "On `tokens`: the model requests booked." },
248
+ tokens: closed({ input: { type: "integer", minimum: 0, description: "Input not read from cache." }, output: { type: "integer", minimum: 0 }, cache_read: { type: "integer", minimum: 0 }, cache_write: { type: "integer", minimum: 0 } }, "On `tokens`: `quantity` by kind."),
249
+ unmetered_requests: { type: "integer", minimum: 0, description: "On `tokens`: requests that reported no tokens (booked with no usage, or sent and never answered), in no token count." },
250
+ not_metered_calls: { type: "integer", minimum: 1, description: "On `tools`: calls with no price set (an MCP tool its owner set none for), as GET /usage counts them. They ran outside the run's cost and its cap, so they are in neither `quantity` nor `usd`: a line of such calls alone has `quantity` 0 and `usd` 0." },
251
+ },
252
+ };
253
+ /** One browser session on GET /runs/{run_id}/usage (browser-sessions.ts). */
254
+ const BROWSER_SESSION = {
255
+ type: "object", additionalProperties: false,
256
+ required: ["provider", "tag", "provider_session_id", "started_at", "ended_at", "release_reason", "charged_seconds", "provider_record", "provider_record_status"],
257
+ properties: {
258
+ provider: { type: "string", description: "The browser provider, as the `browser_time` line's `provider` names it." },
259
+ tag: { type: "string", description: "The run's own name for the session, the same on every read." },
260
+ provider_session_id: { type: ["string", "null"], description: "The provider's id for the session, by which its own records and bill find it. Null when no session was made (its create failed) or its end is not recorded." },
261
+ started_at: { type: ["string", "null"], format: "date-time", description: "When this server began opening the session. Null while its end is not recorded." },
262
+ ended_at: { type: ["string", "null"], format: "date-time", description: "When this server let the session go. Null when its end is not recorded (a run whose process was lost before the release was told): unknown, never zero." },
263
+ release_reason: { type: ["string", "null"], description: "Why the session ended, in the browser's words: `tool` (the agent closed it), `idle`, `relaunch`, `close` (its run let it go), `ended` (the provider ended it), `lost`, `create_failed`." },
264
+ charged_seconds: { type: ["number", "null"], minimum: 0, description: "The seconds of the session's time this server charged, on its own clock: what the `browser_time` line sums, the provider's minimum per session included where the browser charged one at the release. How long the session ran is `ended_at` less `started_at`. Null when none was charged (a free provider's, or no charge recorded)." },
265
+ provider_record: {
266
+ type: ["object", "null"], additionalProperties: false, required: ["started_at", "ended_at", "proxy_bytes"],
267
+ description: "The provider's own record of the session, read once when it was let go, for matching it to the provider's invoice. Null unless `provider_record_status` is `read`. A field is null where the provider's record does not hold it.",
268
+ properties: {
269
+ started_at: { type: ["string", "null"], format: "date-time" },
270
+ ended_at: { type: ["string", "null"], format: "date-time", description: "Null where the provider had not ended it when read." },
271
+ proxy_bytes: { type: ["integer", "null"], minimum: 0, description: "The bytes the session moved through the provider's proxy, as the provider counts them." },
272
+ },
273
+ },
274
+ provider_record_status: { enum: ["read", "not_offered", "not_found", "failed", "no_session", null], description: "What came of reading the provider's record: `read`; `not_offered`, the provider keeps none this server reads; `not_found`, the provider did not know the session; `failed`, the read failed or timed out; `no_session`, none was made. Null while the session's end is not recorded." },
275
+ },
276
+ };
277
+ /** One computer a run made on GET /runs/{run_id}/usage (run-usage.ts computerIntervalsOf, store computer_intervals). */
278
+ const COMPUTER_INTERVAL = {
279
+ type: "object", additionalProperties: false,
280
+ required: ["provider", "provider_id", "kind", "gpu", "cpus", "memory_mb", "started_at", "ended_at", "kept"],
281
+ properties: {
282
+ provider: { type: "string", description: "The computer provider, as this server's registry names it (the agent's computer setting's `provider`: `docker`, `e2b`, `daytona`, ...)." },
283
+ provider_id: { type: "string", description: "The provider's own id for the computer, by which its console, its API and its invoice find it." },
284
+ kind: { type: ["string", "null"], description: "`sandbox`, `desktop` or `phone`. Null when not known." },
285
+ gpu: {
286
+ type: ["object", "null"], additionalProperties: false, required: ["type", "count"],
287
+ description: "The GPU the computer's create asked for. Null when it asked for none.",
288
+ properties: { type: { type: ["string", "null"] }, count: { type: ["integer", "null"], minimum: 0 } },
289
+ },
290
+ cpus: { type: ["number", "null"], minimum: 0, description: "The CPUs the computer's create asked for. Null when it asked for none: a hosted provider that sizes its own machines is never given a number here, and none is guessed." },
291
+ memory_mb: { type: ["integer", "null"], minimum: 0, description: "The memory, in MB, the computer's create asked for. Null when it asked for none." },
292
+ started_at: { type: "string", format: "date-time", description: "When the provider's create answered with the computer, on this server's clock." },
293
+ ended_at: { type: ["string", "null"], format: "date-time", description: "When the provider's delete of the computer answered ok, on this server's clock. Null while none did: the computer may still be running (a run that ended with one open left it behind), or its delete failed or its answer is unknown. Never a guessed end." },
294
+ kept: { type: "boolean", description: "The run's park kept the computer past its claim, for the person's answer (it is deleted once its keep's time passes, or at the run's end)." },
295
+ },
296
+ };
297
+ const RUN_USAGE = {
298
+ type: "object", additionalProperties: false, required: ["run_id", "ended_at", "currency", "total", "lines", "browser_sessions", "computer_intervals", "reason"],
299
+ properties: {
300
+ run_id: ref("schemas/Id"),
301
+ ended_at: { type: ["string", "null"], format: "date-time", description: "When the run ended: the moment the lines cover. Null while it is at work. The lines change only while the run works, and a follow-up can open an ended run again (a trigger's often does); its next end is a later one. Keep `ended_at` beside the lines: a later read with another `ended_at`, or null, means the run moved since. `run.ended` fires at each end." },
302
+ currency: { const: "USD" },
303
+ total: {
304
+ type: ["object", "null"], additionalProperties: false, required: ["usd"], description: "The run's cost, joined from its lines. Null with no lines.",
305
+ properties: { usd: { type: ["number", "null"], minimum: 0, description: "The lines joined by the rule `cost.usd` is: the run's `cost.usd` on GET /runs/{run_id}. Null when a line's charge is unknown." }, ...COST_WORDS },
306
+ },
307
+ lines: { type: ["array", "null"], items: RUN_USAGE_LINE, description: "`tokens` lines first, then `tools`, then `browser_time`, each by its model, charger or provider. A meter the run used nothing of has no line. Null when the server can't split the run (`reason`)." },
308
+ browser_sessions: { type: ["array", "null"], items: BROWSER_SESSION, description: "One record per browser session the run opened, in the order it opened them, for matching `browser_time` to the provider's own records and invoice by its session id. Empty for a run that opened none. Null exactly when `lines` is. Its words are cut of this server's secrets and the run's sign-ins, as the lines' names are.", "x-agentrun-serve": "runusage/2" },
309
+ computer_intervals: { type: ["array", "null"], items: COMPUTER_INTERVAL, description: "One record per computer the run made through its provider (a sandbox, a desktop, a phone), by when each was made: how long each lived for the run, one left running after it (`ended_at` null), and the provider's own id to match its invoice by. Not the agent's own persistent computer, a paired computer, or a browser's sessions (those are `browser_sessions`). Computer time is not priced yet: its cost is on no line and not in `total`. Empty for a run that made none (or one made before this server kept them). Null exactly when `lines` is. Its words are cut of this server's secrets and the run's sign-ins, as the lines' names are.", "x-agentrun-serve": "runusage/3" },
310
+ reason: { enum: ["running", "not_booked", "reopened", null], description: "Why `lines` is null: `running`, the run is at work and its booking still moves; `not_booked`, its figure is not its booking's (an imported run's, a native or SDK run's harness figure, a CLI run whose model requests went past its model proxy); `reopened`, a learning run a follow-up opened again, whose `cost.usd` is its first round's and whose booking can't be split by round. Null with lines." },
311
+ },
312
+ };
228
313
  /** GET /runs/{run_id}/trace's answer (run-trace.ts). */
229
314
  const RUN_TRACE = {
230
315
  type: "object", additionalProperties: false, required: ["run_id", "model_requests", "spans", "dropped"],
@@ -859,7 +944,7 @@ const COMPUTER_PROVIDER = closedWith({
859
944
  required: { type: "array", items: { type: "string" }, description: "The names of the secrets the provider needs; any other may stay unset." },
860
945
  ready: { type: "boolean", description: "Whether a run could have its computer of this kind here now: it fits this server's folder mode and every required key is saved." },
861
946
  runs_refused: PROVIDER_RUNS_REFUSED,
862
- folder: { enum: ["bind", "archil", "sync", null], description: "The kind of the run's folder a run of an agent with this computer holds on this server now, by the rule a run's claim picks it by (this server's folder mode, and the provider's keys and image as this server has them): `bind`, a folder of this machine bound in (Mode 1: Docker); `archil`, the owner's Archil disk mounted (Mode 2, where the provider takes an Archil mount and Archil's image is in its account, and its computer of this kind does not dial this server: Modal's sandbox, and E2B's and Agent37's sandbox and desktop; Daytona's sandbox once DAYTONA_ARCHIL_EGRESS and AGENTRUN_DAYTONA_SNAPSHOT are set); `sync`, a synced folder the runner keeps on the owner's disk (Mode 2, any other computer that takes a folder, Modal's desktop among them: it dials this server, so it takes no Archil mount). Null where it holds none: a phone, a browser, a desktop whose provider takes no folder in this mode, or a sandbox this mode refuses (`why` says why). For a computer with no GPUs: `gpu.mounts` says which kinds its GPU computers take. A kind alone, never a key, an image or an address." },
947
+ folder: { enum: ["bind", "archil", "sync", null], description: "The kind of the run's folder a run of an agent with this computer holds on this server now, by the rule a run's claim picks it by (this server's folder mode, and the provider's keys and image as this server has them). `bind`: a folder of this machine (Mode 1). `archil`: the owner's Archil disk, where the provider takes an Archil mount, has Archil's image and does not dial this server. `sync`: a synced folder the runner keeps, for any other computer that takes a folder in Mode 2. Null: none. For a computer with no GPUs: `gpu.mounts` says which kinds its GPU computers take. A kind alone, never a key, an image or an address." },
863
948
  shell: CHOICE_SHELL,
864
949
  host_tools: CHOICE_HOST_TOOLS,
865
950
  }, {
@@ -1531,7 +1616,7 @@ const LEARNING_EXTENSIONS = {
1531
1616
  "/runs/{run_id}/grade": {
1532
1617
  put: {
1533
1618
  operationId: "gradeRun", tags: ["runs"], summary: "Grade an ended run's answer: right or wrong, and the fields a right answer holds",
1534
- description: `A person's feedback or an eval's label on a run that ended, kept for its agent (one grade a run: a later one replaces it; the newest ${GRADES_KEPT} are kept). Promotion reads none: a revision's check is scored against the agent's own recorded answers. A replay run is never graded. The run's path never changes on a grade: a grade of a run its learned workflow answered alone, right or wrong, is kept and nothing more ($0); a run the agent finished, graded with a \`label\`, opens again on a look-back on it. That round asks the agent no turn of the job's, only its end-of-run turn, and its spend is the run's learning (\`feedback\`).`,
1619
+ description: `A person's feedback or an eval's label on a run that ended, kept for its agent (one grade a run: a later one replaces it; the newest ${GRADES_KEPT} are kept). Promotion reads none: a revision's check is scored against the agent's own recorded answers. A replay run is never graded. The run's path never changes on a grade: a grade of a run its learned workflow answered alone, right or wrong, is kept and nothing more ($0); a run the agent finished, graded with a \`label\`, opens again on a look-back on it. That round asks the agent no turn of the job's, only its end-of-run turn, and its spend is the run's learning (\`feedback\`). A run that reads ended while it still learns from that end (its \`learning.state\` \`reflecting\`: its own look-back, or a grade's round) is \`409 run_learning\`, nothing kept: grade it once \`learning.state\` moves on.`,
1535
1620
  parameters: [ref("parameters/RunId")],
1536
1621
  requestBody: { required: true, content: { "application/json": { schema: { type: "object", additionalProperties: false, required: ["correct"], properties: { correct: { type: "boolean" }, expected: { type: "object", description: "The fields a right answer's JSON holds." }, source: { enum: [...GRADE_SOURCES], default: "feedback" }, label: { type: "string", maxLength: LABEL_MAX, description: "The grade's words (a teacher's label, a reviewer's note): what the run's look-back reads." } } } } } },
1537
1622
  responses: { "200": json(GRADE, "The run's grade."), ...errors(400, 401, 404, 409, 429, 500) },
@@ -1768,10 +1853,11 @@ const FILE_LIST = { type: "object", additionalProperties: false, required: ["fil
1768
1853
  const EXTENSIONS = {
1769
1854
  "/agents/{agent_id}": {
1770
1855
  delete: {
1771
- operationId: "deleteAgent", tags: ["agents"], summary: "Delete an agent another system owns",
1772
- description: "Deletes an agent made by an inline run (`POST /runs` with `external`) whole: its runs and everything kept of them (journals, launch records, messages, files), its triggers, its learning, its saved sign-ins, its own computer and disk, its revisions and the agent. A run whose launch named an Archil disk (`archil_disk`, the caller's) has its own folder there deleted; the disk and everything else on it are kept, and a disk Archil says is gone has nothing left to delete. Shared things (MCP servers, keys, computers) are kept. In order: the agent refuses new runs (a mark in the store that outlives a restart: a run, an inline run, a trigger's firing, an SDK run or a message that would open one of its runs again is `409 agent_not_runnable`, as is a new trigger of it, off too, a trigger moved to it or turned on, and a write to its home or learning), and its runs still going are cancelled and waited for; then its learning (its learning folder, and its promotions and grades); then the rest. `204` when it is gone; a second `DELETE` is `404`. An agent made here is `409 agent_not_external`: archive it instead. `409 runs_in_flight` (a run did not end in time, or only its application ends it) and `409 learning_busy` (learning work in flight; each names what in `details.runs`) leave the agent refusing runs, as does `503 unavailable` while something it owns elsewhere is not deleted there yet: a trigger's registration upstream (Composio), a saved sign-in at its vendor, its own computer at its provider, its Archil disk (Archil failing or not reached, a run of another agent on it, or Archil off on this server), or a run's folder on a disk its launch named (Archil failing, a computer still holding the folder, or Archil off), or a trigger that reached the agent after its triggers were removed. Each is deleted there before the record here that names it, so none is left behind: send the `DELETE` again, which also finishes a delete that stopped part way.",
1856
+ operationId: "deleteAgent", tags: ["agents"], summary: "Delete an agent another system owns, or purge an archived agent made here",
1857
+ description: "An agent made here, once archived (`POST /agents/{agent_id}/archive`), is purged by the rule `DELETE /runs/{run_id}` purges a run by: its revisions' content (instructions, skills, notes), its name and description, its learning, its triggers, its saved sign-ins, its own computer, disk and folders go, and each of its runs is purged (a tombstone, its cost kept). The agent's row stays as its tombstone: every route of it answers `410 purged` with `details` {agent_id, archived_at, purged_at}, and no list shows it. What its runs cost stays in `/usage` and `/stats`. `204` when it is purged; a second `DELETE` is `204` too. An agent made here that is not archived is `409 agent_not_archived`, nothing purged; `409 run_not_final` while a run of it is live (`details.runs`), nothing purged; `503 unavailable` as below, the next `DELETE` finishing it. Purging one agent touches no other. Deleting or purging takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token: any other console session is `403 forbidden`.\n\n" +
1858
+ "An agent made by an inline run (`POST /runs` with `external`) is deleted whole, archived or not: its runs and everything kept of them (journals, launch records, messages, files), its triggers, its learning, its saved sign-ins, its own computer and disk, its revisions and the agent. A run whose launch named an Archil disk (`archil_disk`, the caller's) has its own folder there deleted; the disk and everything else on it are kept, and a disk Archil says is gone has nothing left to delete. Shared things (MCP servers, keys, computers) are kept. In order: the agent refuses new runs (a mark in the store that outlives a restart: a run, an inline run, a trigger's firing, an SDK run or a message that would open one of its runs again is `409 agent_not_runnable`, as is a new trigger of it, off too, a trigger moved to it or turned on, and a write to its home or learning), and its runs still going are cancelled and waited for; then its learning (its learning folder, and its promotions and grades); then the rest. `204` when it is gone; a second `DELETE` is `404`. `409 runs_in_flight` (a run did not end in time, or only its application ends it) and `409 learning_busy` (learning work in flight; each names what in `details.runs`) leave the agent refusing runs, as does `503 unavailable` while something it owns elsewhere is not deleted there yet: a trigger's registration upstream (Composio), a saved sign-in at its vendor, its own computer at its provider, its Archil disk (Archil failing or not reached, a run of another agent on it, or Archil off on this server), or a run's folder on a disk its launch named (Archil failing, a computer still holding the folder, or Archil off), or a trigger that reached the agent after its triggers were removed. Each is deleted there before the record here that names it, so none is left behind: send the `DELETE` again, which also finishes a delete that stopped part way.",
1773
1859
  parameters: [AGENT_ID],
1774
- responses: { "204": { description: "Deleted." }, ...errors(401, 404, 409, 429, 500, 503) },
1860
+ responses: { "204": { description: "Deleted, or purged." }, ...errors(401, 403, 404, 409, 429, 500, 503) },
1775
1861
  "x-agentrun-serve": "agentdelete/1",
1776
1862
  },
1777
1863
  },
@@ -1922,6 +2008,15 @@ const EXTENSIONS = {
1922
2008
  responses: { "200": json(RUN_TRACE, "The run's spans as they stand."), ...errors(401, 403, 404, 429, 500) },
1923
2009
  },
1924
2010
  },
2011
+ "/runs/{run_id}/usage": {
2012
+ get: {
2013
+ operationId: "getRunUsage", tags: ["runs"], summary: "What a run cost, by model, by who charged for its tools, and by browser provider",
2014
+ description: "One run's cost, line by line: its model requests by model (and the provider they went to, where this server sent them itself), its paid tool calls by who charged for them, and its browser time by provider. Each line has its quantity as measured, its dollars as the run's booking holds them, and how those were reached (`basis`). This server prices nothing here: the lines are the charges `cost.usd` already joins, so they add up to the run's `cost.usd` (`total`), and a charge no one knows is null, never $0. It reads the same for every kind of run that books its cost: an agentic run on any harness that sends its model requests through this server, and a workflow run with its decisions. Learning's spend for the run is not here: its end-of-run learning turn is this server's work for the agent, which `cost.usd` leaves out too; it is on the run read's `learning_usd`. While the run works, and for a run the server cannot split, `lines` is null and `reason` says why. A name on a line (a model, a provider, a charger) is cut of this server's secrets and the sign-ins the run was handed, as the run's trace is; 403 `forbidden` while this server can't read the browser sign-in the run was handed, as its trace answers.",
2015
+ parameters: [ref("parameters/RunId")],
2016
+ responses: { "200": json(RUN_USAGE, "The run's usage lines, or why it has none."), ...errors(401, 403, 404, 429, 500) },
2017
+ "x-agentrun-serve": "runusage/1",
2018
+ },
2019
+ },
1925
2020
  "/runs/{run_id}/browser": {
1926
2021
  get: {
1927
2022
  operationId: "getRunBrowser", tags: ["runs"], summary: "Watch the run's browser live and take it over: its viewer link, for the owner",
@@ -2045,6 +2140,13 @@ const EXTENSIONS = {
2045
2140
  },
2046
2141
  },
2047
2142
  "/runs/{run_id}": {
2143
+ delete: {
2144
+ operationId: "deleteRun", tags: ["runs"], summary: "Purge a run's content and keep its cost",
2145
+ description: "Purges a run that is not live: what it was given and what it did go, what it cost stays. Gone: its launch record (its input and prompt), its journal and timeline, its messages and commands, its outputs and files, the answers kept under its idempotency keys, its folders (on this machine, and its own folder on an Archil disk, its agent's or one its launch named; the disk and everything else on it are kept), its settings, the grades its agent keeps of it, and its kept learning's content (its learning's end, merged or dropped, stays, as `/stats` counts it). Its row stays as its tombstone: every route of it answers `410 purged` with `details` {run_id, agent_id, state, started_at, ended_at, cost_usd, cost_upper_bound, tools_usd, purged_at}, and no run list shows it. `/usage`, `/stats` and the spend a cap reads sum it as before: no total moves. The runs made from it are purged with it, each the same way: its audit's shadow run, the replay runs of its input and a learning run its kept learning names. Once it is purged, no replay or shadow run of it is started. Its agent, the agent's other runs and what its agent learned are kept: a promotion record keeps its decision, numbers and run ids (the run's among them), and what it copied from the run (a disagreement's input and answers, the grader's words, and the words a hold's reason quoted from them) is blanked; the learning folder's history may still name the run's id. `204` when it is purged; a second `DELETE` is `204` too; a run this server never had is `404`. Live (queued, working, waiting on a person or an approval, or held by a runner): `409 run_not_final` (`details.runs`, the run or each run made from it that is live, or a replay or shadow run of it a check or an audit started while the `DELETE` ran, which the next `DELETE` purges first), nothing purged; cancel it first (`POST /runs/{run_id}/cancel`). A run that ended and takes a follow-up (`idle`), or that a person stopped, is not live; one that reads so before its runner has written it ended is waited for (up to 30 seconds), then purged. `503 unavailable` while its folder on an Archil disk is not deleted there yet (Archil failing or off, a computer still holding the folder): the run is not purged, and the `DELETE` sent again finishes it, as it finishes a purge that stopped part way. Takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token: any other console session is `403 forbidden`.",
2146
+ parameters: [ref("parameters/RunId")],
2147
+ responses: { "204": { description: "Purged, now or before." }, ...errors(401, 403, 404, 409, 429, 500, 503) },
2148
+ "x-agentrun-serve": "purge/1",
2149
+ },
2048
2150
  patch: {
2049
2151
  operationId: "raiseRunCap", tags: ["runs"], summary: "Raise a run's spend cap",
2050
2152
  description: "Raises `max_cost_usd` of a run that named one, agentic or workflow; only a raise: the new cap is above the run's current cap, its last raise included (422 otherwise, and for a run with no cap); the same raise sent again (a retry) changes nothing and answers as the first did. The run's serve.json keeps it before anything else, so its next process and a server started again run under it. A run paused at its cap (`pending.kind` budget) goes on: the answer comes at once (`resumed` true, its `message_id`), and once its process has been let go the server sends it one follow-up turn under that id, \"The cap was raised to $X; continue the task.\", which runs under the new cap; it is sent once, by a server started again if this one stopped before it went. A second raise before it goes answers the same `message_id`; one that cannot be sent is tried again, then the run ends failed, saying why. Caps within 1e-9 are the same cap. A run working holds the new cap from its next step; a step already under way keeps the cap it was admitted at (`note` says so). A workflow run takes no follow-up: paused at its cap, the step that waits there is judged again under the new cap in its process, or, once the pause let its process go (10 minutes on), the run is opened again under it and resumes from its journal, sending no completed node again (`resumed` true, no `message_id`); a working one's process holds the new cap from its next check. 409 not_continuable for an ended run, and for a run a person stopped (send it a message to go on, then raise its cap).",
@@ -2991,7 +3093,7 @@ const LEARNING_NULL = "Null for a run that does not learn: its agent's `learning
2991
3093
  const LEARNING = {
2992
3094
  oneOf: [
2993
3095
  closedWith({
2994
- state: { enum: [...LEARNING_STATES], description: "`seeded` when the run started from what its agent learned; `reflecting` while its end-of-run step runs (its compile turn, its owner's correction), and until what it wrote is checked (after the run ended, so it may still read `reflecting` once the run reads completed or failed); `merged` once what it kept is on the folder's main; `dropped` when learning was skipped or refused, with `reason`." },
3096
+ state: { enum: [...LEARNING_STATES], description: "`seeded` when the run started from what its agent learned; `reflecting` while its end-of-run step runs (its compile turn, its owner's correction), and until what it wrote is checked); `reflecting` after the run's job ended (its own look-back, or the feedback round a grade opened) keeps the run's end: the run reads completed, failed or cancelled, with its `ended_at`, `result` and `error` as its job left them, and is read again after `poll_after_ms` (above 0) until its learning settles, its timeline `final: false` till then; stop answers `stopped: false` and cancel `already_terminal: true`, and a run tells `run.ended` once; `merged` once what it kept is on the folder's main; `dropped` when learning was skipped or refused, with `reason`." },
2995
3097
  reason: LEARNING_REASON,
2996
3098
  detail: { type: ["string", "null"], maxLength: 300, description: "Where the run's learning stands, in one sentence in a person's words (at most 300 characters, ending in an ellipsis when cut; a workflow's name in it is cut of the host's secrets as they are now before it is cut short, so none is shown in part), the same as its timeline row says: \"Started from 2 corrections and 1 workflow.\", \"Keeping what this run learned…\", \"Learned the workflow <name>.\", \"Kept your correction.\", \"Waiting for your OK: workflow <name>.\", \"Nothing new to keep from this run.\", \"Not kept: it didn't pass the checks (<rules>).\", \"Not kept: learning stopped (<why>).\" and so on. Never a secret or a value from the input, cut of the host's secrets as they are now. For a person: a client that acts on it reads `state` and `reason`, whose codes do not change." },
2997
3099
  at: { type: "string", format: "date-time", description: "When the state last changed." },
@@ -3465,7 +3567,9 @@ const FIELD_EXTENSIONS = {
3465
3567
  hold_window: { type: "integer", minimum: 1, maximum: AUDIT_MAX, default: AUDIT_DEFAULTS.hold_window, description: "The audit rows of the serving revision the hold rule reads: its newest this many (an owner's grade on a served run is one too)." },
3466
3568
  hold_disagree: { type: "integer", minimum: 1, maximum: AUDIT_MAX, default: AUDIT_DEFAULTS.hold_disagree, description: "When at least this many of those rows disagree, the workflow stops serving (a hold, source `audit`) and is recompiled once with them as data, then checked again: promoted serves again, otherwise it stops. At most `hold_window`." },
3467
3569
  stop_window: { type: "integer", minimum: 1, maximum: AUDIT_MAX, default: AUDIT_DEFAULTS.stop_window, description: "A second hold within this many served runs of the first stops the workflow for good, asking no compile." },
3468
- } }], default: false, description: "Whether an agentic revision's runs learn: `true`, its owner's corrections and learned workflows; an object, the same with the loop's numbers set on it (`compile_after`, `agree_min`, `alone_min`, `agree_on`, `audit_every`, `audit_every_later`, `audit_later_after`, `hold_window`, `hold_disagree`, `stop_window`, each optional: one left out is its default; `true` is every default); `false`, nothing. A run that learns starts from what its agent has learned, its corrections.md whole in its instructions under `# Learned` and its learned workflows behind its learned_workflow tool; once its job is due, it is asked one compile turn that writes the job as a learned workflow, checked and committed. Kept when a definition says so, true, false or an object (its numbers in one order); a number out of range or an unknown key is a 422 `wrong_type`; absent, off, and an answer shows none. An edit that leaves it out keeps the agent's. A workflow revision keeps none. On a server whose learning is off (`capabilities.features.learning`), no run learns, whatever this says.", "x-agentrun-serve": "learning/1" },
3570
+ repick: { type: "boolean", default: false, description: "`true`: a learned workflow compiled from now on re-picks its answer's quotes from the pages its run fetched. When a quote in its first answer is in none of those pages, its one re-pick writes the answer again from the pages themselves (each sent as data, told it is untrusted text from the web and never instructions, with no tools), not from its compact notes alone. It is read when a draft is committed, so a workflow already kept is unchanged until its next compile. An agent whose workflows run through an SDK bridge ignores it. `false` or absent: the re-pick reads its compact notes and its draft." },
3571
+ repick_max_chars: { type: "integer", minimum: 1, maximum: REPICK_MAX_CHARS_MAX, default: REPICK_MAX_CHARS_DEFAULT, description: "The most characters of state a re-pick over the pages sends its model: past it, the longest strings (the pages) are cut first, each to one length and marked where it was cut. Its cost is the served run's, under the run's cost cap like every model request of the run. Read with `repick`, at each compile." },
3572
+ } }], default: false, description: "Whether an agentic revision's runs learn: `true`, its owner's corrections and learned workflows; an object, the same with the loop's numbers set on it (`compile_after`, `agree_min`, `alone_min`, `agree_on`, `audit_every`, `audit_every_later`, `audit_later_after`, `hold_window`, `hold_disagree`, `stop_window`, `repick`, `repick_max_chars`, each optional: one left out is its default; `true` is every default); `false`, nothing. A run that learns starts from what its agent has learned, its corrections.md whole in its instructions under `# Learned` and its learned workflows behind its learned_workflow tool; once its job is due, it is asked one compile turn that writes the job as a learned workflow, checked and committed. Kept when a definition says so, true, false or an object (its numbers in one order); a number out of range or an unknown key is a 422 `wrong_type`; absent, off, and an answer shows none. An edit that leaves it out keeps the agent's. A workflow revision keeps none. On a server whose learning is off (`capabilities.features.learning`), no run learns, whatever this says.", "x-agentrun-serve": "learning/1" },
3469
3573
  checkout: { enum: ["pull_request", "none"], description: "What the server checks out in each run's folder before its first turn, an agentic definition's alone. `pull_request`: the pull request the run's GitHub event names (a GitHub trigger's firing: its repository, number, head and base), at its head, detached, in `repo/`, with its base and their merge base fetched beside it (refs `pr/head`, `pr/base`, `pr/merge-base`). The fetch is the server's own, one command on the run's folder, with an installation token of the server's GitHub App narrowed to that repository and `contents: read`, which the agent never holds: it is never in the folder, the checkout's git config, its remote's URL, the agent's environment or the log. With no App, or one not installed there, the fetch is anonymous, which a public repository answers. The run's system prompt says what was checked out, or why nothing was (no pull request named, the fetch failed), so it can read the change another way, such as the GitHub MCP. The checkout is removed when the run's claim ends. An edit that leaves it out keeps the agent's; `none` clears it. A template sets it from its manifest's `checkout`.", "x-agentrun-serve": "checkout/1" },
3470
3574
  },
3471
3575
  AgentCreate: {
@@ -3955,8 +4059,8 @@ export function openapiDocument(capabilityOf, adapters = TRIGGER_ADAPTERS) {
3955
4059
  }
3956
4060
  // A contract field this server takes with a meaning of its own, said on it.
3957
4061
  definition.properties.max_cost_usd = { ...definition.properties.max_cost_usd, "x-agentrun-serve-note": "The agent's default cap of each run started without a max_cost_usd of its own (a run's own wins), kept with its revision: above 0 sets it, 0 clears it (no default), and an edit that leaves the field out keeps the agent's, so leaving a field out never removes a spend limit. An agentic definition's or a workflow's alike." };
3958
- definition.properties.output_schema = { ...definition.properties.output_schema, "x-agentrun-serve-note": "An agentic definition's alone (a workflow's output is its workflow's): the JSON Schema its final answer's last fenced json block meets, at most 64 KiB, refused at save when it does not compile. A completed run's result.output is that block's value when it meets the schema, else null. An edit that leaves the field out keeps the agent's. A template's answer schema (its manifest's `output`) is set here at apply. Its `x-carried`, when given, is an array of unique names of its root `properties`, the fields of the answer a schedule trigger's next run reads back: a last completed result over 32 KiB (as 2-space JSON, in UTF-8 bytes) is handed to that run as those fields alone, read from the schema of the run that produced it. Carried arrays are kept oldest first (the template owns that order; the engine reads no dates): when the fields are over 32 KiB themselves, the largest carried array gives up its oldest entry (its first), one at a time, measured again after each (a tie: the first in `x-carried`), until they fit, and the words name each array's count dropped. A scalar or object is never cut: with no entry left to drop, none of it is handed, said so. Any other `x-carried` is refused at save (field `definition.output_schema.x-carried`)." };
3959
- definition.properties.input_schema = { ...definition.properties.input_schema, "x-agentrun-serve-note": "An agentic definition's alone (a workflow's input is its workflow's own schema): a JSON Schema object schema (`type: object`), at most 64 KiB, refused at save when it does not compile. Every run's `input` is checked against it with the full compiler, by POST /agents/{agent_id}/runs, a trigger's start_run target (at save and when it fires) and a template's triggers, and refused 422 `input_invalid` with an issue at each path (`input.company`, `input.topics.1`). `content` is reserved: named, it is `{type: string}`; it is always taken as text (the run's message), and it stays required when the schema requires nothing else. The run's first message is `content`, then the other fields as one fenced json block under the line `Input:`. Absent: `{content: string}`. An edit that leaves the field out keeps the agent's. A template's `inputs` are set here at apply." };
4062
+ definition.properties.output_schema = { ...definition.properties.output_schema, "x-agentrun-serve-note": "An agentic definition's alone (a workflow's output is its workflow's): the JSON Schema its final answer's last fenced json block meets, at most 64 KiB, refused at save when it does not compile. A completed run's result.output is that block's value when it meets the schema, else null. An edit that leaves the field out keeps the agent's. A template's answer schema (its manifest's `output`) is set here at apply. Over 32 KiB, a scheduled run is handed only the fields the producing run's schema names in `x-carried`; carried arrays lose entries from the front until they fit, and the run is told how many. A save refuses an `x-carried` that is not unique root property names." };
4063
+ definition.properties.input_schema = { ...definition.properties.input_schema, "x-agentrun-serve-note": "An agentic definition's alone (a workflow's input is its workflow's own schema): a JSON Schema object schema (`type: object`), at most 64 KiB, refused at save when it does not compile. Every run's `input` is checked against it with the full compiler, by POST /agents/{agent_id}/runs, a trigger's start_run target (at save and when it fires) and a template's triggers, and refused 422 `input_invalid` with an issue at each path (`input.company`, `input.topics.1`). `content` is reserved: named, it is `{type: string}`; it is always taken as text (the run's message). It is required when the schema has no field of its own; when the schema's own fields are all optional, a run gives `content` or one of them, and an input with none is refused at `input.content`. The run's first message is `content`, then the other fields as one fenced json block under the line `Input:`. Absent: `{content: string}`. An edit that leaves the field out keeps the agent's. A template's `inputs` are set here at apply." };
3960
4064
  const runResult = schemas.RunResult;
3961
4065
  runResult.properties.output = { ...runResult.properties.output, "x-agentrun-serve-note": "A workflow run's output, as its workflow ended; an agentic run's, its final answer's last fenced json block when it meets the agent's output_schema, else null (no schema, no block, not JSON, or a value the schema refuses). The runner gives the model the schema in its instructions on every harness, and asks once more, in the same session under the same cap, when the answer misses it; output_error says why one still missed." };
3962
4066
  // instructions XOR workflow (validate.ts): a workflow revision has none. version, skills and tools: this server
@@ -4197,8 +4301,9 @@ export function openapiDocument(capabilityOf, adapters = TRIGGER_ADAPTERS) {
4197
4301
  const own = Object.keys(ERROR_STATUS).filter((code) => Array.isArray(errorCode.enum) && !errorCode.enum.includes(code));
4198
4302
  if (own.length) {
4199
4303
  errorCode.enum = [...errorCode.enum, ...own];
4200
- // The newest addition that widened it: a client that validates against cappause/1 refuses runner_refused.
4201
- errorCode["x-agentrun-serve"] = "runners/1";
4304
+ // The newest addition that widened it: a client that validates against runners/1 refuses run_not_final, purged and
4305
+ // agent_not_archived.
4306
+ errorCode["x-agentrun-serve"] = "purge/1";
4202
4307
  fields.push(...own.map((code) => `ErrorCode.${code}`));
4203
4308
  }
4204
4309
  // A start (or a message) while every runner here refused to claim any run: 503 runner_refused, not retryable, in the
@@ -4237,6 +4342,21 @@ export function openapiDocument(capabilityOf, adapters = TRIGGER_ADAPTERS) {
4237
4342
  composio_in_use: closed({ triggers: { type: "array", items: closed({ id: { type: "string" }, name: { type: "string" } }), description: "The composio triggers that use it." } }),
4238
4343
  runs_in_flight: closed({ runs: { type: "array", items: { type: "string" }, description: "The agent's runs not ended (DELETE /agents/{agent_id})." } }),
4239
4344
  learning_busy: closed({ runs: { type: "array", items: { type: "string" }, description: "What of the agent's learning is at work (DELETE /agents/{agent_id}): each run of it not ended (its compile turn, a check's replay or an audit's shadow among them), by its id." } }),
4345
+ run_not_final: closed({ runs: { type: "array", items: { type: "string" }, description: "What is live (DELETE /runs/{run_id}, and an archived agent's DELETE /agents/{agent_id}): the run itself, each run made from it that is live, or each live run of the agent, by its id." } }),
4346
+ purged: {
4347
+ oneOf: [
4348
+ closed({
4349
+ run_id: { type: "string" }, agent_id: { type: "string" },
4350
+ state: { enum: ["ended", "stopped", "failed"], description: "The run's state as its row kept it: only a run that is not live is purged." },
4351
+ started_at: { type: "string", format: "date-time" }, ended_at: { type: ["string", "null"], format: "date-time" },
4352
+ cost_usd: { type: ["number", "null"], minimum: 0, description: "What it cost, as `/usage` sums it: its known cost, else its upper bound." },
4353
+ cost_upper_bound: { type: "boolean", description: "`cost_usd` is an upper bound, not a known cost." },
4354
+ tools_usd: { type: ["number", "null"], minimum: 0, description: "What its paid tools cost, as `/usage`'s tools meter read it; null when none was read." },
4355
+ purged_at: { type: "string", format: "date-time" },
4356
+ }, "A purged run's tombstone (every route of /runs/{run_id})."),
4357
+ closed({ agent_id: { type: "string" }, archived_at: { type: ["string", "null"], format: "date-time" }, purged_at: { type: "string", format: "date-time" } }, "A purged agent's tombstone (every route of /agents/{agent_id})."),
4358
+ ],
4359
+ },
4240
4360
  };
4241
4361
  const extensions = [];
4242
4362
  for (const [path, item] of Object.entries(EXTENSIONS)) {
@@ -4245,6 +4365,17 @@ export function openapiDocument(capabilityOf, adapters = TRIGGER_ADAPTERS) {
4245
4365
  extensions.push(`${method.toUpperCase()} ${path}`);
4246
4366
  }
4247
4367
  }
4368
+ // purge/1: every route of a purged run or agent (DELETE /runs/{run_id}, DELETE /agents/{agent_id}) answers 410 purged
4369
+ // with its tombstone, its DELETE alone 204 again. A contract operation that gains the 410 is changed, and says so.
4370
+ doc.components.responses = {
4371
+ ...doc.components.responses,
4372
+ Gone: {
4373
+ description: "`purged`: the run or agent was purged (`DELETE /runs/{run_id}`, `DELETE /agents/{agent_id}`); `details` is its tombstone.",
4374
+ headers: { "X-Request-Id": ref("headers/RequestId") },
4375
+ content: { "application/json": { schema: ref("schemas/Error") } },
4376
+ "x-agentrun-serve": "purge/1",
4377
+ },
4378
+ };
4248
4379
  // examples/1: a working body for the operations in REQUEST_EXAMPLES, on the JSON media type; a contract operation that
4249
4380
  // gains one is changed, and says so.
4250
4381
  for (const [path, item] of Object.entries(doc.paths)) {
@@ -4282,6 +4413,33 @@ export function openapiDocument(capabilityOf, adapters = TRIGGER_ADAPTERS) {
4282
4413
  Object.assign(doc.paths, hooks, NATIVE_PATHS, SDK_PATHS, OBSERVATION_PATHS);
4283
4414
  doc.info["x-agentrun-serve"].extensions.push(...Object.entries({ ...NATIVE_PATHS, ...SDK_PATHS, ...OBSERVATION_PATHS }).flatMap(([path, item]) => Object.keys(item).map(method => `${method.toUpperCase()} ${path}`)));
4284
4415
  doc.info["x-agentrun-serve"].extensions.push(...Object.keys(hooks).map((path) => `POST ${path}`));
4416
+ // purge/1, on every operation there is by now (each rewritten, never a shared constant's own object changed); `changed`
4417
+ // is info's own list. Every route of a purged run or agent, and each that writes to an agent its body names (a trigger
4418
+ // made for it or moved to it, a template applied onto it), which a purged one refuses.
4419
+ const namesAgent = new Set(["createTrigger", "updateTrigger", "applyTemplate"]);
4420
+ for (const [path, item] of Object.entries(doc.paths)) {
4421
+ const ofPurgeable = /^\/(runs\/\{run_id\}|agents\/\{agent_id\})(\/|$)/.test(path);
4422
+ if (!ofPurgeable && !Object.values(item).some((op) => typeof op === "object" && op !== null && namesAgent.has(op.operationId)))
4423
+ continue;
4424
+ const ops = { ...item };
4425
+ for (const [method, op] of Object.entries(ops)) {
4426
+ if (method === "parameters" || method.startsWith("x-") || !op.responses)
4427
+ continue;
4428
+ if (op.operationId === "deleteRun" || op.operationId === "deleteAgent")
4429
+ continue;
4430
+ if (!ofPurgeable && !namesAgent.has(op.operationId))
4431
+ continue;
4432
+ ops[method] = { ...op, responses: { ...op.responses, "410": ref("responses/Gone") } };
4433
+ if (op["x-agentrun-serve"] !== undefined)
4434
+ continue;
4435
+ // An operation whose responses an earlier addition changed keeps that one's mark, as a schema two additions widen does.
4436
+ const marks = (op["x-agentrun-serve-changed"] ?? {});
4437
+ ops[method]["x-agentrun-serve-changed"] = { ...marks, responses: marks.responses ?? "purge/1" };
4438
+ if (!changed.includes(`${method.toUpperCase()} ${path}`))
4439
+ changed.push(`${method.toUpperCase()} ${path}`);
4440
+ }
4441
+ doc.paths[path] = ops;
4442
+ }
4285
4443
  return doc;
4286
4444
  }
4287
4445
  /** The document as served on `port`: the owner's session cookie named as the console sets it on that port
@@ -43,7 +43,8 @@ export type LedgerRefusal = Refusal;
43
43
  export type PaidBooking = {
44
44
  /** `chargedBy`: who charges for it (the charge's `charged_by` on main's records: parallel, monid, an MCP server, a
45
45
  * browser vendor), named on its runner.request. `under`: the model session whose tool call it runs in (RunTools.admit),
46
- * whose requests in flight it is judged beside and never waits on. */
46
+ * whose requests in flight it is judged beside and never waits on. `reported`: it settles at the provider's own figure
47
+ * for the call, written on its runner.request (GET /runs/{run_id}/usage says a `tools` line's basis by it). */
47
48
  admit(request: {
48
49
  id: string;
49
50
  name: string;
@@ -57,6 +58,7 @@ export type PaidBooking = {
57
58
  hold?: true;
58
59
  ref?: string;
59
60
  under?: string;
61
+ reported?: true;
60
62
  }): Promise<unknown>;
61
63
  /** `givenBack`: the hold let go unused, nothing sent (RunTools.settle). */
62
64
  settle(id: string, usd: number | null, options?: {
@@ -118,6 +120,7 @@ export declare function paidStep<T>(paid: PaidBooking, call: string | undefined,
118
120
  owed?: true;
119
121
  hold?: true;
120
122
  ref?: string;
123
+ reported?: true;
121
124
  }, run: () => Promise<T>, chargeOf: (outcome: {
122
125
  result: T;
123
126
  } | {
@@ -149,7 +149,7 @@ export async function paidStep(paid, call, fee, run, chargeOf, pause) {
149
149
  const id = `${call ?? fee.ref ?? fee.name}#${(paidSeq += 1)}`;
150
150
  let admitted;
151
151
  try {
152
- admitted = await paid.admit({ id, name: fee.name, holdUsd: fee.holdUsd, basis: fee.basis, ...(call === undefined ? {} : { call }), chargedBy: fee.by, ...(fee.tool ? { tool: fee.tool } : {}), ...(fee.tag ? { tag: fee.tag } : {}), ...(fee.owed ? { owed: true } : {}), ...(fee.hold ? { hold: true } : {}), ...(fee.ref === undefined ? {} : { ref: fee.ref }) });
152
+ admitted = await paid.admit({ id, name: fee.name, holdUsd: fee.holdUsd, basis: fee.basis, ...(call === undefined ? {} : { call }), chargedBy: fee.by, ...(fee.tool ? { tool: fee.tool } : {}), ...(fee.tag ? { tag: fee.tag } : {}), ...(fee.owed ? { owed: true } : {}), ...(fee.hold ? { hold: true } : {}), ...(fee.ref === undefined ? {} : { ref: fee.ref }), ...(fee.reported ? { reported: true } : {}) });
153
153
  }
154
154
  catch (error) {
155
155
  await pauseOn(error, pause);
@@ -44,7 +44,7 @@ export declare function servedRunLearning(deps: {
44
44
  feedback_status: "running" | "ended" | "not_run" | null;
45
45
  source: "feedback" | "eval";
46
46
  graded_at: string;
47
- path: "agent" | "workflow" | "replay" | "handed_back" | "audit";
47
+ path: "agent" | "workflow" | "replay" | "audit" | "handed_back";
48
48
  workflow_digest: string | null;
49
49
  feedback: "correction" | null;
50
50
  run_id: string;
@@ -0,0 +1,110 @@
1
+ import { type BrowserSessionLine } from "./browser-sessions.js";
2
+ import { type CostBasis, type CostWords } from "./runner/metrics.js";
3
+ import type { RunLaunch } from "./run-launch.js";
4
+ import { type SignInReader } from "./run-view.js";
5
+ import { type ComputerIntervalRow, type Store } from "./store/index.js";
6
+ import { type EntryLike } from "./timeline/index.js";
7
+ /** The meters a run's lines are on: the contract's `tokens` and `browser_time`, and this server's `tools`. */
8
+ export type UsageMeter = "tokens" | "tools" | "browser_time";
9
+ /** One line of a run's cost: one model, one charger or one browser provider on a meter. Which it is: `model` and
10
+ * `provider` on `tokens` (the model the requests were sent on; the provider they went to, named only when the server
11
+ * sent them there itself, null behind a gateway, whose upstream the server does not know), `charged_by` on `tools` (who
12
+ * charged for the calls) and `provider` beside it (the same name: the vendor that charges for a call is its provider),
13
+ * `provider` on `browser_time`; every other one null, and null where the record names none, never "". `quantity` in `unit`: tokens
14
+ * (input, cache read, cache write and output, as each request reported them), charges booked (one per paid call), or
15
+ * seconds of browser session time on this server's clock, unrounded; null when none was measured. `usd` and its words
16
+ * are the cost block's (CostWords): null when a charge is unknown, with `so_far_usd` and `unpriced` beside it;
17
+ * `upper_bound` when a cut request counts at its hold. Not the contract's UsageLine (GET /usage's, a sum over many
18
+ * runs by group): a line of one run. */
19
+ export type RunUsageLine = {
20
+ meter: UsageMeter;
21
+ model: string | null;
22
+ provider: string | null;
23
+ charged_by: string | null;
24
+ quantity: number | null;
25
+ unit: "token" | "call" | "second";
26
+ basis: CostBasis;
27
+ requests?: number;
28
+ tokens?: {
29
+ input: number;
30
+ output: number;
31
+ cache_read: number;
32
+ cache_write: number;
33
+ };
34
+ unmetered_requests?: number;
35
+ not_metered_calls?: number;
36
+ } & CostWords;
37
+ /** Why a run has no lines: `running`, it is at work and its booking still moves; `not_booked`, its figure is not its
38
+ * booking's (an imported run's, a native or SDK run's harness's own, a CLI run whose model requests went past its proxy);
39
+ * `reopened`, a learning run a follow-up opened again, whose `cost.usd` is its first round's and whose booking can't be
40
+ * split by round. */
41
+ export type UsageReason = "running" | "not_booked" | "reopened";
42
+ export type RunUsage = {
43
+ run_id: string;
44
+ /** When the run ended: the moment its lines cover. Null while it is at work. A follow-up opens an ended run again
45
+ * (store/sqlite/run-patch.ts REOPEN_SET clears it), and its next end is a later one: a reader that keeps it beside the
46
+ * lines knows from a later read whether the run moved since. */
47
+ ended_at: string | null;
48
+ currency: "USD";
49
+ /** The lines joined by the one rule (costWordsOf): the run's `cost.usd`, with what is known of it when it is unknown
50
+ * (`so_far_usd`, `unpriced`) and `upper_bound` when it is a bound. Null with no lines. */
51
+ total: CostWords | null;
52
+ lines: RunUsageLine[] | null;
53
+ /** One record per browser session the run opened (browser-sessions.ts), for matching `browser_time` to the provider's
54
+ * own records by its session id; null exactly when `lines` is. */
55
+ browser_sessions: BrowserSessionLine[] | null;
56
+ /** One record per computer the run made (computerIntervalsOf), by when each was made; null exactly when `lines` is.
57
+ * Computer time is not priced: its cost is in no line and not in `total`. */
58
+ computer_intervals: ComputerIntervalLine[] | null;
59
+ reason: UsageReason | null;
60
+ };
61
+ /** One computer the run made through its provider (a sandbox, a desktop, a phone), as GET /runs/{run_id}/usage serves
62
+ * it: the provider (this server's id for it) and the provider's own id for the computer, its kind, what its create asked
63
+ * for (null where it asked none: a hosted vendor sizes its own), when it was made, when its provider's delete answered ok
64
+ * (`ended_at`, null while none did: still running, or its delete failed or was never asked), and whether the run's park
65
+ * kept it past its claim. */
66
+ export type ComputerIntervalLine = {
67
+ provider: string;
68
+ provider_id: string;
69
+ kind: string | null;
70
+ gpu: {
71
+ type: string | null;
72
+ count: number | null;
73
+ } | null;
74
+ cpus: number | null;
75
+ memory_mb: number | null;
76
+ started_at: string;
77
+ ended_at: string | null;
78
+ kept: boolean;
79
+ };
80
+ /** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
81
+ export declare function computerIntervalsOf(rows: readonly ComputerIntervalRow[]): ComputerIntervalLine[];
82
+ /** A workflow decision's receipt as the lines read it (store-reads/decisions.ts): by its `decision_id`, which its
83
+ * request's booking names (`decision:<id>`), the model and provider that answered it, and how its cost was reached. */
84
+ export type DecisionReceiptLike = {
85
+ model?: unknown;
86
+ provider?: unknown;
87
+ cost_basis?: unknown;
88
+ usage?: unknown;
89
+ };
90
+ /** A run's lines from its journal `entries` (every conversation, in log order), its end-of-run turns already left out:
91
+ * its model requests and decisions by model (`tokens`), its paid calls by who charged (`tools`), its browser time by
92
+ * provider (`browser_time`); and their join, `total`. A meter with nothing booked has no line. `launch` names the
93
+ * run's own model's provider; `receipts`, a workflow's decisions by id, the model and provider each was answered on
94
+ * (its booking names the decision alone), which this server called itself. */
95
+ export declare function usageLinesOf(entries: readonly EntryLike[], launch?: Pick<RunLaunch, "model">, receipts?: ReadonlyMap<string, DecisionReceiptLike>): {
96
+ lines: RunUsageLine[];
97
+ total: CostWords;
98
+ };
99
+ /** Run `runId`'s usage lines (GET /runs/{run_id}/usage); undefined for an unknown run. No lines (`reason`) while it is at
100
+ * work, for a run whose figure is not its booking's, and for a learning run a follow-up opened again: the cases where
101
+ * `cost.tools_usd` is null for the same reasons. Its state, launch, learning rounds and journal are read in one snapshot
102
+ * of the store (one moment): a follow-up that reopens the run between two reads can't put its requests under its end. */
103
+ export declare function runUsageOverStore(store: Store, runId: string): Promise<RunUsage | undefined>;
104
+ /** Run `runId`'s usage lines as served: each name taken from its record (a model, its provider, a tool's charger) through
105
+ * the run's cut, as its trace serves a model's name, since a decision provider or a tool names itself in what it
106
+ * returns. A run withheld (its sign-in can't be read back here) is refused (403), as its trace is. */
107
+ export declare function servedRunUsage(deps: {
108
+ serverSecrets: () => string[];
109
+ signIns?: SignInReader;
110
+ }, store: Store, runId: string): Promise<RunUsage | undefined>;