@parcha/agentrun-serve 0.1.0-beta.47 → 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 (185) hide show
  1. package/CHANGELOG.md +68 -1
  2. package/README.md +218 -20
  3. package/dist/acp-package.d.ts +24 -6
  4. package/dist/adapter-facts.d.ts +0 -4
  5. package/dist/adapter-facts.js +1 -4
  6. package/dist/adapters.d.ts +3 -12
  7. package/dist/adapters.js +1 -70
  8. package/dist/agent-delete.d.ts +33 -10
  9. package/dist/agent-delete.js +184 -26
  10. package/dist/agents-store.d.ts +6 -2
  11. package/dist/agents-store.js +18 -5
  12. package/dist/agents.d.ts +8 -1
  13. package/dist/agents.js +14 -4
  14. package/dist/answer-json.d.ts +10 -0
  15. package/dist/answer-json.js +23 -0
  16. package/dist/api-only.d.ts +5 -2
  17. package/dist/api-only.js +10 -2
  18. package/dist/archil-routes.d.ts +1 -1
  19. package/dist/archil-routes.js +4 -3
  20. package/dist/browser-live.d.ts +9 -4
  21. package/dist/browser-live.js +18 -5
  22. package/dist/browser-sessions.d.ts +56 -0
  23. package/dist/browser-sessions.js +117 -0
  24. package/dist/cap.js +7 -9
  25. package/dist/cli.js +6 -6
  26. package/dist/computer-routes.d.ts +6 -14
  27. package/dist/computer-routes.js +8 -10
  28. package/dist/computers.d.ts +6 -2
  29. package/dist/computers.js +4 -2
  30. package/dist/conformance.d.ts +4 -0
  31. package/dist/conformance.js +6 -0
  32. package/dist/console/assets/index-Bzn4eUYF.js +715 -0
  33. package/dist/console/assets/index-CR2ZGei1.css +1 -0
  34. package/dist/console/index.html +2 -2
  35. package/dist/errors.d.ts +4 -1
  36. package/dist/errors.js +15 -5
  37. package/dist/harness-check.d.ts +3 -1
  38. package/dist/harness-check.js +99 -70
  39. package/dist/harness-cursor.d.ts +10 -27
  40. package/dist/harness-cursor.js +5 -84
  41. package/dist/harness-goose.d.ts +4 -29
  42. package/dist/harness-goose.js +6 -86
  43. package/dist/harness-module.d.ts +4 -0
  44. package/dist/harness-module.js +1 -0
  45. package/dist/harness-owned.d.ts +52 -0
  46. package/dist/harness-owned.js +92 -0
  47. package/dist/harness-recipe.js +2 -24
  48. package/dist/harness-table.d.ts +109 -6
  49. package/dist/harness-table.js +242 -28
  50. package/dist/harness.js +2 -2
  51. package/dist/import.js +4 -3
  52. package/dist/key-refusal.d.ts +2 -1
  53. package/dist/key-refusal.js +18 -2
  54. package/dist/learn/check.d.ts +11 -2
  55. package/dist/learn/check.js +12 -9
  56. package/dist/learn/promote.d.ts +18 -1
  57. package/dist/learn/promote.js +47 -0
  58. package/dist/learn/repick.d.ts +34 -0
  59. package/dist/learn/repick.js +201 -0
  60. package/dist/learn/secrets.d.ts +4 -0
  61. package/dist/learn/secrets.js +23 -0
  62. package/dist/learned-workflow.d.ts +2 -0
  63. package/dist/learned-workflow.js +18 -1
  64. package/dist/learning-model.d.ts +18 -0
  65. package/dist/learning-model.js +77 -0
  66. package/dist/learning-setting.d.ts +13 -0
  67. package/dist/learning-setting.js +23 -1
  68. package/dist/llms.txt +1 -0
  69. package/dist/model-form.js +12 -12
  70. package/dist/model.d.ts +5 -4
  71. package/dist/model.js +19 -13
  72. package/dist/openapi.js +203 -15
  73. package/dist/page.d.ts +1 -0
  74. package/dist/page.js +1 -1
  75. package/dist/paid-calls.d.ts +4 -1
  76. package/dist/paid-calls.js +1 -1
  77. package/dist/run-learning-served.d.ts +1 -1
  78. package/dist/run-secrets.d.ts +2 -2
  79. package/dist/run-secrets.js +6 -5
  80. package/dist/run-trace.js +6 -3
  81. package/dist/run-usage.d.ts +110 -0
  82. package/dist/run-usage.js +312 -0
  83. package/dist/runner/adapter-loop.d.ts +4 -1
  84. package/dist/runner/adapter-loop.js +52 -22
  85. package/dist/runner/adapter-run-spec.d.ts +3 -2
  86. package/dist/runner/adapter-run-spec.js +8 -4
  87. package/dist/runner/adapters/index.d.ts +4 -2
  88. package/dist/runner/adapters/index.js +6 -42
  89. package/dist/runner/cli-run-spec.js +10 -6
  90. package/dist/runner/conformance/harness.d.ts +2 -0
  91. package/dist/runner/conformance/harness.js +18 -4
  92. package/dist/runner/conformance/host-tools.d.ts +4 -0
  93. package/dist/runner/conformance/host-tools.js +14 -0
  94. package/dist/runner/feedback-round.d.ts +29 -1
  95. package/dist/runner/feedback-round.js +54 -3
  96. package/dist/runner/journal-kinds.d.ts +3 -1
  97. package/dist/runner/learning-end.js +49 -18
  98. package/dist/runner/loop-contract.d.ts +3 -0
  99. package/dist/runner/meta-tools.js +4 -2
  100. package/dist/runner/monid-run.js +2 -2
  101. package/dist/runner/presence.d.ts +3 -0
  102. package/dist/runner/presence.js +19 -12
  103. package/dist/runner/promotion.d.ts +62 -4
  104. package/dist/runner/promotion.js +154 -17
  105. package/dist/runner/reflect-hook.js +3 -2
  106. package/dist/runner/sdk-loop.js +25 -1
  107. package/dist/runner/workflow-spec.js +3 -2
  108. package/dist/runs-over-store.d.ts +5 -3
  109. package/dist/runs-over-store.js +11 -11
  110. package/dist/sdk/check.d.ts +31 -0
  111. package/dist/sdk/check.js +58 -0
  112. package/dist/sdk/runs.d.ts +10 -2
  113. package/dist/sdk/runs.js +87 -17
  114. package/dist/sdk/schema.js +11 -3
  115. package/dist/server.d.ts +6 -3
  116. package/dist/server.js +297 -98
  117. package/dist/store/index.d.ts +2 -2
  118. package/dist/store/index.js +1 -1
  119. package/dist/store/journal/storage.js +1 -1
  120. package/dist/store/open.d.ts +1 -1
  121. package/dist/store/open.js +1 -1
  122. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  123. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  124. package/dist/store/schema.d.ts +15 -1
  125. package/dist/store/schema.js +50 -5
  126. package/dist/store/sqlite/connection.d.ts +4 -1
  127. package/dist/store/sqlite/connection.js +5 -0
  128. package/dist/store/sqlite/run-patch.d.ts +8 -3
  129. package/dist/store/sqlite/run-patch.js +15 -7
  130. package/dist/store/sqlite/store.d.ts +5 -2
  131. package/dist/store/sqlite/store.js +283 -77
  132. package/dist/store/sqlite/worker.d.ts +9 -0
  133. package/dist/store/sqlite/worker.js +18 -1
  134. package/dist/store/store.d.ts +162 -27
  135. package/dist/store/store.js +63 -0
  136. package/dist/store-reads/analytics.js +2 -1
  137. package/dist/store-reads/cap.d.ts +8 -2
  138. package/dist/store-reads/cap.js +27 -3
  139. package/dist/store-reads/learning.d.ts +1 -1
  140. package/dist/store-reads/learning.js +5 -2
  141. package/dist/store-reads/runs.js +2 -0
  142. package/dist/store-reads/stats.js +4 -2
  143. package/dist/store-view.d.ts +12 -3
  144. package/dist/store-view.js +70 -27
  145. package/dist/template-eval.js +5 -2
  146. package/dist/template-github-permissions.d.ts +5 -1
  147. package/dist/template-github-permissions.js +7 -3
  148. package/dist/timeline/index.d.ts +1 -1
  149. package/dist/timeline/index.js +1 -1
  150. package/dist/timeline/timeline.d.ts +8 -0
  151. package/dist/timeline/timeline.js +18 -6
  152. package/dist/tool-gate.d.ts +8 -4
  153. package/dist/tool-gate.js +6 -7
  154. package/dist/tool-plane.d.ts +4 -0
  155. package/dist/tool-plane.js +10 -10
  156. package/dist/tools.js +9 -0
  157. package/dist/trigger-targets.d.ts +14 -2
  158. package/dist/trigger-targets.js +73 -4
  159. package/dist/triggers.d.ts +2 -1
  160. package/dist/triggers.js +5 -2
  161. package/dist/validate.d.ts +4 -2
  162. package/dist/validate.js +18 -4
  163. package/dist/viewer-credential.d.ts +24 -0
  164. package/dist/viewer-credential.js +53 -0
  165. package/dist/workspace/computer-for-claim.d.ts +5 -1
  166. package/dist/workspace/computer-for-claim.js +47 -18
  167. package/dist/workspace/computer-intervals.d.ts +20 -0
  168. package/dist/workspace/computer-intervals.js +49 -0
  169. package/dist/workspace/computer-janitor.d.ts +7 -3
  170. package/dist/workspace/computer-janitor.js +14 -6
  171. package/dist/workspace/computer-kept.d.ts +7 -2
  172. package/dist/workspace/computer-kept.js +9 -2
  173. package/dist/workspace/resolve-computer.d.ts +9 -1
  174. package/dist/workspace/resolve-computer.js +29 -22
  175. package/dist/workspace/run-end-computers.d.ts +1 -0
  176. package/dist/workspace/run-end-computers.js +4 -1
  177. package/package.json +18 -10
  178. package/templates/code-review/agent.md +2 -3
  179. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  180. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  181. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  182. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  183. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  184. package/dist/console/assets/index-BBFzAxLB.js +0 -715
  185. package/dist/console/assets/index-BRi-Rgq6.css +0 -1
