@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/server.js CHANGED
@@ -67,12 +67,13 @@ import { screenWaitEnded } from "./browser-wait-ended.js";
67
67
  import { durationMs, logLine } from "./print.js";
68
68
  import { keepPresence, refusedEnd, runnersRefused } from "./runner/presence.js";
69
69
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
70
- 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";
71
71
  import { healEndedCosts } from "./cost-heal.js";
72
72
  import { createLister } from "./run-listing.js";
73
73
  import { HELD_WAITS } from "./runner/journal-kinds.js";
74
74
  import { servedTimelineRows } from "./run-timeline-served.js";
75
75
  import { servedRunTrace } from "./run-trace.js";
76
+ import { servedRunUsage } from "./run-usage.js";
76
77
  import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
77
78
  import { agentPointers, WITHHELD_LEARNING } from "./handed-values.js";
78
79
  import { runCutValues } from "./run-cut.js";
@@ -83,19 +84,19 @@ import { triggerTargets } from "./trigger-targets.js";
83
84
  import { labelFilter, labelsIssues } from "./run-labels.js";
84
85
  import { listRuns as listRunsOverStore, readRun as readRunOverStore, runOfOrigin as runOfOriginOverStore } from "./store-reads/runs.js";
85
86
  import { runEntries } from "./store-reads/journal.js";
86
- import { metersOverStore } from "./store-reads/cap.js";
87
+ import { metersOverStore, spendOverStore } from "./store-reads/cap.js";
87
88
  import { watchRun } from "./live/stream.js";
88
89
  import { stats as statsOverStore } from "./store-reads/stats.js";
89
90
  import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
90
91
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
91
92
  import { openStore, openRunLaunch, sealRunLaunch, StoreLaunchMissing, StoreOwned, storeTarget } from "./store/index.js";
92
- import { agentDeleting, answerOf, logged } from "./agents.js";
93
+ import { agentDeleting, answerOf, logged, purgedAgent } from "./agents.js";
93
94
  import { keepGrade } from "./runner/feedback-round.js";
94
95
  import { gradeRow, notAuditableOf } from "./runner/audit.js";
95
- import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf } from "./learn/audit.js";
96
+ import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf, shadowRunId } from "./learn/audit.js";
96
97
  import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
97
98
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
98
- 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";
99
100
  import { workflowNodesOf } from "./learn/workflow-nodes.js";
100
101
  import { deleteLearning } from "./learn/delete.js";
101
102
  import { runModelRef } from "./model.js";
@@ -121,7 +122,7 @@ import { analyticsFilter, analyticsView, statsView } from "./stats.js";
121
122
  import { joinedBasis } from "./runner/metrics.js";
122
123
  import { agentLoopOverStore } from "./store-reads/loop.js";
123
124
  import { printable } from "./learn/index.js";
124
- 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";
125
126
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
126
127
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
127
128
  import { toolKeysOverStore } from "./tool-keys-store.js";
@@ -173,7 +174,7 @@ import { recordingsFolder } from "./workspace/paths.js";
173
174
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
174
175
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
175
176
  import { runOver } from "./computer-commands.js";
176
- import { mintViewerCredential, VIEWER_PARAM, viewerCookie, viewerCredentialFor, viewerCredentialKey, viewerCredentialOf, viewerExpiry } from "./viewer-credential.js";
177
+ import { mintViewerCredential, VIEWER_PARAM, viewerCookie, viewerCredentialFor, viewerCredentialKey, viewerCredentialOf } from "./viewer-credential.js";
177
178
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
178
179
  import { createAttachRoutes, liveRelays, pairedView } from "./computer-attach.js";
179
180
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
@@ -184,12 +185,12 @@ import { noAccount, openAccount } from "./email/account.js";
184
185
  import { emailRoute } from "./email/routes.js";
185
186
  import { addressForms, openCalendar } from "./calendar/address.js";
186
187
  import { calendarRoute } from "./calendar/routes.js";
187
- 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";
188
189
  import { computerOfPlace } from "./computer-setting.js";
189
190
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
190
191
  import { fauxComputers } from "./faux-computers.js";
191
192
  import { writesHeld } from "./workspace.js";
