@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.31

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 (172) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/README.md +739 -116
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +18 -7
  6. package/dist/agents.js +19 -10
  7. package/dist/app.js +101 -26
  8. package/dist/background.d.ts +29 -0
  9. package/dist/background.js +397 -0
  10. package/dist/box-egress-vm.d.ts +125 -0
  11. package/dist/box-egress-vm.js +350 -0
  12. package/dist/box-egress.d.ts +99 -0
  13. package/dist/box-egress.js +259 -0
  14. package/dist/box-image.d.ts +1 -1
  15. package/dist/box-image.js +9 -7
  16. package/dist/box-relay-vm.d.ts +84 -0
  17. package/dist/box-relay-vm.js +410 -0
  18. package/dist/box-relay.d.ts +8 -5
  19. package/dist/box-relay.js +14 -9
  20. package/dist/boxes.d.ts +28 -5
  21. package/dist/boxes.js +44 -18
  22. package/dist/browser-cost.d.ts +41 -0
  23. package/dist/browser-cost.js +158 -0
  24. package/dist/cap.d.ts +130 -21
  25. package/dist/cap.js +339 -67
  26. package/dist/cli.js +30 -4
  27. package/dist/coding-tools.d.ts +7 -3
  28. package/dist/coding-tools.js +16 -10
  29. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  30. package/dist/console/assets/index-CnJBf7Lc.js +486 -0
  31. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/content-filter.d.ts +7 -0
  34. package/dist/content-filter.js +23 -0
  35. package/dist/decision-rows.d.ts +11 -3
  36. package/dist/decision-rows.js +18 -11
  37. package/dist/decisions.d.ts +3 -3
  38. package/dist/decisions.js +4 -3
  39. package/dist/errors.d.ts +2 -0
  40. package/dist/errors.js +5 -2
  41. package/dist/files.d.ts +9 -1
  42. package/dist/files.js +10 -2
  43. package/dist/grade.d.ts +11 -11
  44. package/dist/grade.js +43 -55
  45. package/dist/graph-served.d.ts +23 -0
  46. package/dist/graph-served.js +75 -0
  47. package/dist/graph-view.d.ts +7 -5
  48. package/dist/graph-view.js +10 -3
  49. package/dist/harness-app.d.ts +4 -2
  50. package/dist/harness-app.js +110 -19
  51. package/dist/harness-opencode/adapter.d.ts +45 -0
  52. package/dist/harness-opencode/adapter.js +272 -0
  53. package/dist/harness-opencode/binary.d.ts +18 -0
  54. package/dist/harness-opencode/binary.js +87 -0
  55. package/dist/harness-opencode/config.d.ts +24 -0
  56. package/dist/harness-opencode/config.js +61 -0
  57. package/dist/harness-opencode/harness.d.ts +77 -0
  58. package/dist/harness-opencode/harness.js +620 -0
  59. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  60. package/dist/harness-opencode/host/mcp.js +208 -0
  61. package/dist/harness-opencode/host/policy.d.ts +71 -0
  62. package/dist/harness-opencode/host/policy.js +419 -0
  63. package/dist/harness-opencode/host/server.d.ts +55 -0
  64. package/dist/harness-opencode/host/server.js +165 -0
  65. package/dist/harness-opencode/index.d.ts +9 -0
  66. package/dist/harness-opencode/index.js +6 -0
  67. package/dist/harness-opencode/verify.d.ts +32 -0
  68. package/dist/harness-opencode/verify.js +75 -0
  69. package/dist/harness-opencode/versions.d.ts +33 -0
  70. package/dist/harness-opencode/versions.js +64 -0
  71. package/dist/harness.d.ts +4 -1
  72. package/dist/harness.js +5 -2
  73. package/dist/host-check.d.ts +12 -0
  74. package/dist/host-check.js +34 -0
  75. package/dist/host-tools.d.ts +12 -2
  76. package/dist/host-tools.js +26 -12
  77. package/dist/host.js +6 -2
  78. package/dist/hosted-search.js +5 -1
  79. package/dist/import.d.ts +2 -2
  80. package/dist/import.js +4 -3
  81. package/dist/key-check.d.ts +3 -2
  82. package/dist/key-check.js +7 -3
  83. package/dist/key-refusal.js +8 -4
  84. package/dist/key-words.d.ts +37 -0
  85. package/dist/key-words.js +40 -0
  86. package/dist/learn/check.d.ts +10 -1
  87. package/dist/learn/check.js +19 -1
  88. package/dist/learn/grade.d.ts +6 -2
  89. package/dist/learn/grade.js +28 -14
  90. package/dist/learn/index.d.ts +3 -3
  91. package/dist/learn/index.js +3 -3
  92. package/dist/learn/notes.js +2 -1
  93. package/dist/learn/reflect.d.ts +2 -2
  94. package/dist/learn/reflect.js +53 -5
  95. package/dist/learn/secrets.js +28 -8
  96. package/dist/learn/skills.d.ts +19 -4
  97. package/dist/learn/skills.js +95 -6
  98. package/dist/learned-workflow.d.ts +59 -0
  99. package/dist/learned-workflow.js +191 -0
  100. package/dist/learning-routes.d.ts +30 -1
  101. package/dist/learning-routes.js +173 -19
  102. package/dist/learning-run.d.ts +8 -6
  103. package/dist/learning-run.js +70 -27
  104. package/dist/learning-words.d.ts +12 -5
  105. package/dist/learning-words.js +34 -13
  106. package/dist/learning.d.ts +52 -3
  107. package/dist/learning.js +204 -4
  108. package/dist/mcp-gateway.d.ts +96 -0
  109. package/dist/mcp-gateway.js +408 -0
  110. package/dist/mcp-meta.d.ts +17 -0
  111. package/dist/mcp-meta.js +38 -0
  112. package/dist/mcp-servers.d.ts +33 -9
  113. package/dist/mcp-servers.js +58 -10
  114. package/dist/mcp.js +5 -5
  115. package/dist/model.d.ts +13 -11
  116. package/dist/model.js +11 -10
  117. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  118. package/dist/openapi.js +407 -54
  119. package/dist/page.d.ts +2 -0
  120. package/dist/page.js +3 -0
  121. package/dist/paid-calls.d.ts +5 -1
  122. package/dist/paid-calls.js +1 -1
  123. package/dist/pause.d.ts +2 -0
  124. package/dist/place.d.ts +29 -5
  125. package/dist/place.js +51 -11
  126. package/dist/print.d.ts +7 -0
  127. package/dist/print.js +13 -0
  128. package/dist/propose.d.ts +2 -0
  129. package/dist/propose.js +38 -8
  130. package/dist/request-start.d.ts +12 -4
  131. package/dist/request-start.js +139 -15
  132. package/dist/run-box.d.ts +56 -4
  133. package/dist/run-box.js +183 -23
  134. package/dist/runnable.d.ts +13 -3
  135. package/dist/runnable.js +63 -6
  136. package/dist/runs.d.ts +266 -37
  137. package/dist/runs.js +884 -90
  138. package/dist/secrets.d.ts +27 -0
  139. package/dist/secrets.js +38 -2
  140. package/dist/server.d.ts +141 -36
  141. package/dist/server.js +562 -118
  142. package/dist/sign-ins.d.ts +99 -0
  143. package/dist/sign-ins.js +288 -0
  144. package/dist/skills.d.ts +16 -4
  145. package/dist/skills.js +35 -7
  146. package/dist/stats.d.ts +7 -2
  147. package/dist/stats.js +28 -7
  148. package/dist/tool-gate.d.ts +281 -0
  149. package/dist/tool-gate.js +585 -0
  150. package/dist/tool-keys.d.ts +48 -11
  151. package/dist/tool-keys.js +46 -8
  152. package/dist/tool-plane.d.ts +116 -27
  153. package/dist/tool-plane.js +232 -50
  154. package/dist/tools.d.ts +69 -14
  155. package/dist/tools.js +148 -26
  156. package/dist/trigger-secrets.d.ts +32 -0
  157. package/dist/trigger-secrets.js +143 -0
  158. package/dist/triggers.d.ts +439 -0
  159. package/dist/triggers.js +863 -0
  160. package/dist/turn-end.d.ts +3 -2
  161. package/dist/turn-end.js +3 -2
  162. package/dist/usage-lines.d.ts +26 -0
  163. package/dist/usage-lines.js +28 -0
  164. package/dist/validate.d.ts +2 -0
  165. package/dist/validate.js +11 -2
  166. package/dist/web-fetch.js +3 -3
  167. package/dist/webhooks.d.ts +11 -4
  168. package/dist/webhooks.js +17 -1
  169. package/launcher/agentrun-serve +1 -1
  170. package/package.json +16 -14
  171. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  172. package/dist/console/assets/index-By-jkqki.css +0 -1
package/dist/runs.js CHANGED
@@ -5,19 +5,22 @@
5
5
  // again on its directory, and resumes from its store.
6
6
  import { spawn } from "node:child_process";
7
7
  import { createHash, randomBytes } from "node:crypto";
8
- import { closeSync, existsSync, openSync, rmSync, writeFileSync } from "node:fs";
8
+ import { closeSync, existsSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
9
  import { open as openFile, rm, stat } from "node:fs/promises";
10
10
  import { join } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
13
13
  import { processAlive } from "@parcha/agentrun-kernel/host";
14
+ import { doorTook } from "@parcha/pi-durable-disk";
14
15
  import { AgentHomeError } from "@parcha/pi-durable-agent";
15
- import { registerLabel, registerTurnEnding, runMetricsWithDecisions, timelineOf, timelineReducer } from "@parcha/pi-durable-agent/timeline";
16
+ import { chargedTool, isMessageRow, registerLabel, registerTurnEnding, REQUEST_STARTED, runMetricsWithDecisions, timelineOf, timelineReducer } from "@parcha/pi-durable-agent/timeline";
16
17
  import { HARNESS_LOG_EVENT, harnessModelKeys, thinkingFor } from "./adapters.js";
17
18
  import { DEFAULT_HARNESS, harnessOfBody, steersMidTurn } from "./harness.js";
18
19
  import { hostMemory, memoryFull, neverFits, runMibOf, runsMemoryMib } from "./host.js";
19
20
  import { storeBusy, storeError, whenFree } from "./agents.js";
20
- import { FOLLOW_UP_OPEN_ENV, LAUNCH_LOST, readJson, RUN_CANCELLED, RUN_DOOR_TOKEN, RUN_LAUNCHING, RUN_META, runDoorToken, writeWhole } from "./files.js";
21
+ import { FOLLOW_UP_OPEN_ENV, LAUNCH_LOST, readJson, RUN_CANCELLED, RUN_DOOR_TOKEN, RUN_LAUNCHING, RUN_META, runDoorToken, SETUP_LOST, writeDurableSync, writeWhole } from "./files.js";
22
+ import { MCP_PIN, mcpCredentialsOf, mcpPinOf } from "./mcp-gateway.js";
23
+ import { META_REASON, metaToolOf } from "./mcp-meta.js";
21
24
  import { KEPT_AUTOSTOP_MINUTES, keepWhenIdle, wakeBoxes } from "./daytona-api.js";
22
25
  import { LEARNING_LABEL, shortOf } from "./learning.js";
23
26
  import { labelled, LearningRuns, reflecting, reflects, withLearning } from "./learning-run.js";
@@ -26,24 +29,30 @@ import { rowPaths } from "./workspace-paths.js";
26
29
  import { ASK_TOOL, toolingOf, workflowTools } from "./tools.js";
27
30
  import { withDecisions } from "./decision-rows.js";
28
31
  import { DECISION_KEY_FD_ENV, decisionKeysFor, providersNamed } from "./decisions.js";
29
- import { ApiError, unsupported } from "./errors.js";
32
+ import { ApiError, invalid, unsupported } from "./errors.js";
30
33
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
31
- import { CAP_ENV, CAP_REFUSAL_PREFIX, SPEND_CAP_REACHED } from "./cap.js";
34
+ import { CAP_ENV, CAP_REFUSAL_PREFIX, CAP_REFUSED_FIELD, CAP_TOLERANCE, FIT_TOLERANCE, money, roomRefusal, SPEND_CAP_REACHED, spentIn } from "./cap.js";
32
35
  import { DEFAULT_MODEL_ENV, EFFORT_ENV, GATEWAY_KEY_ENV, hostModel, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, thinkingOf, withoutFaux, workflowNodes } from "./model.js";
33
36
  import { llmAnswers, pausedIn, readNodeLog, RUN_PAUSED } from "./pause.js";
34
37
  import { durationMs } from "./print.js";
35
- import { handsParallel, planeFor, recheckPlane, TOOL_PLANE_ENV } from "./tool-plane.js";
38
+ import { handsParallel, keptFromBefore, keptVendor, planeFor, recheckPlane, relaunchPlane, TOOL_PLANE_ENV } from "./tool-plane.js";
39
+ import { APPROVAL_ENTRY, APPROVAL_ROW, NO_APPROVER_ENV, previewOf, RESUME_PREFIX, TURN_ORIGIN_FILE } from "./tool-gate.js";
36
40
  import { ChangeClock, RowLog } from "./rows.js";
37
41
  import { TOOL_KEYS } from "./tool-keys.js";
38
42
  import { isObject } from "./validate.js";
39
43
  import { firstMessage } from "./run-manifest.js";
40
44
  import { REFLECT_REQUEST, Turns } from "./turns.js";
41
- import { DECISION_KEYS, handover, hostSecrets, secret, SECRET_NAMES, SECRETS_FD_ENV, SECRETS_LEN_ENV, withoutSecrets, withSecrets } from "./secrets.js";
45
+ import { DECISION_KEYS, handover, handoverSignIn, hostSecrets, mcpHandover, mcpSecretValues, secret, SECRET_NAMES, SECRETS_FD_ENV, SECRETS_LEN_ENV, withoutSecrets, withSecrets } from "./secrets.js";
42
46
  import { MIN_SECRET } from "./learn/secrets.js";
43
47
  import { keyRefusal, redacted, redactedAnswer, redactedLive, redactedOutput, runKeyOf, withoutLoopback } from "./key-refusal.js";
44
- import { BOX_KEYS } from "./boxes.js";
48
+ import { GRAPH_CACHE_BYTES, PartCache, servedPart } from "./graph-served.js";
49
+ import { CONTENT_FILTER_WORDS, contentFiltered, MODERATED } from "./content-filter.js";
50
+ import { BOX_KEYS, VM_PROVIDER } from "./boxes.js";
45
51
  import { remotePlace, storedPlace } from "./place.js";
46
- import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox, sweepRunBoxes } from "./run-box.js";
52
+ import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox, RUN_LABEL, sweepRunBoxes } from "./run-box.js";
53
+ import { BACKGROUND_DIR, endBackground } from "./background.js";
54
+ import { removeEgressDir, RUN_BOX_ALLOW_ENV } from "./box-egress.js";
55
+ import { RUN_BOX_VOLUME_ENV } from "./box-egress-vm.js";
47
56
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
48
57
  export const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
49
58
  const TERMINAL = new Set(["completed", "failed", "cancelled"]);
@@ -117,6 +126,8 @@ function workflowEnding(record) {
117
126
  return undefined;
118
127
  return { status: detail.workflow, ...(typeof detail.code === "string" ? { code: detail.code } : {}), ...(typeof detail.message === "string" ? { message: detail.message } : {}) };
119
128
  }
129
+ /** A call withdrawn with its run (a cancel, or a stop while it waited): never run, and an answer after is 409. */
130
+ const withdrawn = (answer) => answer?.decision === "canceled" || answer?.decision === "withdrawn";
120
131
  /** `review` at the run's saved end `endedAt`, so review.at and ended_at are one time. */
