@parcha/agentrun-serve 0.1.0-beta.32 → 0.1.0-beta.33

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 (163) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +78 -46
  3. package/dist/adapters.d.ts +0 -3
  4. package/dist/adapters.js +0 -7
  5. package/dist/agents.d.ts +1 -1
  6. package/dist/api-only.d.ts +14 -0
  7. package/dist/api-only.js +33 -0
  8. package/dist/archil-routes.d.ts +1 -1
  9. package/dist/box-egress-vm.d.ts +0 -8
  10. package/dist/box-egress-vm.js +0 -10
  11. package/dist/box-egress.d.ts +0 -4
  12. package/dist/box-egress.js +1 -16
  13. package/dist/box-paths.d.ts +25 -2
  14. package/dist/box-paths.js +79 -11
  15. package/dist/box-relay.d.ts +0 -11
  16. package/dist/box-relay.js +0 -20
  17. package/dist/box-settings.d.ts +46 -0
  18. package/dist/box-settings.js +107 -0
  19. package/dist/boxes.d.ts +4 -1
  20. package/dist/browser-cost.js +2 -1
  21. package/dist/browser-person.d.ts +0 -2
  22. package/dist/browser-person.js +0 -2
  23. package/dist/budget.d.ts +0 -4
  24. package/dist/budget.js +0 -7
  25. package/dist/cap.d.ts +0 -7
  26. package/dist/cap.js +0 -22
  27. package/dist/cli.js +23 -8
  28. package/dist/computers.d.ts +1 -1
  29. package/dist/console/assets/index-Dn0ngwG9.js +535 -0
  30. package/dist/console/assets/index-DvW6Aled.css +1 -0
  31. package/dist/console/index.html +2 -2
  32. package/dist/daytona-api.d.ts +0 -11
  33. package/dist/daytona-api.js +1 -82
  34. package/dist/docker-host-addresses.d.ts +37 -0
  35. package/dist/docker-host-addresses.js +110 -0
  36. package/dist/files.d.ts +0 -8
  37. package/dist/files.js +0 -17
  38. package/dist/github-connection.d.ts +1 -1
  39. package/dist/github-connection.js +1 -1
  40. package/dist/harness-install.d.ts +23 -0
  41. package/dist/harness-install.js +99 -4
  42. package/dist/harness.d.ts +4 -3
  43. package/dist/harness.js +16 -1
  44. package/dist/import.js +52 -13
  45. package/dist/learn/secrets.d.ts +2 -1
  46. package/dist/learn/secrets.js +19 -6
  47. package/dist/learned-workflow.d.ts +5 -4
  48. package/dist/learned-workflow.js +6 -3
  49. package/dist/learning-routes.d.ts +9 -46
  50. package/dist/learning-routes.js +25 -29
  51. package/dist/learning-run.d.ts +4 -231
  52. package/dist/learning-run.js +7 -651
  53. package/dist/live/translate.js +1 -1
  54. package/dist/mcp-gateway.d.ts +0 -3
  55. package/dist/mcp-gateway.js +0 -13
  56. package/dist/mcp-probe.d.ts +2 -2
  57. package/dist/mcp-probe.js +2 -2
  58. package/dist/mcp-servers-store.js +1 -1
  59. package/dist/openapi.js +3 -3
  60. package/dist/page.js +3 -1
  61. package/dist/paid-calls.js +3 -2
  62. package/dist/pause.d.ts +0 -2
  63. package/dist/pause.js +1 -8
  64. package/dist/place.d.ts +0 -5
  65. package/dist/place.js +0 -10
  66. package/dist/print.d.ts +2 -1
  67. package/dist/print.js +4 -2
  68. package/dist/run-db.d.ts +0 -2
  69. package/dist/run-db.js +0 -4
  70. package/dist/run-learning-served.d.ts +38 -0
  71. package/dist/run-learning-served.js +9 -0
  72. package/dist/run-secrets.d.ts +33 -0
  73. package/dist/run-secrets.js +53 -0
  74. package/dist/run-timeline-served.js +5 -2
  75. package/dist/run-view.d.ts +5 -9
  76. package/dist/run-view.js +4 -22
  77. package/dist/runner/adapter-loop.d.ts +8 -2
  78. package/dist/runner/adapter-loop.js +44 -12
  79. package/dist/runner/adapter-run-spec.d.ts +8 -0
  80. package/dist/runner/adapter-run-spec.js +6 -5
  81. package/dist/runner/adapters/pi.d.ts +4 -0
  82. package/dist/runner/adapters/pi.js +4 -1
  83. package/dist/runner/beside.js +19 -8
  84. package/dist/runner/claim-secrets.js +1 -1
  85. package/dist/runner/cli-run-spec.js +15 -1
  86. package/dist/runner/journal-kinds.d.ts +6 -0
  87. package/dist/runner/live-ticker.d.ts +1 -1
  88. package/dist/runner/live-ticker.js +28 -4
  89. package/dist/runner/loop-contract.d.ts +3 -2
  90. package/dist/runner/main.d.ts +11 -4
  91. package/dist/runner/main.js +39 -10
  92. package/dist/runner/mcp-claim.d.ts +1 -1
  93. package/dist/runner/mcp-claim.js +1 -1
  94. package/dist/runner/model-route.js +21 -2
  95. package/dist/runner/redact.d.ts +8 -2
  96. package/dist/runner/redact.js +11 -2
  97. package/dist/runner/workflow-spec.js +5 -9
  98. package/dist/runs-over-store.d.ts +1 -1
  99. package/dist/runs-over-store.js +16 -5
  100. package/dist/seal-key.d.ts +54 -15
  101. package/dist/seal-key.js +272 -84
  102. package/dist/sealed-settings.d.ts +2 -2
  103. package/dist/sealed-settings.js +3 -10
  104. package/dist/secrets.d.ts +2 -10
  105. package/dist/secrets.js +21 -17
  106. package/dist/server-secrets-store.js +1 -1
  107. package/dist/server-secrets.js +3 -0
  108. package/dist/server.d.ts +10 -6
  109. package/dist/server.js +89 -41
  110. package/dist/store/index.d.ts +1 -1
  111. package/dist/store/index.js +1 -1
  112. package/dist/store/open.d.ts +12 -2
  113. package/dist/store/open.js +23 -3
  114. package/dist/store/postgres/migrate.js +18 -1
  115. package/dist/store/sqlite/store.js +23 -8
  116. package/dist/store/store.d.ts +3 -0
  117. package/dist/store-reads/journal.d.ts +16 -0
  118. package/dist/store-reads/journal.js +82 -6
  119. package/dist/store-view.js +38 -5
  120. package/dist/tool-keys.d.ts +4 -3
  121. package/dist/tool-keys.js +7 -4
  122. package/dist/tools.d.ts +1 -1
  123. package/dist/tools.js +4 -1
  124. package/dist/trigger-schedule.js +2 -1
  125. package/dist/trigger-secrets-shown.js +5 -1
  126. package/dist/workspace/computer-deps.d.ts +29 -0
  127. package/dist/workspace/computer-deps.js +48 -1
  128. package/dist/workspace/computer-for-claim.d.ts +7 -3
  129. package/dist/workspace/computer-for-claim.js +1 -1
  130. package/dist/workspace/computer-providers.d.ts +6 -2
  131. package/dist/workspace/computer-providers.js +1 -1
  132. package/dist/workspace/index.d.ts +1 -1
  133. package/dist/workspace/index.js +1 -1
  134. package/dist/workspace.d.ts +0 -3
  135. package/dist/workspace.js +0 -3
  136. package/launcher/agentrun-serve +6 -33
  137. package/package.json +14 -14
  138. package/templates/inbound-lead/agent.md +1 -1
  139. package/templates/kyb/agent.md +1 -1
  140. package/dist/app.d.ts +0 -5
  141. package/dist/app.js +0 -514
  142. package/dist/bounds.d.ts +0 -26
  143. package/dist/bounds.js +0 -137
  144. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  145. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  146. package/dist/content-filter.d.ts +0 -7
  147. package/dist/content-filter.js +0 -23
  148. package/dist/disk.d.ts +0 -33
  149. package/dist/disk.js +0 -85
  150. package/dist/door-line.d.ts +0 -23
  151. package/dist/door-line.js +0 -83
  152. package/dist/harness-app.d.ts +0 -69
  153. package/dist/harness-app.js +0 -1162
  154. package/dist/request-start.d.ts +0 -27
  155. package/dist/request-start.js +0 -381
  156. package/dist/run-box.d.ts +0 -205
  157. package/dist/run-box.js +0 -661
  158. package/dist/run-holder.d.ts +0 -52
  159. package/dist/run-holder.js +0 -139
  160. package/dist/runs.d.ts +0 -1200
  161. package/dist/runs.js +0 -4103
  162. package/dist/served-only.d.ts +0 -5
  163. package/dist/served-only.js +0 -12