192
- import { deleteExternalAgent, oneAtATime } from "./agent-delete.js";
193
+ import { deleteExternalAgent, oneAtATime, purgeAgent, purgeRun, purgingKey } from "./agent-delete.js";
193
194
  import { agentComputerHoldKey } from "./workspace/agent-computer.js";
194
195
  import { sdkRunKey } from "./sdk/runs.js";
195
196
  import { waitEndedKey } from "./browser-wait-ended.js";
@@ -267,6 +268,19 @@ async function tokenIn(file) {
267
268
  }
268
269
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
269
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
+ }
270
284
  export const ROUTES = [
271
285
  { method: "GET", pattern: /^\/observations$/, name: "getObservations" },
272
286
  { method: "GET", pattern: /^\/connectors$/, name: "listRemoteConnectors" },
@@ -315,6 +329,8 @@ export const ROUTES = [
315
329
  { method: "POST", pattern: /^\/runs$/, name: "createInlineRun" },
316
330
  { method: "GET", pattern: /^\/runs\/([^/]+)$/, name: "getRun" },
317
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" },
318
334
  { method: "GET", pattern: /^\/runs\/([^/]+)\/timeline$/, name: "getTimeline" },
319
335
  { method: "POST", pattern: /^\/runs\/([^/]+)\/messages$/, name: "sendMessage" },
320
336
  { method: "POST", pattern: /^\/runs\/([^/]+)\/stop$/, name: "stopRun" },
@@ -327,6 +343,8 @@ export const ROUTES = [
327
343
  { method: "GET", pattern: /^\/runs\/([^/]+)\/graph$/, name: "getRunGraph" },
328
344
  // A run's trace (run-trace.ts): each model request and tool call as a span, with its time, tokens and cost.
329
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" },
330
348
  { method: "POST", pattern: /^\/workflows\/validate$/, name: "validateWorkflow" },
331
349
  { method: "POST", pattern: /^\/runs\/([^/]+)\/pause$/, name: "pauseRun" },
332
350
  { method: "POST", pattern: /^\/runs\/([^/]+)\/resume$/, name: "resumeRun" },
@@ -1144,12 +1162,8 @@ async function startHolding(options, data, checked, stops) {
1144
1162
  const sealKey = seal.key;
1145
1163
  // SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
1146
1164
  const sdkSecret = sdkRunSecret(sealKey);
1147
- // An API-only server's viewer credentials (viewer-credential.ts) are signed with another key from it: every server on
1148
- // this store checks them alike, across restarts.
1165
+ // An API-only server's viewer credentials: viewer-credential.ts.
1149
1166
  const viewerKey = viewerCredentialKey(sealKey);
1150
- /** Whether `credential` opens run `runId`'s live view now: minted for that run, not expired, and its run not ended,
1151
- * read from the store each time (its revocation). */
1152
- const viewerHolds = async (credential, runId) => credential !== undefined && viewerCredentialFor(viewerKey, runId, credential, Date.now()) && !(await runOver(store, runId));
1153
1167
  // Each run's viewers are asked under that run's key (live-reach.ts reachForRun).
1154
1168
  const answers = (runId) => (handover) => viewerAnswers(handover, reachForRun(reach, runId));
1155
1169
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
@@ -1587,6 +1601,8 @@ async function startHolding(options, data, checked, stops) {
1587
1601
  getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1588
1602
  needAgent,
1589
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),
1590
1606
  runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
1591
1607
  completedOutput: async (runId) => {
1592
1608
  const view = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
@@ -2217,21 +2233,42 @@ async function startHolding(options, data, checked, stops) {
2217
2233
  * so nothing is written after the delete passed over it. The request's body is read before, outside the turn. */
2218
2234
  const agentWrite = (id, work) => deleteInTurn(id, async () => {
2219
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);
2220
2239
  if (entry.agent.archivedAt && entry.agent.externalRef !== null)
2221
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);
2222
2257
  return work();
2223
2258
  });
2224
2259
  const AGAIN = "It starts no run meanwhile: send the DELETE again to finish it.";
2225
- /** `work`, a thing a deleted agent owns elsewhere deleted there: a refusal of one of `codes` (it is not deleted there
2226
- * yet) answered as the delete answers each such one, 503 unavailable, retryable, saying to send the DELETE again. */
2227
- 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) => {
2228
2265
  try {
2229
2266
  await work();
2230
2267
  }
2231
2268
  catch (error) {
2232
2269
  if (!(error instanceof ApiError && codes.includes(error.code)))
2233
2270
  throw error;
2234
- 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 });
2235
2272
  }
2236
2273
  };
2237
2274
  /** What DELETE /agents/{id} does outside the store's rows, on this server (agent-delete.ts AgentDeleteHost). */
@@ -2283,13 +2320,20 @@ async function startHolding(options, data, checked, stops) {
2283
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.
2284
2321
  await notYetWith(() => archil.removeAgentDisk({ id: agentId, archived: true, external: true, liveOn: (diskId) => liveRunsOnDisk(store.runs, agentId, diskId) }), ["upstream_failed", "precondition_failed", "unavailable"]);
2285
2322
  },
2286
- forgetRun: async (agentId, runId) => {
2323
+ forgetRun: async (agentId, runId, alone) => {
2324
+ const again = alone ? RUN_AGAIN : AGAIN;
2287
2325
  // Its own folder on a disk its launch named (the caller's disk, which stays): read from its launch record, which goes
2288
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
2289
- // 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.
2290
2329
  const launched = await store.runs.launch(runId).then((row) => readLaunchBody(row.body)?.archilDisk, (error) => (error instanceof StoreLaunchMissing ? undefined : Promise.reject(error)));
2291
2330
  if (launched?.kind === "launch")
2292
- 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
+ }
2293
2337
  // The run's folder (its work and what sits beside it), its scratch and its native context, on this machine.
2294
2338
  for (const folder of [dirname(runFolder(data, agentId, runId)), scratchFolder(data, agentId, runId), join(data, "native-context", runId)])
2295
2339
  await rm(folder, { recursive: true, force: true });
@@ -2307,6 +2351,25 @@ async function startHolding(options, data, checked, stops) {
2307
2351
  await rm(join(data, "scratch", agentDirName(agentId)), { recursive: true, force: true });
2308
2352
  await forgetKept("agent", agentId);
2309
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
+ },
2310
2373
  waitMs: options.agentDeleteWaitMs ?? 30_000,
2311
2374
  pollMs: 200,
2312
2375
  ...(options.agentDeleteAt ? { at: options.agentDeleteAt } : {}),
@@ -2676,7 +2739,10 @@ async function startHolding(options, data, checked, stops) {
2676
2739
  warnings = saved.warnings;
2677
2740
  return saved.stamp;
2678
2741
  };
2679
- 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) });
2680
2746
  reconcileComputer(entry.agent.id);
