@parcha/agentrun-serve 0.0.0-bootstrap.0 → 0.1.0-beta.29

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 (229) hide show
  1. package/CHANGELOG.md +560 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +1724 -0
  5. package/dist/adapters.d.ts +205 -0
  6. package/dist/adapters.js +459 -0
  7. package/dist/agents.d.ts +124 -0
  8. package/dist/agents.js +302 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +324 -0
  11. package/dist/bound-files.d.ts +4 -0
  12. package/dist/bound-files.js +164 -0
  13. package/dist/box/record.d.ts +6 -0
  14. package/dist/box/record.js +41 -0
  15. package/dist/box/sweep.d.ts +53 -0
  16. package/dist/box/sweep.js +193 -0
  17. package/dist/box-image.d.ts +98 -0
  18. package/dist/box-image.js +283 -0
  19. package/dist/box-relay.d.ts +42 -0
  20. package/dist/box-relay.js +222 -0
  21. package/dist/boxes.d.ts +54 -0
  22. package/dist/boxes.js +182 -0
  23. package/dist/cap.d.ts +224 -0
  24. package/dist/cap.js +721 -0
  25. package/dist/catalog.d.ts +20 -0
  26. package/dist/catalog.js +53 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +167 -0
  29. package/dist/coding-tools.d.ts +31 -0
  30. package/dist/coding-tools.js +81 -0
  31. package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
  32. package/dist/console/assets/index-BN7oVcO4.js +445 -0
  33. package/dist/console/assets/index-By-jkqki.css +1 -0
  34. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  35. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  36. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  37. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  38. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  39. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  40. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  41. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  42. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  53. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  54. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  57. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  58. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  59. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  60. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  61. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  62. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  63. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  64. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  65. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  66. package/dist/console/index.html +15 -0
  67. package/dist/daytona-api.d.ts +21 -0
  68. package/dist/daytona-api.js +101 -0
  69. package/dist/decision-rows.d.ts +11 -0
  70. package/dist/decision-rows.js +116 -0
  71. package/dist/decisions.d.ts +94 -0
  72. package/dist/decisions.js +184 -0
  73. package/dist/effort-guidance.d.ts +5 -0
  74. package/dist/effort-guidance.js +14 -0
  75. package/dist/environment.d.ts +5 -0
  76. package/dist/environment.js +11 -0
  77. package/dist/errors.d.ts +72 -0
  78. package/dist/errors.js +66 -0
  79. package/dist/exa-keyless.d.ts +35 -0
  80. package/dist/exa-keyless.js +202 -0
  81. package/dist/fetch-page.d.ts +114 -0
  82. package/dist/fetch-page.js +182 -0
  83. package/dist/files.d.ts +60 -0
  84. package/dist/files.js +153 -0
  85. package/dist/grade.d.ts +96 -0
  86. package/dist/grade.js +348 -0
  87. package/dist/graph-view.d.ts +100 -0
  88. package/dist/graph-view.js +212 -0
  89. package/dist/harness-app.d.ts +38 -0
  90. package/dist/harness-app.js +626 -0
  91. package/dist/harness.d.ts +53 -0
  92. package/dist/harness.js +74 -0
  93. package/dist/home-path.d.ts +27 -0
  94. package/dist/home-path.js +78 -0
  95. package/dist/host-tools.d.ts +20 -0
  96. package/dist/host-tools.js +140 -0
  97. package/dist/host.d.ts +39 -0
  98. package/dist/host.js +81 -0
  99. package/dist/hosted-search.d.ts +27 -0
  100. package/dist/hosted-search.js +129 -0
  101. package/dist/import-sources.d.ts +104 -0
  102. package/dist/import-sources.js +629 -0
  103. package/dist/import-summary.d.ts +25 -0
  104. package/dist/import-summary.js +75 -0
  105. package/dist/import-worker.d.ts +26 -0
  106. package/dist/import-worker.js +41 -0
  107. package/dist/import.d.ts +145 -0
  108. package/dist/import.js +1221 -0
  109. package/dist/index.d.ts +7 -0
  110. package/dist/index.js +6 -0
  111. package/dist/key-check.d.ts +36 -0
  112. package/dist/key-check.js +108 -0
  113. package/dist/key-refusal.d.ts +51 -0
  114. package/dist/key-refusal.js +187 -0
  115. package/dist/learn/check.d.ts +99 -0
  116. package/dist/learn/check.js +259 -0
  117. package/dist/learn/grade.d.ts +79 -0
  118. package/dist/learn/grade.js +433 -0
  119. package/dist/learn/index.d.ts +7 -0
  120. package/dist/learn/index.js +11 -0
  121. package/dist/learn/invisible.d.ts +5 -0
  122. package/dist/learn/invisible.js +42 -0
  123. package/dist/learn/notes.d.ts +59 -0
  124. package/dist/learn/notes.js +146 -0
  125. package/dist/learn/reflect.d.ts +49 -0
  126. package/dist/learn/reflect.js +167 -0
  127. package/dist/learn/secrets.d.ts +18 -0
  128. package/dist/learn/secrets.js +111 -0
  129. package/dist/learn/skills.d.ts +84 -0
  130. package/dist/learn/skills.js +198 -0
  131. package/dist/learning-routes.d.ts +196 -0
  132. package/dist/learning-routes.js +609 -0
  133. package/dist/learning-run.d.ts +304 -0
  134. package/dist/learning-run.js +797 -0
  135. package/dist/learning-words.d.ts +73 -0
  136. package/dist/learning-words.js +171 -0
  137. package/dist/learning.d.ts +377 -0
  138. package/dist/learning.js +801 -0
  139. package/dist/llm.d.ts +40 -0
  140. package/dist/llm.js +37 -0
  141. package/dist/llms.txt +37 -0
  142. package/dist/mcp-servers.d.ts +115 -0
  143. package/dist/mcp-servers.js +445 -0
  144. package/dist/mcp.d.ts +51 -0
  145. package/dist/mcp.js +392 -0
  146. package/dist/model.d.ts +184 -0
  147. package/dist/model.js +484 -0
  148. package/dist/monid.d.ts +74 -0
  149. package/dist/monid.js +277 -0
  150. package/dist/openapi/agentrun-v2.openapi.json +4805 -0
  151. package/dist/openapi.d.ts +10 -0
  152. package/dist/openapi.js +1417 -0
  153. package/dist/owner.d.ts +55 -0
  154. package/dist/owner.js +222 -0
  155. package/dist/packs.d.ts +71 -0
  156. package/dist/packs.js +180 -0
  157. package/dist/page.d.ts +32 -0
  158. package/dist/page.js +133 -0
  159. package/dist/paid-calls.d.ts +46 -0
  160. package/dist/paid-calls.js +110 -0
  161. package/dist/pause.d.ts +68 -0
  162. package/dist/pause.js +97 -0
  163. package/dist/pdf-pages.d.ts +44 -0
  164. package/dist/pdf-pages.js +147 -0
  165. package/dist/place.d.ts +46 -0
  166. package/dist/place.js +105 -0
  167. package/dist/print.d.ts +20 -0
  168. package/dist/print.js +29 -0
  169. package/dist/propose.d.ts +38 -0
  170. package/dist/propose.js +82 -0
  171. package/dist/quiet-sqlite-warning.d.ts +1 -0
  172. package/dist/quiet-sqlite-warning.js +14 -0
  173. package/dist/request-start.d.ts +14 -0
  174. package/dist/request-start.js +226 -0
  175. package/dist/result.d.ts +3 -0
  176. package/dist/result.js +5 -0
  177. package/dist/rows.d.ts +46 -0
  178. package/dist/rows.js +121 -0
  179. package/dist/run-box.d.ts +134 -0
  180. package/dist/run-box.js +440 -0
  181. package/dist/run-manifest.d.ts +27 -0
  182. package/dist/run-manifest.js +60 -0
  183. package/dist/runnable.d.ts +80 -0
  184. package/dist/runnable.js +162 -0
  185. package/dist/runs.d.ts +840 -0
  186. package/dist/runs.js +2279 -0
  187. package/dist/secret-cut.d.ts +27 -0
  188. package/dist/secret-cut.js +109 -0
  189. package/dist/secrets.d.ts +50 -0
  190. package/dist/secrets.js +140 -0
  191. package/dist/server-lock.d.ts +44 -0
  192. package/dist/server-lock.js +140 -0
  193. package/dist/server.d.ts +626 -0
  194. package/dist/server.js +1756 -0
  195. package/dist/sessions.d.ts +4 -0
  196. package/dist/sessions.js +105 -0
  197. package/dist/skills.d.ts +31 -0
  198. package/dist/skills.js +68 -0
  199. package/dist/stats.d.ts +101 -0
  200. package/dist/stats.js +82 -0
  201. package/dist/tool-keys.d.ts +151 -0
  202. package/dist/tool-keys.js +273 -0
  203. package/dist/tool-plane.d.ts +143 -0
  204. package/dist/tool-plane.js +242 -0
  205. package/dist/tools.d.ts +147 -0
  206. package/dist/tools.js +253 -0
  207. package/dist/turn-end.d.ts +23 -0
  208. package/dist/turn-end.js +14 -0
  209. package/dist/turns.d.ts +34 -0
  210. package/dist/turns.js +202 -0
  211. package/dist/uploads.d.ts +104 -0
  212. package/dist/uploads.js +474 -0
  213. package/dist/usage.d.ts +29 -0
  214. package/dist/usage.js +58 -0
  215. package/dist/validate.d.ts +55 -0
  216. package/dist/validate.js +175 -0
  217. package/dist/web-fetch.d.ts +64 -0
  218. package/dist/web-fetch.js +262 -0
  219. package/dist/web-search.d.ts +54 -0
  220. package/dist/web-search.js +136 -0
  221. package/dist/webhooks.d.ts +182 -0
  222. package/dist/webhooks.js +487 -0
  223. package/dist/workspace-paths.d.ts +33 -0
  224. package/dist/workspace-paths.js +104 -0
  225. package/dist/workspace.d.ts +88 -0
  226. package/dist/workspace.js +369 -0
  227. package/launcher/agentrun-serve +109 -0
  228. package/package.json +96 -1
  229. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,626 @@
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
+ import { randomUUID } from "node:crypto";
25
+ import { AssistantEntry, ROOT_CONVERSATION_ID, ToolResultEntry, UserEntry } from "@earendil-works/pi-durable";
26
+ import { modelPortFor, RUNNER_RECORDS } from "@parcha/agentrun-kernel";
27
+ import { confineOf } from "./adapters.js";
28
+ import { hostTools } from "./host-tools.js";
29
+ import { CAP_REFUSED_FIELD, capToolSpend, holdsInFlight, useSpend } from "./cap.js";
30
+ import { durableSessions } from "./sessions.js";
31
+ import { handsParallel, planeOf } from "./tool-plane.js";
32
+ import { parallelOf } from "./web-fetch.js";
33
+ import { WEB_SEARCH_TOOL } from "./web-search.js";
34
+ import { ADAPTER_API, MESSAGE, MESSAGE_END, TURN_END } from "./turn-end.js";
35
+ import { REQUEST_CONTINUED, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_STARTED, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
36
+ /** The root's marker of a paid request already written as a pi.assistant entry. */
37
+ export const BOOKED = "adapter.request";
38
+ /** The cost of a request whose answer was written at unknown cost, and its tokens, written once it came in: the timeline
39
+ * adds it to the run's cost without counting a request, and a later open reads it as that request's cost being in. */
40
+ export const PRICED_LATE = REQUEST_COST_LATE;
41
+ /** How long a turn's end waits for its requests' costs, booked once the proxy has answered the harness. */
42
+ export const BOOKING_WAIT_MS = 2_000;
43
+ /** The root's record of a message the door accepted, and of its end: `sent` to the session, or dropped by a stop. */
44
+ export { MESSAGE, MESSAGE_END } from "./turn-end.js";
45
+ /** A turn's end on the root (turn-end.ts): the message it took, the session's own outcome (`completed`, `interrupted`,
46
+ * `failed`) and the turn's answer, in the commit of the turn's last entries (its answer, its costs, any error). The only
47
+ * record that a turn which took the person's message is over: a request without content is written alike whether it
48
+ * ended the turn or not. */
49
+ export { TURN_END } from "./turn-end.js";
50
+ /** A row id's place in the store: its entry's id. */
51
+ const placeOf = (id) => Number(id.slice(id.lastIndexOf(":") + 1));
52
+ const now = () => Date.now();
53
+ 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("") : "";
54
+ /** A request's tokens as pi counts them (`input` excludes cached tokens), the `usage` a cost entry carries; undefined
55
+ * when it has no input or output count, or no token at all (a usage that was not read is zeros, never a count). */
56
+ function tokensOf(usage) {
57
+ if (!usage || typeof usage !== "object")
58
+ return undefined;
59
+ const u = usage;
60
+ const count = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
61
+ const [input, output] = [count(u.input), count(u.output)];
62
+ if (input === undefined || output === undefined)
63
+ return undefined;
64
+ const tokens = { input, output, cacheRead: count(u.cacheRead) ?? 0, cacheWrite: count(u.cacheWrite) ?? 0 };
65
+ return tokens.input + tokens.output + tokens.cacheRead + tokens.cacheWrite > 0 ? tokens : undefined;
66
+ }
67
+ /** One request as pi's own assistant message: its content, the model it asked for (the harness's id when that is not
68
+ * known), and its usage with the cost when it is known. Tokens not known are 0, which pi's timeline reads as unknown.
69
+ * `error`: a turn that ended on an error, as pi's own reads (the cap's refusal is spend_cap_reached), at $0. */
70
+ function assistantMessage(harness, model, request, text, calls, error) {
71
+ if (error !== undefined) {
72
+ 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 } } };
73
+ }
74
+ const usage = request?.usage;
75
+ const known = usage !== undefined && usage.usd !== null && usage.usd !== undefined;
76
+ const tokens = { input: usage?.input ?? 0, output: usage?.output ?? 0, cacheRead: usage?.cacheRead ?? 0, cacheWrite: usage?.cacheWrite ?? 0 };
77
+ return {
78
+ role: "assistant",
79
+ content: [...(text ? [{ type: "text", text }] : []), ...calls],
80
+ api: ADAPTER_API,
81
+ provider: harness,
82
+ model: model ?? harness,
83
+ usage: {
84
+ ...tokens,
85
+ totalTokens: tokens.input + tokens.output + tokens.cacheRead + tokens.cacheWrite,
86
+ // No total when the price is unknown: the timeline's sum is then unknown, never this request at 0.
87
+ cost: known ? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: usage.usd } : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
88
+ },
89
+ stopReason: calls.length ? "toolUse" : "stop",
90
+ timestamp: now(),
91
+ };
92
+ }
93
+ /** The door and the open of a run whose session is `spec` on `adapter`, with the host tools `tools` names (built at the
94
+ * open, over the run's environment; its coding tools from `coding`, the run's coding source, host-tools.ts).
95
+ * `budgetUsd`: the run's spend cap. `cancelled`: whether the run was cancelled (request-start.ts `cancelledIn`): once it
96
+ * says so, no model request leaves, as on pi. `cwd`: the run's workspace, the directory its file tools confine to, where
97
+ * the harness works too (the adapter's io.cwd), so a path the model builds from its working directory is one the tools
98
+ * take (in a box, coding-tools.ts names it at the box's work dir). */
99
+ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [], dir, cap, cancelled = () => false, cwd, coding, stopRecord) {
100
+ const plane = planeOf(process.env);
101
+ // The web tools' Parallel key, when one resolves to Parallel, read as the run's app loads, before its process starts
102
+ // one of its own (web-fetch.ts).
103
+ if (handsParallel(plane))
104
+ parallelOf(process.env);
105
+ // web_search resolved native is the harness's own search (adapters.ts turns it on, with its input allowance): no host
106
+ // tool of the name.
107
+ if (plane.web_search === "native")
108
+ tools = tools.filter((name) => name !== WEB_SEARCH_TOOL);
109
+ // The run's cap, or its cancel, refused a request: the turn ends on it, and its refusal is written as pi's is.
110
+ let refused;
111
+ // 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
112
+ // run's usage counts no request for it.
113
+ let capRefused = false;
114
+ const CANCELLED = "the run was cancelled: the model request was not sent";
115
+ // What the run's paid tools charged, in earlier processes (read at the open) and this one: null once one is unknown.
116
+ let charged = 0;
117
+ // Each admitted request's worst case until its cost is booked: the booking's spend counts it only then.
118
+ const inFlight = holdsInFlight();
119
+ const plus = (a, b) => (a === null || b === null ? null : a + b);
120
+ const guard = (request) => {
121
+ const byCancel = cancelled();
122
+ const answer = byCancel ? { refuse: CANCELLED } : cap?.beforeRequest({ ...request, spentUsd: plus(request.spentUsd, charged) });
123
+ if (answer && "refuse" in answer) {
124
+ refused = answer.refuse;
125
+ capRefused = !byCancel;
126
+ return answer;
127
+ }
128
+ // Admitted, limited to the output what is left of the cap buys (which the runner hands the model proxy, and holds it
129
+ // at): the worst case the cap holds for it, which the runner records, and counts it at if its cost never comes in.
130
+ const limit = answer?.outputTokensMax;
131
+ const admitted = { ...request, ...(limit === undefined ? {} : { outputTokensMax: limit }) };
132
+ const hold = cap?.worstOf?.(admitted);
133
+ inFlight.admitted(hold);
134
+ if (hold === undefined && limit === undefined)
135
+ return undefined;
136
+ // Stopped part way by its client, it counts by what streamed (cap.ts stoppedOf), never more than its hold (the runner).
137
+ const stoppedOf = cap?.stoppedOf;
138
+ const stopped = hold !== undefined && stoppedOf ? { stoppedUsd: (streamed) => stoppedOf(admitted, streamed) ?? hold } : {};
139
+ return { ...(hold === undefined ? {} : { holdUsd: hold }), ...(limit === undefined ? {} : { outputTokensMax: limit }), ...stopped };
140
+ };
141
+ /** The cancel, as the booking's stop: read again after this check and after the request's record is written, so a
142
+ * cancel that lands between them still keeps the request from leaving. */
143
+ const cancelStop = () => {
144
+ if (!cancelled())
145
+ return undefined;
146
+ refused ??= CANCELLED;
147
+ return new Error(CANCELLED);
148
+ };
149
+ // A paid request whose cost could not be written: the booking admits no request after it, and the turn stops on it.
150
+ let halted;
151
+ const results = new Map();
152
+ let run;
153
+ let session;
154
+ let opened;
155
+ let openedDone = () => { };
156
+ opened = new Promise((resolve) => (openedDone = resolve));
157
+ let turn;
158
+ // A person's stop of the turn in flight: its interrupt, which the turn's end waits for before it settles the turn.
159
+ let stopping;
160
+ // The door's emit, from attach as the door opens: a recovered turn, started by no submit, reports through it too.
161
+ let emit;
162
+ let attached = false;
163
+ const queue = [];
164
+ const stop = new AbortController();
165
+ // The current request's content, and the requests whose cost is in but whose entry is not written yet.
166
+ let text = "";
167
+ let calls = [];
168
+ // The turn's answer entry so far (its last request with text and no call), the MESSAGE its turn took, and whether the
169
+ // 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
170
+ // resumes it if the session still holds it open, or restores its end, as onOpen's `restored`, if the session ended it).
171
+ let answer;
172
+ let taking;
173
+ let draining = false;
174
+ const costed = [];
175
+ const written = new Set();
176
+ // The request the harness asked last, and the requests whose answer has an entry (taken as its write begins).
177
+ let current;
178
+ const answered = new Set();
179
+ // Requests written at unknown cost (their cost not in when their turn ended), and those whose cost is written.
180
+ const unpriced = new Set();
181
+ const priced = new Set();
182
+ // Requests admitted and not yet booked, by turn: the proxy answers the harness before it books a response, so a turn
183
+ // can end with its last request's cost still on its way.
184
+ const open = new Set();
185
+ // The model each request asked for, by number: its entry names it.
186
+ const models = new Map();
187
+ let booked = () => { };
188
+ /** Until every admitted request is booked, or `ms` pass. */
189
+ const bookings = async (ms) => {
190
+ for (const deadline = Date.now() + ms; open.size && Date.now() < deadline;) {
191
+ await new Promise((resolve) => {
192
+ booked = resolve;
193
+ setTimeout(resolve, Math.max(0, deadline - Date.now())).unref();
194
+ });
195
+ }
196
+ };
197
+ // Writes in order, one at a time: the entries keep the order their events came in.
198
+ let writing = Promise.resolve();
199
+ const later = (work) => (writing = writing.then(work, work));
200
+ const commit = (change) => run.harness.commit(change, context);
201
+ /** A cost for a request already written: one written at unknown cost (below) gets its cost now, as an entry of its
202
+ * own (one of `writes`, the flush's commit), so the run's spend counts it, once; any other is a duplicate. */
203
+ const priceLate = (late, writes) => {
204
+ if (!unpriced.has(late.request) || priced.has(late.request))
205
+ return;
206
+ const tokens = tokensOf(late.usage);
207
+ 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 } : {}) } }));
208
+ priced.add(late.request);
209
+ };
210
+ const writtenAt = () => costed.findIndex((c) => written.has(c.request));
211
+ /** Writes what the current request has: its entry with the content so far and the oldest cost not yet written.
212
+ * Content with no cost yet waits for one, but at a turn's end (`final`) it is written as a request of unknown cost.
213
+ * 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
214
+ * turn's end is in the commit of its last entries. The bookkeeping goes first: a commit the store refuses ends the
215
+ * process, and the next open reads the root again. */
216
+ const flush = (final = false, end) => later(async () => {
217
+ const writes = [];
218
+ const commitAll = async () => {
219
+ if (end)
220
+ writes.push(end);
221
+ if (writes.length)
222
+ await commit(async (tx) => { for (const write of writes)
223
+ await write(tx); });
224
+ };
225
+ // Each cost for a request already written, wherever it sits: a response is booked when its stream closes, so a
226
+ // late cost can come in after a later request's.
227
+ for (let at = writtenAt(); at >= 0; at = writtenAt())
228
+ priceLate(costed.splice(at, 1)[0], writes);
229
+ if ((!text && !calls.length && !costed.length) || (!costed.length && !final))
230
+ return commitAll();
231
+ const request = costed.shift();
232
+ const content = { text, calls };
233
+ text = "";
234
+ calls = [];
235
+ // At a turn's end with no cost in: the request still unbooked is the one this content answers. It is written at
236
+ // unknown cost and marked booked, so a later open never writes it again.
237
+ const unbooked = !request && final && open.size ? Math.min(...open) : undefined;
238
+ if (unbooked !== undefined)
239
+ open.delete(unbooked);
240
+ const marked = request?.request ?? unbooked;
241
+ if (marked !== undefined)
242
+ answered.add(marked);
243
+ writes.push(async (tx) => {
244
+ const entry = await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, marked === undefined ? undefined : models.get(marked), request, content.text, content.calls)] });
245
+ // The turn's answer so far: its last request with text and no call.
246
+ if (content.text && !content.calls.length)
247
+ answer = entry.id;
248
+ // Its cost still to come: the timeline reads it pending, not a cost no one will ever know.
249
+ if (unbooked !== undefined)
250
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_COST_PENDING, data: { key: spec.key, request: unbooked } });
251
+ if (marked !== undefined)
252
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: BOOKED, data: { key: spec.key, request: marked, ...(request ? {} : { unpriced: true }) } });
253
+ });
254
+ if (marked !== undefined)
255
+ written.add(marked);
256
+ if (request)
257
+ priced.add(request.request);
258
+ else if (marked !== undefined)
259
+ unpriced.add(marked);
260
+ // More costs than content: each later one still gets its own entry, cost only. One that came in meanwhile for a
261
+ // request already written is a late cost, or a duplicate.
262
+ while (costed.length) {
263
+ const next = costed.shift();
264
+ if (written.has(next.request)) {
265
+ priceLate(next, writes);
266
+ continue;
267
+ }
268
+ answered.add(next.request);
269
+ writes.push(async (tx) => {
270
+ await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, models.get(next.request), next, "", [])] });
271
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: BOOKED, data: { key: spec.key, request: next.request } });
272
+ });
273
+ written.add(next.request);
274
+ priced.add(next.request);
275
+ }
276
+ await commitAll();
277
+ });
278
+ const onModel = (event) => {
279
+ if (event.type === "request_start") {
280
+ inFlight.started(event.turn);
281
+ current = event.turn;
282
+ open.add(event.turn);
283
+ models.set(event.turn, event.model);
284
+ void flush();
285
+ // Marked on the root as it leaves, as a pi run's request is (request-start.ts): one never answered, a run that ends
286
+ // without opening again (cancelled, or failed) reads as cut, its cost unknown, never as the sum without it.
287
+ // A store that refuses it has refused a write already, and the process ends on that.
288
+ later(() => commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_STARTED, data: { key: spec.key, request: event.turn } })))).catch(() => undefined);
289
+ }
290
+ else {
291
+ open.delete(event.turn);
292
+ inFlight.ended(event.turn);
293
+ costed.push({ request: event.turn, usage: event.usage });
294
+ booked();
295
+ // A cost that came in after its answer was written goes in now, not at some later flush, and so does one that came
296
+ // in with no turn running, which no turn's flush would write. If that write fails, the next open writes it from
297
+ // the session's booking, once.
298
+ if (written.has(event.turn) || turn === undefined)
299
+ flush().catch(() => undefined);
300
+ }
301
+ };
302
+ const onEvent = (event) => {
303
+ if (event.type === "text")
304
+ text += event.delta;
305
+ else if (event.type === "tool_start") {
306
+ const call = { type: "toolCall", id: event.callId, name: event.name, arguments: (event.args ?? {}) };
307
+ // A call of the current request's answer after that answer's entry was written (at its first call's end): written
308
+ // now as the answer's continuation, so its result never comes before it and the next answer never holds it.
309
+ const request = current;
310
+ if (text || calls.length || request === undefined || !answered.has(request))
311
+ calls.push(call);
312
+ else {
313
+ later(() => commit(async (tx) => {
314
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_CONTINUED, data: { key: spec.key, request } });
315
+ await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, models.get(request), undefined, "", [call])] });
316
+ }).then(() => undefined));
317
+ }
318
+ }
319
+ else if (event.type === "tool_end") {
320
+ void flush();
321
+ later(() => commit(async (tx) => {
322
+ await tx.appendEntry(ToolResultEntry, ROOT_CONVERSATION_ID, {
323
+ model: [{ role: "toolResult", toolCallId: event.callId, toolName: event.name, content: [{ type: "text", text: results.get(event.callId)?.text ?? (event.isError ? "The tool failed." : "Done.") }], isError: event.isError, timestamp: now() }],
324
+ data: { diagnostics: [] },
325
+ });
326
+ }).then(() => undefined));
327
+ }
328
+ };
329
+ /** The session's requests, from its runner records, by number: the model each asked for, and the usage of each it
330
+ * booked. A booking written before runner.turn kept tokens has none: its entry's zeros read as unknown. */
331
+ const inSession = (records) => {
332
+ const asked = new Map();
333
+ const booked = new Map();
334
+ let admitted = 0;
335
+ for (const record of records) {
336
+ const data = (record.data ?? {});
337
+ if (record.kind === RUNNER_RECORDS.request) {
338
+ admitted = typeof data.turn === "number" ? data.turn : admitted + 1;
339
+ if (typeof data.model === "string")
340
+ asked.set(admitted, data.model);
341
+ }
342
+ // A request withdrawn as its record was written (a stop came then) never left: it is no request of the run's.
343
+ else if (record.kind === RUNNER_RECORDS.turn && data.unsent !== true) {
344
+ const request = typeof data.turn === "number" ? data.turn : admitted;
345
+ 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 });
346
+ }
347
+ }
348
+ return { asked, booked };
349
+ };
350
+ /** The person's message: the session's new turn, then its entry and its end on the root. */
351
+ const sendOf = (message) => async () => {
352
+ await message.recorded;
353
+ taking = message.id;
354
+ await session.send(message.content);
355
+ await later(() => commit(async (tx) => {
356
+ await tx.appendEntry(UserEntry, ROOT_CONVERSATION_ID, { model: [{ role: "user", content: [{ type: "text", text: message.content }], timestamp: now() }] });
357
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE_END, data: { key: spec.key, id: message.id, sent: true } });
358
+ }).then(() => undefined));
359
+ };
360
+ /** Turns until nothing waits: the turn, then each message that waited for it, as one busy period on the door (as a pi
361
+ * run's follow-ups are), so the server never reads the run idle, and done, while an accepted message is unanswered. A
362
+ * message that arrives meanwhile waits its place. `carried`: the first turn's answer so far, when it is a turn an
363
+ * earlier process left open and this one recovers (its answer already on the root); a new message's turn starts with
364
+ * none. */
365
+ const runTurns = (first, carried) => {
366
+ turn = (async () => {
367
+ emit?.({ type: "run_start" });
368
+ for (let start = first, carry = carried; start; carry = undefined) {
369
+ let failed;
370
+ let status = "failed";
371
+ answer = carry;
372
+ try {
373
+ await start();
374
+ const end = await session.turnEnd();
375
+ status = end.status;
376
+ if (end.status === "failed")
377
+ failed = end.error ?? "the turn failed";
378
+ }
379
+ catch (error) {
380
+ failed = String(error?.message ?? error);
381
+ }
382
+ finally {
383
+ // A turn the person stopped can still be open in the session (an interrupt writes no end there, and a prompt it
384
+ // stopped before the harness placed it is still pending). It is settled once the interrupt is done, before the
385
+ // turn's end and any next message, so nothing of it goes on or is sent again. An adapter without the settle is
386
+ // left as before. A settle that fails leaves the turn to the next open, which settles it from the stop record.
387
+ if (stopping) {
388
+ await stopping.catch(() => undefined);
389
+ stopping = undefined;
390
+ if (session?.state === "open_turn" && typeof session.settleOpenTurn === "function")
391
+ await session.settleOpenTurn().catch(() => undefined);
392
+ }
393
+ // The last request's cost, booked once the proxy has answered: waited for, so the answer is written with it.
394
+ await bookings(BOOKING_WAIT_MS);
395
+ // A turn that failed (the cap's refusal, a cost the booking could not write, or the harness's own failure) writes
396
+ // its error and ends failed. The run's status is its last turn's end (turns.ts): with no message waiting, the run
397
+ // fails on this error, as a pi run does; a message waiting behind it is still sent, and when that turn completes,
398
+ // the run completes with its answer, this failure kept in the timeline.
399
+ const why = refused ?? halted?.message ?? (failed === undefined ? undefined : `${harness}: ${failed}`);
400
+ const unsent = refused !== undefined && capRefused;
401
+ refused = undefined;
402
+ capRefused = false;
403
+ const pending = open.size > 0;
404
+ // The turn's end, in the commit of its last entries (flush's one commit): the run's end is read from it alone
405
+ // (turns.ts). A turn the instance's own stop cut gets none: the next open resumes it while the session holds it
406
+ // open, or restores its end from the root (completed with its answer) when the session had ended it.
407
+ const cut = draining && why === undefined && status === "interrupted";
408
+ await flush(true, cut ? undefined : async (tx) => {
409
+ if (why !== undefined) {
410
+ // 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.
411
+ if (unsent)
412
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_STARTED, data: { [CAP_REFUSED_FIELD]: true } });
413
+ await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, undefined, undefined, "", [], why)] });
414
+ }
415
+ const data = {
416
+ key: spec.key, ...(taking === undefined ? {} : { message: taking }), status: why === undefined ? status : "failed",
417
+ answer: why === undefined && status === "completed" ? (answer ?? null) : null, ...(why === undefined ? {} : { error: why }), cost: pending ? "pending" : "booked",
418
+ };
419
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: TURN_END, data });
420
+ });
421
+ await writing;
422
+ // A cost that came in while this turn ended, after its flush: written now, while the run still reads busy, so a
423
+ // message that comes in meanwhile waits its place below and goes on as the next turn of this busy period.
424
+ if (costed.length)
425
+ await flush().catch(() => undefined);
426
+ }
427
+ // Stopping: the messages still waiting are sent by the next open, which finds them with no end.
428
+ const next = draining ? undefined : queue.shift();
429
+ start = next === undefined ? undefined : sendOf(next);
430
+ }
431
+ // Nothing from here to run_end waits: a message that comes in once the run reads idle starts the next busy period,
432
+ // after this run_end. A cost that comes in from now on is written as it comes in (onModel).
433
+ turn = undefined;
434
+ // A stop that came after this busy period's last turn had ended stopped nothing: it is not the next one's.
435
+ stopping = undefined;
436
+ emit?.({ type: "run_end" });
437
+ })();
438
+ };
439
+ const door = {
440
+ attach(given) {
441
+ emit = given;
442
+ attached = true;
443
+ },
444
+ async submit(input, ctx) {
445
+ if (!attached)
446
+ emit = ctx.emit;
447
+ await opened;
448
+ if (turn && input.whenBusy === "reject")
449
+ return { accepted: false, reason: "busy" };
450
+ const id = randomUUID();
451
+ const content = textOf(input.content);
452
+ const message = { id, content, recorded: commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE, data: { key: spec.key, id, content } }))) };
453
+ if (turn)
454
+ queue.push(message);
455
+ else
456
+ runTurns(sendOf(message));
457
+ await message.recorded;
458
+ return { accepted: true };
459
+ },
460
+ async abort(ctx) {
461
+ if (!attached)
462
+ emit = ctx.emit;
463
+ // The instance stopping (a drain, a fence, a park) is no one's stop: the turn it cuts gets no end, the next open
464
+ // resumes it (or restores its end, when the session had ended it), and the messages waiting stay, for it to send.
465
+ if (ctx.reason === "stop") {
466
+ draining = true;
467
+ if (!turn)
468
+ return "idle";
469
+ await session?.interrupt();
470
+ return "aborted";
471
+ }
472
+ const dropped = queue.splice(0);
473
+ if (dropped.length) {
474
+ await Promise.all(dropped.map((message) => message.recorded));
475
+ await commit(async (tx) => {
476
+ for (const message of dropped)
477
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE_END, data: { key: spec.key, id: message.id, sent: false } });
478
+ });
479
+ }
480
+ if (!turn)
481
+ return "idle";
482
+ stopping = session?.interrupt();
483
+ await stopping;
484
+ return "aborted";
485
+ },
486
+ busy: () => turn !== undefined,
487
+ };
488
+ return {
489
+ door,
490
+ async onOpen(durable) {
491
+ run = durable;
492
+ const sessions = durableSessions(durable.harness, context);
493
+ // The requests already written on the root, and the messages accepted and never sent, from any earlier process.
494
+ const root = await durable.harness.conversation(ROOT_CONVERSATION_ID, context);
495
+ const accepted = new Map();
496
+ const paid = [];
497
+ // The turn that took the last message sent, while the root has no end for it (a process died before the commit of
498
+ // its last entries, or its own stop cut it): the message, whether the bridge wrote that turn's error, and its answer
499
+ // so far (its newest request with text and no call).
500
+ let unended;
501
+ // The person's messages on the root: the newest one's entry id, and how many, for the run's stop record.
502
+ let lastUser;
503
+ let users = 0;
504
+ for (let cursor; root;) {
505
+ const page = await root.entries({ order: "ascending" }, 500, cursor, context);
506
+ for (const entry of page.items) {
507
+ const data = entry.data;
508
+ if (entry.kind === TOOL_COST || entry.kind === TOOL_STARTED)
509
+ paid.push(entry);
510
+ const message = entry.model?.[0];
511
+ if (unended && message?.api === ADAPTER_API && message.stopReason === "error")
512
+ unended.failed = true;
513
+ if (unended && message?.api === ADAPTER_API && message.stopReason === "stop" && textOf(message.content))
514
+ unended.answer = entry.id;
515
+ if (message?.role === "user") {
516
+ users += 1;
517
+ lastUser = Number(entry.id);
518
+ }
519
+ if (data?.key !== spec.key)
520
+ continue;
521
+ if (entry.kind === BOOKED && typeof data.request === "number") {
522
+ written.add(data.request);
523
+ (data.unpriced === true ? unpriced : priced).add(data.request);
524
+ }
525
+ else if (entry.kind === PRICED_LATE && typeof data.request === "number")
526
+ priced.add(data.request);
527
+ else if (entry.kind === MESSAGE && typeof data.id === "string")
528
+ accepted.set(data.id, { id: data.id, content: String(data.content ?? ""), recorded: Promise.resolve() });
529
+ else if (entry.kind === MESSAGE_END && typeof data.id === "string") {
530
+ accepted.delete(data.id);
531
+ if (data.sent === true)
532
+ unended = { message: data.id, failed: false, answer: null };
533
+ }
534
+ else if (entry.kind === TURN_END)
535
+ unended = undefined;
536
+ }
537
+ if (page.next === undefined)
538
+ break;
539
+ cursor = page.next;
540
+ }
541
+ // What the paid tools charged in earlier processes, as the cap counts it: a call a crash cut at its held figure.
542
+ charged = capToolSpend(paid);
543
+ // The prefix pi's commands start under in this run, from pi-durable-disk's own builder: the harness's process too.
544
+ const env = (await durable.env({ conversationId: ROOT_CONVERSATION_ID, read: undefined }, context));
545
+ if (typeof env.confinePrefix !== "function")
546
+ throw new Error("the run's environment gives no confinement for the harness's process");
547
+ const adapter = await make(confineOf(env.confinePrefix()));
548
+ const writer = await sessions.open(spec.key);
549
+ const records = await writer.read();
550
+ // Before the cut requests are booked, which may write their entries.
551
+ for (const [request, model] of inSession(records).asked)
552
+ models.set(request, model);
553
+ const booking = await modelPortFor(writer, {
554
+ records,
555
+ key: spec.key,
556
+ ...(budgetUsd !== undefined ? { budgetUsd } : {}),
557
+ beforeRequest: guard,
558
+ onEvent: onModel,
559
+ stopped: () => halted ?? cancelStop(),
560
+ stop: (reason, message) => {
561
+ const error = new Error(message ?? reason);
562
+ if (reason === "model_error" && !halted) {
563
+ halted = error;
564
+ void session?.interrupt();
565
+ }
566
+ return error;
567
+ },
568
+ });
569
+ // A request a crash cut off is booked once, unknown, before anything is sent.
570
+ await booking.bookCut();
571
+ // A paid tool's check before it spends: the session's requests, each booked once the proxy has answered (waited
572
+ // for, as at a turn's end), one still in flight at the worst case the cap held for it (as pi's spend counts it),
573
+ // with the run's charges; its charge joins them.
574
+ if (budgetUsd !== undefined) {
575
+ useSpend({
576
+ cap: budgetUsd,
577
+ spent: async () => (await bookings(BOOKING_WAIT_MS), plus(plus(booking.spentUsd(), charged), inFlight.total())),
578
+ add: (usd) => void (charged = plus(charged, usd)),
579
+ });
580
+ }
581
+ // Each request the session booked and the root has no entry for: its cost, with no content.
582
+ // Each request the session booked and the root does not have, or has at unknown cost only: written now, once.
583
+ for (const [request, usage] of inSession(await writer.read()).booked)
584
+ if (!written.has(request) || (unpriced.has(request) && !priced.has(request)))
585
+ costed.push({ request, usage });
586
+ await flush();
587
+ session = await adapter.open({ ...spec, tools: hostTools(durable, tools, context, results, coding) }, { writer, models: booking.models, signal: stop.signal, onEvent, ...(dir ? { dir } : {}), ...(cwd ? { cwd } : {}) });
588
+ // A turn the person stopped is still open in the session (an interrupt writes no end there), and it is not resumed.
589
+ // The run's stop record names the person's newest message when they stopped: with no message on the root newer than
590
+ // it, the open turn is the stopped one. The session settles it, ended interrupted, and the next message is a turn of
591
+ // its own. A turn a crash or a drain cut has no stop record newer than the newest message, and is resumed as before.
592
+ const stopped = stopRecord?.stopped_at !== undefined
593
+ ? lastUser !== undefined && lastUser <= placeOf(stopRecord.stopped_at)
594
+ : stopRecord?.stopped_after !== undefined && stopRecord.stopped_after === users;
595
+ // An adapter written before settleOpenTurn has none: its stopped turn is recovered, as before.
596
+ if (session.state === "open_turn" && stopped && typeof session.settleOpenTurn === "function")
597
+ await session.settleOpenTurn();
598
+ // That turn is over in the session, and an earlier process died before it wrote the turn's end: written now, after
599
+ // what this open wrote and before any new turn. A turn the person stopped reads interrupted, from the stop record:
600
+ // settled by this open, or by an earlier one that died before it wrote this end. Otherwise the session says only that
601
+ // the turn is over; how it ended is what the root holds of it: failed when the bridge wrote its error, completed when
602
+ // its answer (a request with text and no call) is there. With neither, the turn is not known to have completed: it
603
+ // ends interrupted, and the run waits for the person (turns.ts), never answered "". The end names the message the
604
+ // turn took, as every turn end does.
605
+ const restored = session.state === "idle" && unended ? (stopped ? "interrupted" : unended.failed ? "failed" : unended.answer !== null ? "completed" : "interrupted") : undefined;
606
+ 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 } }))));
607
+ // A turn the session holds open is the last message's, resumed now.
608
+ if (session.state === "open_turn" && unended)
609
+ taking = unended.message;
610
+ queue.push(...accepted.values());
611
+ // With nothing waiting, that end is the run's: written while the door is idle. A message accepted and never sent
612
+ // still waits, and a server started anew counts none: the door is busy (run_start) before that end goes out, and
613
+ // the message's turn follows in the same busy period, so no server reads the run done before it answers.
614
+ if (restored && !queue.length)
615
+ await restore(restored);
616
+ openedDone();
617
+ // Its answer so far is the root's, which a recovery that streams no new text keeps as the turn's.
618
+ if (session.state === "open_turn")
619
+ runTurns(() => session.recover(), unended?.answer ?? undefined);
620
+ else if (queue.length) {
621
+ const next = sendOf(queue.shift());
622
+ runTurns(restored ? async () => (await restore(restored), await next()) : next);
623
+ }
624
+ },
625
+ };
626
+ }