package/dist/server.js CHANGED
@@ -1,9 +1,7 @@
1
1
  import { maintainObservations, Observations } from './observation/observer.js';
2
2
  import { isObservationRoute, observationHttp } from './observation/http.js';
3
3
  import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
4
- import { askRouteOf } from "./runner/sdk-ask.js";
5
- import { PI_WIRES } from "./runner/adapter-run-spec.js";
6
- import { routeOf as sdkModelRoute } from "./runner/model-route.js";
4
+ import { learningModelOf } from "./learning-model.js";
7
5
  import { answerSkill } from './skill-route.js';
8
6
  import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './native/remote.js';
9
7
  import { REMOTE_HISTORY_BODY_BYTES } from './native/history.js';
@@ -18,6 +16,7 @@ import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from
18
16
  import { createServer } from "node:http";
19
17
  import proxyaddr from "proxy-addr";
20
18
  import { apiOnlyRefusal, servedApiOnly } from "./api-only.js";
19
+ import { carriedFields } from "./answer-json.js";
21
20
  import { dirname, join, relative, resolve, sep } from "node:path";
22
21
  import { pathToFileURL } from "node:url";
23
22
  import { Worker } from "node:worker_threads";
@@ -68,12 +67,13 @@ import { screenWaitEnded } from "./browser-wait-ended.js";
68
67
  import { durationMs, logLine } from "./print.js";
69
68
  import { keepPresence, refusedEnd, runnersRefused } from "./runner/presence.js";
70
69
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
71
- import { builtOfNow, factsOverStore, listedItem, momentOverStore, summaryOverStore, timelineOverStore, toolsUsdOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
70
+ import { builtOfNow, factsOverStore, listedItem, lookingBackEnd, momentOverStore, summaryOverStore, timelineOverStore, toolsUsdOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
72
71
  import { healEndedCosts } from "./cost-heal.js";
73
72
  import { createLister } from "./run-listing.js";
74
73
  import { HELD_WAITS } from "./runner/journal-kinds.js";
75
74
  import { servedTimelineRows } from "./run-timeline-served.js";
76
75
  import { servedRunTrace } from "./run-trace.js";
76
+ import { servedRunUsage } from "./run-usage.js";
77
77
  import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
78
78
  import { agentPointers, WITHHELD_LEARNING } from "./handed-values.js";
79
79
  import { runCutValues } from "./run-cut.js";
@@ -84,19 +84,19 @@ import { triggerTargets } from "./trigger-targets.js";
84
84
  import { labelFilter, labelsIssues } from "./run-labels.js";
85
85
  import { listRuns as listRunsOverStore, readRun as readRunOverStore, runOfOrigin as runOfOriginOverStore } from "./store-reads/runs.js";
86
86
  import { runEntries } from "./store-reads/journal.js";
87
- import { metersOverStore } from "./store-reads/cap.js";
87
+ import { metersOverStore, spendOverStore } from "./store-reads/cap.js";
88
88
  import { watchRun } from "./live/stream.js";
89
89
  import { stats as statsOverStore } from "./store-reads/stats.js";
90
90
  import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
91
91
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
92
92
  import { openStore, openRunLaunch, sealRunLaunch, StoreLaunchMissing, StoreOwned, storeTarget } from "./store/index.js";
93
- import { agentDeleting, answerOf, logged } from "./agents.js";
93
+ import { agentDeleting, answerOf, logged, purgedAgent } from "./agents.js";
94
94
  import { keepGrade } from "./runner/feedback-round.js";
95
95
  import { gradeRow, notAuditableOf } from "./runner/audit.js";
96
- import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf } from "./learn/audit.js";
96
+ import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf, shadowRunId } from "./learn/audit.js";
97
97
  import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
98
98
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
99
- import { championOf, GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf, servingStateOf, shownDeep } from "./learn/promote.js";
99
+ import { championOf, forgetRunCopies, GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf, servingStateOf, shownDeep } from "./learn/promote.js";
100
100
  import { workflowNodesOf } from "./learn/workflow-nodes.js";
101
101
  import { deleteLearning } from "./learn/delete.js";
102
102
  import { runModelRef } from "./model.js";
@@ -122,7 +122,7 @@ import { analyticsFilter, analyticsView, statsView } from "./stats.js";
122
122
  import { joinedBasis } from "./runner/metrics.js";
123
123
  import { agentLoopOverStore } from "./store-reads/loop.js";
124
124
  import { printable } from "./learn/index.js";
125
- import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore } from "./store-reads/learning.js";
125
+ import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore, runLearningEnd } from "./store-reads/learning.js";
126
126
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
127
127
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
128
128
  import { toolKeysOverStore } from "./tool-keys-store.js";
@@ -173,6 +173,8 @@ import { recordingsOf, recordingsWorkspace } from "./run-recordings.js";
173
173
  import { recordingsFolder } from "./workspace/paths.js";
174
174
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
175
175
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
176
+ import { runOver } from "./computer-commands.js";
177
+ import { mintViewerCredential, VIEWER_PARAM, viewerCookie, viewerCredentialFor, viewerCredentialKey, viewerCredentialOf } from "./viewer-credential.js";
176
178
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
177
179
  import { createAttachRoutes, liveRelays, pairedView } from "./computer-attach.js";
178
180
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
@@ -183,12 +185,12 @@ import { noAccount, openAccount } from "./email/account.js";
183
185
  import { emailRoute } from "./email/routes.js";
184
186
  import { addressForms, openCalendar } from "./calendar/address.js";
185
187
  import { calendarRoute } from "./calendar/routes.js";
186
- import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, runDiskKey } from "./archil-settings.js";
188
+ import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, runDiskKept, runDiskKey } from "./archil-settings.js";
187
189
  import { computerOfPlace } from "./computer-setting.js";