2681
2747
  return { entry: edited, warnings };
2682
2748
  }
@@ -3499,11 +3565,12 @@ async function startHolding(options, data, checked, stops) {
3499
3565
  }
3500
3566
  // ---- usage ----------------------------------------------------------------------------------------------------------
3501
3567
  // Each ended run's meters, over the one store (store-reads/cap metersOverStore, cap.ts meterFiguresFrom over A's journal):
3502
- // kept, as a settled run's journal no longer changes, keyed by its end, so a run opened again and ended again is read
3503
- // 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.
3504
3571
  const endedMeters = new Map();
3505
3572
  const metersOf = async (row) => {
3506
- const key = `${row.id} ${row.endedAt}`;
3573
+ const key = `${row.id} ${row.endedAt} ${row.costUsd}`;
3507
3574
  let meters = endedMeters.get(key);
3508
3575
  if (!meters) {
3509
3576
  // An ended run's meter figures over the one store: cap.ts meterFiguresFrom over A's journal, its paid tools' charges
@@ -3945,23 +4012,30 @@ async function startHolding(options, data, checked, stops) {
3945
4012
  authFailed(`/v2${path}`, "replay_without_session");
3946
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).");
3947
4014
  }
3948
- // A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
3949
- // approving a note is (never a token a run, an MCP client or a script may hold). An API-only server has no owner: there
3950
- // the server's token, its backend's own, takes a run's computer, checked below as every route's token is.
3951
- if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || (found.name === "getRunComputer" && !options.apiOnly)) && !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) {
3952
4021
  const what = found.name.endsWith("Browser") ? "browser" : "computer";
3953
4022
  authFailed(`/v2${path}`, `${what}_without_session`);
3954
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).`);
3955
4024
  }
3956
- // A run's desktop or phone view drives it once taken over: the owner's signed-in page alone (computer-routes.ts decides).
3957
- if (COMPUTER_ROUTES.has(found.name) && !options.apiOnly && !byOwnerSession(req) && req.headers.authorization !== undefined)
3958
- authFailed(`/v2${path}`, "computer_without_session");
3959
4025
  // Answering a tool call that waits for approval (tool-gate.ts) is the same: the owner's signed-in page alone, never a
3960
4026
  // token, which the run's own process, an agent's MCP client or a script may hold.
3961
4027
  if (found.name === "answerApproval" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3962
4028
  authFailed(`/v2${path}`, "approve_without_session");
3963
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).");
3964
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
+ }
3965
4039
  // Saving, replacing or removing a secret (secret-writes.ts): the one check. Who may is mayWriteSecrets' alone (the
3966
4040
  // owner's session); which writes are secret is each plane's registered predicate, read from the body, so a token's
3967
4041
  // non-secret edit on the same route still goes through. A body that does not read counts as the plane says of none.
@@ -4040,6 +4114,20 @@ async function startHolding(options, data, checked, stops) {
4040
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.");
4041
4115
  const [, first, second] = found.pattern.exec(path);
4042
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
+ }
4043
4131
  switch (found.name) {
4044
4132
  case "startSdkRun": {
4045
4133
  if (!req.headers["idempotency-key"])
@@ -4170,8 +4258,10 @@ async function startHolding(options, data, checked, stops) {
4170
4258
  if (body.version === undefined || (typeof body.version === "number" && body.version <= entry.version))
4171
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}` }]);
4172
4260
  }
