@parcha/agentrun-serve 0.0.0-stage → 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 +1723 -2
  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 +94 -4
  229. package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/tools.js ADDED
@@ -0,0 +1,253 @@
1
+ import { pathToFileURL } from "node:url";
2
+ import { defineExtension, defineTool } from "@earendil-works/pi-durable";
3
+ import { writeInWork } from "./workspace.js";
4
+ import { FETCH_PAGE_TOOL, fetchOptions, HTML_READ_CHARS, TEXT_CAP } from "./fetch-page.js";
5
+ import { DEFAULT_HARNESS, HARNESSES } from "./harness.js";
6
+ import { REPLAY } from "./host-tools.js";
7
+ import { LLM_TOOL } from "./llm.js";
8
+ import { DOCUMENTS_ENV, PDF_PAGES_TOOL, pdfPages } from "./pdf-pages.js";
9
+ import { monidTool } from "./monid.js";
10
+ import { FAUX_ENV, workflowNodes } from "./model.js";
11
+ import { bookedIn, booking } from "./paid-calls.js";
12
+ import { forModel } from "./result.js";
13
+ import { fetchFor, runPages, WEB_FETCH_TOOL, webFetchTool } from "./web-fetch.js";
14
+ import { searchFor, WEB_SEARCH_TOOL, webSearchTool } from "./web-search.js";
15
+ import { capabilityOf, explainsView, isUnavailable, NO_PARALLEL_KEY, PICKABLE, PROVIDERS, whyUnavailable, withDefaults } from "./tool-plane.js";
16
+ import { PARALLEL_KEY_ENV } from "./decisions.js";
17
+ export const ASK_TOOL = "ask_person";
18
+ /** Under `--faux` only: a module whose default export gives the browser's `{ provider, driver }`, in place of
19
+ * Browserbase's (the tests' fake backend). */
20
+ export const FAUX_BROWSER_ENV = "AGENTRUN_SERVE_FAUX_BROWSER";
21
+ /** What the result of `ask_person` says; the person's page shows the question as a waiting row. */
22
+ export const asked = (question) => `Asked the person: ${question.slice(0, 500)}. Waiting for their answer.`;
23
+ export const askPerson = defineTool({
24
+ name: ASK_TOOL,
25
+ description: "Ask the person who started this run a question you cannot answer yourself. Call it alone. It ends your turn; the person's reply comes as their next message.",
26
+ parameters: {
27
+ type: "object",
28
+ additionalProperties: false,
29
+ properties: { question: { type: "string", minLength: 1, description: "The question, in one or two plain sentences." } },
30
+ required: ["question"],
31
+ },
32
+ replay: "safe",
33
+ execute: async (args) => {
34
+ const { question } = args;
35
+ return forModel(asked(question), { details: { question }, control: { terminate: true } });
36
+ },
37
+ });
38
+ /** `tool` alone in an extension named `name`, installed in the run's registry. */
39
+ function installTool(host, name, tool) {
40
+ const extension = defineExtension({ name, tools: [tool] });
41
+ host.install(extension);
42
+ return { tools: [tool], extensions: [extension] };
43
+ }
44
+ const callOnly = (summary, effect) => ({
45
+ summary, needs: [], nodes: false, callOnly: true, effect,
46
+ bind: async () => { throw new Error("a call-only tool binds no agent tool"); },
47
+ });
48
+ /** web_fetch, bound under `name`: its own, or a legacy name for it (LEGACY_NAMES, fetch_page). */
49
+ const webFetchEntry = (name) => ({
50
+ summary: `Read one public web page from a public host through the guarded direct fetch, or through Parallel's extract where Parallel is picked (falling back to the direct fetch, saying why, when Parallel answers no page), a part at a time (offset, max_chars; the page fetched once a run): { ok, url, status, title, text, chars, truncated?, original_chars?, beyond_read?, offset?, next_offset?, html_chars?, converted?, links, links_omitted?, via, parallel?, refused?, error? }; html_chars, the page's whole length, when its HTML was cut at ${HTML_READ_CHARS.toLocaleString("en-US")} characters before it was read, so its text is only the start of the page; converted: "text" when the text is plain text, its conversion to markdown having run out of time; a private or local address, a port other than 80 or 443, or a scheme other than http(s) is refused, never sent to Parallel.`,
51
+ needs: [],
52
+ nodes: true,
53
+ bind: async (host) => {
54
+ const tool = booking(webFetchTool(host.env, name));
55
+ const extension = defineExtension({ name: name.replaceAll("_", "-"), tools: [tool] });
56
+ host.install(extension);
57
+ return { tools: [tool], extensions: [extension] };
58
+ },
59
+ // A call node's Page is the workflow's, not a model's context: it reads the most of a part by default, from the page
60
+ // the run read (runPages) where it holds the URL. Its request to Parallel, when it makes one, is booked under the call
61
+ // (paid-calls.ts); a part from what the run read makes none and books nothing.
62
+ effect: async (args, run) => bookedIn(run.ledger, async () => fetchFor(run.env, args.url, { ...(await fetchOptions(run.env, FAUX_ENV)), offset: args.offset, maxChars: args.max_chars ?? TEXT_CAP, pages: runPages, signal: run.signal })),
63
+ });
64
+ /** A coding tool, from the run's coding source: a name it does not hold (bash on the runner) binds no tool. */
65
+ const fileTool = (name, summary, sandboxOnly = false) => ({
66
+ summary,
67
+ needs: [],
68
+ nodes: !sandboxOnly,
69
+ ...(sandboxOnly ? { sandboxOnly: true } : {}),
70
+ bind: async (host) => {
71
+ const tools = host.coding.tools.filter((tool) => tool.name === name);
72
+ return { tools, extensions: tools.length ? [host.coding.extension] : [] };
73
+ },
74
+ });
75
+ /** Where the browser files what it reads: `work/evidence/`, so the run's files show it and the agent can read it back. A
76
+ * text body follows one line of the read's facts; a capture's bytes go beside its facts. Each read takes the next free
77
+ * number, reserved by an exclusive create, so reads at once (parallel nodes, one turn's calls) and the reads of a later
78
+ * process never overwrite one another. */
79
+ export const evidenceIn = (work) => {
80
+ let seq = 0;
81
+ return {
82
+ file: async (label, record) => {
83
+ const facts = JSON.stringify({ label, tool: record.tool, ...record.facts });
84
+ const text = typeof record.body === "string";
85
+ for (;;) {
86
+ const name = `${String(++seq).padStart(4, "0")}-${record.tool}`;
87
+ try {
88
+ // Never through a link a box's command planted in work/ (files.ts).
89
+ await writeInWork(work, ["evidence"], text ? `${name}.md` : `${name}.json`, text ? `${facts}\n\n${record.body}` : `${facts}\n`);
90
+ }
91
+ catch (error) {
92
+ if (error.code === "EEXIST")
93
+ continue;
94
+ throw error;
95
+ }
96
+ if (text)
97
+ return { path: `evidence/${name}.md`, bodyLine: 3 };
98
+ await writeInWork(work, ["evidence"], `${name}.${record.ext ?? "bin"}`, record.body);
99
+ return { path: `evidence/${name}.json`, bodyPath: `evidence/${name}.${record.ext ?? "bin"}` };
100
+ }
101
+ },
102
+ };
103
+ };
104
+ /** A Browserbase browser driven through Stagehand, on pi-browser's durable adapter: its sessions' custody lives in the
105
+ * run's own store. No recording and no live view; a session the run still holds is released when the run is let go. */
106
+ const browserTool = {
107
+ summary: "Drive a Browserbase browser: open pages, read and screenshot them, and act on them.",
108
+ needs: ["BROWSERBASE_API_KEY", "BROWSERBASE_PROJECT_ID"],
109
+ nodes: true,
110
+ // Its downloads and uploads go through work/ by path (pi-browser), which a box's command could turn through a link.
111
+ runnerOnly: true,
112
+ bind: async (host) => {
113
+ const [{ BACKGROUND_CONTEXT: context }, { createBrowserExtension }, { DEFAULT_BROWSER_POLICY }] = await Promise.all([
114
+ import("@earendil-works/chord/context"),
115
+ import("@parcha/pi-browser/durable"),
116
+ import("@parcha/pi-browser"),
117
+ ]);
118
+ const faux = host.env[FAUX_ENV] ? host.env[FAUX_BROWSER_ENV] : undefined;
119
+ const parts = faux
120
+ ? (await import(pathToFileURL(faux).href)).default(host.env)
121
+ : { provider: (await import("@parcha/pi-browser/providers/browserbase")).browserbaseProvider({ env: host.env }), driver: (await import("@parcha/pi-browser/driver/stagehand")).stagehandDriver() };
122
+ const browser = createBrowserExtension({ provider: () => parts.provider, driver: parts.driver, evidence: evidenceIn(host.where.work), workspace: () => host.where.work });
123
+ const extension = browser.extension;
124
+ host.install(extension);
125
+ host.onConversation(async (tx, conversationId) => {
126
+ Object.assign(await tx.doc(browser.docs.Config, conversationId), { label: "run", run: host.where.ref.id, policy: DEFAULT_BROWSER_POLICY });
127
+ });
128
+ host.beforeResume(async (harness) => void (await browser.reconcile(harness, () => true, context)));
129
+ host.beforeRelease(async (harness) => {
130
+ const held = await harness.snapshot(browser.docs.Inventory, context);
131
+ for (const id of new Set(Object.values(held?.rows ?? {}).filter((row) => row.state !== "released").map((row) => row.conversationId))) {
132
+ const conversation = await harness.conversation(id, context);
133
+ if (conversation)
134
+ await browser.release(conversation, "close", context);
135
+ }
136
+ await browser.drain(harness, context);
137
+ });
138
+ return { tools: browser.tools, extensions: [extension] };
139
+ },
140
+ };
141
+ export const TOOLS = Object.freeze({
142
+ read: fileTool("read", "Read a file in the run's work/."),
143
+ write: fileTool("write", "Write a file in the run's work/."),
144
+ edit: fileTool("edit", "Edit a file in the run's work/."),
145
+ bash: fileTool("bash", "Run a bash command in the run's box, from its work/, never on this server itself: only an agent whose place is a sandbox names it. Its output's tail; 300 s unless the call names a timeout.", true),
146
+ [ASK_TOOL]: {
147
+ summary: "Ask the person who started the run; the turn ends until a message answers.",
148
+ needs: [],
149
+ nodes: false,
150
+ bind: async (host) => installTool(host, "person", askPerson),
151
+ },
152
+ [WEB_FETCH_TOOL]: webFetchEntry(WEB_FETCH_TOOL),
153
+ [WEB_SEARCH_TOOL]: {
154
+ summary: "Search the web: codex's own search (claude-agent's where it is picked), on pi the model provider's hosted search (Anthropic, OpenAI), with none of those Parallel's Search API where the server holds its key, else Exa's keyless search; or the provider picked: { query, n? } -> { provider, query, results: [{ url, title, snippet, published? }], text? }, provider naming the one that served it, 1 to 25 results, each snippet at most 3,000 characters; { error } when the search gives no answer.",
155
+ needs: [],
156
+ nodes: true,
157
+ bind: async (host) => installTool(host, "web-search", booking(webSearchTool(host.env))),
158
+ effect: async (args, run) => bookedIn(run.ledger, () => searchFor(run.env, args, run.signal)),
159
+ },
160
+ browser: browserTool,
161
+ // monid's catalog on one key (monid.ts): every harness calls each by its wire name, `monid_discover` and the rest.
162
+ "monid.discover": monidTool("discover"),
163
+ "monid.inspect": monidTool("inspect"),
164
+ "monid.run": monidTool("run"),
165
+ [PDF_PAGES_TOOL]: callOnly("A workflow call: { path, maxPages?, dpi? } -> { name, pageCount, dpi, pages: [{ page, image }], text }; the document's first pages drawn as PNGs under work/pages/<stem>/<dpi>/ (the dpi lowered so a page's long side is at most 1568 px), from the server's documents (--documents) or the run's work directory.", (args, run) => pdfPages(args, { work: run.work, documents: run.env[DOCUMENTS_ENV], signal: run.signal })),
166
+ [LLM_TOOL]: callOnly("A workflow call: { prompt, system?, maxTokens?, tier? } -> { text, model, usage, cost_usd }; one completion on the model of the tier (default), no tools and no loop.", (args, run) => {
167
+ if (!run.complete)
168
+ throw new Error("llm: this run has no model to complete on");
169
+ return run.complete(args, run.signal);
170
+ }),
171
+ });
172
+ /** Every name a revision may name, those a workflow's model node may, and those a workflow's call node may run. */
173
+ export const BOUND_TOOLS = Object.keys(TOOLS).filter((name) => !TOOLS[name].callOnly);
174
+ export const NODE_TOOLS = BOUND_TOOLS.filter((name) => TOOLS[name].nodes);
175
+ export const CALL_TOOLS = Object.keys(TOOLS).filter((name) => TOOLS[name].effect !== undefined);
176
+ /** Whether `name` is one of `allowed`, or a legacy name for one (fetch_page, web_fetch's): a revision that names it
177
+ * still saves and runs, though the table lists it no more. */
178
+ export const allows = (allowed, name) => allowed.includes(capabilityOf(name));
179
+ /** The tools a run's learned workflow draft may name (learn/check.ts): those of the agent's `granted` tools a workflow's
180
+ * model or call node runs here (NODE_TOOLS, CALL_TOOLS), each as granted and by its capability's name. A harness's own
181
+ * tool (Bash, exec_command, apply_patch) is never one, so the DSL refuses a draft that names it. */
182
+ export const learnedWorkflowTools = (granted) => [...new Set(granted.filter((name) => allows(NODE_TOOLS, name) || allows(CALL_TOOLS, name)).flatMap((name) => [name, capabilityOf(name)]))];
183
+ /** The tools a workflow names (`nodes` from workflowNodes): on its model nodes (`tools`), and on its `call` nodes
184
+ * `via: "tool"` (`tool`). */
185
+ export function workflowTools(nodes) {
186
+ const named = new Set();
187
+ const calls = new Set();
188
+ for (const node of nodes) {
189
+ if (node.node === "call" && node.via === "tool" && typeof node.tool === "string")
190
+ calls.add(node.tool);
191
+ else if (Array.isArray(node.tools))
192
+ for (const name of node.tools)
193
+ if (typeof name === "string")
194
+ named.add(name);
195
+ }
196
+ return { nodes: [...named], calls: [...calls] };
197
+ }
198
+ /** The tools a revision grants its run: an agentic revision's `tools`; a workflow revision's `tools` with those its model
199
+ * and call nodes name, which its run binds whether `tools` lists them or not. */
200
+ export async function grantedTools(revision) {
201
+ if (revision.kind !== "workflow")
202
+ return [...(revision.tools ?? [])];
203
+ const { inspectWorkflow } = await import("@parcha/agentrun-dsl");
204
+ const named = workflowTools(workflowNodes(revision.workflow, inspectWorkflow(revision.workflow)));
205
+ return [...new Set([...(revision.tools ?? []), ...named.nodes, ...named.calls])];
206
+ }
207
+ /** The table's entry for `name`, or undefined for a name it does not hold. */
208
+ export const toolOf = (name) => (Object.hasOwn(TOOLS, name) ? TOOLS[name] : name === FETCH_PAGE_TOOL ? webFetchEntry(FETCH_PAGE_TOOL) : undefined);
209
+ /** What a stored revision's tools resolve from (tool-plane.ts): the tools it grants, its harness, model and settings. */
210
+ export async function toolingOf(revision) {
211
+ const tools = await grantedTools(revision.kind === "agentic" ? { kind: "agentic", tools: revision.body.tools } : { kind: "workflow", tools: revision.body.tools, workflow: revision.body.workflow });
212
+ return { tools, ...(revision.kind === "workflow" ? { workflow: true } : {}), ...(revision.body.harness ? { harness: revision.body.harness } : {}), ...(revision.kind === "agentic" && revision.body.model ? { model: revision.body.model } : {}), ...(revision.body.toolSettings ? { overrides: revision.body.toolSettings } : {}) };
213
+ }
214
+ /** The variables `entry` needs that `env` does not set, by name. */
215
+ export const missingEnv = (entry, env) => entry.needs.filter((name) => !env[name]);
216
+ /** What keeps `names` from being bound here: names outside the table (or, for a workflow's model nodes, that a node may
217
+ * not name), and the variables each tool in it needs that `env` does not set. Undefined when nothing does. */
218
+ export function toolRefusal(names, env, where = "agent") {
219
+ const allowed = where === "nodes" ? NODE_TOOLS : where === "calls" ? CALL_TOOLS : BOUND_TOOLS;
220
+ const unbound = names.filter((name) => !allows(allowed, name));
221
+ if (unbound.length) {
222
+ const said = { agent: "agentrun-serve binds the tools", nodes: "A workflow's model nodes get the tools", calls: "A workflow's call nodes run the tools" }[where];
223
+ return { message: `${said} ${allowed.join(", ")}; this ${where === "agent" ? "revision" : "workflow"} also ${where === "calls" ? "calls" : "names"} ${unbound.join(", ")}.`, unbound, missing: {} };
224
+ }
225
+ const missing = Object.fromEntries(names.map((name) => [name, missingEnv(toolOf(name), env)]).filter(([, vars]) => vars.length));
226
+ const lacking = Object.entries(missing);
227
+ if (!lacking.length)
228
+ return undefined;
229
+ const said = lacking.map(([name, vars]) => `the tool ${name} needs ${vars.join(" and ")}`).join("; ");
230
+ return { message: `This server's environment does not set what the revision's tools need: ${said}.`, unbound: [], missing };
231
+ }
232
+ /** Every tool as capabilities show it, the server's one tool catalog: available here, or the variables it is missing
233
+ * (names only), and the harnesses that run it (another harness than pi runs only the host tools, host-tools.ts). A tool
234
+ * a user picks a provider for (tool-plane.ts) gives the providers offered, the server's (`provider`, the default where it
235
+ * sets none), the default, and what it resolves to on each harness under the server's `settings`: available where any
236
+ * is not unavailable, and missing PARALLEL_API_KEY where Parallel is picked without it. An unavailable tool says why
237
+ * (`reason`). `noBox`: why no box can run a sandbox-only tool here (place.ts noBoxReason), which leaves it
238
+ * unavailable with that reason; undefined, a box can. */
239
+ export const toolsView = (env, settings = {}, noBox) => {
240
+ const views = explainsView(env, settings);
241
+ const picked = withDefaults(settings);
242
+ return Object.entries(TOOLS).map(([name, entry]) => {
243
+ const view = PICKABLE.includes(name) ? views[name] : undefined;
244
+ const plane = view?.resolves;
245
+ const missing = plane && Object.values(plane).includes(NO_PARALLEL_KEY) ? [PARALLEL_KEY_ENV] : missingEnv(entry, env);
246
+ const boxless = entry.sandboxOnly ? noBox : undefined;
247
+ const available = (plane ? Object.values(plane).some((resolution) => !isUnavailable(resolution)) : missing.length === 0) && boxless === undefined;
248
+ // Unavailable says why: a sandbox-only tool no box here can run, why none can (`noBox`); on a tool a user picks a
249
+ // provider for, the resolutions' own words (`web_search is turned off in settings`); else the variables it needs.
250
+ const reason = available ? undefined : boxless ?? (plane ? [...new Set(Object.values(plane).filter(isUnavailable).map(whyUnavailable))].join("; ") : `Needs ${missing.join(", ")}`);
251
+ return { name, summary: entry.summary, nodes: entry.nodes, calls: entry.effect !== undefined, ...(entry.callOnly ? { call_only: true } : {}), ...(entry.sandboxOnly ? { sandbox_only: true } : {}), available, ...(reason ? { reason } : {}), ...(missing.length ? { missing } : {}), harnesses: name in REPLAY ? [...HARNESSES] : [DEFAULT_HARNESS], ...(plane ? { providers: [...PROVIDERS[name]], provider: picked[name].provider, default_provider: PROVIDERS[name][0], resolves: plane, why: view.why } : {}) };
252
+ });
253
+ };
@@ -0,0 +1,23 @@
1
+ /** `{ kind: TURN_END, data: TurnEndData }`: a turn of the session `key` is over. Written in the same commit as the turn's
2
+ * last entries. #1424's first form held only `key` and `status`, and closes the message sent last before it. */
3
+ export declare const TURN_END = "adapter.turn_end";
4
+ /** The root's record of a message the door accepted (`{ key, id, content }`), and of its end (`{ key, id, sent }`):
5
+ * `sent` to the session, or dropped by a stop. The bridge writes a TURN_END naming the message once its turn is over;
6
+ * for a message an older bridge sent and wrote no end for, the run's next process writes it as it opens. */
7
+ export declare const MESSAGE = "adapter.message";
8
+ export declare const MESSAGE_END = "adapter.message_end";
9
+ /** What a turn's end says: the message it took (the MESSAGE id), the session's own outcome (`failed` too when the bridge
10
+ * wrote the turn's error, in `error`), the entry of the turn's answer (its last request with text and no call; null
11
+ * when the turn showed no text), and whether a request it made is still unbooked (its cost then comes later, as a
12
+ * PRICED_LATE entry). */
13
+ export type TurnEndData = {
14
+ key: string;
15
+ message?: string;
16
+ status: "completed" | "interrupted" | "failed";
17
+ answer?: number | null;
18
+ error?: string;
19
+ cost?: "booked" | "pending";
20
+ };
21
+ /** The `api` of every assistant message serve's bridge writes for a claude-agent or codex request (harness-app.ts): its
22
+ * stop reason says nothing of the turn's end (a cost, a cut, an interruption and an answer read alike). */
23
+ export declare const ADAPTER_API = "agentrun-adapter";
@@ -0,0 +1,14 @@
1
+ // The end of a claude-agent or codex turn on a run's root conversation (harness-app.ts writes it; turns.ts reads it), and
2
+ // the root's records of the messages the turns take. Data entries: no model, so the timeline shows no row for them and
3
+ // the meters do not count them.
4
+ /** `{ kind: TURN_END, data: TurnEndData }`: a turn of the session `key` is over. Written in the same commit as the turn's
5
+ * last entries. #1424's first form held only `key` and `status`, and closes the message sent last before it. */
6
+ export const TURN_END = "adapter.turn_end";
7
+ /** The root's record of a message the door accepted (`{ key, id, content }`), and of its end (`{ key, id, sent }`):
8
+ * `sent` to the session, or dropped by a stop. The bridge writes a TURN_END naming the message once its turn is over;
9
+ * for a message an older bridge sent and wrote no end for, the run's next process writes it as it opens. */
10
+ export const MESSAGE = "adapter.message";
11
+ export const MESSAGE_END = "adapter.message_end";
12
+ /** The `api` of every assistant message serve's bridge writes for a claude-agent or codex request (harness-app.ts): its
13
+ * stop reason says nothing of the turn's end (a cost, a cut, an interruption and an answer read alike). */
14
+ export const ADAPTER_API = "agentrun-adapter";
@@ -0,0 +1,34 @@
1
+ /** How a message's turn ended. `answer`: the entry of its answer, null when the turn showed no text. `asked`: a pi turn
2
+ * that ended on a tool asking the person (ask_person ends the turn, and the run waits for their answer). */
3
+ export type TurnEnd = {
4
+ status: "answered" | "asked" | "failed" | "interrupted";
5
+ answer: number | null;
6
+ error?: string;
7
+ };
8
+ /** The request id prefix of a run's end-of-run turn (learning-run.ts): the server's message, never the person's. */
9
+ export declare const REFLECT_REQUEST = "learn-reflect-";
10
+ export declare class Turns {
11
+ #private;
12
+ /** Reads `entries` (the root's, in order) and `submissions` (its input submissions, as pi-durable records them, or as
13
+ * the door's snapshot carries them with `answer_text`), at `now`. `skip`: entries of no turn of the run's own (its
14
+ * end-of-run turn's). Reading the same records again changes nothing: a turn's first end stands. */
15
+ note(entries: readonly unknown[], submissions?: readonly unknown[], skip?: (id: number) => boolean, now?: number): void;
16
+ /** A reconnect's snapshot (the door's `inputs`): the run's inputs from the newest settled one on, and every earlier one
17
+ * not settled yet. It is the whole state, where an event batch carries only changes: a message this ledger holds
18
+ * open that is missing from it, from before its newest settled input, settled while the stream was down. That one
19
+ * is closed, its own end unread and never the run's (the settled one after it is newer). One still queued, a
20
+ * follow-up a steer settled ahead of, is in the snapshot and stays open. */
21
+ snapshot(inputs: readonly unknown[], skip?: (id: number) => boolean, now?: number): void;
22
+ /** How many messages the run took whose turns have not ended. */
23
+ get open(): number;
24
+ /** The newest message's turn's end, once no message is open. */
25
+ end(): TurnEnd | undefined;
26
+ /** The whole text of entry `id`, an answer read here; undefined for one not read. */
27
+ text(id: number): string | undefined;
28
+ /** The whole text of the newest answer with text the run gave: what its cap keeps, and the answer of a run read by its
29
+ * rows. */
30
+ get newestText(): string | undefined;
31
+ /** When the turn of a message still open last wrote (its message taken, or an entry or a settlement since), as ms;
32
+ * undefined when none is open. */
33
+ progressAt(): number | undefined;
34
+ }
package/dist/turns.js ADDED
@@ -0,0 +1,202 @@
1
+ // The person's messages a run took, and how each one's turn ended, read from the run's own records, never from the
2
+ // order of its rows or from when its door said idle (runs.ts decide()):
3
+ // pi the input submission of each message, which pi-durable settles in the commit that appends the turn's
4
+ // last entry: `done` with the answer's entry, or `unanswered` (aborted, or the model's error);
5
+ // claude-agent, the bridge's records on the root (turn-end.ts): MESSAGE as the door accepts a message, MESSAGE_END
6
+ // codex as it is sent (or dropped by a stop), and TURN_END, in the commit of the turn's last entries.
7
+ // A message is open from the moment the run took it until its turn's end closes it, so a follow-up queued behind a turn
8
+ // keeps the run open whatever the door says meanwhile.
9
+ import { newestSettledInput } from "@parcha/pi-durable-disk/internals";
10
+ import { ADAPTER_API, MESSAGE, MESSAGE_END, TURN_END } from "./turn-end.js";
11
+ /** The request id prefix of a run's end-of-run turn (learning-run.ts): the server's message, never the person's. */
12
+ export const REFLECT_REQUEST = "learn-reflect-";
13
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ /** An answer's whole text: its text blocks, as a run's answer has always read. */
15
+ const textOf = (content) => typeof content === "string" ? content : Array.isArray(content) ? content.filter((b) => isObject(b) && b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim() : "";
16
+ const later = (a, b) => (a.placed !== undefined && b.placed !== undefined ? a.placed > b.placed : a.order > b.order);
17
+ export class Turns {
18
+ #messages = new Map();
19
+ #texts = new Map();
20
+ /** The assistant entries that asked for tools: a turn settled on one ended on a tool's own end (ask_person's). */
21
+ #calls = new Set();
22
+ /** The bridge's message whose turn runs (the one sent last), and its newest answer since then. */
23
+ #sent;
24
+ #since;
25
+ /** The newest error the bridge wrote on the root since that message was sent: an older bridge's turn end has none. */
26
+ #sinceError;
27
+ #newestText;
28
+ #seen = 0;
29
+ #progress;
30
+ /** Reads `entries` (the root's, in order) and `submissions` (its input submissions, as pi-durable records them, or as
31
+ * the door's snapshot carries them with `answer_text`), at `now`. `skip`: entries of no turn of the run's own (its
32
+ * end-of-run turn's). Reading the same records again changes nothing: a turn's first end stands. */
33
+ note(entries, submissions = [], skip, now = Date.now()) {
34
+ for (const value of entries) {
35
+ if (!isObject(value) || typeof value.kind !== "string")
36
+ continue;
37
+ const id = typeof value.id === "number" ? value.id : undefined;
38
+ if (id !== undefined && skip?.(id))
39
+ continue;
40
+ // An entry not read before (a snapshot reads every one again): only such an entry moves what is read by place, the
41
+ // message sent last and its answer since. Any new entry while a message is open is its turn's progress.
42
+ const fresh = id === undefined || id > this.#seen;
43
+ if (id !== undefined && fresh) {
44
+ this.#seen = id;
45
+ if (this.open > 0)
46
+ this.#progress = now;
47
+ }
48
+ const data = isObject(value.data) ? value.data : undefined;
49
+ const first = Array.isArray(value.model) && isObject(value.model[0]) ? value.model[0] : undefined;
50
+ if (value.kind === "pi.assistant" && id !== undefined && Array.isArray(first?.content) && first.content.some((b) => isObject(b) && b.type === "toolCall"))
51
+ this.#calls.add(id);
52
+ // An answer's text: a stop's, or a stop at the length limit (pi ends the turn on both, settled on that entry).
53
+ if (value.kind === "pi.assistant" && (first?.stopReason === "stop" || first?.stopReason === "length") && id !== undefined) {
54
+ const text = textOf(first.content);
55
+ this.#texts.set(id, text);
56
+ if (text && fresh)
57
+ this.#newestText = text;
58
+ if (text && fresh && first.api === ADAPTER_API)
59
+ this.#since = id;
60
+ }
61
+ else if (value.kind === "pi.assistant" && first?.api === ADAPTER_API && first.stopReason === "error" && typeof first.errorMessage === "string") {
62
+ if (fresh)
63
+ this.#sinceError = first.errorMessage;
64
+ }
65
+ else if (value.kind === MESSAGE && typeof data?.id === "string") {
66
+ this.#take(`m:${data.id}`, now, id ?? this.#seen);
67
+ }
68
+ else if (value.kind === MESSAGE_END && typeof data?.id === "string") {
69
+ const message = this.#messages.get(`m:${data.id}`);
70
+ if (!message || message.sent)
71
+ continue;
72
+ // Dropped by a stop before it was sent: no turn took it.
73
+ if (data.sent !== true) {
74
+ if (!message.end)
75
+ this.#messages.delete(message.key);
76
+ continue;
77
+ }
78
+ message.sent = true;
79
+ if (!fresh)
80
+ continue;
81
+ // Turns are taken one at a time: one sent means the one sent before it had its turn, which is over (an older
82
+ // bridge wrote no end for it).
83
+ if (this.#sent && !this.#sent.end)
84
+ this.#sent.end = { status: "answered", answer: this.#since ?? null };
85
+ this.#sent = message;
86
+ this.#since = undefined;
87
+ this.#sinceError = undefined;
88
+ }
89
+ else if (value.kind === TURN_END && data) {
90
+ // #1424's first form names no message: it ends the turn of the message sent last, read in place.
91
+ const message = typeof data.message === "string" ? this.#messages.get(`m:${data.message}`) : fresh ? this.#sent : undefined;
92
+ if (!message || message.end)
93
+ continue;
94
+ const status = data.status === "completed" ? "answered" : data.status === "interrupted" ? "interrupted" : "failed";
95
+ const answer = "answer" in data ? (typeof data.answer === "number" ? data.answer : null) : (this.#since ?? null);
96
+ // #1424's bridge wrote a failed turn's error on the root, then its end with none (and a relaunch writes one for a
97
+ // turn whose end it never wrote): the error is the bridge's newest since that message was sent.
98
+ const error = typeof data.error === "string" ? data.error : status === "failed" && message === this.#sent ? this.#sinceError : undefined;
99
+ message.end = { status, answer: status === "answered" ? answer : null, ...(error === undefined ? {} : { error }) };
100
+ }
101
+ }
102
+ for (const value of submissions)
103
+ this.#settle(value, skip, now);
104
+ }
105
+ /** A reconnect's snapshot (the door's `inputs`): the run's inputs from the newest settled one on, and every earlier one
106
+ * not settled yet. It is the whole state, where an event batch carries only changes: a message this ledger holds
107
+ * open that is missing from it, from before its newest settled input, settled while the stream was down. That one
108
+ * is closed, its own end unread and never the run's (the settled one after it is newer). One still queued, a
109
+ * follow-up a steer settled ahead of, is in the snapshot and stays open. */
110
+ snapshot(inputs, skip, now = Date.now()) {
111
+ this.note([], inputs, skip, now);
112
+ const records = inputs.filter((value) => isObject(value) && value.type === "input" && typeof value.id === "number" && typeof value.status === "string");
113
+ const held = new Set(records.map((value) => `s:${value.id}`));
114
+ // The newest settled input as the door's snapshot chose it, by the same rule: the run's own, never the end-of-run turn's.
115
+ const newest = newestSettledInput(records, REFLECT_REQUEST);
116
+ if (newest < 0)
117
+ return;
118
+ const through = records[newest].id;
119
+ for (const message of this.#messages.values())
120
+ if (message.key.startsWith("s:") && !message.end && message.order < through && !held.has(message.key))
121
+ message.end = { status: "answered", answer: null };
122
+ }
123
+ /** One input submission: a message taken while queued or placed, closed once it is settled. */
124
+ #settle(value, skip, now) {
125
+ if (!isObject(value) || value.type !== "input" || typeof value.id !== "number")
126
+ return;
127
+ if ((typeof value.requestId === "string" && value.requestId.startsWith(REFLECT_REQUEST)) || (typeof value.entry === "number" && skip?.(value.entry)))
128
+ return;
129
+ const key = `s:${value.id}`;
130
+ const known = this.#messages.get(key);
131
+ // Withdrawn before it was placed (a stop): no turn took it.
132
+ if (value.status === "unanswered" && typeof value.entry !== "number") {
133
+ if (known && !known.end)
134
+ this.#messages.delete(key);
135
+ return;
136
+ }
137
+ const message = known ?? this.#take(key, now, value.id);
138
+ if (typeof value.entry === "number")
139
+ message.placed = value.entry;
140
+ if (message.end)
141
+ return;
142
+ // Only a move of its status is its turn's progress: a reconnect's snapshot carries the same record again.
143
+ const moved = message.status !== value.status;
144
+ message.status = value.status;
145
+ if (value.status === "done") {
146
+ const answer = typeof value.answer === "number" ? value.answer : null;
147
+ if (answer !== null && typeof value.answer_text === "string")
148
+ this.#texts.set(answer, value.answer_text);
149
+ // Settled on the entry that asked for its tools: a tool ended the turn (ask_person), so the person is asked, not
150
+ // answered. The door's snapshot says so for an entry it does not hold (`answer_calls`).
151
+ message.end = answer !== null && (this.#calls.has(answer) || value.answer_calls === true) ? { status: "asked", answer: null } : { status: "answered", answer };
152
+ }
153
+ else if (value.status === "unanswered") {
154
+ message.end = value.reason === "aborted" ? { status: "interrupted", answer: null } : { status: "failed", answer: null, error: typeof value.detail === "string" ? value.detail : String(value.reason ?? "the turn failed") };
155
+ }
156
+ else if (moved && this.open > 0)
157
+ this.#progress = now;
158
+ }
159
+ #take(key, now, order) {
160
+ const known = this.#messages.get(key);
161
+ if (known)
162
+ return known;
163
+ const message = { key, order };
164
+ this.#messages.set(key, message);
165
+ this.#progress = now;
166
+ return message;
167
+ }
168
+ /** The message whose turn ran last: by where pi placed each input when both were placed, else by when the run took it. */
169
+ #newest() {
170
+ let newest;
171
+ for (const message of this.#messages.values())
172
+ if (!newest || later(message, newest))
173
+ newest = message;
174
+ return newest;
175
+ }
176
+ /** How many messages the run took whose turns have not ended. */
177
+ get open() {
178
+ let n = 0;
179
+ for (const message of this.#messages.values())
180
+ if (!message.end)
181
+ n++;
182
+ return n;
183
+ }
184
+ /** The newest message's turn's end, once no message is open. */
185
+ end() {
186
+ return this.open ? undefined : this.#newest()?.end;
187
+ }
188
+ /** The whole text of entry `id`, an answer read here; undefined for one not read. */
189
+ text(id) {
190
+ return this.#texts.get(id);
191
+ }
192
+ /** The whole text of the newest answer with text the run gave: what its cap keeps, and the answer of a run read by its
193
+ * rows. */
194
+ get newestText() {
195
+ return this.#newestText;
196
+ }
197
+ /** When the turn of a message still open last wrote (its message taken, or an entry or a settlement since), as ms;
198
+ * undefined when none is open. */
199
+ progressAt() {
200
+ return this.open ? this.#progress : undefined;
201
+ }
202
+ }
@@ -0,0 +1,104 @@
1
+ import { type Json } from "./validate.js";
2
+ /** `limits.max_upload_bytes`: the largest file a reservation names and a PUT sends. */
3
+ export declare const MAX_UPLOAD_BYTES: number;
4
+ /** `limits.max_files_per_run`: the most files one run names (the contract's `RunCreate.file_ids` takes at most 100). */
5
+ export declare const MAX_FILES_PER_RUN = 20;
6
+ /** Where a run finds its files: `work/inputs/<path>`, each file's `path` with its folders. */
7
+ export declare const INPUTS_DIR = "inputs";
8
+ /** The data directory's folder of uploads. */
9
+ export declare const UPLOADS_DIR = "files";
10
+ /** Where a file's bytes go: its own PUT, as a path from the server's root, so it resolves against the server's address
11
+ * as given (`http://host:port`) or as the contract's `/v2` server URL alike. */
12
+ export declare const uploadUrl: (id: string) => string;
13
+ /** Test seams, tests only: as a run's copy starts, with the run's work/, before any file is copied; and as a file sent in
14
+ * one call writes its record, with the file's folder, its bytes in place. */
15
+ export declare const uploadTestHooks: {
16
+ beforeCopy?: (work: string) => Promise<void> | void;
17
+ beforeRecord?: (dir: string) => Promise<void> | void;
18
+ };
19
+ /** The contract's FileUpload: the file, and where to send its bytes (for a file sent in one call, ready, a PUT of the
20
+ * same bytes, which changes nothing). */
21
+ export type FileUploadAnswer = {
22
+ file: UploadedFile;
23
+ upload: {
24
+ method: "PUT";
25
+ url: string;
26
+ expires_at: string;
27
+ };
28
+ };
29
+ /** A file sent in one call, its bytes in and checked, before it is made: `fingerprint` is what an Idempotency-Key is
30
+ * matched on (its path, type, length and hash), `commit` makes it, ready, and `discard` drops the bytes of one not made. */
31
+ export type Received = {
32
+ fingerprint: Json;
33
+ commit(): Promise<FileUploadAnswer>;
34
+ discard(): Promise<void>;
35
+ };
36
+ /** The contract's File: `pending` until its bytes arrive, then `ready`, its `sha256` the bytes' own. */
37
+ export type UploadedFile = {
38
+ file_id: string;
39
+ path: string;
40
+ size_bytes: number;
41
+ content_type: string;
42
+ sha256: string | null;
43
+ status: "pending" | "ready";
44
+ created_at: string;
45
+ expires_at: null;
46
+ };
47
+ /** Why `path` is not the contract's FilePathString (relative, `/` between segments, no empty segment and none that starts
48
+ * with `.`, no backslash or NUL, at most 1024 characters), or a segment is longer than a name on disk; undefined when it
49
+ * is one. */
50
+ export declare function pathProblem(path: string): string | undefined;
51
+ /** `name` for the first, then `name-2`, `name-3`, ... before its extension (`report-2.pdf`), cut to fit a name on disk:
52
+ * its stem first, down to one character, then its extension. */
53
+ export declare function suffixed(name: string, n: number): string;
54
+ export declare class Uploads {
55
+ private readonly root;
56
+ /** The commit of each file's bytes in progress: one at a time per file, so of two PUTs at once one makes it ready and
57
+ * the other is checked against it. */
58
+ private readonly commits;
59
+ /** `root`: `<data>/files`. */
60
+ constructor(root: string);
61
+ /** Why `path` cannot be a file's path here: not the contract's FilePathString, a segment longer than a name on disk,
62
+ * or a run's copy of it (`<data>/runs/<run id>/work/inputs/<path>`, room for a suffix on each segment included) longer
63
+ * than a path the system opens. Undefined when it can. */
64
+ private problemOf;
65
+ /** The file `id`, or null when there is none. */
66
+ get(id: string): Promise<UploadedFile | null>;
67
+ /** Every file's id, newest first: a UUIDv7 sorts by its time. The files' list reads them a page at a time. */
68
+ ids(): Promise<string[]>;
69
+ /** At a start, under the data directory's lock (one server per data directory, so no PUT of this server is in flight):
70
+ * removes the temp files a crash left, by the exact names this module writes them under. That is `.incoming.*.tmp`
71
+ * under the root, and `bytes.*.tmp` in a folder named as a file's id. Each goes only when lstat says it is a regular
72
+ * file: a link or anything else named like one stays, nothing is followed, and only those folders are entered, one
73
+ * level. A file's bytes and its record are never touched: a folder left with only its temp keeps the rest, as after a
74
+ * failed PUT. A root that is not a real directory (a link to storage another server may share) is not swept at all: the
75
+ * lock covers this data directory, not where a link goes. Answers how many it removed. */
76
+ sweep(): Promise<number>;
77
+ /** Deletes the file `id`, pending or ready, or 404. A run that copied it keeps its copy. In turn with a PUT's commit, so
78
+ * a PUT that ends after the delete answers 404 and makes nothing. */
79
+ remove(id: string): Promise<void>;
80
+ /** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
81
+ private answer;
82
+ /** POST /v2/files?path=...: the body is the file's bytes, whatever its type but a multipart form (415, with the call
83
+ * that works). The query takes `path`, and `content_type` and `sha256` when given; the length is the body's and the hash
84
+ * its own. The type is `content_type`, else the request's when it names one (not octet-stream, not curl's form type),
85
+ * else the path's extension's, else octet-stream. The bytes stream to a dot-named file of their own under the root,
86
+ * never held whole; over MAX_UPLOAD_BYTES is 413, a `sha256` they do not have 422. Nothing is made until `commit`. */
87
+ take(query: URLSearchParams, requestType: string | undefined, body: AsyncIterable<Buffer>): Promise<Received>;
88
+ /** POST /v2/files: the body checked as the contract's FileCreate, then a pending file; with where to send its bytes. */
89
+ reserve(body: Json): Promise<FileUploadAnswer>;
90
+ /** PUT /v2/files/{file_id}: `body` is the bytes, streamed to a file of their own beside the record, never held whole.
91
+ * Their length must be the reserved `size_bytes` and their hash the reserved `sha256` when one was given (422 at that
92
+ * field), and they are at most MAX_UPLOAD_BYTES (413). Then they are renamed into place and the file is ready. A
93
+ * ready file's bytes are checked the same way against its own and kept: the same bytes again change nothing. */
94
+ receive(id: string, body: AsyncIterable<Buffer>): Promise<UploadedFile>;
95
+ /** `work` in turn for file `id`. The chain holds only settled turns, so one that failed never fails the next. */
96
+ private exclusive;
97
+ /** A run's `file_ids`: each a file that is ready, none twice, at most MAX_FILES_PER_RUN, or 422 at `file_ids`. */
98
+ readyFiles(ids: readonly unknown[]): Promise<UploadedFile[]>;
99
+ /** Copies `files` into `work/inputs/`, each at its `path` with its folders, in order, before the run's process exists:
100
+ * a name taken already (the same path twice, or a file where another's folder goes) gets the next free suffix
101
+ * (`notes-2.txt`, `docs-2/`), the same for the same files in the same order. Each copy is a new file, made as the
102
+ * agent store makes a run's skill files (its mode from the umask): never a link to the upload. */
103
+ copyInto(work: string, files: readonly UploadedFile[]): Promise<void>;
104
+ }