188
190
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
189
191
  import { fauxComputers } from "./faux-computers.js";
190
192
  import { writesHeld } from "./workspace.js";
191
- import { deleteExternalAgent, oneAtATime } from "./agent-delete.js";
193
+ import { deleteExternalAgent, oneAtATime, purgeAgent, purgeRun, purgingKey } from "./agent-delete.js";
192
194
  import { agentComputerHoldKey } from "./workspace/agent-computer.js";
193
195
  import { sdkRunKey } from "./sdk/runs.js";
194
196
  import { waitEndedKey } from "./browser-wait-ended.js";
@@ -266,6 +268,19 @@ async function tokenIn(file) {
266
268
  }
267
269
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
268
270
  const SESSION_S = SESSION_MS / 1000;
271
+ const isoOrNull = (ms) => (ms === null ? null : new Date(ms).toISOString());
272
+ /** 410 purged for a route of a purged run (Runs.purge): its tombstone, what is kept of it. `tools_usd`: its paid tools'
273
+ * meter as /usage read it at its purge (null: unknown, or none read). */
274
+ function purgedRun(row) {
275
+ const meters = row.metrics?.purged?.meters;
276
+ return new ApiError("purged", `The run ${row.id} was purged: what it was given and did is gone, and its cost stays in every total.`, {
277
+ details: {
278
+ run_id: row.id, agent_id: row.agentId, state: row.state, started_at: isoOrNull(row.startedAt), ended_at: isoOrNull(row.endedAt),
279
+ cost_usd: row.costUsd ?? row.costAtMostUsd, cost_upper_bound: row.costUsd === null && row.costAtMostUsd !== null, tools_usd: typeof meters?.tools === "number" ? meters.tools : null,
280
+ purged_at: isoOrNull(row.purgedAt),
281
+ },
282
+ });
283
+ }
269
284
  export const ROUTES = [
270
285
  { method: "GET", pattern: /^\/observations$/, name: "getObservations" },
271
286
  { method: "GET", pattern: /^\/connectors$/, name: "listRemoteConnectors" },
@@ -314,6 +329,8 @@ export const ROUTES = [
314
329
  { method: "POST", pattern: /^\/runs$/, name: "createInlineRun" },
315
330
  { method: "GET", pattern: /^\/runs\/([^/]+)$/, name: "getRun" },
316
331
  { method: "PATCH", pattern: /^\/runs\/([^/]+)$/, name: "raiseRunCap" },
332
+ // A final run deleted whole, with the runs made from it (agent-delete.ts deleteRun).
333
+ { method: "DELETE", pattern: /^\/runs\/([^/]+)$/, name: "deleteRun" },
317
334
  { method: "GET", pattern: /^\/runs\/([^/]+)\/timeline$/, name: "getTimeline" },
318
335
  { method: "POST", pattern: /^\/runs\/([^/]+)\/messages$/, name: "sendMessage" },
319
336
  { method: "POST", pattern: /^\/runs\/([^/]+)\/stop$/, name: "stopRun" },
@@ -326,6 +343,8 @@ export const ROUTES = [
326
343
  { method: "GET", pattern: /^\/runs\/([^/]+)\/graph$/, name: "getRunGraph" },
327
344
  // A run's trace (run-trace.ts): each model request and tool call as a span, with its time, tokens and cost.
328
345
  { method: "GET", pattern: /^\/runs\/([^/]+)\/trace$/, name: "getRunTrace" },
346
+ // A run's usage lines (run-usage.ts): by meter, model, charger and provider, each with its quantity and its cost.
347
+ { method: "GET", pattern: /^\/runs\/([^/]+)\/usage$/, name: "getRunUsage" },
329
348
  { method: "POST", pattern: /^\/workflows\/validate$/, name: "validateWorkflow" },
330
349
  { method: "POST", pattern: /^\/runs\/([^/]+)\/pause$/, name: "pauseRun" },
331
350
  { method: "POST", pattern: /^\/runs\/([^/]+)\/resume$/, name: "resumeRun" },
@@ -336,6 +355,8 @@ export const ROUTES = [
336
355
  // store-backed take-over lands). The run routes stay together.
337
356
  { method: "GET", pattern: /^\/runs\/([^/]+)\/computer$/, name: "getRunComputer" },
338
357
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/take-over$/, name: "takeOverRunComputer" },
358
+ // An API-only server's viewer credential for a run's live view (viewer-credential.ts), minted for its backend.
359
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/viewer$/, name: "createRunComputerViewer" },
339
360
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/hand-back$/, name: "handBackRunComputer" },
340
361
  // A held computer's (computer-held-routes.ts): a run started with hold: true waits for its start, takes its owner's
341
362
  // protocol calls, and keeps its computer after its agent's end until released.
@@ -560,9 +581,10 @@ async function planStep(step) {
560
581
  }
561
582
  async function needsOf(env) {
562
583
  const chosen = await chooseModel(env, undefined);
584
+ const learning_model = await learningModelOf(env);
563
585
  if ("why" in chosen)
564
- return { needs: chosen.needs, priced: null };
565
- return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0 };
586
+ return { needs: chosen.needs, priced: null, learning_model };
587
+ return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0, learning_model };
566
588
  }
567
589
  /** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
568
590
  * env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
@@ -598,7 +620,7 @@ export function forCaller(caps, ownerSession) {
598
620
  * needsOf says it for a revision that names no model (null when it runs). `runnerShell`: the sandbox-only tools a run
599
621
  * on the runner has a shell for here (tools.ts shellTools; bash in Mode 2), available with no box. `switched`: the two
600
622
  * start-time switches the server takes as options (switchedOnBy reads them from `env`, as the CLI sets them). */
601
- function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, refused = {}, runnerShell, isolation = "process", switched = switchedOnBy(env)) {
623
+ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, learning_model }, toolSettings, boxes, refused = {}, runnerShell, isolation = "process", switched = switchedOnBy(env)) {
602
624
  const models = { ...modelSource(env), ready: needs === null, needs, priced };
603
625
  // Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
604
626
  const memory = hostMemory();
@@ -621,6 +643,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
621
643
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
622
644
  places: placesOf(boxes, boxAllowOf(env)),
623
645
  models,
646
+ learning_model,
624
647
  /** `pending`: a workflow draft with a call no price covers is kept to wait for its owner's OK, served to no run;
625
648
  * `approve`: whether the caller can approve one, which takes the owner's password session (forCaller), and
626
649
  * `approve_needs` when not. */
@@ -1139,6 +1162,8 @@ async function startHolding(options, data, checked, stops) {
1139
1162
  const sealKey = seal.key;
1140
1163
  // SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
1141
1164
  const sdkSecret = sdkRunSecret(sealKey);
1165
+ // An API-only server's viewer credentials: viewer-credential.ts.
1166
+ const viewerKey = viewerCredentialKey(sealKey);
1142
1167
  // Each run's viewers are asked under that run's key (live-reach.ts reachForRun).
1143
1168
  const answers = (runId) => (handover) => viewerAnswers(handover, reachForRun(reach, runId));
1144
1169
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
@@ -1576,12 +1601,17 @@ async function startHolding(options, data, checked, stops) {
1576
1601
  getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1577
1602
  needAgent,
1578
1603
  momentOf: (runId) => momentOverStore(store, runId, viewDepsFor(ownOriginOf())),
1604
+ // Read when a firing's message is sent (declared below, with the delete turn).
1605
+ runWrite: (agentId, runId, work) => runWrite(agentId, runId, work),
1579
1606
  runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
1580
1607
  completedOutput: async (runId) => {
1581
1608
  const view = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
1582
1609
  if (view?.status !== "completed")
1583
1610
  return undefined;
1584
- return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null };
1611
+ // The fields its next run is handed when the whole result is too large: its own revision's output schema's, the one
1612
+ // its result.output was checked against (store-view.ts), never the agent's current one.
1613
+ const carried = typeof view.revision === "string" ? carriedFields((await store.agents.revision(view.revision))?.body?.outputSchema) : undefined;
1614
+ return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null, ...(carried ? { carried } : {}) };
1585
1615
  },
1586
1616
  };