4173
- // The check above is a fast path; the store compares If-Match again inside the commit, so of two edits that read
4174
- // 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.
4175
4265
  const { entry: edited, warnings } = await reviseAgentOf(entry, contract ? { definition: body } : body, { contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
4176
4266
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
4177
4267
  }
@@ -4185,39 +4275,47 @@ async function startHolding(options, data, checked, stops) {
4185
4275
  return send(res, 200, { revisions: page, next_cursor: nextCursor(offset + limit, all.length) });
4186
4276
  }
4187
4277
  case "setCurrent": {
4188
- 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).
4189
4280
  const body = await bodyOf(req);
4190
- const extra = unknownFields(body, ["revision"]);
4191
- if (extra.length)
4192
- throw invalid(extra);
4193
- const revision = body.revision;
4194
- if (typeof revision !== "string" || !ID.test(revision))
4195
- throw invalid([{ field: "revision", reason: revision === undefined ? "missing" : "wrong_type", message: "revision is a revision id of this agent" }]);
4196
- const candidate = await agents.revision(id, revision);
4197
- if (!candidate)
4198
- throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
4199
- if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
4200
- 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.");
4201
- if (nativeOf(candidate.revision.body)) {
4202
- const overrides = nativeModelOverrides(candidate.revision.body);
4203
- if (overrides.length)
4204
- throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
4205
- const execution = nativeExecutionOverrides(candidate.revision.body);
4206
- if (execution.length)
4207
- throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
4208
- }
4209
- 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
+ });
4210
4304
  reconcileComputer(id);
4211
4305
  return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
4212
4306
  }