121
132
  const reviewAt = (review, endedAt) => (review ? { kind: review.kind, node: review.node, reason: review.reason, at: endedAt } : null);
122
133
  /** A failed run's error from its row and serve.json: its own, else the row's summary. */
@@ -124,6 +135,8 @@ const errorOfRow = (row, meta) => ({ code: meta?.error?.code ?? "run_failed", me
124
135
  /** An ended run's review from its row and serve.json: an escalated one's as its end saved it, else (an end saved before
125
136
  * reviews were kept) the row's summary; null for every other run. */
126
137
  const reviewOfRow = (row, meta) => row.state !== "escalated" ? null : (meta?.review ?? { kind: null, node: null, reason: row.summary ?? "The workflow escalated." });
138
+ /** A value's sha256, of its JSON. */
139
+ const digestOf = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
127
140
  const ASKED = "Asked you: ";
128
141
  registerLabel(ASK_TOOL, (args) => `${ASKED}${typeof args.question === "string" ? args.question : ""}`, undefined, { name: "Ask you a question" });
129
142
  // ask_person ends its turn (tools.ts): the person's reply is their next message, never a steer.
@@ -150,7 +163,7 @@ export function withAsks(rows) {
150
163
  export function withOverCap(rows, cap) {
151
164
  const at = rows.findLastIndex((row) => row.kind === "usage");
152
165
  const usd = rows[at]?.usage?.usd;
153
- if (cap === undefined || typeof usd !== "number" || usd <= cap)
166
+ if (cap === undefined || typeof usd !== "number" || usd <= cap + FIT_TOLERANCE)
154
167
  return rows;
155
168
  const { usage: _, ...usage } = rows[at];
156
169
  const over = { ...usage, id: `${usage.id}:over_cap`, kind: "phase", summary: `Spent $${usd.toFixed(4)}, $${(usd - cap).toFixed(4)} over the run's cap of $${cap}`, text: null };
@@ -165,6 +178,12 @@ function noteTurns(run, entries, submissions = [], snapshot) {
165
178
  if (!isObject(value) || typeof value.id !== "number")
166
179
  continue;
167
180
  run.lastEntry = Math.max(run.lastEntry ?? 0, value.id);
181
+ // A refusal for room's own start mark: what the cap counted as taken, and the least the request needed.
182
+ const data = value.kind === REQUEST_STARTED && isObject(value.data) && value.data[CAP_REFUSED_FIELD] === true ? value.data : undefined;
183
+ if (data)
184
+ run.capMark = value.id;
185
+ if (data)
186
+ run.capRefusal = typeof data.spentUsd === "number" && typeof data.needsUsd === "number" ? { spentUsd: data.spentUsd, needsUsd: data.needsUsd } : undefined;
168
187
  // The end-of-run turn's assistant messages, whole, by entry: what the turn answered, whose notes learning reads
169
188
  // (learning-run.ts). The ledger skips them; this is their only reader here.
170
189
  if (value.kind === "pi.assistant" && reflects(run.meta.reflect, value.id) && Array.isArray(value.model) && isObject(value.model[0])) {
@@ -184,6 +203,112 @@ const pendingOf = (rows) => {
184
203
  const last = meaningful(rows);
185
204
  return last?.kind === "waiting" ? { kind: "question", question: last.text ?? last.summary ?? "", asked_at: last.timestamp } : null;
186
205
  };
206
+ /** Notes the tool calls that wait for approval in `entries` (the run's stored entries), and those whose answer its process
207
+ * acted on. */
208
+ function noteApprovals(run, entries) {
209
+ for (const value of entries) {
210
+ if (!isObject(value) || value.kind !== APPROVAL_ENTRY || !isObject(value.data) || typeof value.data.id !== "string")
211
+ continue;
212
+ const data = value.data;
213
+ run.approvals ??= new Map();
214
+ const known = run.approvals.get(data.id);
215
+ if (data.phase === "requested" && !known)
216
+ run.approvals.set(data.id, { id: data.id, tool: String(data.tool), call_id: String(data.call_id), args_json: "args" in data ? (JSON.stringify(data.args ?? {}) ?? "{}") : String(data.args_preview ?? ""), requested_at: String(data.requested_at), ...(typeof data.price === "number" || data.price === "not metered" ? { price: data.price } : {}) });
217
+ else if (data.phase === "resolved" && known)
218
+ known.resolved = true;
219
+ }
220
+ }
221
+ /** The tool call that waits for a person's answer: requested in the run's store, not resolved there, not answered. */
222
+ const waitingApproval = (run) => [...(run.approvals?.values() ?? [])].find((a) => !a.resolved && !run.meta.approvals?.[a.id]);
223
+ /** What is shown of a call's arguments: the whole of them redacted with the run's redactor, then cut (previewOf), so
224
+ * no cut leaves the head of a held key. */
225
+ const shownArgs = (approval, redact) => previewOf(redact(approval.args_json));
226
+ /** `entries` with the gate's resume messages (RESUME_PREFIX) redacted whole with `redact`, before the timeline cuts
227
+ * them: the message carries a call's arguments and its result, which may hold a held key. */
228
+ function redactGateMessages(entries, redact) {
229
+ return entries.map((entry) => {
230
+ const first = isObject(entry) && Array.isArray(entry.model) ? entry.model[0] : undefined;
231
+ if (!isObject(first) || first.role !== "user")
232
+ return entry;
233
+ const content = first.content;
234
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((block) => (isObject(block) && block.type === "text" ? String(block.text ?? "") : "")).join("") : "";
235
+ if (!text.startsWith(RESUME_PREFIX))
236
+ return entry;
237
+ const redacted = typeof content === "string" ? redact(content) : content.map((block) => (isObject(block) && block.type === "text" && typeof block.text === "string" ? { ...block, text: redact(block.text) } : block));
238
+ return { ...entry, model: [{ ...first, content: redacted }, ...entry.model.slice(1)] };
239
+ });
240
+ }
241
+ /** The run's pending approval (`pending`, kind approval): the call that waits; else undefined. */
242
+ const approvalOf = (run, redact) => {
243
+ const waiting = waitingApproval(run);
244
+ return waiting ? { kind: "approval", id: waiting.id, tool: waiting.tool, call_id: waiting.call_id, args_preview: shownArgs(waiting, redact), requested_at: waiting.requested_at, ...(waiting.price !== undefined ? { price: waiting.price } : {}) } : undefined;
245
+ };
246
+ /** One answered (allow or deny) whose answer the run's process has not acted on yet. */
247
+ const actingOn = (run) => [...(run.approvals?.values() ?? [])].some((a) => !a.resolved && run.meta.approvals?.[a.id] && !withdrawn(run.meta.approvals[a.id]));
248
+ /** The row after each tool call that waited for approval, beside its result's row. Its arguments are redacted whole
249
+ * (`redact`, the Timeline's own: no held key), before any cut. */
250
+ function withApprovals(rows, run, redact) {
251
+ if (!run.approvals?.size)
252
+ return [...rows];
253
+ const byCall = new Map([...run.approvals.values()].map((approval) => [approval.call_id, approval]));
254
+ const waiting = waitingApproval(run);
255
+ return rows.flatMap((row) => {
256
+ const approval = row.kind === "tool_result" && row.tool_use_id ? byCall.get(row.tool_use_id) : undefined;
257
+ if (!approval)
258
+ return [row];
259
+ const args = shownArgs(approval, redact);
260
+ const said = run.meta.approvals?.[approval.id]?.decision;
261
+ const byMessage = run.meta.approvals?.[approval.id]?.by === "message";
262
+ const head = approval === waiting ? "Waiting for your approval" : byMessage ? "Declined by your message" : said === "withdrawn" ? "Withdrawn when the run was stopped" : said === "canceled" ? "Withdrawn when the run was cancelled" : "Asked your approval";
263
+ const summary = `${head}: ${approval.tool} ${clip(args, 400)}`;
264
+ // A message that would have declined the call, which a stop or a cancel overrode: its words were never sent, and
265
+ // the row says so (the record keeps them whole).
266
+ const dropped = run.meta.approvals?.[approval.id]?.superseded;
267
+ const text = dropped?.by === "message" && dropped.note !== undefined ? `${args}\n\nNot sent: the run was ${said === "canceled" ? "cancelled" : "stopped"}. Your message: ${redact(dropped.note)}` : args;
268
+ return [row, { ...row, id: `${row.id}:approval`, kind: APPROVAL_ROW, summary, text, tool_name: approval.tool, tool_status: null, tool_input_preview: clip(args, 500), tool_result_preview: null, tool_result_size_bytes: null }];
269
+ });
270
+ }
271
+ /** A dollar figure to a millionth, as the timeline's cost.usd is. */
272
+ const micro = (usd) => Math.round(usd * 1e6) / 1e6;
273
+ /** How many tries a raised run's follow-up gets, and the waits between them, before the run fails with why. */
274
+ const CONTINUE_TRIES = 3;
275
+ const CONTINUE_RETRY_MS = [1_000, 3_000];
276
+ /** How many of the refused request's least a run paused at its cap is offered on top of what was taken (suggestedCap). */
277
+ export const SUGGESTED_RAISE_FACTOR = 10;
278
+ /** The raise a run paused at its cap is offered: what the cap counted as taken plus SUGGESTED_RAISE_FACTOR times the
279
+ * refused request's least, rounded up to a whole dollar, and always above the cap (the next dollar above it, if not),
280
+ * so a PATCH with it is a raise. */
281
+ export const suggestedCap = (cap, spentUsd, needsUsd) => {
282
+ // A hair under, so a sum a float puts just past a whole dollar (3.0000000000000004) stays that dollar.
283
+ const up = Math.ceil(spentUsd + SUGGESTED_RAISE_FACTOR * needsUsd - 1e-9);
284
+ // Above the cap as a raise must be (by more than CAP_TOLERANCE, takeRaise), so a PATCH with it is always taken.
285
+ return up > cap + CAP_TOLERANCE ? up : Math.floor(cap + CAP_TOLERANCE) + 1;
286
+ };
287
+ /** A run paused at its cap waits on a raise: its cap, what the cap counted as taken and the least the refused request
288
+ * needs (its refusal's mark; none from a store written before it kept them), the raise it is offered (suggestedCap),
289
+ * the refusal's words, and when it came (its error row's time). The figures are as the cap counts them, never rounded.
290
+ * What was taken is the store's spend once its process is gone (`spentNow`), when that is lower: the refusal counted
291
+ * requests still answering at what it held for them, and they have settled. */
292
+ const budgetPending = (run, spentNow) => {
293
+ const said = pausedAt(run);
294
+ const cap = run.meta.max_cost_usd;
295
+ if (said === undefined || cap === undefined)
296
+ return undefined;
297
+ const r = run.capRefusal;
298
+ const spent = r && spentNow !== undefined ? Math.min(r.spentUsd, spentNow) : r?.spentUsd;
299
+ // Shown as cost.usd is (to a millionth of a dollar), the suggestion from the figures as the cap counts them.
300
+ const figures = r && spent !== undefined ? { spent_usd: micro(spent), needs_usd: micro(r.needsUsd), suggested_cap_usd: suggestedCap(cap, spent, r.needsUsd) } : {};
301
+ return { kind: "budget", cap_usd: cap, ...figures, said, at: meaningful(run.rows)?.timestamp ?? run.updatedAt };
302
+ };
303
+ /** The waiting row of a run paused at its cap, after the refusal's error row: "Paused at the run's $1 cap: Not sent: …". */
304
+ function withPaused(rows, said, cap) {
305
+ const at = rows.findLastIndex((row) => row.kind === "error");
306
+ if (at < 0)
307
+ return [...rows];
308
+ const error = rows[at];
309
+ const paused = { ...error, id: `${error.id}:paused`, kind: "waiting", summary: `Paused at the run's ${money(cap)} cap: ${clip(said, 400)}`, text: clip(said, 2000), tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null };
310
+ return [...rows.slice(0, at + 1), paused, ...rows.slice(at + 1)];
311
+ }
187
312
  /** An import's answer, the one row reading of an answer left: its records hold no turn's end (it ran elsewhere), so its
188
313
  * last meaningful row is its answer when that row is one, a final answer's or a text row's. */
189
314
  const importAnswerOf = (rows) => {
@@ -196,9 +321,19 @@ export const costOf = (rows) => {
196
321
  const usage = usageOf(rows);
197
322
  return usage ? (usage.usage?.usd ?? null) : 0;
198
323
  };
199
- /** What a run's paid tools charged, from the same rows its cost is read from: each charge's line carries it (`usage` on a
200
- * `phase` row); null when one is unknown. A call still marked, in flight or cut, is no charge here. */
201
- export const toolCostOf = (rows) => rows.reduce((sum, row) => (row.kind !== "phase" || !row.usage ? sum : sum === null || row.usage.usd === null ? null : sum + row.usage.usd), 0);
324
+ /** Whether `row` carries a paid tool's charge counted here: `tool`'s alone when given, every other tool's with `others`
325
+ * (chargedTool: a charge's own `phase` row, or a browser call's row its charges fold into). */
326
+ const chargeOf = (row, tool, others) => {
327
+ const charged = chargedTool(row);
328
+ return charged !== undefined && (tool === undefined || (others ? charged !== tool : charged === tool));
329
+ };
330
+ /** What a run's paid tools charged (`tool`'s alone, when given; every other tool's with `others`), from the same rows its
331
+ * cost is read from: each charge's line carries it (`usage` on a `phase` row), and a browser call's row what its charges
332
+ * came to; null when one is unknown. A call still marked, in flight or cut, is no charge here. */
333
+ export const toolCostOf = (rows, tool, others = false) => rows.reduce((sum, row) => (!chargeOf(row, tool, others) ? sum : sum === null || row.usage.usd === null ? null : sum + row.usage.usd), 0);
334
+ /** What a run's paid tools are known to have charged (`tool`'s alone, when given; every other tool's with `others`): each
335
+ * charge's line that names its cost, a charge of unknown cost adding nothing (a browser call's row, what is known of it). */
336
+ export const knownToolCostOf = (rows, tool, others = false) => rows.reduce((sum, row) => (!chargeOf(row, tool, others) ? sum : sum + (row.usage.usd ?? row.usage.so_far_usd ?? 0)), 0);
202
337
  /** A run's cost for its views: its usage row's, else what the store kept when it carried the run back (0 before any
203
338
  * request). A usage row that says unknown, or says nothing, stays unknown: what the store kept dates from before a
204
339
  * follow-up. */
@@ -246,8 +381,9 @@ function answerOfRun(run) {
246
381
  const imported = run.imported ? importAnswerOf(run.rows) : undefined;
247
382
  return lastAnswer(run) ?? imported?.text ?? imported?.summary ?? null;
248
383
  }
249
- const usersOf = (rows) => rows.filter((r) => r.kind === "user_message").length;
250
- const lastUserMessage = (rows) => rows.findLast((r) => r.kind === "user_message")?.id;
384
+ // A run's messages are its message rows (isMessageRow): a person's, and those the server wrote, the message its turn took.
385
+ const usersOf = (rows) => rows.filter(isMessageRow).length;
386
+ const lastUserMessage = (rows) => rows.findLast(isMessageRow)?.id;
251
387
  // A row's place in the store: its entry's id. The store mints conversation and entry ids from one counter, so entry ids
252
388
  // order rows across conversations and the conversation is no part of the order.
253
389
  const placeOf = (id) => Number(id.slice(id.lastIndexOf(":") + 1));
@@ -257,9 +393,57 @@ export const stoppedAt = (meta, rows) => {
257
393
  if (meta.stopped_at === undefined)
258
394
  return meta.stopped_after !== undefined && meta.stopped_after === usersOf(rows);
259
395
  const at = placeOf(meta.stopped_at);
260
- return !rows.some((r) => r.kind === "user_message" && placeOf(r.id) > at);
396
+ return !rows.some((r) => isMessageRow(r) && placeOf(r.id) > at);
261
397
  };
262
398
  const stopped = (run) => stoppedAt(run.meta, run.rows);
399
+ /** The words of the cap's refusal for room an agentic run stands paused at: its newest message's turn ended on it (cap.ts
400
+ * roomRefusal: what is left of its cap cannot buy the next request's least, which a higher cap would send), and nothing
401
+ * came since. The run then waits for its cap to be raised (input_required, `pending.kind` budget), never failed; a
402
+ * refusal no cap fixes (an unknown spend, no price) still fails it (decide). Undefined for any other run. */
403
+ const refusedAt = (run) => {
404
+ if (run.kind !== "agentic" || run.cancel || run.submitted > 0 || run.turns.open > 0 || stopped(run))
405
+ return undefined;
406
+ const end = run.turns.end();
407
+ return end?.status === "failed" ? roomRefusal(end.error) : undefined;
408
+ };
409
+ /** The pause a run stands at, by its refusal's own start mark (its entry), so no row shown after it moves it; a store
410
+ * with no such mark keys it to the refusal's row. Undefined when it stands at no refusal for room. */
411
+ const pauseOf = (run) => {
412
+ if (refusedAt(run) === undefined)
413
+ return undefined;
414
+ if (run.capMark !== undefined)
415
+ return `mark:${run.capMark}`;
416
+ const row = meaningful(run.rows)?.id;
417
+ return row === undefined ? undefined : `row:${row}`;
418
+ };
419
+ /** Its cap was raised since the refusal it stands at (a raise names that pause): it waits for its follow-up then, not
420
+ * for a raise (input_required, idle). */
421
+ const raisedSince = (run) => {
422
+ const pause = pauseOf(run);
423
+ return pause !== undefined && run.meta.cap_raised?.some((raise) => raise.pause === pause) === true;
424
+ };
425
+ /** The follow-up a raise of the pause it stands at asked for and that has not gone yet: one per pause. */
426
+ const continuationOf = (run) => {
427
+ // A run that has ended, or is ending (its follow-up's tries spent: failRaised, a cancel), sends none any more.
428
+ if (run.outcome || run.finishing || run.cancel)
429
+ return undefined;
430
+ const pause = pauseOf(run);
431
+ const next = run.meta.cap_continue;
432
+ return pause !== undefined && next?.pause === pause && !next.sent ? next : undefined;
433
+ };
434
+ /** A process by its pid and start ticks (Linux /proc; the pid alone elsewhere): a pid used again is another process. */
435
+ function processIdentity(pid) {
436
+ if (pid === undefined)
437
+ return undefined;
438
+ try {
439
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
440
+ return `${pid}:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
441
+ }
442
+ catch {
443
+ return String(pid);
444
+ }
445
+ }
446
+ const pausedAt = (run) => (raisedSince(run) ? undefined : refusedAt(run));
263
447
  /** What a stop keeps of where the run stands: the person's last message, by its id, or the place before any. */
264
448
  export const stopMark = (rows) => ({ stopped_at: lastUserMessage(rows) ?? `${ROOT_CONVERSATION_ID}:0` });
265
449
  /** The rows a snapshot that no longer holds them leaves served: those committed entries made. A row any connection
@@ -299,16 +483,33 @@ export function statusOf(run) {
299
483
  return { status: "input_required", state: "idle" };
300
484
  if (!users)
301
485
  return { status: "queued", state: "working" };
486
+ // A tool call parked for approval (tool-gate.ts) waits for the person; once answered, its process acts on it.
487
+ if (run.kind === "agentic" && run.submitted === 0 && !run.working) {
488
+ if (waitingApproval(run))
489
+ return { status: "input_required", state: "waiting" };
490
+ if (actingOn(run))
491
+ return { status: "working", state: "working" };
492
+ }
302
493
  // Every message's turn is over and the newest one's ended interrupted, with no stop of the person's saying so (the
303
494
  // harness ended it on its own): the run waits for the person, as after a stop, never working for good.
304
495
  if (run.kind === "agentic" && run.submitted === 0 && run.turns.end()?.status === "interrupted")
305
496
  return { status: "input_required", state: "idle" };
497
+ // Paused at its cap: it waits for the cap to be raised; raised, for a message, if the raise's own follow-up did not go.
498
+ if (refusedAt(run) !== undefined)
499
+ return pausedAt(run) !== undefined ? { status: "input_required", state: "waiting" } : { status: "input_required", state: "idle" };
306
500
  if (run.working)
307
501
  return { status: "working", state: "working" };
308
502
  if (meaningful(run.rows)?.kind === "waiting")
309
503
  return { status: "input_required", state: "waiting" };
310
504
  return { status: "working", state: "idle" };
311
505
  }
506
+ /** The trigger a serve.json says started its run, as read back: `{id, firing_key}`, or null. */
507
+ function triggerOf(meta) {
508
+ const trigger = meta?.trigger;
509
+ return isObject(trigger) && typeof trigger.id === "string" && typeof trigger.firing_key === "string" ? { id: trigger.id, firing_key: trigger.firing_key } : null;
510
+ }
511
+ /** Why a message that may not answer a person's question is not sent. */
512
+ export const WAITS_ON_A_PERSON = "The run is waiting on a person.";
312
513
  /** The server's own secrets, which a run's process never gets: the API token, by name or by value, the seal key
313
514
  * the tool keys are kept under (tool-keys.ts), and the boxes' keys (boxes.ts), which only the server's box providers use. */
314
515
  const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", ...BOX_KEYS]);
@@ -432,6 +633,8 @@ export async function lastLogLine(run) {
432
633
  await file.close();
433
634
  }
434
635
  }
636
+ /** Seams for tests, each unset in a server: `personsTurn` holds a person's turn just after its origin went. */
637
+ export const runsTestHooks = {};
435
638
  export class Runs {
436
639
  options;
437
640
  runs = new Map();
@@ -440,9 +643,12 @@ export class Runs {
440
643
  /** What decides the secrets each revision's runs are handed (needsOf), by revision id: read once, from the revision the
441
644
  * run is pinned to, never from a request. The keys themselves are read at each launch (keysFor). */
442
645
  needs = new Map();
443
- /** Each workflow run's last graph read whole: what a poll that met a busy store answers, marked stale. */
444
- graphs = new Map();
646
+ /** Every run's graph as served, part by part (servedGraph), and each workflow run's last graph read whole, which a
647
+ * poll that met a busy store answers, marked stale: one LRU by bytes across runs (graph-served.ts PartCache). */
648
+ graphCache = new PartCache(GRAPH_CACHE_BYTES);
445
649
  adopting = new Map();
650
+ /** The hosts this server's next remote box asks for: the setting's, until the provider cannot keep a list here, then none. */
651
+ remoteAllow;
446
652
  clock = new ChangeClock();
447
653
  cli = fileURLToPath(new URL("./cli.js", import.meta.resolve("@parcha/pi-durable-disk")));
448
654
  app = fileURLToPath(new URL("./app.js", import.meta.url));
@@ -460,6 +666,8 @@ export class Runs {
460
666
  /** The runs' learning (learning-run.ts): a step this file calls as a run starts, ends, settles, opens again and is
461
667
  * recovered, handed what it moves of a run. */
462
668
  learning;
669
+ /** When this server took the data root (one server a root): a run started since is its own, never one to recover. */
670
+ bootedAt = new Date().toISOString();
463
671
  constructor(options) {
464
672
  this.options = options;
465
673
  this.learning = new LearningRuns(options, {
@@ -483,8 +691,15 @@ export class Runs {
483
691
  /** A test's seam (startServe's `beforeReopenLaunch`): awaited by a reopen after the run reads open again and before its
484
692
  * launch, so a test can hold a reopen there. */
485
693
  beforeReopenLaunch;
694
+ /** A test's seam (startServe's `onRunLoad`): told each run read in from its store, its timeline with it. */
695
+ onRunLoad;
486
696
  /** A test's seam (startServe's `beforeSubmit`): awaited by a message before it goes to the run's door. */
487
697
  beforeSubmit;
698
+ /** A test's seam (startServe's `beforeMetaSave`): awaited before a run's serve.json is written; one that throws fails
699
+ * the write, as a full disk would. */
700
+ beforeMetaSave;
701
+ /** A test's seam (startServe's `messageOrigin`): the origin a message sent through the messages route carries. */
702
+ messageOrigin;
488
703
  get store() {
489
704
  return this.options.agents.store;
490
705
  }
@@ -514,14 +729,19 @@ export class Runs {
514
729
  return pending;
515
730
  }
516
731
  async load(row) {
732
+ this.onRunLoad?.(row.id);
517
733
  const dir = join(this.options.agents.dir, "runs", row.id);
518
734
  const stored = (await readJson(join(dir, RUN_META)));
735
+ const trigger = triggerOf(stored);
519
736
  const meta = {
520
737
  title: typeof stored?.title === "string" ? stored.title : "",
521
738
  created_at: typeof stored?.created_at === "string" ? stored.created_at : row.startedAt,
522
739
  ...(isObject(stored?.input) ? { input: stored.input } : {}),
523
740
  ...(typeof stored?.effort === "string" ? { effort: stored.effort } : {}),
524
741
  ...(typeof stored?.max_cost_usd === "number" ? { max_cost_usd: stored.max_cost_usd } : {}),
742
+ // Each raise of its cap, and the follow-up a stopped server never sent, which the next sends (resumeRaised).
743
+ ...(Array.isArray(stored?.cap_raised) ? { cap_raised: stored.cap_raised } : {}),
744
+ ...(isObject(stored?.cap_continue) ? { cap_continue: stored.cap_continue } : {}),
525
745
  ...(stored?.error ? { error: stored.error } : {}),
526
746
  ...(stored && "output" in stored ? { output: stored.output } : {}),
527
747
  ...(isObject(stored?.review) ? { review: stored.review } : {}),
@@ -532,7 +752,11 @@ export class Runs {
532
752
  ...(stored?.place ? { place: storedPlace(stored.place) } : {}),
533
753
  ...(isObject(stored?.learning) ? { learning: stored.learning } : {}),
534
754
  ...(isObject(stored?.reflect) ? { reflect: stored.reflect } : {}),
755
+ ...(isObject(stored?.approvals) ? { approvals: stored.approvals } : {}),
756
+ ...(trigger ? { trigger } : {}),
535
757
  };
758
+ // A turn's origin a server before this one set is not known to be the turn running now: it goes.
759
+ await rm(join(dir, TURN_ORIGIN_FILE), { force: true }).catch(() => undefined);
536
760
  // A seed copy a server went down during is taken back before anything holds the run: its relaunch, a settle, a
537
761
  // follow-up (learning-run.ts onLoad).
538
762
  if (stored)
@@ -541,6 +765,7 @@ export class Runs {
541
765
  const run = this.blank(row, dir, meta, known?.version ?? 0, harnessOfBody(known?.revision.body ?? {}), known ? await toolingOf(known.revision) : undefined, known?.revision);
542
766
  this.runs.set(row.id, run);
543
767
  run.launching = existsSync(join(dir, RUN_LAUNCHING));
768
+ run.notSetUp = row.state === "running" && !isObject(stored?.input);
544
769
  const record = await this.record(run);
545
770
  // An ended run is ended before its rows are read, so they never make it a wait: a last row that asks is no notice.
546
771
  if (row.state !== "running")
@@ -593,10 +818,15 @@ export class Runs {
593
818
  }
594
819
  /** Writes the run's serve.json as it is when its turn comes; then tells learning what it now holds (the ledger's line
595
820
  * once the run's learning ended). */
596
- saveMeta(run) {
821
+ /** Writes the run's serve.json, after any write already under way: `meta`, a copy its caller publishes to run.meta
822
+ * only once this resolves (a raise, takeRaise), else run.meta, each as it stands when the write starts. */
823
+ saveMeta(run, meta) {
597
824
  run.saving = (run.saving ?? Promise.resolve()).catch(() => undefined).then(async () => {
598
- const { learning } = run.meta;
599
- await writeWhole(join(run.dir, RUN_META), `${JSON.stringify(run.meta)}\n`);
825
+ // A copy is built as its write starts, from run.meta as it stands then.
826
+ const written = meta ? meta() : run.meta;
827
+ const { learning } = written;
828
+ await this.beforeMetaSave?.(run.id, written);
829
+ await writeWhole(join(run.dir, RUN_META), `${JSON.stringify(written)}\n`);
600
830
  await this.learning.onSaved(run, learning);
601
831
  });
602
832
  return run.saving;
@@ -666,15 +896,16 @@ export class Runs {
666
896
  run.metrics = runMetricsWithDecisions(read.map((r) => r.entry), run.kind === "workflow" ? (run.decisions ?? []) : []);
667
897
  run.working = false;
668
898
  noteTurns(run, entries, submissions);
669
- this.take(run, timelineOf(entries, { settled: true, path: rowPaths(run.dir), redact: this.redactor(run) }));
899
+ noteApprovals(run, entries);
900
+ this.take(run, timelineOf(redactGateMessages(entries, this.redactor(run)), { settled: true, path: rowPaths(run.dir), redact: this.redactor(run) }));
670
901
  }
671
902
  /** New rows in: into the log, then the run's status, then whatever the status asks for. */
672
903
  /** `keep`: rows that stay served though `rows` no longer holds them (the live path's committed rows). */
673
904
  take(run, rows, keep) {
674
- run.rows = withOverCap(labelled(run.meta.reflect, withAsks(rows.filter((r) => !QUIET.test(r.id)))), run.meta.max_cost_usd);
905
+ run.rows = withOverCap(labelled(run.meta.reflect, withApprovals(withAsks(rows.filter((r) => !QUIET.test(r.id))), run, this.redactor(run))), run.meta.max_cost_usd);
675
906
  // Counted by id: a snapshot of a compacted conversation shows fewer user messages than before, which is not more
676
907
  // messages waiting, so a count of rows would leave the run working forever.
677
- const arrived = run.rows.filter((r) => r.kind === "user_message" && !run.users.has(r.id));
908
+ const arrived = run.rows.filter((r) => isMessageRow(r) && !run.users.has(r.id));
678
909
  for (const row of arrived)
679
910
  run.users.add(row.id);
680
911
  run.submitted = Math.max(0, run.submitted - arrived.length);
@@ -682,13 +913,25 @@ export class Runs {
682
913
  this.show(run);
683
914
  this.refresh(run);
684
915
  }
916
+ /** The approval rows as the run's answers say them now (a stop or a cancel withdraws a call, an answer settles one),
917
+ * shown at once: an answer takes no new rows. */
918
+ restate(run) {
919
+ if (!run.approvals?.size)
920
+ return;
921
+ run.rows = withApprovals(run.rows.filter((row) => row.kind !== APPROVAL_ROW), run, this.redactor(run));
922
+ this.show(run);
923
+ }
685
924
  /** The run's rows into its log, as served: a workflow run's decisions and the run's learning row are the served view's
686
925
  * only, never the run's own rows, which its cost and its answer are read from. */
687
926
  show(run) {
688
927
  // The decisions' rows are the served view's only: the run's own rows, which its cost is read from, stay its model nodes'.
689
- const own = run.decisions === undefined ? run.rows : withDecisions(run.rows, run.decisions);
928
+ // Their summary and text are redacted whole, then cut (decision-rows.ts): a provider's error can quote a held key.
929
+ const own = run.decisions === undefined ? run.rows : withDecisions(run.rows, run.decisions, this.decisionShown(run));
690
930
  // An error row reads as the run's error does (errorWords): a refused key in plain words, no loopback address.
691
- const rows = own.map((row) => (row.kind === "error" ? this.servedError(run, row) : row));
931
+ const served = own.map((row) => (row.kind === "error" ? this.servedError(run, row) : row));
932
+ // A run paused at its cap says so after the refusal, as the row its status reads.
933
+ const said = pausedAt(run);
934
+ const rows = said === undefined || run.meta.max_cost_usd === undefined ? served : withPaused(served, said, run.meta.max_cost_usd);
692
935
  if (run.log.sync(withLearning(rows, run.meta.learning, this.learning.shown()), run.keep))
693
936
  run.updatedAt = new Date().toISOString();
694
937
  }
@@ -710,24 +953,33 @@ export class Runs {
710
953
  return undefined;
711
954
  const cap = run.meta.max_cost_usd;
712
955
  const cost = costOf(run.rows);
713
- if (cap !== undefined && cost !== null && cost > cap)
956
+ if (cap !== undefined && cost !== null && cost > cap + FIT_TOLERANCE)
714
957
  return { outcome: "failed", abort: true, error: { code: SPEND_CAP_REACHED, message: `The run cost $${cost.toFixed(4)}, $${(cost - cap).toFixed(4)} over its cap of $${cap}.`, retryable: false } };
715
958
  if (run.submitted > 0)
716
959
  return undefined;
717
960
  if (run.turns.open > 0 || stopped(run))
718
961
  return undefined;
962
+ // A tool call waits for a person's approval, or for its answer to be acted on: the run goes on after it.
963
+ if (waitingApproval(run) || actingOn(run))
964
+ return undefined;
719
965
  const end = run.turns.end();
720
966
  if (end?.status === "answered")
721
967
  return { outcome: "completed" };
722
968
  if (end?.status !== "failed")
723
969
  return undefined;
724
970
  const message = end.error ?? "The run failed.";
971
+ // The cap's refusal for room pauses the run instead (pausedAt): a raise sends what was refused.
972
+ if (roomRefusal(message) !== undefined)
973
+ return undefined;
725
974
  // The cap's refusal in the run's process (cap.ts); a provider error with this exact prefix would read as one too.
726
975
  // Its code is `spend_cap_reached: `, or with a note after it (`spend_cap_reached (out of budget): `, cap.ts); the message is
727
976
  // the words after it.
728
977
  const capped = CAP_REFUSAL_PREFIX.exec(message);
729
978
  if (capped)
730
979
  return { outcome: "failed", error: { code: SPEND_CAP_REACHED, message: message.slice(capped[0].length), retryable: false } };
980
+ // The provider's content filter stopped the answer (content-filter.ts): moderated, in words a person can act on.
981
+ if (contentFiltered(message))
982
+ return { outcome: "failed", error: { code: MODERATED, message: CONTENT_FILTER_WORDS, retryable: false } };
731
983
  return { outcome: "failed", error: { code: "run_failed", message: this.errorWords(run, message) ?? message, retryable: false } };
732
984
  }
733
985
  /** A run's error as a person reads it, in its error box and on its Timeline row alike: a refused key in plain words
@@ -764,7 +1016,7 @@ export class Runs {
764
1016
  * saved or deleted changes the values' digest, and the next view redacts again. */
765
1017
  servedOnce(run, slot, input, redact) {
766
1018
  const values = this.refusedValues(run);
767
- const keys = createHash("sha256").update(JSON.stringify([...values].sort())).digest("hex");
1019
+ const keys = digestOf([...values].sort());
768
1020
  const last = run.served?.[slot];
769
1021
  if (last && last.keys === keys && last.input === input)
770
1022
  return last.out;
@@ -772,12 +1024,43 @@ export class Runs {
772
1024
  run.served = { ...run.served, [slot]: { keys, input, out } };
773
1025
  return out;
774
1026
  }
1027
+ /** A workflow run's graph as serve serves it: its nodes, each decision and each call (its input, output and error) with
1028
+ * no held secret, by its answer's rule (redactedOutput), and only then cut: a map item's label at 200 characters, a
1029
+ * call's error at 2000, and a text stored cut (a decision's state past 64 KB, an error logged cut) less its last 6
1030
+ * times the longest held value plus 16 characters, where a value the stored cut split would sit. The view a busy
1031
+ * store's read keeps is the one graph-view.ts made, whole, so a key saved after it is still found. Each part is
1032
+ * served once per content and held value set: a console polls the graph while the run goes. */
1033
+ servedGraph(run, view) {
1034
+ const values = this.refusedValues(run);
1035
+ const keys = digestOf([...values].sort());
1036
+ const once = (kind, value) => {
1037
+ const at = `part:${keys}:${kind}:${digestOf(value)}`;
1038
+ const kept = this.graphCache.get(at);
1039
+ if (kept !== undefined)
1040
+ return kept;
1041
+ const out = servedPart(kind, value, values);
1042
+ this.graphCache.set(at, out, Buffer.byteLength(JSON.stringify(out) ?? ""));
1043
+ return out;
1044
+ };
1045
+ return { ...view, nodes: once("nodes", view.nodes), decisions: view.decisions.map((value) => once("decision", value)), effects: view.effects.map((value) => once("effect", value)) };
1046
+ }
775
1047
  /** The timeline's redaction of `run`'s error rows and of what a tool's result shows (its summary and preview), applied
776
1048
  * before a row is cut (timelineOf's `redact`), so a cut never leaves the head of a key. Every such cut is within
777
1049
  * redacted()'s SHOWN, so its window holds. */
1050
+ /** How a run's decision rows show a text (decision-rows.ts Shown): the run's redactor, and as many characters held back
1051
+ * from a text stored cut as a held value takes in its widest form. */
1052
+ decisionShown(run) {
1053
+ const values = this.refusedValues(run);
1054
+ return { redact: (text) => redacted(text, values), hold: 6 * values.reduce((most, value) => Math.max(most, value.length), 0) + 16 };
1055
+ }
778
1056
  redactor(run) {
779
1057
  return (text) => redacted(text, this.refusedValues(run));
780
1058
  }
1059
+ /** The last line of the run process's log (lastLogLine) for a failure's message, with every value its errors never
1060
+ * show cut out: its process may have written a secret or its sign-in's pointer there. */
1061
+ async lastLine(run) {
1062
+ return this.redactor(run)(await lastLogLine(run));
1063
+ }
781
1064
  /** Every secret value `run`'s errors never show, as learning's checker holds them (learning-run.ts refused): this
782
1065
  * server's secrets wherever its launcher put them and the keys saved on it, what each launch handed the run, and the
783
1066
  * server's own tokens. */
@@ -795,11 +1078,49 @@ export class Runs {
795
1078
  return keyRefusal(text, runKeyOf(env, run.harness ?? run.tooling?.harness, run.tooling?.model), this.refusedValues(run));
796
1079
  }
797
1080
  /** Records the run's status as a change when it moves, and lets go of a live run that answered, failed or is over its cap. */
1081
+ /** What a run paused at its cap has spent once its process is gone: its store's spend as the cap reads it (spentIn),
1082
+ * read once per pause (its refusal's row). None while its process lives, nor when the store says unknown or cannot
1083
+ * be read: the refusal's own figure stands then. */
1084
+ spentNow(run) {
1085
+ const mark = meaningful(run.rows)?.id;
1086
+ if (mark === undefined || !run.capRefusal || this.live(run) || pausedAt(run) === undefined)
1087
+ return undefined;
1088
+ // One read per pause, and a failed read again after a while, never kept until a restart.
1089
+ if (run.capSpent?.mark !== mark || (run.capSpent.usd === null && Date.now() - (run.capSpent.at ?? 0) > 30_000)) {
1090
+ let usd = null;
1091
+ try {
1092
+ usd = spentIn(this.storeFile(run));
1093
+ }
1094
+ catch (error) {
1095
+ warn(run.id, `its store's spend was not read (${error.message}); its refusal's figure stands`);
1096
+ }
1097
+ run.capSpent = { mark, usd, at: Date.now() };
1098
+ }
1099
+ return run.capSpent.usd ?? undefined;
1100
+ }
1101
+ /** The run's live process, by its pid and start ticks (processIdentity). */
1102
+ liveIdentity(run) {
1103
+ return processIdentity(run.child?.pid ?? run.orphan);
1104
+ }
798
1105
  refresh(run) {
799
1106
  this.mark(run);
1107
+ // A run whose cap was raised at its pause goes on once the process paused there is gone (resumeRaised): with no
1108
+ // process, or one another launch started (a server stopped between that launch and its message: the door takes the
1109
+ // message once, by its id). Never while one waits to be tried again.
1110
+ const next = continuationOf(run);
1111
+ const letting = next !== undefined && next.paused !== undefined && this.live(run) && this.liveIdentity(run) === next.paused;
1112
+ if (next && run.resuming === undefined && !this.closing && !run.cancel && !run.finishing && !run.outcome && !letting)
1113
+ void this.resumeRaised(run, next);
800
1114
  if (!this.live(run) || run.finishing || run.outcome)
801
1115
  return;
802
1116
  const end = this.decide(run);
1117
+ // Paused at its cap, its process is let go: it waits without one, holding no place, until its cap is raised. Once
1118
+ // per pause (its refusal's row): SIGTERM drains and releases it, and the settle that follows leaves it waiting. A
1119
+ // raised one's paused process is let go too (a server started again finds it so).
1120
+ if (!end && (pausedAt(run) !== undefined || letting) && run.parked !== waitMark(run)) {
1121
+ run.parked = waitMark(run);
1122
+ this.terminate(run);
1123
+ }
803
1124
  if (!end)
804
1125
  return;
805
1126
  if (end.error)
@@ -869,8 +1190,8 @@ export class Runs {
869
1190
  /** Every run's box let go that nothing owns, and every run cgroup no record names: once, before any run of this server
870
1191
  * starts, opens again or relaunches, so a box or cgroup being made is never swept away. */
871
1192
  sweepOnce() {
872
- const { box, runBoxes, remoteBoxes } = this.options;
873
- if (!box && !runBoxes && !remoteBoxes)
1193
+ const { box, runBoxes, remoteBoxes, vmBoxes } = this.options;
1194
+ if (!box && !runBoxes && !remoteBoxes && !vmBoxes)
874
1195
  return Promise.resolve();
875
1196
  this.swept ??= (async () => {
876
1197
  const rows = await this.options.agents.request(() => this.store.listRuns());
@@ -882,18 +1203,21 @@ export class Runs {
882
1203
  }
883
1204
  // A remote box of an ended run is pulled first, so what it changed after its run's last pull is kept, and goes only
884
1205
  // once that pull landed: one that fails keeps the box for the next start, its lifetime bounding it.
1206
+ const dirOf = (id) => join(this.options.agents.dir, "runs", id);
1207
+ const pulledFirst = (boxes, daytona) => (id, boxId) => pullRemoteBox(boxes, { id, dir: dirOf(id) }, boxContext(REMOTE_SYNC_MS)).then(() => true, async (error) => {
1208
+ warn(id, `its box is kept: its pull failed (${error.message}); the next start tries again`);
1209
+ await this.keepBox(id, boxId, daytona);
1210
+ return false;
1211
+ });
1212
+ if (vmBoxes) {
1213
+ await sweepRunBoxes(vmBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst(vmBoxes, false)).catch((error) => warn("-", `its start's sweep of Modal sandboxes failed (${error.message}); the next start sweeps again`));
1214
+ }
885
1215
  if (remoteBoxes) {
886
- const dirOf = (id) => join(this.options.agents.dir, "runs", id);
887
- const pulledFirst = (id, boxId) => pullRemoteBox(remoteBoxes, { id, dir: dirOf(id) }, boxContext(REMOTE_SYNC_MS)).then(() => true, async (error) => {
888
- warn(id, `its box is kept: its pull failed (${error.message}); the next start tries again`);
889
- await this.keepBox(id, boxId);
890
- return false;
891
- });
892
1216
  // A box kept at a run's end that Daytona stopped once idle is woken first, so this sweep pulls it like the rest.
893
1217
  const api = this.options.remoteApi;
894
1218
  if (api)
895
1219
  await wakeBoxes(api, (id) => ended.has(id)).catch((error) => warn("-", `the stopped boxes of ended runs were not woken (${error.message}); the next start tries again`));
896
- await sweepRunBoxes(remoteBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst).catch((error) => warn("-", `its start's sweep of remote run boxes failed (${error.message}); the next start sweeps again`));
1220
+ await sweepRunBoxes(remoteBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst(remoteBoxes, true)).catch((error) => warn("-", `its start's sweep of remote run boxes failed (${error.message}); the next start sweeps again`));
897
1221
  }
898
1222
  if (!box)
899
1223
  return;
@@ -919,17 +1243,33 @@ export class Runs {
919
1243
  const place = run.meta.place;
920
1244
  if (place?.mode !== "sandbox")
921
1245
  return;
1246
+ // The relay's hold on the run's programs (box-relay-vm.ts) ends with the run, whatever becomes of its box: one kept
1247
+ // for a later pull, or one whose destroy failed, still lets them go, and their output with them.
1248
+ this.options.vmRelay?.drop(run.id);
922
1249
  const remote = remotePlace(place);
923
- const boxes = remote ? this.options.remoteBoxes : this.options.runBoxes;
1250
+ const boxes = remote ? this.remoteOf(place) : this.options.runBoxes;
924
1251
  if (!boxes)
925
1252
  return;
1253
+ // Its background processes first (background.ts), so each one's exit code and whole log are in work/ before the
1254
+ // pull and the destroy. A bound box with no work/background/ started none, and costs no command here. A failure only
1255
+ // warns: the destroy ends them all the same.
1256
+ if (remote || existsSync(join(run.dir, "work", BACKGROUND_DIR))) {
1257
+ try {
1258
+ const ended = await endBackground(boxes, { [RUN_LABEL]: run.id }, boxContext());
1259
+ if (ended)
1260
+ this.options.log?.("background_ended", { run: run.id, ended });
1261
+ }
1262
+ catch (error) {
1263
+ warn(run.id, `its background processes were not ended before its box goes (${error.message}); destroying the box ends them`);
1264
+ }
1265
+ }
926
1266
  if (remote) {
927
1267
  try {
928
1268
  await this.pullBox(run, true);
929
1269
  }
930
1270
  catch (error) {
931
1271
  if (error instanceof PullIncomplete && error.lasting) {
932
- await this.keepBox(run.id, error.box);
1272
+ await this.keepBox(run.id, error.box, place.box === "daytona");
933
1273
  return warn(run.id, `its box is kept, not destroyed: ${error.message}; what came back is in its files, and the box stops after ${KEPT_AUTOSTOP_MINUTES} idle minutes, its files kept for the next start's pull`);
934
1274
  }
935
1275
  const why = `its box's last pull failed (${error.message})`;
@@ -940,6 +1280,8 @@ export class Runs {
940
1280
  }
941
1281
  try {
942
1282
  await destroyRunBoxes(boxes, run.id, boxContext());
1283
+ // The box's egress proxy directory (box-egress.ts), its socket the run's process left: nothing binds it now.
1284
+ await removeEgressDir(run.id).catch(() => undefined);
943
1285
  }
944
1286
  catch (error) {
945
1287
  warn(run.id, `its box was not destroyed (${error.message}); the next start sweeps it`);
@@ -947,28 +1289,30 @@ export class Runs {
947
1289
  }
948
1290
  /** A remote box kept because its copy back is not whole: said in the log, and set to stop once idle, so it costs its
949
1291
  * disk alone until the next start's pull (which wakes it) or its lifetime. */
950
- async keepBox(runId, boxId) {
1292
+ async keepBox(runId, boxId, daytona = true) {
951
1293
  this.options.log?.("box_kept", { run: runId, box: boxId, reason: "pull_incomplete" });
952
- const api = this.options.remoteApi;
1294
+ // A VM box keeps its lifetime alone: the provider has no idle stop to set.
1295
+ const api = daytona ? this.options.remoteApi : undefined;
953
1296
  if (api)
954
1297
  await keepWhenIdle(api, boxId).catch((error) => warn(runId, `its kept box was not kept from deletion or set to stop when idle (${error.message})`));
955
1298
  }
956
1299
  /** What wakes run `runId`'s remote box when Daytona stopped or paused it (a class that pauses when idle, while the run
957
1300
  * waited for a person): how many it woke. */
958
- wakeOf(runId) {
959
- const api = this.options.remoteApi;
1301
+ wakeOf(runId, place) {
1302
+ // Only Daytona stops or pauses a box: a VM box that ended is made again.
1303
+ const api = place?.mode === "sandbox" && place.box !== "daytona" ? undefined : this.options.remoteApi;
960
1304
  return api && (() => wakeBoxes(api, (id) => id === runId));
961
1305
  }
962
1306
  /** Pulls run `run`'s remote box into its work/, after any pull already running: at a turn's end in the background (a
963
1307
  * failure warns, and the next pull brings it), or awaited (`strict`: a failure throws). */
964
1308
  pullBox(run, strict = false) {
965
- const boxes = this.options.remoteBoxes;
966
1309
  const place = run.meta.place;
967
- if (!boxes || !place || !remotePlace(place))
1310
+ const boxes = place && remotePlace(place) ? this.remoteOf(place) : undefined;
1311
+ if (!boxes || !place)
968
1312
  return Promise.resolve();
969
1313
  // After any pull already running, and after the box's making and seed when one is under way.
970
1314
  const pull = Promise.all([run.pulling, run.boxing?.catch(() => undefined)]).then(async () => {
971
- const pulled = await pullRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), this.wakeOf(run.id));
1315
+ const pulled = await pullRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), this.wakeOf(run.id, place));
972
1316
  if (pulled)
973
1317
  this.options.log?.("box_pulled", { run: run.id, changed: pulled.changed, files: pulled.files, bytes: pulled.bytes, removed: pulled.removed });
974
1318
  });
@@ -995,17 +1339,33 @@ export class Runs {
995
1339
  /** Whether run `id` is one this server holds in a remote box and has not ended: the relay serves no other. */
996
1340
  servesBox(id) {
997
1341
  const run = this.runs.get(id);
998
- return Boolean(this.options.remoteBoxes && run && !run.outcome && run.meta.place && remotePlace(run.meta.place));
1342
+ return Boolean(run && !run.outcome && run.meta.place && remotePlace(run.meta.place) && this.remoteOf(run.meta.place));
1343
+ }
1344
+ /** The server's provider of a remote place's boxes: the VM box's, or Daytona's. */
1345
+ remoteOf(place) {
1346
+ return place.mode === "sandbox" && place.box === VM_PROVIDER.id ? this.options.vmBoxes : this.options.remoteBoxes;
999
1347
  }
1000
1348
  /** Run `id`'s remote box, found or made and seeded: what its process asks the relay for at its first tool call. */
1001
1349
  ensureBox(id) {
1002
1350
  const run = this.runs.get(id);
1003
- const boxes = this.options.remoteBoxes;
1004
- if (!run || !boxes || !this.servesBox(id))
1351
+ const place = run?.meta.place;
1352
+ const boxes = place && this.remoteOf(place);
1353
+ if (!run || !place || !boxes || !this.servesBox(id))
1005
1354
  return Promise.reject(new Error(`no run ${id} of this server is in a remote box`));
1355
+ // The VM box has no network (its provider's host list cannot be read back), and takes the box limits.
1356
+ const vm = place.mode === "sandbox" && place.box === VM_PROVIDER.id;
1006
1357
  // After any pull of this run's box, so a seed never meets a pull.
1007
1358
  run.boxing ??= (run.pulling ?? Promise.resolve())
1008
- .then(() => ensureRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), this.wakeOf(run.id)))
1359
+ .then(() => ensureRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), vm ? { allow: "none", ...(this.options.vmLimits ? { limits: this.options.vmLimits } : {}) } : {
1360
+ wake: this.wakeOf(run.id, place),
1361
+ allow: (this.remoteAllow ??= this.options.boxAllow ?? "none"),
1362
+ onNoList: (code, message) => {
1363
+ if (this.remoteAllow === "none")
1364
+ return;
1365
+ this.remoteAllow = "none";
1366
+ this.options.onNoBoxList?.(code, message);
1367
+ },
1368
+ }))
1009
1369
  .finally(() => void (run.boxing = undefined));
1010
1370
  return run.boxing;
1011
1371
  }
@@ -1027,7 +1387,7 @@ export class Runs {
1027
1387
  /** After an archive (a run's, or an agent's, which archives its runs): the box of every run now archived is let go,
1028
1388
  * now when its process is gone, else when it exits. */
1029
1389
  async archived() {
1030
- if (!this.options.box && !this.options.runBoxes && !this.options.remoteBoxes)
1390
+ if (!this.options.box && !this.options.runBoxes && !this.options.remoteBoxes && !this.options.vmBoxes)
1031
1391
  return;
1032
1392
  for (const row of await this.options.agents.request(() => this.store.listRuns())) {
1033
1393
  if (!row.archivedAt)
@@ -1047,7 +1407,8 @@ export class Runs {
1047
1407
  // The learning a server left between steps, picked up once every running run is read (learning-run.ts).
1048
1408
  const recoverLearning = this.learning.recover();
1049
1409
  await this.sweepOnce();
1050
- const rows = await this.options.agents.request(() => this.store.listRuns());
1410
+ // Only what an earlier server left: a store slow to answer here must not hand back a run a create is setting up now.
1411
+ const rows = (await this.options.agents.request(() => this.store.listRuns())).filter((row) => row.startedAt < this.bootedAt);
1051
1412
  for (const row of rows) {
1052
1413
  if (row.state !== "running" || row.importedFrom)
1053
1414
  continue;
@@ -1071,7 +1432,7 @@ export class Runs {
1071
1432
  run.updatedAt = new Date().toISOString();
1072
1433
  // What it waits on: an ask_person question (waiting), else a stopped turn, for the person's next message.
1073
1434
  if (status === "input_required")
1074
- this.notice(run, "run.needs_input", waitMark(run), { kind: state === "waiting" ? "question" : "stopped" });
1435
+ this.notice(run, "run.needs_input", waitMark(run), { kind: state !== "waiting" ? "stopped" : waitingApproval(run) ? "approval" : pausedAt(run) !== undefined ? "budget" : "question" });
1075
1436
  }
1076
1437
  /** Tells webhooks.ts (`notify`) of a moment of the run under `marker`: a wait it reached (mark), or an end the agent store
1077
1438
  * has (settle, persistLater, reopen). What it already queued it queues no more. */
@@ -1169,8 +1530,11 @@ export class Runs {
1169
1530
  // snapshot of them on a (re)connect (pi-durable-disk's `inputs`), read as their whole state.
1170
1531
  const submissions = events.flatMap((e) => (e.type === "submission" && e.record !== undefined ? [e.record] : []));
1171
1532
  const inputs = events.find((e) => e.type === "snapshot" && Array.isArray(e.inputs))?.inputs;
1172
- noteTurns(run, events.flatMap((e) => (Array.isArray(e.entries) ? e.entries : e.entry !== undefined ? [e.entry] : [])), submissions, inputs);
1173
- reducer.apply(events);
1533
+ const entries = events.flatMap((e) => (Array.isArray(e.entries) ? e.entries : e.entry !== undefined ? [e.entry] : []));
1534
+ noteTurns(run, entries, submissions, inputs);
1535
+ noteApprovals(run, entries);
1536
+ const redact = this.redactor(run);
1537
+ reducer.apply(events.map((e) => (Array.isArray(e.entries) ? { ...e, entries: redactGateMessages(e.entries, redact) } : e.entry !== undefined ? { ...e, entry: redactGateMessages([e.entry], redact)[0] } : e)));
1174
1538
  // A stopped turn is over while the run's process lives on: a request it cut is a charge with no price (costsofar/1),
1175
1539
  // as the settled read counts it, never one in flight.
1176
1540
  if (!run.working && stopped(run))
@@ -1222,7 +1586,7 @@ export class Runs {
1222
1586
  continue;
1223
1587
  }
1224
1588
  if (launched)
1225
- throw new ApiError("internal", `the run's process exited before it served: ${await lastLogLine(run)}`);
1589
+ throw new ApiError("internal", `the run's process exited before it served: ${await this.lastLine(run)}`);
1226
1590
  const pid = holderPid(record);
1227
1591
  const fresh = record?.status === "running" && typeof record.heartbeatAt === "string" && Date.now() - Date.parse(record.heartbeatAt) < LEASE_MS && (pid === undefined || alive(pid));
1228
1592
  // A run already going is never refused a place, but one whose harness this host's memory never holds (after a
@@ -1230,8 +1594,14 @@ export class Runs {
1230
1594
  const never = fresh ? undefined : neverFits(run.harness, this.memory);
1231
1595
  if (never)
1232
1596
  throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness: run.harness } });
1233
- if (!fresh)
1234
- this.launch(run), (launched = true);
1597
+ // Its sign-in pinned only for a launch: a run whose process still serves keeps the one it was handed.
1598
+ if (!fresh) {
1599
+ await this.pinSignIn(run);
1600
+ if (run.outcome || run.finishing || run.cancel || this.live(run))
1601
+ continue;
1602
+ this.launch(run);
1603
+ launched = true;
1604
+ }
1235
1605
  }
1236
1606
  if (Date.now() > deadline)
1237
1607
  throw new ApiError("unavailable", "the run did not come up in time", { retry_after_ms: 1000 }, { "retry-after": "1" });
@@ -1262,9 +1632,12 @@ export class Runs {
1262
1632
  await fetch(new URL("/abort", door), { method: "POST", headers: this.headers(run, true), body: "{}", signal: AbortSignal.timeout(5_000) }).catch(() => undefined);
1263
1633
  }
1264
1634
  /** One request to the door of a run whose process lives, never waking it (toDoor wakes no run that is finishing): again
1265
- * while it opens or parks. `turnOrigin`: who sent a turn this request sends (learning-run.ts's REFLECT_ORIGIN), for
1266
- * the per-tool gate to take once this server has one; nothing reads it until then. */
1635
+ * while it opens or parks. `turnOrigin`: who sent a turn this request sends (learning-run.ts's REFLECT_ORIGIN), kept in
1636
+ * the run's directory before it goes, where the tool gate reads it (tool-gate.ts NOTE_ONLY_TEXT); a person's message
1637
+ * removes it. */
1267
1638
  async toLiveDoor(run, path, body, turnOrigin) {
1639
+ if (turnOrigin)
1640
+ await (run.originWrite = writeWhole(join(run.dir, TURN_ORIGIN_FILE), `${JSON.stringify({ origin: turnOrigin })}\n`));
1268
1641
  for (const deadline = Date.now() + 30_000;; await sleep(200)) {
1269
1642
  if (!this.live(run) || run.cancel)
1270
1643
  throw new Error("the run's process is gone");
@@ -1305,6 +1678,47 @@ export class Runs {
1305
1678
  const revision = given ?? (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
1306
1679
  this.needs.set(run.revision, await needsOf(revision));
1307
1680
  }
1681
+ /** `run`'s pinned MCP tools: read from its directory, or at its first launch made from the granted `tools` and the
1682
+ * servers saved now, and written before its process starts. Undefined when it grants none. */
1683
+ mcpPin(run, tools) {
1684
+ const file = join(run.dir, MCP_PIN);
1685
+ if (existsSync(file)) {
1686
+ const pinned = JSON.parse(readFileSync(file, "utf8"));
1687
+ // A pin made before meta tools were refused (mcp-meta.ts) is checked at each launch, never rewritten: one it holds
1688
+ // refuses the launch, as making the pin does.
1689
+ for (const [server, { url, tools: listed }] of Object.entries(pinned)) {
1690
+ for (const tool of listed)
1691
+ if (metaToolOf(url, tool.name))
1692
+ throw new Error(`mcp:${server}/${tool.name} can't be granted: ${META_REASON}`);
1693
+ }
1694
+ return pinned;
1695
+ }
1696
+ if (!tools?.some((name) => name.startsWith("mcp:")) || !this.options.mcpServers)
1697
+ return undefined;
1698
+ const pin = mcpPinOf(tools, this.options.mcpServers);
1699
+ if (!Object.keys(pin).length)
1700
+ return undefined;
1701
+ writeDurableSync(file, JSON.stringify(pin));
1702
+ return pin;
1703
+ }
1704
+ /** The saved sign-in the run's browser starts from (sign-ins.ts), resolved before each launch: made at the vendor when
1705
+ * its agent has none, and leased to this run to save unless another run of the agent holds the lease. One that cannot
1706
+ * be had (the vendor not answering, a seal key changed) leaves its browser signed out, said in its log. */
1707
+ async pinSignIn(run) {
1708
+ // Its browser as this launch will find it (launch: a vendor whose key is gone since is unavailable, and gets none).
1709
+ const browser = run.meta.tool_plane && recheckPlane(run.meta.tool_plane, withSecrets(process.env, "all", this.options.storedKeys)).browser;
1710
+ const signIns = this.options.signIns;
1711
+ run.signIn = browser && signIns ? ((await signIns.forRun(run.agentId, run.id, browser).catch((error) => void warn(run.id, `its browser starts signed out: ${error.message}`))) ?? undefined) : undefined;
1712
+ // Never shown in its errors, from now on: a server started since its launch has handed it nothing yet.
1713
+ if (run.signIn && run.signIn.ref.length >= MIN_SECRET)
1714
+ (run.handed ??= new Set()).add(run.signIn.ref);
1715
+ }
1716
+ /** Lets go of the save lease the run holds on its agent's sign-in, if any: at once when its process let its sessions go
1717
+ * (`clean`), else by the gone rule (sign-ins.ts). */
1718
+ async releaseSignIn(run, clean = true) {
1719
+ run.signIn = undefined;
1720
+ await this.options.signIns?.release(run.agentId, run.id, run.dir, clean).catch((error) => warn(run.id, `its sign-in's save lease is not let go: ${error.message}`));
1721
+ }
1308
1722
  launch(run, followUp = run.followUpOpen === true) {
1309
1723
  if (run.child || this.closing || run.cancel || run.outcome || run.finishing || run.preparing)
1310
1724
  return;
@@ -1318,9 +1732,24 @@ export class Runs {
1318
1732
  const served = withSecrets(process.env, "all", this.options.storedKeys);
1319
1733
  const needs = this.needs.get(run.revision);
1320
1734
  const handed = needs ? keysFor(needs, served) : NO_TOOL_KEYS;
1321
- const secrets = handover(handed, this.options.storedKeys);
1735
+ // Its MCP servers: the tools it grants, pinned at its first launch in its directory (mcp-gateway.ts), and the
1736
+ // credentials of those servers alone, read now, on the same pipe.
1737
+ let pin;
1738
+ try {
1739
+ pin = this.mcpPin(run, needs?.tools);
1740
+ }
1741
+ catch (error) {
1742
+ // A granted tool that cannot be pinned refuses the launch in words, rather than a run without the tool.
1743
+ run.error = { code: "run_failed", message: error.message, retryable: false };
1744
+ run.finishing = "failed";
1745
+ void this.settle(run, 1, true);
1746
+ return;
1747
+ }
1748
+ const mcp = pin && this.options.mcpServers ? mcpCredentialsOf(pin, this.options.mcpServers) : undefined;
1749
+ // And its saved sign-in, on the same pipe after them (pinSignIn): a pointer its browser opens, never in its environment.
1750
+ const secrets = Buffer.concat([handover(handed, this.options.storedKeys), ...(mcp ? [mcpHandover(mcp)] : []), ...(run.signIn ? [handoverSignIn(run.signIn)] : [])]);
1322
1751
  // What it was handed, for the check of what its end-of-run turn writes (learning-run.ts).
1323
- this.learning.onLaunch(run, handed);
1752
+ this.learning.onLaunch(run, handed, mcpSecretValues(mcp ?? {}));
1324
1753
  // And for what its errors show (refusedValues): each value handed, kept past a key's rotation.
1325
1754
  run.handed ??= new Set();
1326
1755
  for (const name of handed) {
@@ -1328,8 +1757,18 @@ export class Runs {
1328
1757
  if (value && value.length >= MIN_SECRET)
1329
1758
  run.handed.add(value);
1330
1759
  }
1760
+ for (const value of mcpSecretValues(mcp ?? {}))
1761
+ if (value.length >= MIN_SECRET)
1762
+ run.handed.add(value);
1763
+ if (run.signIn && run.signIn.ref.length >= MIN_SECRET)
1764
+ run.handed.add(run.signIn.ref);
1331
1765
  const env = {
1332
1766
  ...childEnv(process.env, this.options.token),
1767
+ // The run's box's network, as the server resolved it: never the setting itself, which the run's process ignores.
1768
+ [RUN_BOX_ALLOW_ENV]: this.options.dockerAllow === undefined || this.options.dockerAllow === "none" ? "none" : this.options.dockerAllow.join(","),
1769
+ // And, on a Mac, its proxy's volume: set always, empty for none, so a stale value in the server's own environment
1770
+ // never reaches a run.
1771
+ [RUN_BOX_VOLUME_ENV]: this.options.dockerVolume ?? "",
1333
1772
  [SECRETS_FD_ENV]: "3",
1334
1773
  [SECRETS_LEN_ENV]: String(secrets.length),
1335
1774
  ...this.fauxEnv(),
@@ -1360,17 +1799,31 @@ export class Runs {
1360
1799
  // Its tools' providers (tool-plane.ts): resolved at its first launch from its pinned revision and this server's
1361
1800
  // settings, and kept in its serve.json, so a later change of the settings never changes a run's tools; at a later
1362
1801
  // launch only checked again (a Parallel key gone makes Parallel unavailable, never another provider). A new run's are
1363
- // in the serve.json its start writes (start); resolving here is for a run made before that. A description with no secret
1802
+ // in the serve.json its start writes (start); resolving here is for a run made before that, whose browser stays
1803
+ // Browserbase (keptFromBefore), the vendor it had then, kept as its choice and checked again at each launch like the
1804
+ // rest; a vendor's missing-key refusal an earlier server saved reads as that vendor again (keptVendor), saved back. A
1805
+ // description with no secret
1364
1806
  // in it, read by the run's process, never by a request. A key saved through the settings API counts as the launcher's
1365
1807
  // does (secrets.ts), so a saved Parallel key makes Parallel available, and a deleted one unavailable at the next launch.
1366
- const plane = run.meta.tool_plane ? recheckPlane(run.meta.tool_plane, served) : run.tooling ? planeFor(served, run.tooling, this.options.toolSettings?.() ?? {}, { capped: run.meta.max_cost_usd !== undefined }) : {};
1367
- if (!run.meta.tool_plane && Object.keys(plane).length) {
1368
- run.meta.tool_plane = plane;
1808
+ // A capability set to ask or deny since resolves again (a harness's own search cannot wait for a person). Its first
1809
+ // launch, from its start, is told a deny as under ask; a later one is told it denied (relaunchPlane).
1810
+ const settings = this.options.toolSettings?.() ?? {};
1811
+ const capped = run.meta.max_cost_usd !== undefined;
1812
+ const first = run.firstLaunch === true;
1813
+ run.firstLaunch = undefined;
1814
+ const kept = run.meta.tool_plane ? keptVendor(run.meta.tool_plane) : run.tooling ? keptFromBefore(planeFor(served, run.tooling, settings, { capped })) : {};
1815
+ const plane = relaunchPlane(kept, served, run.tooling, settings, { capped, first });
1816
+ if (kept !== run.meta.tool_plane && Object.keys(kept).length) {
1817
+ run.meta.tool_plane = kept;
1369
1818
  void this.saveMeta(run).catch(() => undefined);
1370
1819
  }
1371
1820
  delete env[TOOL_PLANE_ENV];
1372
1821
  if (Object.keys(plane).length)
1373
1822
  env[TOOL_PLANE_ENV] = JSON.stringify(plane);
1823
+ // No one can approve here (accounts off): the run's gate refuses an ask instead of parking it (tool-gate.ts).
1824
+ delete env[NO_APPROVER_ENV];
1825
+ if (this.options.approvers === false)
1826
+ env[NO_APPROVER_ENV] = "1";
1374
1827
  // The decision keys are never in a run's environment, which its tools and its model's provider read (childEnv leaves
1375
1828
  // out every secret): a run's process gets those it needs once on an inherited pipe, by name: its decision
1376
1829
  // providers' (decisionProvidersFor), and Parallel's where one of its web tools resolves to Parallel (its plane,
@@ -1490,9 +1943,13 @@ export class Runs {
1490
1943
  run.working = false;
1491
1944
  const record = await this.record(run);
1492
1945
  const released = RELEASED.has(String(record?.status));
1946
+ run.letGo = released;
1493
1947
  const pid = holderPid(record);
1494
1948
  // A process that is gone serves no door, whatever its last heartbeat says.
1495
1949
  const gone = !this.live(run) && !(pid !== undefined && pid !== process.pid && alive(pid) && this.doorOf(record));
1950
+ // Its sign-in's save lease stays with it (below), but no longer than a session it opened could outlive its process.
1951
+ if (gone)
1952
+ await this.options.signIns?.markGone(run.agentId, run.id).catch((error) => warn(run.id, `its sign-in's lease is not marked: ${error.message}`));
1496
1953
  // Its metrics are this settle's read, or none: never an earlier end's.
1497
1954
  run.metrics = undefined;
1498
1955
  if (released || gone)
@@ -1511,12 +1968,21 @@ export class Runs {
1511
1968
  ended = run.kind === "workflow" ? await this.workflowEnd(run, workflowEnding(record) ?? { status: "stopped" }) : { outcome: "cancelled" };
1512
1969
  else if (run.finishing)
1513
1970
  ended = { outcome: run.finishing };
1971
+ else if (run.notSetUp && gone) {
1972
+ run.error = { code: "run_failed", message: "The server went down while it set the run up, before it saved the run's input; the run never started, and a new one can.", retryable: false, details: { reason: SETUP_LOST } };
1973
+ ended = { outcome: "failed" };
1974
+ }
1514
1975
  else if (run.launching && gone) {
1515
1976
  run.error = { code: "run_failed", message: "The server went down while it started the run's process, which never came up; it is not started again, since starting it may be what took the server down.", retryable: false, details: { reason: LAUNCH_LOST } };
1516
1977
  ended = { outcome: "failed" };
1517
1978
  }
1979
+ else if (exited && !released && code !== null && code !== 0 && (run.resuming !== undefined || continuationOf(run) !== undefined)) {
1980
+ // A raised run's paused process held nothing (its turn had ended at the refusal): its exit without a release, at
1981
+ // its drain's end, say, loses nothing, and the raise's follow-up goes (resumeRaised), never a failed run.
1982
+ return this.refresh(run);
1983
+ }
1518
1984
  else if (exited && !released && code !== null && code !== 0) {
1519
- run.error = { code: "run_failed", message: `The run's process exited (${code}) without releasing the run: ${await lastLogLine(run)}`, retryable: false };
1985
+ run.error = { code: "run_failed", message: `The run's process exited (${code}) without releasing the run: ${await this.lastLine(run)}`, retryable: false };
1520
1986
  ended = { outcome: "failed" };
1521
1987
  }
1522
1988
  else if (!gone && this.doorOf(record))
@@ -1532,16 +1998,25 @@ export class Runs {
1532
1998
  if (!ended) {
1533
1999
  // Work left and no process: opened again. A run that waits for the person waits without one, until a message.
1534
2000
  const stalled = run.kind === "workflow" || statusOf(run).status !== "input_required";
1535
- if (!gone || !stalled || this.closing)
2001
+ // Its sign-in's save lease stays with it until it ends (carryBack), through a relaunch or a restart: a session it
2002
+ // opened before its process went may still be live at the vendor, and would write back over another run's. One
2003
+ // that let go cleanly to wait for its person released its sessions first, so its lease goes now.
2004
+ if (gone && released && !stalled)
2005
+ await this.releaseSignIn(run);
2006
+ // A raised run's follow-up, under way or still to go, opens the run's next process itself (resumeRaised): its
2007
+ // paused process going is no process lost, and no relaunch is counted for it.
2008
+ const continuing = run.resuming !== undefined || continuationOf(run) !== undefined || run.child !== undefined;
2009
+ if (!gone || !stalled || this.closing || continuing)
1536
2010
  return this.refresh(run);
1537
2011
  // Opened again without a place, as a run already going, unless its harness never fits this host (a restart on a
1538
2012
  // smaller one): that run fails with why.
1539
2013
  const never = neverFits(run.harness, this.memory);
1540
2014
  if (!never && run.relaunches < MAX_RELAUNCHES) {
1541
2015
  await this.pinNeeds(run);
2016
+ await this.pinSignIn(run);
1542
2017
  return this.relaunch(run);
1543
2018
  }
1544
- run.error = { code: "run_failed", message: never ?? `The run's process went ${MAX_RELAUNCHES + 1} times before the run ended: ${await lastLogLine(run)}`, retryable: false };
2019
+ run.error = { code: "run_failed", message: never ?? `The run's process went ${MAX_RELAUNCHES + 1} times before the run ended: ${await this.lastLine(run)}`, retryable: false };
1545
2020
  ended = { outcome: "failed" };
1546
2021
  }
1547
2022
  await this.carryBack(run, ended.outcome, ended.state, ended.summary);
@@ -1582,6 +2057,9 @@ export class Runs {
1582
2057
  /** Ends the run in the agent store, once: how it ended, its cost, a line for the list and its metrics. A store held by
1583
2058
  * another writer is tried again with backoff; past the last try the run stays unsettled, and the next start carries it back. */
1584
2059
  async carryBack(run, outcome, state, summary) {
2060
+ // Ended, it saves to its agent's sign-in no more; but a process that went without letting its sessions go may have
2061
+ // left one live at the vendor, so its lease then ends by the gone rule. One never launched (letGo unset) has none.
2062
+ await this.releaseSignIn(run, run.letGo !== false);
1585
2063
  // Its process is gone: its box goes with its end, whatever the end (a follow-up after it gets a fresh box; work/ stays).
1586
2064
  // A remote box's last pull lands first: the end is not recorded until its files are in work/.
1587
2065
  await this.dropBox(run, true);
@@ -1788,18 +2266,23 @@ export class Runs {
1788
2266
  // Its tools' providers, resolved before the run exists (tool-plane.ts) and kept in the serve.json its start writes first,
1789
2267
  // so a launch after a crash reads them back, never the settings of that moment, and keeping them is no write of its own.
1790
2268
  const tooling = await toolingOf(revision);
1791
- const plane = tooling ? planeFor(withSecrets(process.env, "all", this.options.storedKeys), tooling, this.options.toolSettings?.() ?? {}, { capped: options.maxCostUsd !== undefined }) : {};
2269
+ const plane = tooling ? planeFor(withSecrets(process.env, "all", this.options.storedKeys), tooling, this.options.toolSettings?.() ?? {}, { capped: options.maxCostUsd !== undefined, run: true }) : {};
1792
2270
  // A run that learns: its seed read before it is made (learning-run.ts).
1793
2271
  const pin = await this.learning.onStart(entry.agent.id, revision);
1794
- const started = await this.options.agents.request(() => this.store.startRun({ agent: entry.agent.id, revision: revision.id })).catch((error) => storeError(error, "revision"));
2272
+ const started = await this.options.agents.request(() => this.store.startRun({ agent: entry.agent.id, revision: revision.id, ...(options.origin ? { origin: options.origin } : {}) })).catch((error) => storeError(error, "revision"));
2273
+ // Only another writer of the store gets here first under the same origin: its run is the one asked for, set up by it.
2274
+ if (started.existing)
2275
+ return (await this.get(started.runId));
1795
2276
  const at = new Date().toISOString();
1796
2277
  const meta = {
1797
- title: clip(options.title.trim().replace(/\s+/g, " "), 80),
2278
+ // Shown on the run list and its view: no held secret a person pasted into the message it is taken from.
2279
+ title: clip(redacted(options.title.trim().replace(/\s+/g, " "), [...hostSecrets(process.env, this.options.storedKeys), this.options.token, this.options.doorToken]), 80),
1798
2280
  created_at: at,
1799
2281
  input: options.input,
1800
2282
  place: options.place,
1801
2283
  ...(options.effort ? { effort: options.effort } : {}),
1802
2284
  ...(options.maxCostUsd !== undefined ? { max_cost_usd: options.maxCostUsd } : {}),
2285
+ ...(options.trigger ? { trigger: options.trigger } : {}),
1803
2286
  ...(Object.keys(plane).length ? { tool_plane: plane } : {}),
1804
2287
  };
1805
2288
  // The run's input is saved first, as the store has it running: a server that goes down from here on leaves a run the
@@ -1814,6 +2297,7 @@ export class Runs {
1814
2297
  const run = this.blank({ id: started.runId, agent: entry.agent.id, revision: revision.id, kind: revision.kind }, started.dir, meta, version, harnessOfBody(revision.body), tooling, revision);
1815
2298
  // Before the run is known here, so nothing launches it first.
1816
2299
  await this.pinNeeds(run, revision);
2300
+ await this.pinSignIn(run);
1817
2301
  this.runs.set(run.id, run);
1818
2302
  // A seed that failed is a learning row from the start, and its learning's end is in the ledger.
1819
2303
  this.show(run);
@@ -1830,6 +2314,7 @@ export class Runs {
1830
2314
  if (!(await prepared))
1831
2315
  return run;
1832
2316
  }
2317
+ run.firstLaunch = true;
1833
2318
  this.launch(run);
1834
2319
  if (revision.kind === "workflow")
1835
2320
  return run;
@@ -1873,9 +2358,19 @@ export class Runs {
1873
2358
  this.reportedBack(run);
1874
2359
  return true;
1875
2360
  }
1876
- async submit(run, content, whenBusy, requestId, readyMs) {
2361
+ /** One message to the run's door. `origin`: who wrote it when the person did not (a raised cap's follow-up, an
2362
+ * approval's resume), carried to its user entry so the Timeline shows it as the server's (pi-durable-agent's
2363
+ * MessageOrigin); the model reads the same text either way. `answers: false`: the run's door refuses the message
2364
+ * (WAITING) when the run's turn ended on ask_person or a tool call of it waits for its owner's approval (the gate's
2365
+ * park, APPROVAL_ENTRY), and when the run is busy (BUSY), so it is never queued behind a
2366
+ * turn that may end so; decided at the door's admission, past every wait here. */
2367
+ async submit(run, content, whenBusy, requestId, readyMs, origin, answers = true) {
1877
2368
  await this.beforeSubmit?.(run.id, content);
1878
- const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy }, readyMs);
2369
+ const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy, ...(origin ? { origin } : {}), ...(answers ? {} : { answers: false, asks: [ASK_TOOL], parks: [APPROVAL_ENTRY] }) }, readyMs);
2370
+ if (answer.status === 409 && answer.body?.error === "WAITING")
2371
+ throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
2372
+ if (answer.status === 409 && answer.body?.error === "BUSY" && !answers)
2373
+ throw new ApiError("rate_limited", "The run is working: a message that may not answer it waits until it is idle.", { retry_after_ms: 5_000, details: { reason: "working" } });
1879
2374
  if (answer.status >= 400)
1880
2375
  throw new ApiError(answer.status === 409 ? "not_continuable" : "internal", String(answer.body?.message ?? answer.body?.error ?? "the run refused the message"));
1881
2376
  }
@@ -1883,13 +2378,186 @@ export class Runs {
1883
2378
  steers(run) {
1884
2379
  return run.kind !== "agentic" || steersMidTurn(run.harness);
1885
2380
  }
1886
- /** One message to an agentic run, its mode chosen by the run's state (the contract's table). */
1887
- async message(run, content) {
2381
+ /** Whether the run's store already took a message under `requestId`: a trigger's firing sent it, and the server went
2382
+ * down before it wrote so. Read before sending it again, so a completed run is not opened again for a message it
2383
+ * already has. Only for a run with no live process: a live one holds its store, and takes the message through its
2384
+ * door, which takes one per id anyway. The store keeps the id as JSON text, as pi submits it, or as a harness's door
2385
+ * keeps its journal (doorKey), where a busy refusal is not a message taken (doorTook). A store held past the retries
2386
+ * throws as busy. */
2387
+ async tookMessage(run, requestId) {
2388
+ if (this.live(run))
2389
+ return false;
2390
+ const file = this.storeFile(run);
2391
+ if (!(await stat(file).catch(() => null)))
2392
+ return false;
2393
+ const { DatabaseSync } = await import("node:sqlite");
2394
+ return whenFree(async () => {
2395
+ const db = new DatabaseSync(file, { readOnly: true });
2396
+ try {
2397
+ if (db.prepare("SELECT 1 FROM submissions WHERE request_id = ? LIMIT 1").get(JSON.stringify(requestId)) !== undefined)
2398
+ return true;
2399
+ const status = db.prepare("SELECT json_extract(e.record, '$.data.status') AS status FROM submissions s JOIN entries e ON e.id = json_extract(s.record, '$.entry') WHERE s.request_id = ? LIMIT 1");
2400
+ return await doorTook(requestId, (key) => status.get(JSON.stringify(key))?.status ?? undefined);
2401
+ }
2402
+ catch (error) {
2403
+ // A store that keeps no submissions has taken none.
2404
+ if (/no such table/.test(error.message))
2405
+ return false;
2406
+ throw error;
2407
+ }
2408
+ finally {
2409
+ db.close();
2410
+ }
2411
+ }, this.busyDelays(), this.onBusy(run.id, "its store"));
2412
+ }
2413
+ /** Raises the cap of an agentic run that names one, to `cap`: above its own (by more than CAP_TOLERANCE), or the same as
2414
+ * its newest raise (a retry, which changes nothing). serve.json keeps it before any answer, and a raise it could not keep
2415
+ * is undone, so the run's next process opens under it (CAP_ENV), as does a server started again. A run paused at its
2416
+ * cap goes on: the raise names the pause it answers, and the pause gets one follow-up, "The cap was raised to $X;
2417
+ * continue the task." under an id fixed now, which refresh sends once the paused process is gone (resumeRaised), here
2418
+ * or after a restart; a second raise before it goes raises what it says. A run working keeps the cap its process was
2419
+ * opened with until its next process. Raises of one run are taken one at a time. */
2420
+ async raiseCap(run, cap) {
2421
+ const before = run.raising ?? Promise.resolve();
2422
+ const taking = before.catch(() => undefined).then(() => this.takeRaise(run, cap));
2423
+ run.raising = taking.catch(() => undefined);
2424
+ return taking;
2425
+ }
2426
+ async takeRaise(run, cap) {
2427
+ if (run.imported)
2428
+ throw this.importedRefusal(run);
2429
+ if (run.cancel || run.finishing || TERMINAL.has(statusOf(run).status))
2430
+ throw this.finished(run);
2431
+ const from = run.meta.max_cost_usd;
2432
+ if (from === undefined)
2433
+ throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "This run has no cap to raise: a cap is named when a run starts." }]);
2434
+ const last = run.meta.cap_raised?.at(-1);
2435
+ const pause = pauseOf(run);
2436
+ const next = continuationOf(run);
2437
+ // The same raise again (a retry): what the first one did stands.
2438
+ if (Math.abs(cap - from) <= CAP_TOLERANCE && last && Math.abs(last.to - cap) <= CAP_TOLERANCE) {
2439
+ // Resumed, as the first answer said, unless the run has since paused anew at another refusal: no raise of that one.
2440
+ const answered = last.pause !== undefined && run.meta.cap_continue?.pause === last.pause && (pause === undefined || pause === last.pause) ? run.meta.cap_continue : undefined;
2441
+ return answered ? { resumed: true, messageId: answered.message_id } : { resumed: false };
2442
+ }
2443
+ if (!(cap > from + CAP_TOLERANCE))
2444
+ throw invalid([{ field: "max_cost_usd", reason: "invalid", message: `A cap is only raised: name more than the run's ${money(from)}.` }]);
2445
+ // Built on a copy and written first: nothing reads the raise (its cap, the pause it answers, its follow-up) before
2446
+ // serve.json keeps it, so until then a message is still 409 budget_reached, the run reads its old cap and no
2447
+ // follow-up goes; a raise the write fails leaves the run as it was, and a retry raises it again.
2448
+ const raised = [...(run.meta.cap_raised ?? []), { from, to: cap, at: new Date().toISOString(), ...(pause ? { pause } : {}) }];
2449
+ let follow = run.meta.cap_continue;
2450
+ if (pause !== undefined && next === undefined) {
2451
+ // The pause's one follow-up, by an id fixed now, and the process being let go then, which it waits out.
2452
+ const paused = this.live(run) ? this.liveIdentity(run) : undefined;
2453
+ follow = { pause, message_id: `cap-${raised.length}-${randomBytes(4).toString("hex")}`, sent: false, tries: 0, ...(paused ? { paused } : {}) };
2454
+ }
2455
+ else if (next) {
2456
+ // A raise of a pause whose follow-up has not gone: that one follow-up goes, under this cap, with its tries anew.
2457
+ const { error: _, ...rest } = next;
2458
+ follow = { ...rest, tries: 0 };
2459
+ }
2460
+ await this.saveMeta(run, () => ({ ...run.meta, max_cost_usd: cap, cap_raised: raised, ...(follow ? { cap_continue: follow } : {}) }));
2461
+ run.meta.max_cost_usd = cap;
2462
+ run.meta.cap_raised = raised;
2463
+ if (next && follow) {
2464
+ // The same follow-up object resumeRaised may hold, renewed in place.
2465
+ next.tries = 0;
2466
+ delete next.error;
2467
+ }
2468
+ else if (follow)
2469
+ run.meta.cap_continue = follow;
2470
+ if (next && typeof run.resuming === "number")
2471
+ run.resuming = undefined;
2472
+ this.refresh(run);
2473
+ const answered = pause !== undefined ? run.meta.cap_continue : undefined;
2474
+ if (!answered)
2475
+ return { resumed: false, ...(this.live(run) ? { note: `The run's process keeps the ${money(from)} cap it was opened with; the ${money(cap)} cap holds from its next process.` } : {}) };
2476
+ return { resumed: true, messageId: answered.message_id };
2477
+ }
2478
+ /** Sends a raised run its pause's follow-up, under its id (the door takes one id once), at the run's cap now: as a
2479
+ * follow-up to a run whose process has gone (message()), so the process it starts resumes nothing and opens under the
2480
+ * new cap, or to the process another launch started. Marked sent in serve.json. One that cannot be sent is tried
2481
+ * again (CONTINUE_RETRY_MS), and after CONTINUE_TRIES the run fails, saying why: never a pause stuck in silence. */
2482
+ async resumeRaised(run, next) {
2483
+ run.resuming = "sending";
2484
+ if (!this.live(run))
2485
+ run.followUpOpen = true;
2486
+ run.submitted++;
2487
+ this.refresh(run);
2488
+ const cap = run.meta.max_cost_usd ?? 0;
2489
+ try {
2490
+ // The server's line, shown as the server's (MessageOrigin), never as the person's: the model reads the same text.
2491
+ await this.submit(run, `The cap was raised to ${money(cap)}; continue the task.`, "followUp", next.message_id, undefined, { kind: "server", reason: "cap_raised" });
2492
+ // Marked sent once serve.json says so. Should that write fail, it went all the same (the door holds it), and its
2493
+ // run no longer stands at the pause, so nothing sends it again.
2494
+ await this.saveMeta(run, () => ({ ...run.meta, cap_continue: { ...next, sent: true } })).then(() => void (next.sent = true), (error) => warn(run.id, `its raised cap's follow-up went, but is not marked sent: ${error.message}`));
2495
+ run.resuming = undefined;
2496
+ }
2497
+ catch (error) {
2498
+ run.submitted = Math.max(0, run.submitted - 1);
2499
+ // The try counts here whether or not serve.json can say so, so its tries stay bounded.
2500
+ const tried = { tries: next.tries + 1, error: error.message };
2501
+ await this.saveMeta(run, () => ({ ...run.meta, cap_continue: { ...next, ...tried } })).catch(() => undefined);
2502
+ Object.assign(next, tried);
2503
+ if (next.tries >= CONTINUE_TRIES) {
2504
+ run.resuming = undefined;
2505
+ warn(run.id, `its raised cap's follow-up was not sent in ${next.tries} tries (${next.error}); the run fails`);
2506
+ return this.failRaised(run, cap, next.error);
2507
+ }
2508
+ const wait = CONTINUE_RETRY_MS[next.tries - 1] ?? CONTINUE_RETRY_MS.at(-1);
2509
+ warn(run.id, `its raised cap's follow-up was not sent (${next.error}); tried again in ${wait / 1000} s`);
2510
+ const at = Date.now() + wait;
2511
+ run.resuming = at;
2512
+ setTimeout(() => {
2513
+ if (run.resuming !== at)
2514
+ return;
2515
+ run.resuming = undefined;
2516
+ this.refresh(run);
2517
+ }, wait).unref();
2518
+ this.refresh(run);
2519
+ }
2520
+ finally {
2521
+ run.followUpOpen = undefined;
2522
+ }
2523
+ }
2524
+ /** Ends a raised run whose follow-up could not be sent: failed, in words a person can act on. */
2525
+ async failRaised(run, cap, why) {
2526
+ if (run.outcome || run.finishing || run.cancel)
2527
+ return;
2528
+ run.error = { code: "run_failed", message: `The run's cap was raised to ${money(cap)}, but the run could not be sent on (${why ?? "no answer"}). Start it again to go on.`, retryable: false };
2529
+ run.finishing = "failed";
2530
+ run.endedAt = new Date().toISOString();
2531
+ this.mark(run);
2532
+ if (this.live(run))
2533
+ this.terminate(run);
2534
+ else
2535
+ await this.settle(run, null, false);
2536
+ }
2537
+ /** One message to an agentic run, its mode chosen by the run's state (the contract's table). `requestId`: the message's
2538
+ * id in the run's store, which takes one message per id (a trigger's firing key); default a new one. */
2539
+ async message(run, content, requestId, { answers = true } = {}) {
1888
2540
  if (run.imported)
1889
2541
  throw this.importedRefusal(run);
1890
2542
  // A cancelled run takes no message, whether or not its end is written yet.
1891
2543
  if (run.cancel)
1892
2544
  throw this.finished(run);
2545
+ // A message while a tool call waits for approval declines it, with the message as the reason (as Claude Code takes
2546
+ // what is typed at its permission prompt): the gate's resume carries the refusal and their words in one turn, and
2547
+ // nothing else is sent, so no second turn races the parked call.
2548
+ const read = run.kind === "agentic" ? waitingApproval(run) : undefined;
2549
+ if (read) {
2550
+ await this.personsTurn(run);
2551
+ // Read again after that wait, with nothing awaited from here to the decline's own write: an answer, a stop or a
2552
+ // cancel that landed meanwhile stands (the first answer wins, and a stop's withdrawal is never replaced), and the
2553
+ // message is then a message, under the run's state now. It declines only the call it read, which the person saw:
2554
+ // another parked since waits for its own answer.
2555
+ const waiting = waitingApproval(run);
2556
+ if (waiting?.id === read.id && !run.cancel && !run.stopping)
2557
+ return this.declineBy(run, waiting, content);
2558
+ if (run.cancel)
2559
+ throw this.finished(run);
2560
+ }
1893
2561
  // Every wait first, then a last look for a stop in flight, again after any wait a stop came during: from that look
1894
2562
  // to the count below nothing awaits, so no stop can begin in between.
1895
2563
  do {
@@ -1906,6 +2574,15 @@ export class Runs {
1906
2574
  // before they are back.
1907
2575
  if (run.reopening)
1908
2576
  await run.reopening.catch(() => undefined);
2577
+ // A raised run whose follow-up has not gone yet (its paused process still letting go, or the follow-up being sent)
2578
+ // takes a message once it has: after it, as the next turn, never into the process being let go.
2579
+ const following = () => continuationOf(run) !== undefined || run.resuming === "sending";
2580
+ if (following()) {
2581
+ await this.waitWhile(following, 100, "The run's raised cap's follow-up is still being sent");
2582
+ // Its follow-up's turn may have ended the run meanwhile (a quick answer): its end is written first, so the message
2583
+ // then opens it again, as one to any ended run does, never refused for an end still being written.
2584
+ await this.waitWhile(() => run.settles > 0 || Boolean(run.finishing && !run.outcome), 100, "The run's end is still being written");
2585
+ }
1909
2586
  if (run.kind === "agentic" && statusOf(run).status === "completed")
1910
2587
  await (run.reopening ??= this.reopen(run).finally(() => (run.reopening = undefined)));
1911
2588
  } while (run.stopping);
@@ -1913,11 +2590,18 @@ export class Runs {
1913
2590
  const { status, state } = statusOf(run);
1914
2591
  if (TERMINAL.has(status))
1915
2592
  throw this.finished(run);
2593
+ // Paused at its cap: a message would be refused for the same room, so the cap is raised first.
2594
+ const paused = pausedAt(run);
2595
+ if (paused !== undefined)
2596
+ throw new ApiError("budget_reached", `The run is paused at its ${money(run.meta.max_cost_usd ?? 0)} cap: raise the cap first. ${paused}`, { details: { cap_usd: run.meta.max_cost_usd ?? null } });
1916
2597
  // A harness that cannot take a message mid-turn (any but pi, harness.ts) queues it for the turn's end: a new turn of
1917
2598
  // the same run, which the contract calls follow_up, never a steer it does not do.
1918
2599
  const working = status === "queued" || (status === "working" && state === "working");
1919
2600
  const mode = working ? (steers ? "steer" : "follow_up") : status === "input_required" && state === "waiting" ? "answer" : "follow_up";
1920
- const messageId = `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}`;
2601
+ // A message that may not answer (a trigger's): one that would is refused here, past every wait, before it is sent.
2602
+ if (mode === "answer" && !answers)
2603
+ throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
2604
+ const messageId = requestId ?? `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}`;
1921
2605
  // A follow-up to a run the person stopped, whose process has gone: its turn had ended, so the process this message
1922
2606
  // starts resumes nothing. With its process live the message starts none, and a relaunch after that process dies
1923
2607
  // under the message is a crash's, which keeps its row.
@@ -1926,7 +2610,10 @@ export class Runs {
1926
2610
  run.submitted++;
1927
2611
  this.refresh(run);
1928
2612
  try {
1929
- await this.submit(run, content, mode === "steer" ? "steer" : "followUp", messageId);
2613
+ // After every wait, and once the count above holds the run from ending (so no end-of-run turn is asked from here):
2614
+ // one asked while this message waited for the run's end wrote its origin then, after any earlier removal.
2615
+ await this.personsTurn(run);
2616
+ await this.submit(run, content, mode === "steer" ? "steer" : "followUp", messageId, undefined, answers ? this.messageOrigin?.(run.id, content) : undefined, answers);
1930
2617
  }
1931
2618
  catch (error) {
1932
2619
  run.submitted = Math.max(0, run.submitted - 1);
@@ -1938,6 +2625,14 @@ export class Runs {
1938
2625
  }
1939
2626
  return { mode, messageId };
1940
2627
  }
2628
+ /** A person's turn is sent next: no turn from here on is the server's own end-of-run turn (tool-gate.ts NOTE_ONLY_TEXT),
2629
+ * so its origin goes, right before the turn is sent. */
2630
+ async personsTurn(run) {
2631
+ // A write of the origin still in flight lands first, then goes: none starts from here (learning-run.ts reflectTurn).
2632
+ await run.originWrite?.catch(() => undefined);
2633
+ await rm(join(run.dir, TURN_ORIGIN_FILE), { force: true }).catch((error) => warn(run.id, `its turn's origin is not removed: ${error.message}`));
2634
+ await runsTestHooks.personsTurn?.(run.dir);
2635
+ }
1941
2636
  /** Waits, up to a request's deadline, while `holds` (checked every `everyMs`): else 503 `unavailable`, saying `why`. */
1942
2637
  async waitWhile(holds, everyMs, why) {
1943
2638
  for (const deadline = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS); holds(); await sleep(everyMs)) {
@@ -1986,6 +2681,7 @@ export class Runs {
1986
2681
  run.relaunches = 0;
1987
2682
  // A run that learns finds its agent's notes in its work again (learning-run.ts).
1988
2683
  await this.learning.onReopen(run);
2684
+ await this.pinSignIn(run);
1989
2685
  await this.beforeReopenLaunch?.(run.id);
1990
2686
  this.refresh(run);
1991
2687
  // Opened for the follow-up: the run had answered, so its open resumes nothing.
@@ -2017,9 +2713,15 @@ export class Runs {
2017
2713
  // the turn as it stops any working run.
2018
2714
  if (run.kind !== "workflow")
2019
2715
  await this.caughtUp(run);
2716
+ // A tool call that waits for approval is withdrawn by the stop (never run, an answer after is 409); then a turn that
2717
+ // runs meanwhile is stopped as any working run's is, and with none the run is stopped as a stop leaves one.
2718
+ const open = run.kind === "agentic" && !run.cancel && !run.outcome && !run.finishing;
2719
+ const withdrawn = open && waitingApproval(run) ? await this.withdraw(run) : false;
2720
+ // An answer the run's process has not acted on yet is overridden too: a stop wins, so nothing runs and nothing resumes.
2721
+ const superseded = open ? await this.supersede(run, "withdrawn") : false;
2020
2722
  const { status, state } = statusOf(run);
2021
2723
  if (run.kind === "workflow" || !this.live(run) || !(status === "working" && state === "working") || run.submitted > 0)
2022
- return false;
2724
+ return withdrawn || superseded ? this.stopIdle(run) : false;
2023
2725
  run.stopping = true;
2024
2726
  try {
2025
2727
  return await this.stopTurn(run);
@@ -2028,6 +2730,58 @@ export class Runs {
2028
2730
  run.stopping = undefined;
2029
2731
  }
2030
2732
  }
2733
+ /** message()'s decline of the tool call that waits for approval: a deny with the message as its note, which the
2734
+ * run's gate acts on as any deny, resuming the session with the refusal and the person's words in one message. */
2735
+ async declineBy(run, waiting, content) {
2736
+ // The person's message, whole: it is the reason the model reads. Nothing shows the note, so nothing cuts it.
2737
+ run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "deny", note: content, answered_at: new Date().toISOString(), args_shown: shownArgs(waiting, this.redactor(run)), by: "message" } };
2738
+ await this.saveMeta(run);
2739
+ this.restate(run);
2740
+ this.refresh(run);
2741
+ if (!run.outcome && !run.finishing && !run.cancel)
2742
+ void this.ensureLive(run).catch((error) => warn(run.id, `its declined approval waits for its process: ${error.message}`));
2743
+ return { mode: "answer", messageId: `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}` };
2744
+ }
2745
+ /** The answers given and not acted on yet (the run's process has not resolved them), overridden by a stop or a cancel:
2746
+ * `withdrawn` or `canceled`, each keeping the answer it superseded, so nothing runs and nothing resumes, and the
2747
+ * history shows what was given. The run's gate reads the answer again just before it acts (tool-gate.ts). */
2748
+ async supersede(run, decision) {
2749
+ const given = [...(run.approvals?.values() ?? [])].filter((a) => !a.resolved && run.meta.approvals?.[a.id] && !withdrawn(run.meta.approvals[a.id]));
2750
+ if (!given.length)
2751
+ return false;
2752
+ const now = new Date().toISOString();
2753
+ const overridden = given.map((a) => {
2754
+ const was = run.meta.approvals[a.id];
2755
+ return [a.id, { decision, answered_at: now, superseded: { decision: was.decision, answered_at: was.answered_at, ...(was.note !== undefined ? { note: was.note } : {}), ...(was.by ? { by: was.by } : {}) } }];
2756
+ });
2757
+ run.meta.approvals = { ...run.meta.approvals, ...Object.fromEntries(overridden) };
2758
+ await this.saveMeta(run);
2759
+ this.restate(run);
2760
+ return true;
2761
+ }
2762
+ /** Until every tool call of the run that waited for approval is resolved in its store (its process acted on its answer,
2763
+ * or cut it), or `ms` pass. */
2764
+ async untilResolved(run, ms) {
2765
+ for (const end = Date.now() + ms; [...(run.approvals?.values() ?? [])].some((approval) => !approval.resolved) && Date.now() < end;)
2766
+ await sleep(50);
2767
+ }
2768
+ /** stop()'s withdrawal of the tool call that waits for approval: never run, and an answer after is 409. */
2769
+ async withdraw(run) {
2770
+ const waiting = waitingApproval(run);
2771
+ run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "withdrawn", answered_at: new Date().toISOString() } };
2772
+ await this.saveMeta(run);
2773
+ this.restate(run);
2774
+ return true;
2775
+ }
2776
+ /** stop() of a run with no turn to abort (parked on an approval it withdrew): the stop's mark, as a stop saves it. */
2777
+ async stopIdle(run) {
2778
+ delete run.meta.stopped_at;
2779
+ delete run.meta.stopped_after;
2780
+ Object.assign(run.meta, stopMark(run.rows));
2781
+ await this.saveMeta(run);
2782
+ this.refresh(run);
2783
+ return true;
2784
+ }
2031
2785
  /** stop()'s mark and abort, once it took the stop. */
2032
2786
  async stopTurn(run) {
2033
2787
  // Set before the abort: the turn's end can arrive before the door answers, and must not read as an answer.
@@ -2052,6 +2806,25 @@ export class Runs {
2052
2806
  this.refresh(run);
2053
2807
  return true;
2054
2808
  }
2809
+ /** A person's answer to the tool call `id` that waits for approval (tool-gate.ts): kept in the run's serve.json before
2810
+ * it returns, the first answer winning (the same one again changes nothing; another is 409, `already_answered`). The
2811
+ * run's process reads it there, runs or refuses the call, and resumes; a run with no process gets one. */
2812
+ async approve(run, id, decision, note) {
2813
+ const given = run.meta.approvals?.[id];
2814
+ if (!given && !run.approvals?.has(id))
2815
+ throw new ApiError("not_found", `The run ${run.id} has no tool call ${id} waiting for approval.`);
2816
+ if (given) {
2817
+ if (given.decision === decision)
2818
+ return;
2819
+ throw new ApiError("not_continuable", `The tool call ${id} was already ${given.decision === "canceled" ? "canceled with its run" : given.decision === "withdrawn" ? "withdrawn when its run was stopped" : `answered: ${given.decision}`}.`, { details: { reason: "already_answered", decision: given.decision } });
2820
+ }
2821
+ run.meta.approvals = { ...run.meta.approvals, [id]: { decision, ...(note ? { note } : {}), answered_at: new Date().toISOString(), args_shown: shownArgs(run.approvals.get(id), this.redactor(run)) } };
2822
+ await this.saveMeta(run);
2823
+ this.restate(run);
2824
+ this.refresh(run);
2825
+ if (!run.outcome && !run.finishing && !run.cancel)
2826
+ void this.ensureLive(run).catch((error) => warn(run.id, `its answered approval waits for its process: ${error.message}`));
2827
+ }
2055
2828
  /** Record the cancel and signal the run. An agentic run reads `cancelled` from here on (the first end a run comes to is
2056
2829
  * its last: nothing its turn writes later moves it), and is carried back so once its process has exited; a workflow
2057
2830
  * run reads it once it is carried back, with how its workflow stopped. */
@@ -2063,6 +2836,15 @@ export class Runs {
2063
2836
  if (run.outcome || run.finishing)
2064
2837
  return false;
2065
2838
  run.cancel = true;
2839
+ // A tool call that waits for approval is canceled with its run: an answer after this one is refused.
2840
+ const waiting = waitingApproval(run);
2841
+ if (waiting) {
2842
+ run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "canceled", answered_at: new Date().toISOString() } };
2843
+ await this.saveMeta(run).catch((error) => warn(run.id, `its canceled approval is not saved: ${error.message}`));
2844
+ this.restate(run);
2845
+ }
2846
+ // An answer its process has not acted on yet is overridden too: nothing runs and nothing resumes.
2847
+ const superseded = await this.supersede(run, "canceled").catch((error) => (warn(run.id, `its superseded approval is not saved: ${error.message}`), false));
2066
2848
  if (run.kind === "agentic") {
2067
2849
  run.finishing = "cancelled";
2068
2850
  run.endedAt = new Date().toISOString();
@@ -2073,6 +2855,13 @@ export class Runs {
2073
2855
  if (this.live(run)) {
2074
2856
  // The turn is aborted first, so the drain that SIGTERM starts does not wait for it.
2075
2857
  await this.abortTurn(run);
2858
+ // An approved call in flight runs outside any turn: its process's gate cuts it once it reads the cancel (tool-gate.ts),
2859
+ // which ending the process at once would forestall. A short wait for that, never a refusal.
2860
+ if (superseded) {
2861
+ run.meta.cancel_waits_for = [...(run.approvals?.values() ?? [])].filter((approval) => !approval.resolved).map((approval) => approval.id);
2862
+ await this.saveMeta(run).catch((error) => warn(run.id, `its cancel's wait is not saved: ${error.message}`));
2863
+ await this.untilResolved(run, 3_000);
2864
+ }
2076
2865
  this.terminate(run);
2077
2866
  }
2078
2867
  else
@@ -2115,17 +2904,17 @@ export class Runs {
2115
2904
  // A poll never answers home_busy: a store still held answers the live view, or the last whole one, marked stale.
2116
2905
  try {
2117
2906
  const view = await runGraph(given);
2118
- this.graphs.set(run.id, view);
2119
- return { ...view, stale: false };
2907
+ this.graphCache.set(`view:${run.id}`, view, Buffer.byteLength(JSON.stringify(view)));
2908
+ return this.servedGraph(run, { ...view, stale: false });
2120
2909
  }
2121
2910
  catch (error) {
2122
2911
  if (!storeBusy(error))
2123
2912
  throw error;
2124
2913
  warn(run.id, "its store is busy; the graph answers its live view, stale");
2125
- const held = this.graphs.get(run.id);
2914
+ const held = this.graphCache.get(`view:${run.id}`);
2126
2915
  if (held)
2127
- return { ...held, run: given.run, stale: true };
2128
- return { ...(await runGraph({ ...given, liveOnly: true })), stale: true };
2916
+ return this.servedGraph(run, { ...held, run: given.run, stale: true });
2917
+ return this.servedGraph(run, { ...(await runGraph({ ...given, liveOnly: true })), stale: true });
2129
2918
  }
2130
2919
  }
2131
2920
  /** How long a run's process gets after SIGTERM before SIGKILL: its drain and a second to exit. */
@@ -2208,10 +2997,11 @@ export class Runs {
2208
2997
  result: status === "completed" ? { output: run.kind === "workflow" ? (this.servedOutput(run, run.meta.output ?? null)) : null, final_answer: this.servedAnswer(run, finalAnswer) } : kept ? { output: null, final_answer: this.servedAnswer(run, kept) } : null,
2209
2998
  error: status === "failed" ? (run.error ?? { code: "run_failed", message: "The run failed.", retryable: false }) : null,
2210
2999
  review: endedAt === null ? null : reviewAt(run.meta.review ?? (row ? reviewOfRow(row, run.meta) : null), endedAt),
2211
- pending: status === "input_required" && state === "waiting" ? pendingOf(run.rows) : null,
3000
+ pending: status === "input_required" && state === "waiting" ? (approvalOf(run, this.redactor(run)) ?? budgetPending(run, this.spentNow(run)) ?? pendingOf(run.rows)) : null,
2212
3001
  cost: this.cost(run),
2213
3002
  archived_at: stored?.archivedAt ?? null,
2214
3003
  imported_from: run.imported ?? null,
3004
+ trigger: run.meta.trigger ?? null,
2215
3005
  // The notes it read once it settled: while it runs, or runs again for a follow-up, they are still being read.
2216
3006
  learning: this.learning.view(run.meta.learning, TERMINAL.has(status) && run.settled),
2217
3007
  poll_after_ms: TERMINAL.has(status) && run.settled ? 0 : 1000,
@@ -2219,8 +3009,8 @@ export class Runs {
2219
3009
  };
2220
3010
  }
2221
3011
  async summary(run) {
2222
- const { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, archived_at, imported_from, learning } = await this.view(run);
2223
- return { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, ...(effort ? { effort } : {}), created_at, ended_at, error, review, pending, cost, archived_at, imported_from, learning: learning && shortOf(learning) };
3012
+ const { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning } = await this.view(run);
3013
+ return { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, ...(effort ? { effort } : {}), created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning: learning && shortOf(learning) };
2224
3014
  }
2225
3015
  /** A run's status for a list: an ended run's from its row, a running one's from the run itself. */
2226
3016
  async statusOfRow(row) {
@@ -2248,16 +3038,20 @@ export class Runs {
2248
3038
  // A run read from its row alone has ended: it waits on nothing.
2249
3039
  pending: null,
2250
3040
  imported_from: row.importedFrom ?? null,
3041
+ trigger: triggerOf(meta),
2251
3042
  // Its row says it ended: what serve.json holds of its learning is as it settled.
2252
3043
  learning: this.learning.short(isObject(meta?.learning) ? meta.learning : null, true),
2253
3044
  };
2254
3045
  }
2255
- /** A key was saved on this server or deleted from it: each held run's learning row shown again, cut of the keys as
2256
- * they are now (learning-run.ts shown), as its view and its lists already are from the next read on. */
3046
+ /** A key was saved on this server or deleted from it: each held run's learning row and decision rows shown again, cut
3047
+ * of the keys as they are now (learning-run.ts shown, decision-rows.ts), as its view and its lists already are from
3048
+ * the next read on. */
2257
3049
  keysChanged() {
2258
3050
  this.learning.keysChanged();
3051
+ // A run's learning row and its decision rows are shown again with the keys as they are now (show): a key saved after
3052
+ // a workflow ended is redacted from its decisions on the next read, learning or not.
2259
3053
  for (const run of this.runs.values())
2260
- if (run.meta.learning)
3054
+ if (run.meta.learning || run.decisions)
2261
3055
  this.show(run);
2262
3056
  }
2263
3057
  /** A held run's learning, in short (learning-run.ts heldLearning). */