1587
1617
  const targets = triggerTargets(store, triggerDeps);
@@ -2203,21 +2233,42 @@ async function startHolding(options, data, checked, stops) {
2203
2233
  * so nothing is written after the delete passed over it. The request's body is read before, outside the turn. */
2204
2234
  const agentWrite = (id, work) => deleteInTurn(id, async () => {
2205
2235
  const entry = await needAgent(id);
2236
+ // A purged agent's row stays as its tombstone: a write that waited on its purge is 410, never a folder made again.
2237
+ if (entry.agent.purgedAt !== null)
2238
+ throw purgedAgent(entry.agent);
2206
2239
  if (entry.agent.archivedAt && entry.agent.externalRef !== null)
2207
2240
  throw agentDeleting(id);
2241
+ // A purge stopped part way (its mark still there): nothing of the agent is written, nor is it unarchived, until a
2242
+ // DELETE finishes it.
2243
+ if (entry.agent.archivedAt && (await store.settings.get(purgingKey(id))) !== undefined)
2244
+ throw agentDeleting(id);
2245
+ return work();
2246
+ });
2247
+ /** `work`, a write that names run `runId` of agent `agentId` (a message, which may open it again; a grade, which keeps its
2248
+ * id and expected answer), done in the agent's delete turn, the agent and the run read there: a purge of the run (or of
2249
+ * its agent) holds that turn from its live check to its tombstone, so such a write waits for it and is then 410, never
2250
+ * a run opened again under a purge nor a grade saved after one. */
2251
+ const runWrite = (agentId, runId, work) => agentWrite(agentId, async () => {
2252
+ const row = await store.runs.get(runId);
2253
+ if (!row)
2254
+ throw new ApiError("not_found", `no run ${runId}`);
2255
+ if (row.purgedAt !== null)
2256
+ throw purgedRun(row);
2208
2257
  return work();
2209
2258
  });
2210
2259
  const AGAIN = "It starts no run meanwhile: send the DELETE again to finish it.";
2211
- /** `work`, a thing a deleted agent owns elsewhere deleted there: a refusal of one of `codes` (it is not deleted there
2212
- * yet) answered as the delete answers each such one, 503 unavailable, retryable, saying to send the DELETE again. */
2213
- const notYetWith = async (work, codes = ["unavailable"]) => {
2260
+ const RUN_AGAIN = "The run is kept: send the DELETE again to finish it.";
2261
+ /** `work`, a thing a deleted agent or run owns elsewhere deleted there: a refusal of one of `codes` (it is not deleted
2262
+ * there yet) answered as the delete answers each such one, 503 unavailable, retryable, saying to send the DELETE again
2263
+ * (`again`: the words for an agent's delete, or a run's). */
2264
+ const notYetWith = async (work, codes = ["unavailable"], again = AGAIN) => {
2214
2265
  try {
2215
2266
  await work();
2216
2267
  }
2217
2268
  catch (error) {
2218
2269
  if (!(error instanceof ApiError && codes.includes(error.code)))
2219
2270
  throw error;
2220
- throw new ApiError("unavailable", `${error.message.replace(/[.\s]*$/, "")}. ${AGAIN}`, { retry_after_ms: 5_000 });
2271
+ throw new ApiError("unavailable", `${error.message.replace(/[.\s]*$/, "")}. ${again}`, { retry_after_ms: 5_000 });
2221
2272
  }
2222
2273
  };
2223
2274
  /** What DELETE /agents/{id} does outside the store's rows, on this server (agent-delete.ts AgentDeleteHost). */
@@ -2269,13 +2320,20 @@ async function startHolding(options, data, checked, stops) {
2269
2320
  // Archil's failure (424), a live run of another agent on the disk (412) or no key (503): each is retried by the next DELETE.
2270
2321
  await notYetWith(() => archil.removeAgentDisk({ id: agentId, archived: true, external: true, liveOn: (diskId) => liveRunsOnDisk(store.runs, agentId, diskId) }), ["upstream_failed", "precondition_failed", "unavailable"]);
2271
2322
  },
2272
- forgetRun: async (agentId, runId) => {
2323
+ forgetRun: async (agentId, runId, alone) => {
2324
+ const again = alone ? RUN_AGAIN : AGAIN;
2273
2325
  // Its own folder on a disk its launch named (the caller's disk, which stays): read from its launch record, which goes
2274
2326
  // with the run's rows after this, so a failure or a stop here leaves the record that names the disk for the next
2275
- // DELETE. A run on its agent's own disk has none: that disk went whole (removeDisk), its folder with it.
2327
+ // DELETE. A run on its agent's own disk: with its agent's delete that disk went whole (removeDisk), its folder with
2328
+ // it; deleted alone, its folder there is deleted, the disk kept, read from its disk setting, which goes after.
2276
2329
  const launched = await store.runs.launch(runId).then((row) => readLaunchBody(row.body)?.archilDisk, (error) => (error instanceof StoreLaunchMissing ? undefined : Promise.reject(error)));
2277
2330
  if (launched?.kind === "launch")
2278
- await notYetWith(() => archil.removeRunFolder(agentId, runId, launched.diskId), ["unavailable", "upstream_failed"]);
2331
+ await notYetWith(() => archil.removeRunFolder(agentId, runId, launched.diskId), ["unavailable", "upstream_failed"], again);
2332
+ else if (alone) {
2333
+ const own = launched?.diskId ?? (await runDiskKept(store, runId));
2334
+ if (own)
2335
+ await notYetWith(() => archil.removeRunFolder(agentId, runId, own, "agent"), ["unavailable", "upstream_failed"], again);
2336
+ }
2279
2337
  // The run's folder (its work and what sits beside it), its scratch and its native context, on this machine.
2280
2338
  for (const folder of [dirname(runFolder(data, agentId, runId)), scratchFolder(data, agentId, runId), join(data, "native-context", runId)])
2281
2339
  await rm(folder, { recursive: true, force: true });
@@ -2293,6 +2351,25 @@ async function startHolding(options, data, checked, stops) {
2293
2351
  await rm(join(data, "scratch", agentDirName(agentId)), { recursive: true, force: true });
2294
2352
  await forgetKept("agent", agentId);
2295
2353
  },
2354
+ // The replay runs of its input, its audit's shadow run and a learning run it names (the store's), and its audit's shadow
2355
+ // run by its id (one whose launch is gone too).
2356
+ madeFrom: async (runId) => [...new Set([...(await store.runs.madeFrom(runId)), shadowRunId(runId)])],
2357
+ forgetCopies: (agentId, runId) => forgetRunCopies(store.settings, agentId, runId),
2358
+ // /usage's meters and a live read's spend, from its journal, as they read now (store-reads/cap.ts), and how its
2359
+ // learning ended as /stats counts it (its state and reason alone).
2360
+ kept: async (runId) => {
2361
+ const spend = await spendOverStore(store, runId, ctx);
2362
+ const learning = await runLearningEnd(store, runId);
2363
+ return {
2364
+ meters: await metersOverStore(store, runId, ctx),
2365
+ spend: { usd: spend.usd, ...(spend.basis === undefined ? {} : { basis: spend.basis }) },
2366
+ learning: learning ? { state: learning.state, reason: learning.reason } : null,
2367
+ };
2368
+ },
2369
+ turnOver: async (runId) => {
2370
+ const read = await runStatusState(runId);
2371
+ return read.state === "idle" && read.status !== "paused";
2372
+ },
2296
2373
  waitMs: options.agentDeleteWaitMs ?? 30_000,
2297
2374
  pollMs: 200,
2298
2375
  ...(options.agentDeleteAt ? { at: options.agentDeleteAt } : {}),
@@ -2662,7 +2739,10 @@ async function startHolding(options, data, checked, stops) {
2662
2739
  warnings = saved.warnings;
2663
2740
  return saved.stamp;
2664
2741
  };
2665
- const edited = await agents.commit(entry, checkDefinitionBody(body, { creating: false, harnesses }), { check, ...options });
2742
+ // Its last read and its commit in the agent's delete turn (agentWrite), the check outside it: an edit or a template
2743
+ // update whose commit comes once the agent is purged is 410, and one after a purge stopped part way is 409, nothing
2744
+ // written (the store refuses a purged agent's revision too, AgentPurged).
2745
+ const edited = await agents.commit(entry, checkDefinitionBody(body, { creating: false, harnesses }), { check, ...options, inTurn: (work) => agentWrite(entry.agent.id, work) });
2666
2746
  reconcileComputer(entry.agent.id);
2667
2747
  return { entry: edited, warnings };
2668
2748
  }
@@ -3485,11 +3565,12 @@ async function startHolding(options, data, checked, stops) {
3485
3565
  }
3486
3566
  // ---- usage ----------------------------------------------------------------------------------------------------------
3487
3567
  // Each ended run's meters, over the one store (store-reads/cap metersOverStore, cap.ts meterFiguresFrom over A's journal):
3488
- // kept, as a settled run's journal no longer changes, keyed by its end, so a run opened again and ended again is read
3489
- // again. A run whose journal cannot be read leaves it all tokens.
3568
+ // kept, as a settled run's journal no longer changes, keyed by its end and its cost, so a run opened again and ended
3569
+ // again is read again: a grade's round ends it again at the same end time (its look-back keeps the end), its cost moved
3570
+ // by the round's spend. A run whose journal cannot be read leaves it all tokens.
3490
3571
  const endedMeters = new Map();
3491
3572
  const metersOf = async (row) => {
3492
- const key = `${row.id} ${row.endedAt}`;
3573
+ const key = `${row.id} ${row.endedAt} ${row.costUsd}`;
3493
3574
  let meters = endedMeters.get(key);
3494
3575
  if (!meters) {
3495
3576
  // An ended run's meter figures over the one store: cap.ts meterFiguresFrom over A's journal, its paid tools' charges
@@ -3931,22 +4012,30 @@ async function startHolding(options, data, checked, stops) {
3931
4012
  authFailed(`/v2${path}`, "replay_without_session");
3932
4013
  throw new ApiError("forbidden", owner ? "Replaying a learned workflow's revision takes the owner's password sign-in in the console, never a token." : "Replaying a learned workflow's revision takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
3933
4014
  }
3934
- // A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
3935
- // approving a note is (never a token a run, an MCP client or a script may hold).
3936
- if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
4015
+ // A run's live computer view, and its take-over and hand-back (COMPUTER_ROUTES), are a full-control credential for its
4016
+ // computer: the owner's signed-in page alone, as approving a note is (never a token a run, an MCP client or a script
4017
+ // may hold). An API-only server has no owner: there the server's token, its backend's own, takes a run's computer,
4018
+ // checked below as every route's token is.
4019
+ const runComputer = found.name === "getRunComputer" || COMPUTER_ROUTES.has(found.name);
4020
+ if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || (runComputer && !options.apiOnly)) && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3937
4021
  const what = found.name.endsWith("Browser") ? "browser" : "computer";
3938
4022
  authFailed(`/v2${path}`, `${what}_without_session`);
3939
4023
  throw new ApiError("forbidden", owner ? `A run's live ${what} takes the owner's password sign-in in the console, never a token.` : `A run's live ${what} takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).`);
3940
4024
  }
3941
- // A run's desktop or phone view drives it once taken over: the owner's signed-in page alone (computer-routes.ts decides).
3942
- if (COMPUTER_ROUTES.has(found.name) && !byOwnerSession(req) && req.headers.authorization !== undefined)
3943
- authFailed(`/v2${path}`, "computer_without_session");
3944
4025
  // Answering a tool call that waits for approval (tool-gate.ts) is the same: the owner's signed-in page alone, never a
3945
4026
  // token, which the run's own process, an agent's MCP client or a script may hold.
3946
4027
  if (found.name === "answerApproval" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3947
4028
  authFailed(`/v2${path}`, "approve_without_session");
3948
4029
  throw new ApiError("forbidden", owner ? "Answering a tool call's approval takes the owner's password sign-in in the console, never a token." : "Answering a tool call's approval takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
3949
4030
  }
4031
+ // Purging a run or an agent, or deleting another system's agent, cannot be undone: the owner's session or the API
4032
+ // token. A console session counts as the owner's only where it does for a secret (secret-writes.ts: accounts off on a
4033
+ // loopback-bound server); bound off loopback with accounts off, whoever opened the console is no owner. With no
4034
+ // credential at all it is 401, as every route is.
4035
+ if ((found.name === "deleteRun" || found.name === "deleteAgent") && byConsoleSession(req) && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
4036
+ authFailed(`/v2${path}`, "delete_without_owner");
4037
+ throw new ApiError("forbidden", "Deleting a run or an agent takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token.");
4038
+ }
3950
4039
  // Saving, replacing or removing a secret (secret-writes.ts): the one check. Who may is mayWriteSecrets' alone (the
3951
4040
  // owner's session); which writes are secret is each plane's registered predicate, read from the body, so a token's
3952
4041
  // non-secret edit on the same route still goes through. A body that does not read counts as the plane says of none.
@@ -4025,6 +4114,20 @@ async function startHolding(options, data, checked, stops) {
4025
4114
  throw new ApiError("forbidden", "Native connections require AgentRun on the source machine, bound to loopback without a public URL. A hosted browser cannot discover your laptop.");
4026
4115
  const [, first, second] = found.pattern.exec(path);
4027
4116
  const id = first ? decodeURIComponent(first) : "";
4117
+ // A purged run or agent (DELETE /runs/{id}, /agents/{id}): every route of it but its DELETE answers 410 purged, with
4118
+ // its tombstone in the details.
4119
+ if (id && ID.test(id)) {
4120
+ if (found.name !== "deleteRun" && found.pattern.source.startsWith("^\\/runs\\/([^/]+)")) {
4121
+ const row = await store.runs.get(id);
4122
+ if (row && row.purgedAt !== null)
4123
+ throw purgedRun(row);
4124
+ }
4125
+ if (found.name !== "deleteAgent" && found.pattern.source.startsWith("^\\/agents\\/([^/]+)")) {
4126
+ const agent = await store.agents.get(id);
4127
+ if (agent && agent.purgedAt !== null)
4128
+ throw purgedAgent(agent);
4129
+ }
4130
+ }
4028
4131
  switch (found.name) {
4029
4132
  case "startSdkRun": {
4030
4133
  if (!req.headers["idempotency-key"])
@@ -4033,22 +4136,16 @@ async function startHolding(options, data, checked, stops) {
4033
4136
  // A learning SDK run's compile turn is asked on its agent's own model: checked reachable before the run starts.
4034
4137
  let compileModel;
4035
4138
  if (sdkOf(entry.revision?.body) && learnsOf(entry.revision.body.learning) && learning !== "off") {
4036
- try {
4037
- const chosen = await runModelRef(env, (await pinnedOf(entry, {})).revision);
4038
- if (chosen)
4039
- compileModel = `${chosen.provider}/${chosen.modelId}`;
4040
- }
4041
- catch { }
4139
+ const configured = await learningModelOf(env, (await pinnedOf(entry, {})).revision);
4140
+ compileModel = configured.model ?? undefined;
4042
4141
  }
4043
4142
  const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
4044
- const compile = { ...(compileModel ? { model: compileModel } : {}), check: async (model) => {
4045
- try {
4046
- const route = await askRouteOf(model, env, (one) => sdkModelRoute(one, env, "default", PI_WIRES));
4047
- await route.provider.credential();
4048
- }
4049
- catch {
4050
- throw new ApiError("agent_not_runnable", "Self-improving SDK runs need a working server model key to compile workflows. Configure Model keys or turn self-improving off.");
4051
- }
4143
+ const compile = { ...(compileModel ? { model: compileModel } : {}), check: async () => {
4144
+ // SdkRuns checks this only after its durable origin lookup, so a successful admission remains recoverable
4145
+ // when the owner has since changed its model or removed its key.
4146
+ const configured = await learningModelOf(env, entry.revision, { checkCredential: true });
4147
+ if (!configured.ready)
4148
+ throw new ApiError("agent_not_runnable", configured.reason ?? "Configure a server learning model in Settings → API Keys.");
4052
4149
  } };
4053
4150
  const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, startDeps, origin, compile, linkOrigin(req)) }));
4054
4151
  // Re-read the pinned receipt even on an in-memory replay: credentials saved since
@@ -4161,8 +4258,10 @@ async function startHolding(options, data, checked, stops) {
4161
4258
  if (body.version === undefined || (typeof body.version === "number" && body.version <= entry.version))
4162
4259
  throw invalid([{ field: "definition.version", reason: body.version === undefined ? "missing" : "not_an_option", message: `definition.version must be greater than the current one, ${entry.version}` }]);
4163
4260
  }
4164
- // The check above is a fast path; the store compares If-Match again inside the commit, so of two edits that read
4165
- // the same revision exactly one lands.
4261
+ // The checks above are a fast path on the agent as the request found it, its body read after. The commit reads the
4262
+ // agent again in its delete turn (reviseAgentOf, agentWrite): one whose body arrived once the agent was purged is
4263
+ // 410, nothing written. The store compares If-Match again inside the commit, so of two edits that read the same
4264
+ // revision exactly one lands.
4166
4265
  const { entry: edited, warnings } = await reviseAgentOf(entry, contract ? { definition: body } : body, { contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
4167
4266
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
4168
4267
  }
@@ -4176,39 +4275,47 @@ async function startHolding(options, data, checked, stops) {
4176
4275
  return send(res, 200, { revisions: page, next_cursor: nextCursor(offset + limit, all.length) });
4177
4276
  }
4178
4277
  case "setCurrent": {
4179
- const entry = await needAgent(id);
4278
+ // The body read first, outside the agent's delete turn; the move made in it (agentWrite), as an edit's revision is:
4279
+ // one whose body arrives while the agent is purged is 410 (the store refuses it too, AgentPurged).
4180
4280
  const body = await bodyOf(req);
4181
- const extra = unknownFields(body, ["revision"]);
4182
- if (extra.length)
4183
- throw invalid(extra);
4184
- const revision = body.revision;
4185
- if (typeof revision !== "string" || !ID.test(revision))
4186
- throw invalid([{ field: "revision", reason: revision === undefined ? "missing" : "wrong_type", message: "revision is a revision id of this agent" }]);
4187
- const candidate = await agents.revision(id, revision);
4188
- if (!candidate)
4189
- throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
4190
- if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
4191
- throw new ApiError("input_invalid", "This revision changes the native connection. Reconnect or verify through the native connection controls; ordinary revision restore cannot change its source or connection state.");
4192
- if (nativeOf(candidate.revision.body)) {
4193
- const overrides = nativeModelOverrides(candidate.revision.body);
4194
- if (overrides.length)
4195
- throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
4196
- const execution = nativeExecutionOverrides(candidate.revision.body);
4197
- if (execution.length)
4198
- throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
4199
- }
4200
- const moved = await agents.setCurrent(entry, revision);
4281
+ const moved = await agentWrite(id, async () => {
4282
+ const entry = await needAgent(id);
4283
+ const extra = unknownFields(body, ["revision"]);
4284
+ if (extra.length)
4285
+ throw invalid(extra);
4286
+ const revision = body.revision;
4287
+ if (typeof revision !== "string" || !ID.test(revision))
4288
+ throw invalid([{ field: "revision", reason: revision === undefined ? "missing" : "wrong_type", message: "revision is a revision id of this agent" }]);
4289
+ const candidate = await agents.revision(id, revision);
4290
+ if (!candidate)
4291
+ throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
4292
+ if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
4293
+ throw new ApiError("input_invalid", "This revision changes the native connection. Reconnect or verify through the native connection controls; ordinary revision restore cannot change its source or connection state.");
4294
+ if (nativeOf(candidate.revision.body)) {
4295
+ const overrides = nativeModelOverrides(candidate.revision.body);
4296
+ if (overrides.length)
4297
+ throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
4298
+ const execution = nativeExecutionOverrides(candidate.revision.body);
4299
+ if (execution.length)
4300
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
4301
+ }
4302
+ return agents.setCurrent(entry, revision);
4303
+ });
4201
4304
  reconcileComputer(id);
4202
4305
  return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
4203
4306
  }
4204
4307
  case "deleteAgent": {
4205
- // Another system's agent, deleted whole (agent-delete.ts); one delete of an agent at a time, the agent read in its
4206
- // turn, so a DELETE after one that finished is 404.
4308
+ // Another system's agent deleted whole; one made here purged once archived (agent-delete.ts). One delete of an agent
4309
+ // at a time, the agent read in its turn, so a DELETE after one that finished is 404 (deleted) or 204 (purged).
4207
4310
  await deleteInTurn(id, async () => {
4208
- const entry = await needAgent(id);
4209
- if (entry.agent.externalRef === null)
4210
- throw new ApiError("agent_not_external", `The agent ${id} was made here, not by another system's inline run, and is not deleted: archive it instead (POST /v2/agents/${id}/archive), which keeps its runs and stops new ones.`);
4211
- await deleteExternalAgent(agentDeleteHost, id);
4311
+ const { agent } = await needAgent(id);
4312
+ if (agent.purgedAt !== null)
4313
+ return;
4314
+ if (agent.externalRef !== null)
4315
+ return deleteExternalAgent(agentDeleteHost, id);
4316
+ if (agent.archivedAt === null)
4317
+ throw new ApiError("agent_not_archived", `The agent ${id} is not archived: archive it first (POST /v2/agents/${id}/archive), which stops new runs and turns its triggers off, then send the DELETE again. Nothing was purged.`);
4318
+ await purgeAgent(agentDeleteHost, id);
4212
4319
  });
4213
4320
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
4214
4321
  return void res.end();
@@ -4222,7 +4329,9 @@ async function startHolding(options, data, checked, stops) {
4222
4329
  // agent_archived in that same store transaction; unarchived, none turns on. Never archived first by another path,
4223
4330
  // which would turn its triggers off with no reason and leave the answer empty. Both answer the triggers off for
4224
4331
  // the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
4225
- const triggersOff = found.name === "archiveAgent" ? await triggers.agentArchived(id) : await triggers.agentUnarchived(id);
4332
+ // In the agent's delete turn (agentWrite): an unarchive sent while its purge runs waits for it and is 410, so no
4333
+ // run of it starts between the purge's live check and its tombstone.
4334
+ const triggersOff = await agentWrite(id, () => (found.name === "archiveAgent" ? triggers.agentArchived(id) : triggers.agentUnarchived(id)));
4226
4335
  // An archived agent's own computer is deleted (an unarchived one gets a new one at its next persistent run).
4227
4336
  if (found.name === "archiveAgent")
4228
4337
  reconcileComputer(id);
@@ -4293,7 +4402,8 @@ async function startHolding(options, data, checked, stops) {
4293
4402
  if (content.length > MAX_MESSAGE)
4294
4403
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
4295
4404
  // Its mcp_auth and model_key replace the run's in the steer's own write, so the turn it starts uses them.
4296
- const { mode, messageId } = await message(store, run, content, { ...(seal ? { launchSealed: seal } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) });
4405
+ // In its agent's delete turn (runWrite): a message that may open the run again never lands under its purge.
4406
+ const { mode, messageId } = await runWrite(run.agentId, run.id, () => message(store, run, content, { ...(seal ? { launchSealed: seal } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) }));
4297
4407
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
4298
4408
  const { status, state } = await runStatusState(run.id);
4299
4409
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -4321,9 +4431,19 @@ async function startHolding(options, data, checked, stops) {
4321
4431
  const { status, state } = await runStatusState(run.id);
4322
4432
  return send(res, 200, { run_id: run.id, max_cost_usd: cap, resumed, ...(messageId ? { message_id: messageId } : {}), ...(note ? { note } : {}), status, state });
4323
4433
  }
4434
+ case "deleteRun": {
4435
+ // In its agent's delete turn (an agent's delete or purge, or another purge of one of its runs, finishes first), the
4436
+ // run read in that turn, so a DELETE after one that finished is 204 again (purgeRun: a purged run is no work).
4437
+ const row = ID.test(id) ? await store.runs.get(id) : undefined;
4438
+ if (!row)
4439
+ throw new ApiError("not_found", `no run ${id}`);
4440
+ await deleteInTurn(row.agentId, () => purgeRun(agentDeleteHost, id));
4441
+ res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
4442
+ return void res.end();
4443
+ }
4324
4444
  case "stopRun": {
4325
4445
  const run = await needRun(id);
4326
- const stopped = await stopRunOverStore(store, run.id);
4446
+ const stopped = await stopRunOverStore(store, run);
4327
4447
  const { status, state } = await runStatusState(run.id);
4328
4448
  return send(res, 200, { run_id: run.id, stopped, status, state });
4329
4449
  }
@@ -4365,6 +4485,10 @@ async function startHolding(options, data, checked, stops) {
4365
4485
  throw invalid([{ field: "source", reason: "not_an_option", message: `source is one of ${GRADE_SOURCES.join(", ")}` }]);
4366
4486
  if (body.label !== undefined && (typeof body.label !== "string" || body.label.length > LABEL_MAX))
4367
4487
  throw invalid([{ field: "label", reason: "wrong_type", message: `label is a string of at most ${LABEL_MAX} characters: the grade's words` }]);
4488
+ // A run that reads ended while it still learns from that end (its look-back: store-view.ts lookingBackEnd) is graded
4489
+ // once that ends: its row is not ended yet, and the round a grade opens reopens only an ended run.
4490
+ if (!FINAL_STATES.includes(row.state) && (await lookingBackEnd(store, row.id)))
4491
+ throw new ApiError("run_learning", "The run is still learning from its answer: grade it once that ends.");
4368
4492
  if (!FINAL_STATES.includes(row.state))
4369
4493
  throw invalid([{ field: "run_id", reason: "not_allowed", message: "A run is graded once it has ended." }]);
4370
4494
  const m = (isObject(row.metrics) ? row.metrics : {});
@@ -4380,7 +4504,7 @@ async function startHolding(options, data, checked, stops) {
4380
4504
  };
4381
4505
  // The grade and its audit row are written to the agent's learning in its delete turn (agentWrite): a grade whose body
4382
4506
  // came in while a DELETE ran waits for it and finds the agent gone, so nothing is written after its learning went.
4383
- const kept = await agentWrite(row.agentId, async () => {
4507
+ const kept = await runWrite(row.agentId, row.id, async () => {
4384
4508
  // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
4385
4509
  // Its feedback round is a turn with no caller's model key: on the server's key for the run's route, else not opened.
4386
4510
  const graded = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined, (launch) => !serverKeyMissing(env, { kind: "agentic", model: launch.model, native: Boolean(launch.native) })));
@@ -4466,11 +4590,32 @@ async function startHolding(options, data, checked, stops) {
4466
4590
  // store: the hold is the run's journal, a take-over and a hand-back are command rows its runner applies; a browser's
4467
4591
  // hand-back is the browser's own answer row, as POST .../browser/hand-back writes it.
4468
4592
  const run = await needRun(id);
4469
- const answer = await computerRoute(found.name, run.id, {
4470
- ownerSession: byOwnerSession(req), token: req.headers.authorization !== undefined, accounts: owner !== undefined, body: await bodyOf(req),
4471
- }, store, { context: ctx });
4593
+ const answer = await computerRoute(found.name, run.id, await bodyOf(req), store, { context: ctx });
4472
4594
  return send(res, 200, answer, { "cache-control": "no-store" });
4473
4595
  }
4596
+ case "createRunComputerViewer": {
4597
+ // A viewer credential for the run's live view (viewer-credential.ts), for an API-only server's backend to hand its
4598
+ // user: a link on the public address to the run's open viewer, the credential in its query, the viewer's own token
4599
+ // in its fragment. A server with no backend in between has an owner who opens the view in the console: not here.
4600
+ if (!options.apiOnly)
4601
+ throw new ApiError("not_found", "A run's viewer link is minted on an API-only server alone (AGENTRUN_API_ONLY=1): here its owner opens the live view in the console.");
4602
+ const run = await needRun(id);
4603
+ const body = await bodyOf(req);
4604
+ const issues = unknownFields(body, []);
4605
+ if (issues.length)
4606
+ throw invalid(issues);
4607
+ if (!options.publicUrl)
4608
+ throw new ApiError("unsupported_here", "A run's viewer link is on this server's public address, and AGENTRUN_PUBLIC_URL is unset: set it to the address your users' browsers open this server at.");
4609
+ if (await runOver(store, run.id))
4610
+ throw new ApiError("computer_not_live", "This run has ended: its computer has no live view.");
4611
+ const link = await computerViewerLink(store, sealKey, run.id, answers(run.id));
4612
+ if (link === undefined)
4613
+ throw new ApiError("computer_not_live", "This run's computer has no live view open now: ask again once GET /v2/runs/{run_id}/computer reads live.");
4614
+ const { credential, expiresAt } = mintViewerCredential(viewerKey, run.id, Date.now());
4615
+ const [path, fragment] = link.viewer.split("#");
4616
+ const minted = `${options.publicUrl.replace(/\/+$/, "")}${path}?${VIEWER_PARAM}=${credential}${fragment === undefined ? "" : `#${fragment}`}`;
4617
+ return send(res, 201, { url: minted, expires_at: new Date(expiresAt).toISOString() }, { "cache-control": "no-store" });
4618
+ }
4474
4619
  case "startRun":
4475
4620
  case "callRunComputer":
4476
4621
  case "releaseRunComputer": {
@@ -4595,6 +4740,12 @@ async function startHolding(options, data, checked, stops) {
4595
4740
  // The workflow run's graph from its journal over the store (run-reads-over-store): an agentic run has none (404),
4596
4741
  // a run whose output is withheld is refused (403), as the route refused it.
4597
4742
  return send(res, 200, await runGraphView(store, id, runReadsDeps));
4743
+ case "getRunUsage":
4744
+ await needRun(id);
4745
+ // The run's lines from its booking (run-usage.ts), the figures its cost.usd joins: none, with why, while it is at work
4746
+ // or where its figure is not its booking's.
4747
+ // Names through the run's cut, and a withheld run refused (403), as its trace is.
4748
+ return send(res, 200, await servedRunUsage({ serverSecrets, signIns }, store, id));
4598
4749
  case "getRunTrace":
4599
4750
  await needRun(id);
4600
4751
  // The run's spans over its served Timeline rows and its journal (run-trace.ts): cut by the run's one cut, as its
@@ -4915,7 +5066,7 @@ async function startHolding(options, data, checked, stops) {
4915
5066
  // they are now and of the agent's own sign-in pointers, live and forgotten (agentPointers); a write as the
4916
5067
  // definition's: an archived agent's too.
4917
5068
  case "getAgentLearning": {
4918
- await needAgent(id);
5069
+ const entry = await needAgent(id);
4919
5070
  // The agent's learning view: its corrections, workflows and log from its learning folder; its run-fared counts and
4920
5071
  // its impact over the one store (agentLearningOverStore), from each run's launch, journal and learning end.
4921
5072
  const { counts, impact } = await agentLearningOverStore(store, id);
@@ -4924,7 +5075,9 @@ async function startHolding(options, data, checked, stops) {
4924
5075
  // that does not run first.
4925
5076
  const records = await promotionsOf(store.settings, id);
4926
5077
  const costStop = await costStopOverStore(store, id);
4927
- return send(res, 200, await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop)));
5078
+ const body = entry.revision?.body;
5079
+ const modelEnv = !body || sdkOf(body) || nativeOf(body) ? env : envAtPlace(env, resolvePlace(body.place, fallbackPlace(entry.revision.kind === "workflow" ? "workflow" : "agentic", body.tools ?? [])));
5080
+ return send(res, 200, { ...await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop)), learning_model: await learningModelOf(modelEnv, entry.revision) });
4928
5081
  }
4929
5082
  case "getLearningCost": {
4930
5083
  await needAgent(id);
@@ -5230,12 +5383,44 @@ async function startHolding(options, data, checked, stops) {
5230
5383
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
5231
5384
  res.end(text);
5232
5385
  }
5386
+ /**
5387
+ * Whether an API-only server lets this request into run `runId`'s live view, its page and files or (socket) its
5388
+ * WebSocket: from the public address alone (a page navigation may send no Origin; a socket always sends one), with the
5389
+ * viewer credential its backend minted for this run (viewer-credential.ts), not expired, its run not ended (read from
5390
+ * the store each time: its revocation). The credential, or the refusal and its authFailed reason.
5391
+ */
5392
+ async function liveAdmits(req, runId, { socket }) {
5393
+ const sent = req.headers.origin?.toLowerCase();
5394
+ if (sent === undefined ? socket : sent !== publicOrigin) {
5395
+ return { reason: "live_view_origin", error: new ApiError("forbidden", "a run's live view here is opened on this server's public address (AGENTRUN_PUBLIC_URL) alone") };
5396
+ }
5397
+ const credential = viewerCredentialOf(req);
5398
+ if (credential === undefined)
5399
+ return { reason: "no_credential", error: new ApiError("unauthenticated", "a run's live view here takes the viewer link its backend minted (POST /v2/runs/{run_id}/computer/viewer)") };
5400
+ if (!viewerCredentialFor(viewerKey, runId, credential, Date.now()) || (await runOver(store, runId))) {
5401
+ return { reason: "viewer_credential", error: new ApiError("forbidden", "this viewer link is expired, for another run, or its run has ended: ask for a new one") };
5402
+ }
5403
+ return { credential };
5404
+ }
5233
5405
  /** A run's live viewer's page and files (browser-live.ts, /v2/runs/{id}/computer/live/*): the owner's signed-in page
5234
5406
  * alone, GET or HEAD, for a viewer the run's live process has handed over. The bytes are this server's own copy of pi-browser's viewer, never the run's port's:
5235
5407
  * only the viewer's WebSocket reaches the run. */
5236
5408
  async function liveRoute(req, res, runId, family, rest) {
5237
5409
  if (req.method !== "GET" && req.method !== "HEAD")
5238
5410
  throw new ApiError("method_not_allowed", `${req.method} is not a method of a run's live view`, {}, { allow: "GET, HEAD" });
5411
+ if (options.apiOnly) {
5412
+ // API-only: no owner here (liveAdmits). The page's answer sets the credential as the cookie its files and socket carry.
5413
+ const admitted = await liveAdmits(req, runId, { socket: false });
5414
+ if ("error" in admitted) {
5415
+ authFailed(`/v2/runs/${runId}/${family}/live`, admitted.reason);
5416
+ throw admitted.error;
5417
+ }
5418
+ const handover = await liveViewerFor(store, sealKey, runId, rest);
5419
+ if (handover === undefined)
5420
+ throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
5421
+ res.setHeader("set-cookie", viewerCookie(req, runId, admitted.credential));
5422
+ return serveViewerFile(req, res, rest, (handover.kind ?? "browser") === "browser" ? "browser" : "computer");
5423
+ }
5239
5424
  if (!byOwnerSession(req)) {
5240
5425
  authFailed(`/v2/runs/${runId}/${family}/live`, req.headers.authorization === undefined ? "no_credential" : `${family}_without_session`);
5241
5426
  throw req.headers.authorization === undefined ? new ApiError("unauthenticated", `a run's live ${family} view takes the owner's password sign-in in the console`) : new ApiError("forbidden", `a run's live ${family} view takes the owner's password sign-in in the console, never a token`);
@@ -5365,9 +5550,10 @@ async function startHolding(options, data, checked, stops) {
5365
5550
  // away. Its name alone, on any port, as the HTTP routes check it.
5366
5551
  if (names && !names.has(hostName(req.headers.host) ?? ""))
5367
5552
  return deny("403 Forbidden");
5368
- // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings), whose tokens
5369
- // the attach socket takes as unknown there (machinesOnly). A run's hosted machine that dials still reaches it.
5370
- if (options.apiOnly && raw !== ATTACH_PATH)
5553
+ // API-only: paired computers are the console's (Settings), and refused with it, whose tokens the attach socket takes as
5554
+ // unknown there (machinesOnly). A run's hosted machine that dials still reaches it, and a run's computer live view takes
5555
+ // its viewer credential (below); a browser's live view stays the console's.
5556
+ if (options.apiOnly && raw !== ATTACH_PATH && viewing?.[2] !== "computer")
5371
5557
  return deny("404 Not Found");
5372
5558
  // A paired computer's driver or a hosted machine dialing the attach socket (computer-attach.ts): its token, not the
5373
5559
  // owner's, lets it in.
@@ -5383,15 +5569,23 @@ async function startHolding(options, data, checked, stops) {
5383
5569
  return deny("404 Not Found");
5384
5570
  // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
5385
5571
  // (as this request reaches it, or its public address, which a TLS proxy that rewrites Host or drops
5386
- // X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing.
5387
- const sent = String(req.headers.origin ?? "").toLowerCase();
5388
- if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
5389
- return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5390
- if (!owner || !signedIn(req, owner))
5391
- return (authFailed(raw, "live_view_without_session"), deny("401 Unauthorized"));
5572
+ // X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing. API-only:
5573
+ // liveAdmits, below.
5574
+ if (!options.apiOnly) {
5575
+ const sent = String(req.headers.origin ?? "").toLowerCase();
5576
+ if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
5577
+ return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5578
+ if (!owner || !signedIn(req, owner))
5579
+ return (authFailed(raw, "live_view_without_session"), deny("401 Unauthorized"));
5580
+ }
5392
5581
  // Once the run's WebSocket is piped to this socket, a failure here only ends it: an HTTP line would land mid-stream.
5393
5582
  let piping = false;
5394
5583
  void (async () => {
5584
+ if (options.apiOnly) {
5585
+ const admitted = await liveAdmits(req, viewing[1], { socket: true });
5586
+ if ("error" in admitted)
5587
+ return (authFailed(raw, admitted.reason), deny(admitted.error.code === "unauthenticated" ? "401 Unauthorized" : "403 Forbidden"));
5588
+ }
5395
5589
  const run = ID.test(viewing[1]) ? await momentOverStore(store, viewing[1], viewDepsFor(ownOriginOf())) : undefined;
5396
5590
  // The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim): none for a run no
5397
5591
  // runner holds. A /computer/live socket reaches a viewer of every kind, a
@@ -5404,11 +5598,16 @@ async function startHolding(options, data, checked, stops) {
5404
5598
  if (socket.destroyed || closing)
5405
5599
  return void socket.destroy();
5406
5600
  // Checked again after the lookup, then for as long as the socket is open: the sessions that let it in, and no other.
5407
- const held = heldSessions(req);
5408
- const admitted = () => held.some((value) => owner.valid(value));
5409
- if (!admitted())
5410
- return deny("401 Unauthorized");
5411
- viewers.watch(socket, admitted);
5601
+ // API-only: the credential's run not ended, read from the store (its revocation); its expiry bounds the opening alone.
5602
+ if (options.apiOnly)
5603
+ viewers.watch(socket, async () => !(await runOver(store, run.id)));
5604
+ else {
5605
+ const held = heldSessions(req);
5606
+ const admitted = () => held.some((value) => owner.valid(value));
5607
+ if (!admitted())
5608
+ return deny("401 Unauthorized");
5609
+ viewers.watch(socket, admitted);
5610
+ }
5412
5611
  proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reachForRun(reach, run.id));
5413
5612
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
5414
5613
  };