@@ -1,1162 +0,0 @@
1
- // A run on a harness other than pi. The run's process holds one AdapterSession of that harness, durable in the run's own
2
- // store (durableSessions), behind the door hook of pi-durable-disk: the person's message goes to the session's `send`,
3
- // and a message that arrives while a turn runs is sent when it ends, in order. A stop interrupts the turn.
4
- //
5
- // Money has one path. The runner's booking (modelPortFor) records every paid request in the session as the runner does
6
- // for a workflow node; each request then becomes one pi.assistant entry on the root conversation, with its text, its tool
7
- // calls and its cost, beside a marker of the request (session key, request number), so it is written once whatever
8
- // happens. pi's timeline counts a request per pi.assistant entry and sums their cost, and serve's costOf reads that row,
9
- // as for a pi run. A request's cost and its content arrive in either order (a harness may stream before its usage is
10
- // reported), so an entry is written at the next boundary that has both: the next request, a tool's end, the turn's end.
11
- // A harness reports each call as it runs it, so an answer that asks for several tools is written at its first call's end;
12
- // a later call of that answer is written then as its continuation (REQUEST_CONTINUED), before its result, never as part
13
- // of the next request's entry.
14
- // A request the session booked but the root has no entry for (the process died before the boundary) gets one at the
15
- // next open, with its cost and no content.
16
- //
17
- // A paid host tool's charge (monid.run's) is written on the root by the tool (monid.ts), as a TOOL_COST the timeline
18
- // adds to the run's cost. Under a cap it joins what the cap reads as spent: the session's booked requests, plus the
19
- // charges written by earlier processes (read at the open) and this one's.
20
- //
21
- // A message the door accepts is on the root before the door says so, and its end (sent to the session, or dropped by a
22
- // stop) after: one that waited for a turn's end when the process died is sent at the next open. Its end is written once
23
- // the session has it, so a process that dies between the two sends it again rather than never.
24
- //
25
- // A call is on the root as soon as the session records its intent (`tool_start`), in its request's entry once that
26
- // request's cost is in, so the Timeline shows a call while it runs. A call a crash cut off has its intent in the
27
- // session's records and no result on the root: the next open writes its result from those records (a `never` call's
28
- // reads interrupted, as the kernel records it), and its call too when the root never got it. A `safe` call cut off runs
29
- // again and reports itself; the root holds its call once.
30
- //
31
- // A host tool call the tool gate parks for a person's approval (tool-gate.ts) ends its turn: no model request leaves
32
- // after it, and the turn is interrupted once its result is in and the request that asked for it is booked (its end, up to
33
- // BOOKING_WAIT_MS), then settled as a stopped one is, its end interrupted.
34
- // The answer's resume is a message of its own, sent as a person's is; a turn the park ended is not resumed at the next
35
- // open while the call still waits.
36
- import { existsSync, writeFileSync } from "node:fs";
37
- import { randomUUID } from "node:crypto";
38
- import { AssistantEntry, ROOT_CONVERSATION_ID, ToolResultEntry, UserEntry } from "@earendil-works/pi-durable";
39
- import { modelPortFor, RUNNER_RECORDS, TurnParked } from "@parcha/agentrun-kernel";
40
- import { foldSession, INTERRUPTED_TEXT } from "@parcha/agentrun-kernel/kernel";
41
- import { failureText } from "@parcha/agentrun-kernel/process";
42
- import { BARRIER, syncNow } from "@parcha/pi-durable-disk";
43
- import { confineOf } from "./adapters.js";
44
- import { hostTools } from "./host-tools.js";
45
- import { endsTurn } from "./tool-gate.js";
46
- import { BOUND_FIELD, CAP_REFUSAL_CODE, CAP_REFUSED_FIELD, CAP_TOLERANCE, capToolSpend, holdsInFlight, previousOf, refusalFields, paidHolds, takePaidRefusal, typicalCost, useSpend, wrapUpDue, wrapUpWords } from "./cap.js";
47
- import { durableSessions } from "./sessions.js";
48
- import { handsParallel, planeOf } from "./tool-plane.js";
49
- import { parallelOf } from "./web-fetch.js";
50
- import { WEB_SEARCH_TOOL } from "./web-search.js";
51
- import { ADAPTER_API, BOOKED, MESSAGE, MESSAGE_END, TURN_END } from "./turn-end.js";
52
- import { CAP_WRAPUP, originOf, REQUEST_CONTINUED, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_STARTED, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
53
- /** The root's marker of a paid request already written as a pi.assistant entry (turn-end.ts). */
54
- export { BOOKED } from "./turn-end.js";
55
- /** The cost of a request whose answer was written at unknown cost, and its tokens, written once it came in: the timeline
56
- * adds it to the run's cost without counting a request, and a later open reads it as that request's cost being in. */
57
- export const PRICED_LATE = REQUEST_COST_LATE;
58
- /** How long a turn's end waits for its requests' costs, booked once the proxy has answered the harness. */
59
- export const BOOKING_WAIT_MS = 2_000;
60
- /** For tests only: how long each of a harness run's root writes waits first, as on a store slow to write; only under a
61
- * test runner (node --test's NODE_TEST_CONTEXT), at most a second. */
62
- export const ROOT_WRITE_DELAY_ENV = "AGENTRUN_SERVE_TEST_ROOT_WRITE_DELAY_MS";
63
- export function rootWriteDelayMs(env = process.env) {
64
- if (!env.NODE_TEST_CONTEXT)
65
- return 0;
66
- const ms = Number(env[ROOT_WRITE_DELAY_ENV]);
67
- return Number.isFinite(ms) && ms > 0 ? Math.min(ms, 1_000) : 0;
68
- }
69
- /** For tests only: the Nth paid request of a harness run (counting from 1) whose start mark fails to commit, once, as on
70
- * a store that refused the write; only under a test runner (node --test's NODE_TEST_CONTEXT). */
71
- export const START_MARK_FAIL_ENV = "AGENTRUN_SERVE_TEST_START_MARK_FAIL_AT";
72
- export function startMarkFailAt(env = process.env) {
73
- if (!env.NODE_TEST_CONTEXT)
74
- return undefined;
75
- const n = Number(env[START_MARK_FAIL_ENV]);
76
- return Number.isSafeInteger(n) && n > 0 ? n : undefined;
77
- }
78
- /** The root's record of a message the door accepted, and of its end: `sent` to the session, or dropped by a stop. */
79
- export { MESSAGE, MESSAGE_END } from "./turn-end.js";
80
- /** A turn's end on the root (turn-end.ts): the message it took, the session's own outcome (`completed`, `interrupted`,
81
- * `failed`) and the turn's answer, in the commit of the turn's last entries (its answer, its costs, any error). The only
82
- * record that a turn which took the person's message is over: a request without content is written alike whether it
83
- * ended the turn or not. */
84
- export { TURN_END } from "./turn-end.js";
85
- /** A row id's place in the store: its entry's id. */
86
- const placeOf = (id) => Number(id.slice(id.lastIndexOf(":") + 1));
87
- const now = () => Date.now();
88
- const textOf = (content) => typeof content === "string" ? content : Array.isArray(content) ? content.map((part) => (part && typeof part === "object" && "text" in part && typeof part.text === "string" ? part.text : "")).join("") : "";
89
- /** A request's tokens as pi counts them (`input` excludes cached tokens), the `usage` a cost entry carries; undefined
90
- * when it has no input or output count, or no token at all (a usage that was not read is zeros, never a count). */
91
- function tokensOf(usage) {
92
- if (!usage || typeof usage !== "object")
93
- return undefined;
94
- const u = usage;
95
- const count = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
96
- const [input, output] = [count(u.input), count(u.output)];
97
- if (input === undefined || output === undefined)
98
- return undefined;
99
- const tokens = { input, output, cacheRead: count(u.cacheRead) ?? 0, cacheWrite: count(u.cacheWrite) ?? 0 };
100
- return tokens.input + tokens.output + tokens.cacheRead + tokens.cacheWrite > 0 ? tokens : undefined;
101
- }
102
- /** One request as pi's own assistant message: its content, the model it asked for (the harness's id when that is not
103
- * known), and its usage with the cost when it is known. Tokens not known are 0, which pi's timeline reads as unknown.
104
- * `error`: a turn that ended on an error, as pi's own reads (the cap's refusal is spend_cap_reached), at $0. */
105
- /** A recorded tool output's text: a string, or `{ text }` (a tool that answered with images too). */
106
- const outputText = (output) => (typeof output === "string" ? output : output && typeof output === "object" && typeof output.text === "string" ? output.text : JSON.stringify(output ?? null));
107
- function assistantMessage(harness, model, request, text, calls, error) {
108
- if (error !== undefined) {
109
- return { role: "assistant", content: [], api: ADAPTER_API, provider: harness, model: harness, stopReason: "error", errorMessage: error, timestamp: now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
110
- }
111
- const usage = request?.usage;
112
- const known = usage !== undefined && usage.usd !== null && usage.usd !== undefined;
113
- const tokens = { input: usage?.input ?? 0, output: usage?.output ?? 0, cacheRead: usage?.cacheRead ?? 0, cacheWrite: usage?.cacheWrite ?? 0 };
114
- return {
115
- role: "assistant",
116
- content: [...(text ? [{ type: "text", text }] : []), ...calls],
117
- api: ADAPTER_API,
118
- provider: harness,
119
- model: model ?? harness,
120
- usage: {
121
- ...tokens,
122
- totalTokens: tokens.input + tokens.output + tokens.cacheRead + tokens.cacheWrite,
123
- // No total when the price is unknown: the timeline's sum is then unknown, never this request at 0.
124
- cost: known ? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: usage.usd } : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
125
- },
126
- stopReason: calls.length ? "toolUse" : "stop",
127
- timestamp: now(),
128
- };
129
- }
130
- /** A request's cost as the wrap-up's typical cost counts it: its own reported cost (the runner's request_end usage.usd,
131
- * the `usd` of its runner.turn), when known and above 0. Never a figure it was booked or held at (a lost request's hold,
132
- * a stopped one's count): the live process and one opened again count the same. */
133
- const pricedUsd = (usd) => (typeof usd === "number" && Number.isFinite(usd) && usd > 0 ? usd : undefined);
134
- /** The session's own model's priced requests in its records, in order (the wrap-up's typical cost): each runner.turn whose
135
- * own cost is priced (pricedUsd) and whose runner.request was not a side call, as the live process counted them. */
136
- export function ownCosts(records) {
137
- const side = new Set();
138
- const costs = [];
139
- for (const record of records) {
140
- const data = (record.data ?? {});
141
- if (record.kind === RUNNER_RECORDS.request && data.side === true && typeof data.turn === "number")
142
- side.add(data.turn);
143
- if (record.kind !== RUNNER_RECORDS.turn || (typeof data.turn === "number" && side.has(data.turn)))
144
- continue;
145
- const usd = pricedUsd(data.usd);
146
- if (usd !== undefined)
147
- costs.push(usd);
148
- }
149
- return costs;
150
- }
151
- /** The wrap-up's note told under `capUsd` in these records: the note (its row's data) of a runner.turn whose request
152
- * carried it and ended answered, by its booking's rule (`answered`). A request that ended unanswered (an error status, a
153
- * loss, our stop, one that never left) or that a crash cut told nothing. */
154
- export function toldIn(records, capUsd) {
155
- if (capUsd === undefined)
156
- return undefined;
157
- for (const record of records) {
158
- if (record.kind !== RUNNER_RECORDS.turn)
159
- continue;
160
- const data = (record.data ?? {});
161
- const note = data.note;
162
- if (!note || typeof note.capUsd !== "number" || Math.abs(note.capUsd - capUsd) > CAP_TOLERANCE || typeof note.key !== "string" || typeof note.leftUsd !== "number" || typeof note.words !== "string")
163
- continue;
164
- if (data.rule === "answered" || (typeof data.rule === "string" && data.rule.startsWith("answered:")))
165
- return { key: note.key, capUsd: note.capUsd, leftUsd: note.leftUsd, words: note.words };
166
- }
167
- return undefined;
168
- }
169
- /** The door and the open of a run whose session is `spec` on `adapter`, with the host tools `tools` names (built at the
170
- * open, over the run's environment; its coding tools from `coding`, the run's coding source, host-tools.ts).
171
- * `budgetUsd`: the run's spend cap. `cancelled`: whether the run was cancelled (request-start.ts `cancelledIn`): once it
172
- * says so, no model request leaves, as on pi. `cwd`: the run's workspace, the directory its file tools confine to, where
173
- * the harness works too (the adapter's io.cwd), so a path the model builds from its working directory is one the tools
174
- * take (in a box, coding-tools.ts names it at the box's work dir). `gate`: the run's tool gate, which each host tool
175
- * call passes. */
176
- export function adapterRun(make, harness, spec, context, budgetUsd, tools = [], dir, cap, cancelled = () => false, cwd, coding, stopRecord, gate, extra = []) {
177
- const plane = planeOf(process.env);
178
- // The web tools' Parallel key, when one resolves to Parallel, read as the run's app loads, before its process starts
179
- // one of its own (web-fetch.ts).
180
- if (handsParallel(plane))
181
- parallelOf(process.env);
182
- // web_search resolved native is the harness's own search (adapters.ts turns it on, with its input allowance): no host
183
- // tool of the name.
184
- if (plane.web_search === "native")
185
- tools = tools.filter((name) => name !== WEB_SEARCH_TOOL);
186
- // The run's cap, or its cancel, refused a request: the turn ends on it, and its refusal is written as pi's is.
187
- let refused;
188
- // That `refused` is the cap's, not the cancel's: its error entry gets a start mark of its own first, as pi's does, so the
189
- // run's usage counts no request for it.
190
- let capRefused = false;
191
- // A refusal for room's figures, for its start mark (cap.ts RefusalFigures).
192
- let refusedFigures;
193
- const CANCELLED = "the run was cancelled: the model request was not sent";
194
- // What the run's paid tools charged, in earlier processes (read at the open) and this one: null once one is unknown.
195
- let charged = 0;
196
- // Each admitted request's hold until its cost is booked: the booking's spend counts it only then.
197
- const inFlight = holdsInFlight();
198
- // The session's previous request on each model, as the cap prices the next one by it (cap.ts Previous): each admitted
199
- // request's input bound and bound, from the guard (one slot: admissions run one at a time) to its start, by turn, until
200
- // it answers with its usage. In this process only: a new process prices its first request with nothing cached.
201
- let admittedNext;
202
- const sentOf = new Map();
203
- const previous = new Map();
204
- // The run's spend as a paid tool's check reads it (useSpend, set at the open): a paid call refused under it pauses the
205
- // run at this run's next request (guard).
206
- let spend;
207
- const plus = (a, b) => (a === null || b === null ? null : a + b);
208
- // `pending`: the note a request was admitted carrying, until that request (`turn`, once it starts) ends: told when it
209
- // ended answered, else re-armed for the next request. Re-telling is cheap (one note more, held at its bytes); a tell
210
- // lost is not, as the run then reaches its cap unwarned.
211
- const wrap = { costs: [], sent: false, entryDue: false };
212
- /** The note's row (CAP_WRAPUP, display only: whether the note was told is the answered request's runner.turn), now, or
213
- * after the message of the turn it is told in (`entryDue`). */
214
- const writeRow = (data) => {
215
- if (wrap.entryDue)
216
- wrap.row = data;
217
- else
218
- later(() => commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: CAP_WRAPUP, data })))).catch(() => undefined);
219
- };
220
- /** The note for the request the model proxy is placing it in (ModelPort.note), when the wrap-up is due: what is left
221
- * of the cap as admission counts it now (`spentUsd`: what the run spent; what its requests and paid calls in flight
222
- * are held at) under three times the session's own model's typical request, or an earlier admission found it due. */
223
- const takeNote = (spentUsd, model, request) => {
224
- wrap.taken = undefined;
225
- if (budgetUsd === undefined || wrap.sent || wrap.pending || spentUsd === null)
226
- return undefined;
227
- const held = inFlight.total() + paidHolds();
228
- // The request taking the note, priced as its admission will price it: its own bound and asks as its client sent them,
229
- // after the previous request on its model when there is one (the cache), else uncached. Nothing kept in memory, so a
230
- // process opened again judges its first request so too.
231
- const before = model ? previous.get(model) : undefined;
232
- const asked = request ? { ...request, ...(before ? { previous: before } : {}) } : undefined;
233
- // Due by the typical (the measured one once a cost is priced; before that, step 0, this request's own input and a
234
- // typical answer, as pi's judge does) or by this request's least, room for about one more.
235
- const typical = wrap.costs.length > 0 ? typicalCost(wrap.costs, 0) : asked ? cap?.typicalUsd?.(asked) : undefined;
236
- const due = wrapUpDue(budgetUsd, spentUsd, held, typical ?? 0, asked ? cap?.leastUsd?.(asked) : undefined);
237
- if (!due)
238
- return undefined;
239
- const leftUsd = due.leftUsd;
240
- // Worded by what was priced as it is taken: the budget's words with nothing priced, else "finish now".
241
- wrap.taken = { key: spec.key, capUsd: budgetUsd, leftUsd, words: wrapUpWords(leftUsd, wrap.costs.length === 0) };
242
- return wrap.taken.words;
243
- };
244
- const guard = (request) => {
245
- const byCancel = cancelled();
246
- // A note an earlier admission carried whose request never started (refused by a stop after its check): re-armed.
247
- // Admissions run one at a time, and each request starts in its own, so a pending note with no turn yet is that one.
248
- if (wrap.pending && wrap.pending.turn === undefined)
249
- wrap.pending = undefined;
250
- // What the run spent: the booking's (every model request of the session's, the harness's and the run's own beside it,
251
- // a learned workflow node's: one meter) and its paid tools' charges; theirs in flight are held with the paid calls'
252
- // (paidHolds, capBefore).
253
- // A paid call the cap just refused for room (cap.ts takePaidRefusal): this request is refused in its words, so the
254
- // turn ends there and the run waits on a raise, as at a model request's refusal. A refusal no cap fixes comes first.
255
- const paid = byCancel || !cap || request.spentUsd === null ? undefined : takePaidRefusal(spend);
256
- const model = request.model;
257
- // A request the run sends beside the harness's (its host label) is priced with nothing cached by the harness's own, and
258
- // never stands for the harness's previous one: its prompt is another conversation's.
259
- const host = typeof request.host === "string";
260
- const before = typeof model === "string" && !host ? previous.get(model) : undefined;
261
- const judge = (asked) => cap?.beforeRequest({ ...asked, spentUsd: plus(request.spentUsd, charged), ...(before ? { previous: before } : {}) });
262
- // A request carrying the wrap-up's note is judged first as its client sent it (`inputTokensMaxWithoutNote`), as pi's
263
- // judge does: refused so, it is refused; admitted so, it goes with the note only if the note's bytes fit too, and
264
- // otherwise without it (`withoutNote`), the note left for another request. The note never refuses what fits.
265
- const noted = request.noted === true;
266
- const plainInput = request.inputTokensMaxWithoutNote;
267
- let withoutNote = false;
268
- let answer;
269
- if (byCancel)
270
- answer = { refuse: CANCELLED };
271
- else if (paid)
272
- answer = { refuse: `${CAP_REFUSAL_CODE}${paid.words}`, spentUsd: paid.figures.spentUsd, needsUsd: paid.figures.needsUsd, leastCapUsd: paid.figures.leastCapUsd };
273
- else if (noted && typeof plainInput === "number") {
274
- const plain = judge({ ...request, inputTokensMax: plainInput });
275
- const full = plain && "refuse" in plain ? plain : judge(request);
276
- withoutNote = !(plain && "refuse" in plain) && !!full && "refuse" in full;
277
- answer = withoutNote ? plain : full;
278
- }
279
- else
280
- answer = judge(request);
281
- if (answer && "refuse" in answer) {
282
- refused = answer.refuse;
283
- capRefused = !byCancel;
284
- // A note this request carried was never sent: the next request that can take it is told, with what is left then.
285
- // Only this request's: another one refused (a side call) leaves a note taken for a request still to be admitted.
286
- if (noted)
287
- wrap.taken = undefined;
288
- refusedFigures = !byCancel && "needsUsd" in answer && typeof answer.needsUsd === "number" && typeof answer.spentUsd === "number" && typeof answer.leastCapUsd === "number" ? { spentUsd: answer.spentUsd, needsUsd: answer.needsUsd, leastCapUsd: answer.leastCapUsd, ...("boundUsd" in answer && typeof answer.boundUsd === "number" && answer.boundUsd > 0 ? { boundUsd: answer.boundUsd } : {}) } : undefined;
289
- return answer;
290
- }
291
- inFlight.admitted(answer?.holdUsd);
292
- const side = request.side === true;
293
- // The bound its `previous` is read against for the next request on its model: the body as its client sent it, without
294
- // the note (the note goes after the client's content, in this request alone, so the next request's cached prefix is the
295
- // client's body). Its hold above is what it sends, the note included. A host request is marked: it is never `previous`.
296
- const inputTokensMax = noted && typeof plainInput === "number" ? plainInput : request.inputTokensMax;
297
- admittedNext = typeof model === "string" ? { model, ...(inputTokensMax === undefined ? {} : { inputTokensMax }), boundUsd: answer?.boundUsd ?? 0, ...(side ? { side } : {}), ...(host ? { host: true } : {}) } : undefined;
298
- if (!answer)
299
- return undefined;
300
- // Admitted carrying the note: it is pending until this request ends, and told only if it ends answered (its runner.turn
301
- // keeps the note, `note` below). Only the admission of the request that carries it settles the note taken: a side
302
- // call admitted between its take and that admission (the proxy reads the credential between the two) leaves it for
303
- // that request.
304
- const data = noted && !withoutNote && !side ? wrap.taken : undefined;
305
- if (noted)
306
- wrap.taken = undefined;
307
- const carried = data && !wrap.sent && !wrap.pending ? data : undefined;
308
- if (carried)
309
- wrap.pending = { data: carried };
310
- if (admittedNext && carried)
311
- admittedNext.note = true;
312
- // Admitted, limited to the output what is left of the cap buys (which the runner hands the model proxy): what the cap
313
- // holds it at, which the runner records, and counts it at if its cost never comes in; stopped part way by its client,
314
- // what streamed (cap.ts Admitted), never more than its hold (the runner).
315
- return { holdUsd: answer.holdUsd, ...(answer.outputTokensMax === undefined ? {} : { outputTokensMax: answer.outputTokensMax }), stoppedUsd: answer.stoppedUsd, ...(withoutNote ? { withoutNote: true } : {}), ...(carried ? { note: carried } : {}) };
316
- };
317
- /** The cancel, as the booking's stop: read again after this check and after the request's record is written, so a
318
- * cancel that lands between them still keeps the request from leaving. */
319
- const cancelStop = () => {
320
- if (!cancelled())
321
- return undefined;
322
- refused ??= CANCELLED;
323
- return new Error(CANCELLED);
324
- };
325
- // A paid request whose cost could not be written: the booking admits no request after it, and the turn stops on it.
326
- let halted;
327
- // The call the gate parked, until the next message starts a turn: no request leaves meanwhile, and the turn is
328
- // interrupted once the call's result is in and the requests in flight are booked (up to BOOKING_WAIT_MS). Not a
329
- // failure: the turn ends as the person's answer will resume it.
330
- let parked;
331
- // The parked call answered allow (the gate's unpark): the run's own requests beside the harness's (the approved call's
332
- // node) are admitted from then, while the harness's own stay held until the next message's turn. Apart from `parked`,
333
- // which names the call whose result still ends the parked turn: an allow that lands while the harness is still
334
- // recording that result leaves it, so the turn is interrupted as it would be without the allow.
335
- let approved = false;
336
- const PARKED = new TurnParked("the turn ended: a tool call waits for a person's approval");
337
- // Each call's arguments, by its id, for a park named by tool and arguments (endsTurn).
338
- const argsOf = new Map();
339
- /** Results of calls whose answer is not on the root yet, by call id: written right after the entry that holds the call
340
- * (flush), so a result is never above its call. A crash before that leaves the session's record, which the next open
341
- * writes from (settleCutCalls). */
342
- const deferred = new Map();
343
- /** The side calls' requests (a title, a summary on another model): their cost is their own, never the content's. */
344
- const sides = new Set();
345
- /** What each earlier request streamed, closed at the next request's start, oldest first, waiting to be written with its
346
- * own request's cost (flush). */
347
- const segments = [];
348
- /** The calls the root holds from an earlier process (read at the open): one run again after a crash is not written twice. */
349
- const onRoot = new Set();
350
- const results = new Map();
351
- let run;
352
- let session;
353
- // The session's open while it is under way, and whether the door's close has come: a session that lands after the
354
- // close is closed then (closeOnce), never left open by a process that is going.
355
- let opening;
356
- let closing = false;
357
- // One close per session, its promise shared: whichever caller starts it (the door's close, or an open that lands after
358
- // it), every caller awaits the same close to its end, and its failure reaches the door (its log line).
359
- const closes = new WeakMap();
360
- const closeOnce = (it) => {
361
- if (!it)
362
- return Promise.resolve();
363
- let done = closes.get(it);
364
- if (!done) {
365
- done = Promise.resolve().then(() => it.close());
366
- closes.set(it, done);
367
- }
368
- return done;
369
- };
370
- let opened;
371
- let openedDone = () => { };
372
- opened = new Promise((resolve) => (openedDone = resolve));
373
- let turn;
374
- // A person's stop of the turn in flight: its interrupt, which the turn's end waits for before it settles the turn.
375
- let stopping;
376
- // The door's emit, from attach as the door opens: a recovered turn, started by no submit, reports through it too.
377
- let emit;
378
- let attached = false;
379
- const queue = [];
380
- const stop = new AbortController();
381
- // The current request's content, and the requests whose cost is in but whose entry is not written yet.
382
- let text = "";
383
- let calls = [];
384
- // The turn's answer entry so far (its last request with text and no call), the MESSAGE its turn took, and whether the
385
- // instance is stopping (a drain, a fence, a park: no one's stop, so the turn it cuts gets no end, and the next open
386
- // resumes it if the session still holds it open, or restores its end, as onOpen's `restored`, if the session ended it).
387
- let answer;
388
- let taking;
389
- let draining = false;
390
- const costed = [];
391
- const written = new Set();
392
- // The request the harness asked last, and the requests whose answer has an entry (taken as its write begins).
393
- let current;
394
- const answered = new Set();
395
- // Requests written at unknown cost (their cost not in when their turn ended), and those whose cost is written.
396
- const unpriced = new Set();
397
- const priced = new Set();
398
- // Requests admitted and not yet booked, by turn: the proxy answers the harness before it books a response, so a turn
399
- // can end with its last request's cost still on its way.
400
- const open = new Set();
401
- // The requests in flight that the run sent beside the harness's (their host label), each booked on its own.
402
- const hosts = new Set();
403
- // The model each request asked for, by number: its entry names it.
404
- const models = new Map();
405
- let booked = () => { };
406
- /** Until every admitted request is booked, or `ms` pass. */
407
- const bookings = async (ms) => {
408
- for (const deadline = Date.now() + ms; open.size && Date.now() < deadline;) {
409
- await new Promise((resolve) => {
410
- booked = resolve;
411
- setTimeout(resolve, Math.max(0, deadline - Date.now())).unref();
412
- });
413
- }
414
- };
415
- // Writes in order, one at a time: the entries keep the order their events came in.
416
- let writing = Promise.resolve();
417
- const later = (work) => (writing = writing.then(work, work));
418
- // A test's seam (ROOT_WRITE_DELAY_ENV): each root write waits first, as on a store slow to write. None outside a test runner.
419
- const slowWrites = rootWriteDelayMs();
420
- // A test's seam (START_MARK_FAIL_ENV): the Nth paid request's start mark fails to commit, once. None outside a test runner.
421
- const failMarkAt = startMarkFailAt();
422
- let marks = 0;
423
- const commit = (change) => (slowWrites ? new Promise((resolve) => setTimeout(resolve, slowWrites)).then(() => run.harness.commit(change, context)) : run.harness.commit(change, context));
424
- /** A cost for a request already written: one written at unknown cost (below) gets its cost now, as an entry of its
425
- * own (one of `writes`, the flush's commit), so the run's spend counts it, once; any other is a duplicate. */
426
- const priceLate = (late, writes) => {
427
- if (!unpriced.has(late.request) || priced.has(late.request))
428
- return;
429
- const tokens = tokensOf(late.usage);
430
- writes.push((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: PRICED_LATE, data: { key: spec.key, request: late.request, usd: late.usage.usd ?? null, ...(tokens ? { usage: tokens } : {}) } }));
431
- priced.add(late.request);
432
- };
433
- const writtenAt = () => costed.findIndex((c) => written.has(c.request));
434
- /** Writes each request's content as its own entry, with that request's own cost: first the segments closed at a
435
- * request's start (what the request before it streamed), in order, then what the current request has so far.
436
- * Content with no cost yet waits for its own, and holds every later one behind it, but at a turn's end (`final`) it
437
- * is written as a request of unknown cost. A side call's cost, and a cost with no content, is an entry of its own.
438
- * Everything a flush writes is one commit, and `end` (a turn's end: its error and TURN_END) is the last of it, so a
439
- * turn's end is in the commit of its last entries. The bookkeeping goes first: a commit the store refuses ends the
440
- * process, and the next open reads the root again. */
441
- const flush = (final = false, end) => later(async () => {
442
- const writes = [];
443
- const commitAll = async () => {
444
- if (end)
445
- writes.push(end);
446
- if (writes.length)
447
- await commit(async (tx) => { for (const write of writes)
448
- await write(tx); });
449
- };
450
- // Each cost for a request already written, wherever it sits: a response is booked when its stream closes, so a
451
- // late cost can come in after a later request's.
452
- for (let at = writtenAt(); at >= 0; at = writtenAt())
453
- priceLate(costed.splice(at, 1)[0], writes);
454
- // A side call's cost (a title, a summary: no content of the session's) is its own entry, cost only, whenever it
455
- // comes in: never the cost of the content streaming meanwhile.
456
- for (let at = costed.findIndex((c) => sides.has(c.request)); at >= 0; at = costed.findIndex((c) => sides.has(c.request)))
457
- costOnly(costed.splice(at, 1)[0], writes);
458
- // The segments, oldest first: each written with its own request's cost, or waiting for it.
459
- while (segments.length && entryOf(segments[0], final, writes))
460
- segments.shift();
461
- if (segments.length)
462
- return commitAll();
463
- // Then what the current request has so far.
464
- if (text || calls.length) {
465
- const content = { request: current, text, calls };
466
- if (entryOf(content, final, writes)) {
467
- text = "";
468
- calls = [];
469
- }
470
- else
471
- return commitAll();
472
- }
473
- // More costs than content: each later one still gets its own entry, cost only, or is a late cost.
474
- while (costed.length)
475
- costOnly(costed.shift(), writes);
476
- await commitAll();
477
- });
478
- /** `content`'s entry, as its request's (`content.request`), into `writes`: with that request's own cost when it is in;
479
- * else, at a turn's end, at an unknown cost, booked so a later open never writes it again; else not yet (false). The
480
- * content of a request already written is its continuation, shown and never counted again. */
481
- const entryOf = (content, final, writes) => {
482
- const owner = content.request;
483
- const results = async (tx) => {
484
- // The results of its calls that ended before this entry was written, in order, right after it.
485
- for (const call of content.calls) {
486
- const result = deferred.get(call.id);
487
- deferred.delete(call.id);
488
- if (result)
489
- await result(tx);
490
- }
491
- };
492
- if (owner !== undefined && answered.has(owner)) {
493
- writes.push(async (tx) => {
494
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_CONTINUED, data: { key: spec.key, request: owner } });
495
- const entry = await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, models.get(owner), undefined, content.text, content.calls)] });
496
- if (content.text && !content.calls.length)
497
- answer = entry.id;
498
- await results(tx);
499
- });
500
- return true;
501
- }
502
- const at = owner === undefined ? (costed.length ? 0 : -1) : costed.findIndex((c) => c.request === owner);
503
- if (at < 0 && !final)
504
- return false;
505
- const request = at >= 0 ? costed.splice(at, 1)[0] : undefined;
506
- // At a turn's end with no cost in: its own request, still unbooked, is written at unknown cost and marked booked.
507
- // Content with no request of this process's own (a call a resumed turn ran before any request here) is the oldest
508
- // session request still unbooked: never a side call's or the host's own, which stream nothing of the session's.
509
- const mains = owner === undefined ? [...open].filter((r) => !sides.has(r) && !hosts.has(r)) : [];
510
- const unbooked = !request ? (owner !== undefined && open.has(owner) ? owner : mains.length ? Math.min(...mains) : undefined) : undefined;
511
- if (unbooked !== undefined)
512
- open.delete(unbooked);
513
- const marked = request?.request ?? unbooked ?? owner;
514
- if (marked !== undefined)
515
- answered.add(marked);
516
- writes.push(async (tx) => {
517
- const entry = await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, marked === undefined ? undefined : models.get(marked), request, content.text, content.calls)] });
518
- // The turn's answer so far: its last request with text and no call.
519
- if (content.text && !content.calls.length)
520
- answer = entry.id;
521
- // Its cost still to come: the timeline reads it pending, not a cost no one will ever know.
522
- if (unbooked !== undefined)
523
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_COST_PENDING, data: { key: spec.key, request: unbooked } });
524
- if (marked !== undefined)
525
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: BOOKED, data: { key: spec.key, request: marked, ...(request ? {} : { unpriced: true }) } });
526
- await results(tx);
527
- });
528
- if (marked !== undefined)
529
- written.add(marked);
530
- if (request)
531
- priced.add(request.request);
532
- else if (marked !== undefined)
533
- unpriced.add(marked);
534
- return true;
535
- };
536
- /** A request's cost with no content of its own (a side call's, or more costs than content): its own entry, cost only,
537
- * or for a request already written, its late cost. */
538
- const costOnly = (next, writes) => {
539
- if (written.has(next.request))
540
- return priceLate(next, writes);
541
- answered.add(next.request);
542
- writes.push(async (tx) => {
543
- await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, models.get(next.request), next, "", [])] });
544
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: BOOKED, data: { key: spec.key, request: next.request } });
545
- });
546
- written.add(next.request);
547
- priced.add(next.request);
548
- };
549
- const onModel = (event) => {
550
- if (event.type === "request_start") {
551
- inFlight.started(event.turn);
552
- // Its bound, on its start mark: the run's cost serves it while it is in flight (runs.ts).
553
- const admitted = admittedNext;
554
- admittedNext = undefined;
555
- if (admitted)
556
- sentOf.set(event.turn, admitted);
557
- if (admitted?.note && wrap.pending && wrap.pending.turn === undefined)
558
- wrap.pending.turn = event.turn;
559
- const bound = admitted && admitted.boundUsd > 0 ? { [BOUND_FIELD]: admitted.boundUsd } : {};
560
- // A request the run sends beside the harness's (its host label: a learned workflow's node) is the session's like
561
- // any, marked as it leaves and booked once it answers, but it is never the harness's current request: the harness's
562
- // text and calls are never its content, and its entry holds its cost alone, once, at its end (below), never through
563
- // the side calls' cost-only entries. A side call of the harness's own (a title, a summary) streams nothing of the
564
- // session's: what streams meanwhile stays the current request's. Any other request of the session's closes what
565
- // the one before it streamed, now, as that request's own segment (flush writes it with that request's cost), before
566
- // anything of the new one can stream.
567
- if (event.host !== undefined)
568
- hosts.add(event.turn);
569
- else if (admitted?.side)
570
- sides.add(event.turn);
571
- else {
572
- if (text || calls.length)
573
- segments.push({ request: current, text, calls });
574
- text = "";
575
- calls = [];
576
- current = event.turn;
577
- }
578
- open.add(event.turn);
579
- models.set(event.turn, event.model);
580
- void flush();
581
- // Marked on the root before it leaves, as a pi run's request is (request-start.ts): one never answered, a run that
582
- // ends without opening again (cancelled, or failed) reads as cut, its cost unknown, never as the sum without it.
583
- // The runner awaits this before the request is sent, and the mark is synced first, so a lost box never loses the
584
- // mark of a request that went. A mark that fails refuses the request.
585
- const failMark = failMarkAt !== undefined && ++marks === failMarkAt;
586
- return later(async () => {
587
- if (failMark)
588
- throw new Error("the store refused the start mark (a test's seam)");
589
- await commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_STARTED, data: { key: spec.key, request: event.turn, ...bound, ...(event.host === undefined ? {} : { host: event.host }) } })));
590
- })
591
- .then(() => syncNow(run?.store, BARRIER.sideRequestStarted))
592
- .catch((error) => {
593
- // A mark that fails refuses the request, which never leaves and ends with no request_end: nothing of it stays in
594
- // flight (its hold would make every later request look dearer), and a note it carried is left for the next one.
595
- open.delete(event.turn);
596
- inFlight.ended(event.turn);
597
- sentOf.delete(event.turn);
598
- if (wrap.pending?.turn === event.turn)
599
- wrap.pending = undefined;
600
- throw error;
601
- });
602
- }
603
- else {
604
- open.delete(event.turn);
605
- inFlight.ended(event.turn);
606
- // The previous request on its model, now: its usage, as the cap reads it (none when its cost or usage is unknown,
607
- // or it was cut: nothing cached to count on). A host request's is never the harness's previous one.
608
- const sent = sentOf.get(event.turn);
609
- sentOf.delete(event.turn);
610
- // The request that carried the note ended: told only when it ended answered. An error status, a loss, a cut, our stop
611
- // or a request that never left leave the note for the next request. Every path that can carry the note says how its
612
- // request ended (the model proxy, the runner's own withdrawals and cut bookings, the faux harness); only side calls
613
- // and host requests, which never carry it, may say nothing.
614
- // A host request never carries or settles the note.
615
- if (wrap.pending && event.host === undefined && wrap.pending.turn === event.turn) {
616
- const { data } = wrap.pending;
617
- wrap.pending = undefined;
618
- if (event.ended?.end === "answered") {
619
- wrap.sent = true;
620
- writeRow(data);
621
- }
622
- }
623
- // A priced request of the session's own model: the wrap-up's typical cost counts it (step 0 ends with the first; a
624
- // side call, the host's own among them, it never counts).
625
- const costUsd = pricedUsd(event.usage.usd);
626
- if (sent && !sent.side && costUsd !== undefined)
627
- wrap.costs.push(costUsd);
628
- const last = sent && !sent.host && event.usage.usd !== null && !event.usage.cut ? previousOf(event.usage, sent.inputTokensMax, now()) : undefined;
629
- if (sent && !sent.host)
630
- last ? previous.set(sent.model, last) : previous.delete(sent.model);
631
- if (event.host !== undefined || hosts.has(event.turn)) {
632
- // Its own entry, its cost alone, and its BOOKED marker (which closes its bound, bounds.ts), once: never the
633
- // content of the harness's request.
634
- hosts.delete(event.turn);
635
- booked();
636
- if (written.has(event.turn))
637
- return;
638
- written.add(event.turn);
639
- answered.add(event.turn);
640
- priced.add(event.turn);
641
- const host = event.host;
642
- later(() => commit(async (tx) => {
643
- await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, models.get(event.turn), { request: event.turn, usage: event.usage }, "", [])] });
644
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: BOOKED, data: { key: spec.key, request: event.turn, ...(host === undefined ? {} : { host }) } });
645
- })).catch(() => undefined);
646
- return;
647
- }
648
- costed.push({ request: event.turn, usage: event.usage });
649
- booked();
650
- // A cost that came in after its answer was written goes in now, not at some later flush, and so does one that came
651
- // in with no turn running, which no turn's flush would write. If that write fails, the next open writes it from
652
- // the session's booking, once.
653
- // And content with a call waits for this cost to be written: the call shows from then.
654
- if (written.has(event.turn) || turn === undefined || calls.length || segments.length)
655
- flush().catch(() => undefined);
656
- }
657
- };
658
- /** Each call the session recorded (`tool:<id>`) with no result on the root: a process died before it wrote one. Its
659
- * result is written from the session's record of it: its outcome, or for a `never` call with none, interrupted (the
660
- * kernel records that as the session opens again); its call first when the root never got it. A `safe` call with no
661
- * outcome runs again and reports itself. */
662
- const settleCutCalls = (records, resulted) => later(async () => {
663
- const writes = [];
664
- for (const effect of foldSession("", records).effectOrder) {
665
- const callId = effect.key.startsWith("tool:") ? effect.key.slice("tool:".length) : undefined;
666
- if (callId === undefined || resulted.has(callId) || (effect.status !== "completed" && effect.status !== "failed" && !(effect.status === "running" && effect.replay === "never")))
667
- continue;
668
- const name = effect.name.replace(/^tool\./, "");
669
- const isError = effect.status !== "completed";
670
- const said = effect.status === "completed" ? outputText(effect.output) : effect.status === "failed" ? failureText(effect.error ?? { message: "failed" }) : INTERRUPTED_TEXT;
671
- if (!onRoot.has(callId)) {
672
- const call = { type: "toolCall", id: callId, name, arguments: (effect.input ?? {}) };
673
- writes.push(async (tx) => {
674
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_CONTINUED, data: { key: spec.key, request: null } });
675
- await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, undefined, undefined, "", [call])] });
676
- });
677
- onRoot.add(callId);
678
- }
679
- writes.push((tx) => tx.appendEntry(ToolResultEntry, ROOT_CONVERSATION_ID, { model: [{ role: "toolResult", toolCallId: callId, toolName: name, content: [{ type: "text", text: said }], isError, timestamp: now() }], data: { diagnostics: [] } }));
680
- }
681
- if (writes.length)
682
- await commit(async (tx) => { for (const write of writes)
683
- await write(tx); });
684
- });
685
- const onEvent = (event) => {
686
- if (event.type === "text")
687
- text += event.delta;
688
- else if (event.type === "tool_start") {
689
- const call = { type: "toolCall", id: event.callId, name: event.name, arguments: (event.args ?? {}) };
690
- argsOf.set(event.callId, event.args ?? {});
691
- if (onRoot.has(event.callId))
692
- return;
693
- // A call of the current request's answer after that answer's entry was written (at its first call's end): written
694
- // now as the answer's continuation, so its result never comes before it and the next answer never holds it.
695
- const request = current;
696
- // Written as soon as its request's cost is in (now, or when it comes in), so the call shows while it runs.
697
- if (text || calls.length || request === undefined || !answered.has(request)) {
698
- calls.push(call);
699
- void flush();
700
- }
701
- else {
702
- later(() => commit(async (tx) => {
703
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_CONTINUED, data: { key: spec.key, request } });
704
- await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, models.get(request), undefined, "", [call])] });
705
- }).then(() => undefined));
706
- }
707
- }
708
- else if (event.type === "tool_end") {
709
- const said = results.get(event.callId)?.text ?? (event.isError ? "The tool failed." : "Done.");
710
- const result = (tx) => tx.appendEntry(ToolResultEntry, ROOT_CONVERSATION_ID, {
711
- model: [{ role: "toolResult", toolCallId: event.callId, toolName: event.name, content: [{ type: "text", text: said }], isError: event.isError, timestamp: now() }],
712
- data: { diagnostics: [] },
713
- });
714
- // A result is written only after its call's entry is on the root. A call still in the answer not yet written (one
715
- // that ended before its request's cost came in) has its result written with that entry, right after it; any other
716
- // call's entry is written, or queued, before this result.
717
- const waiting = calls.some((call) => call.id === event.callId) || segments.some((segment) => segment.calls.some((call) => call.id === event.callId));
718
- if (waiting)
719
- deferred.set(event.callId, result);
720
- void flush();
721
- if (!waiting)
722
- later(() => commit(async (tx) => void (await result(tx))).then(() => undefined));
723
- // The parked call's result is in: its turn ends here, settled once the interrupt is done (runTurns). The CLI runs a
724
- // tool as soon as its call has streamed, before the request that asked for it has ended (its usage comes with that
725
- // end): the interrupt waits for the requests in flight to be booked, up to BOOKING_WAIT_MS, so that request is booked
726
- // at its price. Past the wait it is cut as before, its cost unknown. No request leaves meanwhile (PARKED).
727
- if (endsTurn(parked, { callId: event.callId, tool: event.name, args: argsOf.get(event.callId) }) && !stopping)
728
- stopping = bookings(BOOKING_WAIT_MS).then(() => session?.interrupt());
729
- }
730
- };
731
- /** The session's requests, from its runner records, by number: the model each asked for, and the usage of each it
732
- * booked. A booking written before runner.turn kept tokens has none: its entry's zeros read as unknown. */
733
- const inSession = (records) => {
734
- const asked = new Map();
735
- const booked = new Map();
736
- let admitted = 0;
737
- for (const record of records) {
738
- const data = (record.data ?? {});
739
- if (record.kind === RUNNER_RECORDS.request) {
740
- admitted = typeof data.turn === "number" ? data.turn : admitted + 1;
741
- if (typeof data.model === "string")
742
- asked.set(admitted, data.model);
743
- }
744
- // A request withdrawn as its record was written (a stop came then) never left: it is no request of the run's.
745
- else if (record.kind === RUNNER_RECORDS.turn && data.unsent !== true) {
746
- const request = typeof data.turn === "number" ? data.turn : admitted;
747
- booked.set(request, { ...(tokensOf(data.usage) ?? { input: 0, output: 0 }), usd: typeof data.usd === "number" ? data.usd : null, estimated: data.usd === null || data.cut === true });
748
- }
749
- }
750
- return { asked, booked };
751
- };
752
- /** The person's message: the session's new turn, then its entry and its end on the root. */
753
- const sendOf = (message) => async () => {
754
- parked = undefined;
755
- approved = false;
756
- argsOf.clear();
757
- await message.recorded;
758
- taking = message.id;
759
- wrap.entryDue = true;
760
- try {
761
- await session.send(message.content);
762
- }
763
- catch (error) {
764
- // No message entry follows: a row held for it is written as it is.
765
- const row = wrap.row;
766
- wrap.entryDue = false;
767
- wrap.row = undefined;
768
- if (row)
769
- later(() => commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: CAP_WRAPUP, data: row })))).catch(() => undefined);
770
- throw error;
771
- }
772
- await later(() => commit(async (tx) => {
773
- await tx.appendEntry(UserEntry, ROOT_CONVERSATION_ID, { model: [{ role: "user", content: [{ type: "text", text: message.content }], timestamp: now() }], ...(message.origin ? { data: { origin: message.origin } } : {}) });
774
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE_END, data: { key: spec.key, id: message.id, sent: true } });
775
- // A wrap-up told in this turn's first request: its row after the message it answers.
776
- const row = wrap.row;
777
- wrap.entryDue = false;
778
- wrap.row = undefined;
779
- if (row)
780
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: CAP_WRAPUP, data: row });
781
- }).then(() => undefined));
782
- };
783
- /** Turns until nothing waits: the turn, then each message that waited for it, as one busy period on the door (as a pi
784
- * run's follow-ups are), so the server never reads the run idle, and done, while an accepted message is unanswered. A
785
- * message that arrives meanwhile waits its place. `carried`: the first turn's answer so far, when it is a turn an
786
- * earlier process left open and this one recovers (its answer already on the root); a new message's turn starts with
787
- * none. */
788
- const runTurns = (first, carried) => {
789
- turn = (async () => {
790
- emit?.({ type: "run_start" });
791
- for (let start = first, carry = carried; start; carry = undefined) {
792
- let failed;
793
- let status = "failed";
794
- answer = carry;
795
- // A turn of its own: a paid call's refusal a stop left pending (its turn stopped before its next request) is
796
- // let go, so this turn's first request is judged as any other, never paused for a call the person moved on from.
797
- if (spend)
798
- takePaidRefusal(spend);
799
- try {
800
- await start();
801
- const end = await session.turnEnd();
802
- status = end.status;
803
- if (end.status === "failed")
804
- failed = end.error ?? "the turn failed";
805
- }
806
- catch (error) {
807
- failed = String(error?.message ?? error);
808
- }
809
- finally {
810
- // A turn the person stopped can still be open in the session (an interrupt writes no end there, and a prompt it
811
- // stopped before the harness placed it is still pending). It is settled once the interrupt is done, before the
812
- // turn's end and any next message, so nothing of it goes on or is sent again. An adapter without the settle is
813
- // left as before. A settle that fails leaves the turn to the next open, which settles it from the stop record.
814
- if (stopping) {
815
- await stopping.catch(() => undefined);
816
- stopping = undefined;
817
- if (session?.state === "open_turn" && typeof session.settleOpenTurn === "function")
818
- await session.settleOpenTurn().catch(() => undefined);
819
- }
820
- // The last request's cost, booked once the proxy has answered: waited for, so the answer is written with it.
821
- await bookings(BOOKING_WAIT_MS);
822
- // A turn that failed (the cap's refusal, a cost the booking could not write, or the harness's own failure) writes
823
- // its error and ends failed. The run's status is its last turn's end (turns.ts): with no message waiting, the run
824
- // fails on this error, as a pi run does; a message waiting behind it is still sent, and when that turn completes,
825
- // the run completes with its answer, this failure kept in the timeline.
826
- // A turn the gate parked ends interrupted, never failed on the request its park refused.
827
- const why = refused ?? halted?.message ?? (failed === undefined || parked !== undefined ? undefined : `${harness}: ${failed}`);
828
- if (parked !== undefined && why === undefined)
829
- status = "interrupted";
830
- // A test's seam, unset in a server (AGENTRUN_SERVE_TEST_CRASH_AFTER_ANSWER, a file that marks it once): a parked
831
- // turn holds its end until the answer's message is recorded, then the process goes by a signal, as a crash
832
- // between the two would leave the run.
833
- if (CRASH_SEAM && parked !== undefined && !existsSync(CRASH_SEAM)) {
834
- await answerIn;
835
- writeFileSync(CRASH_SEAM, "");
836
- process.kill(process.pid, "SIGKILL");
837
- }
838
- const unsent = refused !== undefined && capRefused;
839
- const figures = unsent ? refusedFigures : undefined;
840
- refusedFigures = undefined;
841
- refused = undefined;
842
- capRefused = false;
843
- const pending = open.size > 0;
844
- // The turn's end, in the commit of its last entries (flush's one commit): the run's end is read from it alone
845
- // (turns.ts). A turn the instance's own stop cut gets none: the next open resumes it while the session holds it
846
- // open, or restores its end from the root (completed with its answer) when the session had ended it.
847
- const cut = draining && why === undefined && status === "interrupted";
848
- await flush(true, cut ? undefined : async (tx) => {
849
- if (why !== undefined) {
850
- // A refusal of the cap's: a start mark of its own first, as pi's is, so the run's usage counts no request for it.
851
- if (unsent)
852
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_STARTED, data: { [CAP_REFUSED_FIELD]: true, ...refusalFields(figures) } });
853
- await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, undefined, undefined, "", [], why)] });
854
- }
855
- const data = {
856
- key: spec.key, ...(taking === undefined ? {} : { message: taking }), status: why === undefined ? status : "failed",
857
- answer: why === undefined && status === "completed" ? (answer ?? null) : null, ...(why === undefined ? {} : { error: why }), cost: pending ? "pending" : "booked",
858
- };
859
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: TURN_END, data });
860
- });
861
- await writing;
862
- // A cost that came in while this turn ended, after its flush: written now, while the run still reads busy, so a
863
- // message that comes in meanwhile waits its place below and goes on as the next turn of this busy period.
864
- if (costed.length)
865
- await flush().catch(() => undefined);
866
- }
867
- // Stopping: the messages still waiting are sent by the next open, which finds them with no end.
868
- const next = draining ? undefined : queue.shift();
869
- start = next === undefined ? undefined : sendOf(next);
870
- }
871
- // Nothing from here to run_end waits: a message that comes in once the run reads idle starts the next busy period,
872
- // after this run_end. A cost that comes in from now on is written as it comes in (onModel).
873
- turn = undefined;
874
- // A stop that came after this busy period's last turn had ended stopped nothing: it is not the next one's.
875
- stopping = undefined;
876
- emit?.({ type: "run_end" });
877
- })();
878
- };
879
- /** The gate's resume (tool-gate.ts): the answer as a message of its own, recorded with the gate's mark in one commit,
880
- * then sent as a person's is. */
881
- const CRASH_SEAM = process.env.AGENTRUN_SERVE_TEST_CRASH_AFTER_ANSWER;
882
- let answerRecorded;
883
- const answerIn = new Promise((resolve) => (answerRecorded = resolve));
884
- const resume = async (id, content, mark, origin) => {
885
- await opened;
886
- // The server's message: its origin is written on its user entry, so the Timeline never shows it as the person's.
887
- const message = { id: `approval-${id}`, content, ...(origin ? { origin } : {}), recorded: commit(async (tx) => {
888
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE, data: { key: spec.key, id: `approval-${id}`, content, ...(origin ? { origin } : {}) } });
889
- await mark(tx);
890
- }) };
891
- await message.recorded;
892
- answerRecorded?.();
893
- if (turn)
894
- queue.push(message);
895
- else
896
- runTurns(sendOf(message));
897
- };
898
- const door = {
899
- attach(given) {
900
- emit = given;
901
- attached = true;
902
- },
903
- async submit(input, ctx) {
904
- if (!attached)
905
- emit = ctx.emit;
906
- await opened;
907
- if (turn && input.whenBusy === "reject")
908
- return { accepted: false, reason: "busy" };
909
- const id = randomUUID();
910
- const content = textOf(input.content);
911
- const origin = input.origin;
912
- const message = { id, content, ...(origin ? { origin } : {}), recorded: commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE, data: { key: spec.key, id, content, ...(origin ? { origin } : {}) } }))) };
913
- if (turn)
914
- queue.push(message);
915
- else
916
- runTurns(sendOf(message));
917
- await message.recorded;
918
- return { accepted: true };
919
- },
920
- async abort(ctx) {
921
- if (!attached)
922
- emit = ctx.emit;
923
- // The instance stopping (a drain, a fence, a park) is no one's stop: the turn it cuts gets no end, the next open
924
- // resumes it (or restores its end, when the session had ended it), and the messages waiting stay, for it to send.
925
- if (ctx.reason === "stop") {
926
- draining = true;
927
- if (!turn)
928
- return "idle";
929
- await session?.interrupt();
930
- return "aborted";
931
- }
932
- const dropped = queue.splice(0);
933
- if (dropped.length) {
934
- await Promise.all(dropped.map((message) => message.recorded));
935
- await commit(async (tx) => {
936
- for (const message of dropped)
937
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE_END, data: { key: spec.key, id: message.id, sent: false } });
938
- });
939
- }
940
- if (!turn)
941
- return "idle";
942
- stopping = session?.interrupt();
943
- await stopping;
944
- return "aborted";
945
- },
946
- // The process is letting the run go (the door's stop, busy or idle, after its abort): the session closes, which stops
947
- // the harness's own processes (its CLI, its app-server), so none outlives this one.
948
- async close() {
949
- closing = true;
950
- if (session)
951
- return closeOnce(session);
952
- // An open still under way is stopped where the adapter can stop it (its signal), and the session it lands with is
953
- // closed here, within the door's bound, or by the open itself once it lands (above).
954
- stop.abort();
955
- await closeOnce(await opening?.catch(() => undefined));
956
- },
957
- harness,
958
- busy: () => turn !== undefined,
959
- };
960
- return {
961
- door,
962
- port: (label) => session?.port?.(label),
963
- async onOpen(durable) {
964
- run = durable;
965
- const sessions = durableSessions(durable.harness, context, durable.store);
966
- // The requests already written on the root, and the messages accepted and never sent, from any earlier process.
967
- const root = await durable.harness.conversation(ROOT_CONVERSATION_ID, context);
968
- const accepted = new Map();
969
- const paid = [];
970
- // The turn that took the last message sent, while the root has no end for it (a process died before the commit of
971
- // its last entries, or its own stop cut it): the message, whether the bridge wrote that turn's error, and its answer
972
- // so far (its newest request with text and no call).
973
- let unended;
974
- // The person's messages on the root: the newest one's entry id, and how many, for the run's stop record.
975
- let lastUser;
976
- let users = 0;
977
- // The calls whose result the root holds.
978
- const resulted = new Set();
979
- for (let cursor; root;) {
980
- const page = await root.entries({ order: "ascending" }, 500, cursor, context);
981
- for (const entry of page.items) {
982
- const data = entry.data;
983
- if (entry.kind === TOOL_COST || entry.kind === TOOL_STARTED)
984
- paid.push(entry);
985
- const message = entry.model?.[0];
986
- if (unended && message?.api === ADAPTER_API && message.stopReason === "error")
987
- unended.failed = true;
988
- if (unended && message?.api === ADAPTER_API && message.stopReason === "stop" && textOf(message.content))
989
- unended.answer = entry.id;
990
- if (message?.role === "user") {
991
- users += 1;
992
- lastUser = Number(entry.id);
993
- }
994
- if (message?.api === ADAPTER_API)
995
- for (const block of message.content ?? [])
996
- if (block?.type === "toolCall" && typeof block.id === "string")
997
- onRoot.add(block.id);
998
- if (message?.role === "toolResult" && typeof message.toolCallId === "string")
999
- resulted.add(message.toolCallId);
1000
- if (data?.key !== spec.key)
1001
- continue;
1002
- // The wrap-up was told under this very cap in an earlier process: once per cap (a raise's new cap re-arms it).
1003
- if (entry.kind === CAP_WRAPUP && budgetUsd !== undefined && typeof data.capUsd === "number" && Math.abs(data.capUsd - budgetUsd) <= CAP_TOLERANCE)
1004
- wrap.sent = true;
1005
- if (entry.kind === BOOKED && typeof data.request === "number") {
1006
- written.add(data.request);
1007
- (data.unpriced === true ? unpriced : priced).add(data.request);
1008
- }
1009
- else if (entry.kind === PRICED_LATE && typeof data.request === "number")
1010
- priced.add(data.request);
1011
- else if (entry.kind === MESSAGE && typeof data.id === "string")
1012
- accepted.set(data.id, { id: data.id, content: String(data.content ?? ""), ...(originOf(data.origin) ? { origin: data.origin } : {}), recorded: Promise.resolve() });
1013
- else if (entry.kind === MESSAGE_END && typeof data.id === "string") {
1014
- accepted.delete(data.id);
1015
- if (data.sent === true)
1016
- unended = { message: data.id, failed: false, answer: null };
1017
- }
1018
- else if (entry.kind === TURN_END)
1019
- unended = undefined;
1020
- }
1021
- if (page.next === undefined)
1022
- break;
1023
- cursor = page.next;
1024
- }
1025
- // What the paid tools charged in earlier processes, as the cap counts it: a call a crash cut at its held figure.
1026
- charged = capToolSpend(paid);
1027
- // The prefix pi's commands start under in this run, from pi-durable-disk's own builder: the harness's process too.
1028
- const env = (await durable.env({ conversationId: ROOT_CONVERSATION_ID, read: undefined }, context));
1029
- if (typeof env.confinePrefix !== "function")
1030
- throw new Error("the run's environment gives no confinement for the harness's process");
1031
- const adapter = await make(confineOf(env.confinePrefix()));
1032
- const writer = await sessions.open(spec.key);
1033
- const records = await writer.read();
1034
- // The session's own model's priced requests in earlier processes, in order: the wrap-up's typical cost reads them.
1035
- wrap.costs.push(...ownCosts(records));
1036
- // Told in an earlier process: a request that carried the note under this cap and ended answered (its runner.turn,
1037
- // written as its cost was, keeps the note). Its row is display only: one lost (a commit that failed) is written
1038
- // again now. A request that ended unanswered, or that a crash cut (booked cut, with no note), told nothing.
1039
- const told = toldIn(records, budgetUsd);
1040
- if (told && !wrap.sent) {
1041
- wrap.sent = true;
1042
- later(() => commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: CAP_WRAPUP, data: told })))).catch(() => undefined);
1043
- }
1044
- // Before the cut requests are booked, which may write their entries.
1045
- for (const [request, model] of inSession(records).asked)
1046
- models.set(request, model);
1047
- const booking = await modelPortFor(writer, {
1048
- records,
1049
- key: spec.key,
1050
- ...(budgetUsd !== undefined ? { budgetUsd } : {}),
1051
- beforeRequest: guard,
1052
- onEvent: onModel,
1053
- // The booking's spend is the run's one meter (a learned node's requests are the session's: no side spend of their own).
1054
- note: (model, request) => takeNote(plus(booking.spentUsd(), charged), model, request),
1055
- stopped: (request) => {
1056
- const why = halted ?? cancelStop() ?? (parked === undefined || (approved && request.host !== undefined) ? undefined : PARKED);
1057
- // A stop refuses this request, and each one after it but an approved host request (which never carries the
1058
- // note): a note an admission gave a request the stop then refused never left, so the next request takes it,
1059
- // before the model proxy asks for it (takeNote), not only at that request's own check.
1060
- if (why && wrap.pending && wrap.pending.turn === undefined)
1061
- wrap.pending = undefined;
1062
- return why;
1063
- },
1064
- stop: (reason, message) => {
1065
- const error = new Error(message ?? reason);
1066
- if (reason === "model_error" && !halted) {
1067
- halted = error;
1068
- void session?.interrupt();
1069
- }
1070
- return error;
1071
- },
1072
- });
1073
- // A request a crash cut off is booked once, unknown, before anything is sent.
1074
- await booking.bookCut();
1075
- // A paid tool's check before it spends: the session's requests (the run's own beside the harness's among them), each
1076
- // booked once the proxy has answered (waited for, as at a turn's end), one still in flight at the worst case the cap
1077
- // held for it (as pi's spend counts it), with the run's charges; its charge joins them.
1078
- if (budgetUsd !== undefined) {
1079
- const now = () => plus(plus(booking.spentUsd(), charged), inFlight.total());
1080
- spend = {
1081
- cap: budgetUsd,
1082
- spent: async () => (await bookings(BOOKING_WAIT_MS), plus(booking.spentUsd(), charged)),
1083
- held: () => inFlight.total(),
1084
- add: (usd) => void (charged = plus(charged, usd)),
1085
- now,
1086
- };
1087
- useSpend(spend);
1088
- }
1089
- // Each request the session booked and the root has no entry for: its cost, with no content.
1090
- // Each request the session booked and the root does not have, or has at unknown cost only: written now, once.
1091
- for (const [request, usage] of inSession(await writer.read()).booked)
1092
- if (!written.has(request) || (unpriced.has(request) && !priced.has(request)))
1093
- costed.push({ request, usage });
1094
- await flush();
1095
- await settleCutCalls(records, resulted);
1096
- // The calls that wait for a person's approval, read before any turn goes on.
1097
- await gate?.load(durable, context, coding, extra);
1098
- // The park every gated call of the run's takes, built once: the host tools' here, and the MCP gateway's, which takes
1099
- // the same object beside them (`{ gate, park }`). A call parked by its id or by its tool and arguments ends its turn.
1100
- const park = { commit: (change) => commit(change), parked: (callId) => void (parked = { callId }), parkedBy: (match) => void (parked = match), turn: () => taking };
1101
- // An MCP call from the harness's own client takes the same park, and its result is kept by its call id too, for the
1102
- // root's record of it, as a host tool's is.
1103
- const gateway = spec.mcp;
1104
- const mcp = gateway && { ...gateway, call: async (...[server, tool, args, call]) => {
1105
- const result = await gateway.call(server, tool, args, { ...call, ...(gate ? { park } : {}) });
1106
- if (call.callId)
1107
- results.set(call.callId, { text: result.content.map((block) => block.text).join("\n\n"), isError: result.isError === true });
1108
- return result;
1109
- } };
1110
- opening = adapter.open({ ...spec, ...(mcp ? { mcp } : {}), tools: hostTools(durable, tools, context, results, coding, gate ? { gate, park } : undefined, extra) }, { writer, models: booking.models, signal: stop.signal, onEvent, ...(dir ? { dir } : {}), ...(cwd ? { cwd } : {}) });
1111
- session = await opening;
1112
- // The door closed while it opened (the process is going): this session is closed now, and nothing goes on in it.
1113
- // `closing` is set by the door's close alone, which awaits this same close (closeOnce) and logs its failure; the open
1114
- // waits for it too, and does not fail on it a second time.
1115
- if (closing)
1116
- return void (await closeOnce(session).catch(() => undefined));
1117
- // A turn the person stopped is still open in the session (an interrupt writes no end there), and it is not resumed.
1118
- // The run's stop record names the person's newest message when they stopped: with no message on the root newer than
1119
- // it, the open turn is the stopped one. The session settles it, ended interrupted, and the next message is a turn of
1120
- // its own. A turn a crash or a drain cut has no stop record newer than the newest message, and is resumed as before.
1121
- // A turn the gate parked is settled as a stopped one: its call waits for its answer, which resumes the run. So is
1122
- // one whose parked call was answered before a process went: its request names the turn (gate.parkedIn), so the
1123
- // answer's message, queued, follows it, and the turn is never run again.
1124
- const stopped = (stopRecord?.stopped_at !== undefined
1125
- ? lastUser !== undefined && lastUser <= placeOf(stopRecord.stopped_at)
1126
- : stopRecord?.stopped_after !== undefined && stopRecord.stopped_after === users) || gate?.waiting() === true || gate?.parkedIn(unended?.message) === true;
1127
- // An adapter written before settleOpenTurn has none: its stopped turn is recovered, as before.
1128
- if (session.state === "open_turn" && stopped && typeof session.settleOpenTurn === "function")
1129
- await session.settleOpenTurn();
1130
- // That turn is over in the session, and an earlier process died before it wrote the turn's end: written now, after
1131
- // what this open wrote and before any new turn. A turn the person stopped reads interrupted, from the stop record:
1132
- // settled by this open, or by an earlier one that died before it wrote this end. Otherwise the session says only that
1133
- // the turn is over; how it ended is what the root holds of it: failed when the bridge wrote its error, completed when
1134
- // its answer (a request with text and no call) is there. With neither, the turn is not known to have completed: it
1135
- // ends interrupted, and the run waits for the person (turns.ts), never answered "". The end names the message the
1136
- // turn took, as every turn end does.
1137
- const restored = session.state === "idle" && unended ? (stopped ? "interrupted" : unended.failed ? "failed" : unended.answer !== null ? "completed" : "interrupted") : undefined;
1138
- const restore = (status) => later(() => commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: TURN_END, data: { key: spec.key, message: unended.message, status, answer: status === "completed" ? unended.answer : null } }))));
1139
- // A turn the session holds open is the last message's, resumed now.
1140
- if (session.state === "open_turn" && unended)
1141
- taking = unended.message;
1142
- queue.push(...accepted.values());
1143
- // With nothing waiting, that end is the run's: written while the door is idle. A message accepted and never sent
1144
- // still waits, and a server started anew counts none: the door is busy (run_start) before that end goes out, and
1145
- // the message's turn follows in the same busy period, so no server reads the run done before it answers.
1146
- if (restored && !queue.length)
1147
- await restore(restored);
1148
- openedDone();
1149
- // Its answer so far is the root's, which a recovery that streams no new text keeps as the turn's.
1150
- if (session.state === "open_turn" && !gate?.waiting())
1151
- runTurns(() => session.recover(), unended?.answer ?? undefined);
1152
- else if (queue.length) {
1153
- const next = sendOf(queue.shift());
1154
- runTurns(restored ? async () => (await restore(restored), await next()) : next);
1155
- }
1156
- // The answers from now on: each resumes the session with one message of its own.
1157
- // The allow un-parks the run before the approved call runs: its own model requests (a learned workflow's node, on
1158
- // the session's route) go out; the harness's own wait for the resume's turn, which the park left them for.
1159
- gate?.start(resume, () => void (approved = true));
1160
- },
1161
- };
1162
- }