4213
4307
  case "deleteAgent": {
4214
- // Another system's agent, deleted whole (agent-delete.ts); one delete of an agent at a time, the agent read in its
4215
- // 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).
4216
4310
  await deleteInTurn(id, async () => {
4217
- const entry = await needAgent(id);
4218
- if (entry.agent.externalRef === null)
4219
- 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.`);
4220
- 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);
4221
4319
  });
4222
4320
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
4223
4321
  return void res.end();
@@ -4231,7 +4329,9 @@ async function startHolding(options, data, checked, stops) {
4231
4329
  // agent_archived in that same store transaction; unarchived, none turns on. Never archived first by another path,
4232
4330
  // which would turn its triggers off with no reason and leave the answer empty. Both answer the triggers off for
4233
4331
  // the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
4234
- 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)));
4235
4335
  // An archived agent's own computer is deleted (an unarchived one gets a new one at its next persistent run).
4236
4336
  if (found.name === "archiveAgent")
4237
4337
  reconcileComputer(id);
@@ -4302,7 +4402,8 @@ async function startHolding(options, data, checked, stops) {
4302
4402
  if (content.length > MAX_MESSAGE)
4303
4403
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
4304
4404
  // Its mcp_auth and model_key replace the run's in the steer's own write, so the turn it starts uses them.
4305
- 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 } : {}) }));
4306
4407
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
4307
4408
  const { status, state } = await runStatusState(run.id);
4308
4409
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -4330,9 +4431,19 @@ async function startHolding(options, data, checked, stops) {
4330
4431
  const { status, state } = await runStatusState(run.id);
4331
4432
  return send(res, 200, { run_id: run.id, max_cost_usd: cap, resumed, ...(messageId ? { message_id: messageId } : {}), ...(note ? { note } : {}), status, state });
4332
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
+ }
4333
4444
  case "stopRun": {
4334
4445
  const run = await needRun(id);
4335
- const stopped = await stopRunOverStore(store, run.id);
4446
+ const stopped = await stopRunOverStore(store, run);
4336
4447
  const { status, state } = await runStatusState(run.id);
4337
4448
  return send(res, 200, { run_id: run.id, stopped, status, state });
4338
4449
  }
@@ -4374,6 +4485,10 @@ async function startHolding(options, data, checked, stops) {
4374
4485
  throw invalid([{ field: "source", reason: "not_an_option", message: `source is one of ${GRADE_SOURCES.join(", ")}` }]);
4375
4486
  if (body.label !== undefined && (typeof body.label !== "string" || body.label.length > LABEL_MAX))
4376
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.");
4377
4492
  if (!FINAL_STATES.includes(row.state))
4378
4493
  throw invalid([{ field: "run_id", reason: "not_allowed", message: "A run is graded once it has ended." }]);
4379
4494
  const m = (isObject(row.metrics) ? row.metrics : {});
@@ -4389,7 +4504,7 @@ async function startHolding(options, data, checked, stops) {
4389
4504
  };
4390
4505
  // The grade and its audit row are written to the agent's learning in its delete turn (agentWrite): a grade whose body
4391
4506
  // came in while a DELETE ran waits for it and finds the agent gone, so nothing is written after its learning went.
4392
- const kept = await agentWrite(row.agentId, async () => {
4507
+ const kept = await runWrite(row.agentId, row.id, async () => {
4393
4508
  // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
4394
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.
4395
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) })));
@@ -4475,9 +4590,7 @@ async function startHolding(options, data, checked, stops) {
4475
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
4476
4591
  // hand-back is the browser's own answer row, as POST .../browser/hand-back writes it.
4477
4592
  const run = await needRun(id);
4478
- const answer = await computerRoute(found.name, run.id, {
4479
- ownerSession: byOwnerSession(req), token: req.headers.authorization !== undefined, apiOnly: options.apiOnly === true, accounts: owner !== undefined, body: await bodyOf(req),
4480
- }, store, { context: ctx });
4593
+ const answer = await computerRoute(found.name, run.id, await bodyOf(req), store, { context: ctx });
4481
4594
  return send(res, 200, answer, { "cache-control": "no-store" });
4482
4595
  }
4483
4596
  case "createRunComputerViewer": {
@@ -4627,6 +4740,12 @@ async function startHolding(options, data, checked, stops) {
4627
4740
  // The workflow run's graph from its journal over the store (run-reads-over-store): an agentic run has none (404),
4628
4741
  // a run whose output is withheld is refused (403), as the route refused it.
4629
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));
4630
4749
  case "getRunTrace":
4631
4750
  await needRun(id);
4632
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
@@ -5264,6 +5383,25 @@ async function startHolding(options, data, checked, stops) {
5264
5383
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
5265
5384
  res.end(text);
5266
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
+ }
5267
5405
  /** A run's live viewer's page and files (browser-live.ts, /v2/runs/{id}/computer/live/*): the owner's signed-in page
5268
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:
5269
5407
  * only the viewer's WebSocket reaches the run. */
@@ -5271,27 +5409,16 @@ async function startHolding(options, data, checked, stops) {
5271
5409
  if (req.method !== "GET" && req.method !== "HEAD")
5272
5410
  throw new ApiError("method_not_allowed", `${req.method} is not a method of a run's live view`, {}, { allow: "GET, HEAD" });
5273
5411
  if (options.apiOnly) {
5274
- // API-only: no owner here. The viewer credential its backend minted for this run (viewer-credential.ts), on the
5275
- // public address alone: a navigation sends no Origin, any other request this page's own. The page's answer sets it as
5276
- // the cookie its files and socket carry.
5277
- const sent = req.headers.origin;
5278
- if (sent !== undefined && sent.toLowerCase() !== publicOrigin) {
5279
- authFailed(`/v2/runs/${runId}/${family}/live`, "live_view_origin");
5280
- throw new ApiError("forbidden", "a run's live view here is opened on this server's public address (AGENTRUN_PUBLIC_URL) alone");
5281
- }
5282
- const credential = viewerCredentialOf(req);
5283
- if (credential === undefined) {
5284
- authFailed(`/v2/runs/${runId}/${family}/live`, "no_credential");
5285
- throw new ApiError("unauthenticated", "a run's live view here takes the viewer link its backend minted (POST /v2/runs/{run_id}/computer/viewer)");
5286
- }
5287
- if (!(await viewerHolds(credential, runId))) {
5288
- authFailed(`/v2/runs/${runId}/${family}/live`, "viewer_credential");
5289
- throw new ApiError("forbidden", "this viewer link is expired, for another run, or its run has ended: ask for a new one");
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;
5290
5417
  }
5291
5418
  const handover = await liveViewerFor(store, sealKey, runId, rest);
5292
5419
  if (handover === undefined)
5293
5420
  throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
5294
- res.setHeader("set-cookie", viewerCookie(req, runId, credential, viewerExpiry(credential), Date.now()));
5421
+ res.setHeader("set-cookie", viewerCookie(req, runId, admitted.credential));
5295
5422
  return serveViewerFile(req, res, rest, (handover.kind ?? "browser") === "browser" ? "browser" : "computer");
5296
5423
  }
5297
5424
  if (!byOwnerSession(req)) {
@@ -5442,17 +5569,10 @@ async function startHolding(options, data, checked, stops) {
5442
5569
  return deny("404 Not Found");
5443
5570
  // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
5444
5571
  // (as this request reaches it, or its public address, which a TLS proxy that rewrites Host or drops
5445
- // X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing. API-only: the
5446
- // public address alone, where the minted link opens the page, and the viewer credential for this run (its cookie).
5447
- const sent = String(req.headers.origin ?? "").toLowerCase();
5448
- const credential = options.apiOnly ? viewerCredentialOf(req) : undefined;
5449
- if (options.apiOnly) {
5450
- if (sent === "" || sent !== publicOrigin)
5451
- return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5452
- if (credential === undefined)
5453
- return (authFailed(raw, "no_credential"), deny("401 Unauthorized"));
5454
- }
5455
- else {
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();
5456
5576
  if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
5457
5577
  return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5458
5578
  if (!owner || !signedIn(req, owner))
@@ -5461,8 +5581,11 @@ async function startHolding(options, data, checked, stops) {
5461
5581
  // Once the run's WebSocket is piped to this socket, a failure here only ends it: an HTTP line would land mid-stream.
5462
5582
  let piping = false;
5463
5583
  void (async () => {
5464
- if (options.apiOnly && !(await viewerHolds(credential, viewing[1])))
5465
- return (authFailed(raw, "viewer_credential"), deny("403 Forbidden"));
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
+ }
5466
5589
  const run = ID.test(viewing[1]) ? await momentOverStore(store, viewing[1], viewDepsFor(ownOriginOf())) : undefined;
5467
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
5468
5591
  // runner holds. A /computer/live socket reaches a viewer of every kind, a