@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30

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 (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,154 @@
1
+ // The host tools of a run on a harness other than pi: its coding tools, from the run's coding source (coding-tools.ts:
2
+ // pi's own read, write and edit on the run's environment, or in a box those, bash and the background tools on the
3
+ // box's), so their arguments, their confinement and their refusals are pi's, word for word, pi's web_fetch (also under
4
+ // its legacy name, fetch_page), the public-host guard included, web_search, and monid's three (monid.ts), which stay on this machine.
5
+ // pi's tools take only the environment, their output and their diagnostics from a call's API, and a paid one its call's
6
+ // id and the run's store, so that is all a call here gives them: the output's tail or head as the tool keeps it (pi's
7
+ // limits), then the diagnostics, also when the tool failed. read, the web tools, monid.discover, monid.inspect,
8
+ // bash_output and bash_list may run again after a crash; write, edit, bash, monid.run, bash_background, bash_input and
9
+ // bash_signal never: the kernel records each one's intent before it runs, and a call a crash cut off is answered
10
+ // interrupted, not run again. A tool is named by its catalog name here and goes to the harness under its wire name (catalog.ts: `monid.run` is `monid_run`), which the harness calls and journals. A
11
+ // refusal, an error and a write's or edit's result name a path in the workspace relative to it (`hello.md`), never by
12
+ // the server's data directory (`workspaceRelative`); in a box they name the box's paths. Each call passes the run's tool
13
+ // gate first (tool-gate.ts): a denied call is refused, an asked one parked, and the harness is told so it ends the turn.
14
+ import { StringDecoder } from "node:string_decoder";
15
+ import { withAbortSignal } from "@earendil-works/chord/context";
16
+ import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
17
+ import { wireName } from "./catalog.js";
18
+ import { BOXED_TOOLS, CodingTools } from "./coding-tools.js";
19
+ import { FETCH_PAGE_TOOL } from "./fetch-page.js";
20
+ import { monidTools } from "./monid.js";
21
+ import { booking } from "./paid-calls.js";
22
+ import { withSecrets } from "./secrets.js";
23
+ import { WEB_FETCH_TOOL, webFetchTool } from "./web-fetch.js";
24
+ import { WEB_SEARCH_TOOL, webSearchTool } from "./web-search.js";
25
+ import { realOf, workspaceRelative } from "./workspace-paths.js";
26
+ export { workspaceRelative } from "./workspace-paths.js";
27
+ /** Each tool a harness other than pi runs here, by catalog name, and whether a call a crash cut off may run again.
28
+ * `learned_workflow` (learned-workflow.ts LEARNED_WORKFLOW_TOOL, named here as a string so the modules do not import
29
+ * each other) is never run again. */
30
+ export const REPLAY = { read: "safe", write: "never", edit: "never", bash: "never", [FETCH_PAGE_TOOL]: "safe", [WEB_FETCH_TOOL]: "safe", [WEB_SEARCH_TOOL]: "safe", "monid.discover": "safe", "monid.inspect": "safe", "monid.run": "never", bash_background: "never", bash_output: "safe", bash_input: "never", bash_signal: "never", bash_list: "safe", learned_workflow: "never" };
31
+ /** pi's limits on a tool's output (its DEFAULT_MAX_BYTES and DEFAULT_MAX_LINES), unless the tool names its own: read's
32
+ * head and bash's tail are held to them (the host-bounds test reads pi's own words for them). */
33
+ export const MAX_BYTES = 50 * 1024;
34
+ export const MAX_LINES = 2000;
35
+ /** Whether `byte` continues a UTF-8 character (0b10xxxxxx), so a cut before it would split one. */
36
+ const continues = (byte) => byte !== undefined && (byte & 0xc0) === 0x80;
37
+ /** `bytes` (UTF-8) cut to at most `max` bytes, its tail or its head, at a character boundary: a character the limit
38
+ * would split is left out whole, so the text never ends or starts in a U+FFFD. */
39
+ export function cutUtf8(bytes, max, tail) {
40
+ if (bytes.length <= max)
41
+ return bytes;
42
+ if (tail) {
43
+ let start = bytes.length - max;
44
+ while (continues(bytes[start]))
45
+ start++;
46
+ return bytes.subarray(start);
47
+ }
48
+ // The byte at `end` is the first one left out: while it continues a character, that character goes too.
49
+ let end = max;
50
+ while (end > 0 && continues(bytes[end]))
51
+ end--;
52
+ return bytes.subarray(0, end);
53
+ }
54
+ /** A call's output, held within the tool's limits as it arrives: its tail (bash's) or its head. */
55
+ function bounded(limits) {
56
+ const maxBytes = limits?.maxBytes ?? MAX_BYTES;
57
+ const maxLines = limits?.maxLines ?? MAX_LINES;
58
+ const tail = limits?.retain === "tail";
59
+ // Bytes are decoded as one stream: a character whose bytes arrive in two chunks is one character.
60
+ const decoder = new StringDecoder("utf8");
61
+ let kept = "";
62
+ let cut = false;
63
+ const trim = (text) => {
64
+ const lines = text.split("\n");
65
+ let out = lines.length > maxLines ? (tail ? lines.slice(-maxLines) : lines.slice(0, maxLines)).join("\n") : text;
66
+ const bytes = Buffer.from(out, "utf8");
67
+ if (bytes.length > maxBytes)
68
+ out = Buffer.from(cutUtf8(bytes, maxBytes, tail)).toString("utf8");
69
+ if (out !== text)
70
+ cut = true;
71
+ return out;
72
+ };
73
+ return {
74
+ push(chunk) {
75
+ const text = typeof chunk === "string" ? chunk : decoder.write(Buffer.from(chunk));
76
+ if (!tail && cut)
77
+ return;
78
+ kept += text;
79
+ // Trimmed once it is twice the limit, so a long output costs a bounded amount of memory and work.
80
+ if (kept.length > 2 * maxBytes)
81
+ kept = trim(kept);
82
+ },
83
+ /** What is kept so far, and whether any was cut: pi 1.2's `retainedOutput`. */
84
+ retained: () => {
85
+ const text = trim(kept);
86
+ return { text, truncated: cut };
87
+ },
88
+ text() {
89
+ const out = trim(kept);
90
+ return cut ? (tail ? `[earlier output omitted]\n${out}` : `${out}\n[later output omitted]`) : out;
91
+ },
92
+ };
93
+ }
94
+ /** The tools whose result is pi's own words about a path (`Successfully wrote to <path>`), never a file's text. */
95
+ const SAYS_PATH = new Set(["write", "edit"]);
96
+ const textOf = (content) => Array.isArray(content) ? content.map((block) => (block && typeof block === "object" && "text" in block && typeof block.text === "string" ? block.text : "")).join("") : "";
97
+ /** The host tools `names` names, on the run's coding source `coding`. `gated`: the run's tool gate, which every call
98
+ * passes, and the park it takes (harness-app.ts), told of a call it parked, whose turn the harness ends; none (the
99
+ * gate's own run of an approved call), each call runs as asked. `extra`: the run's own tools beyond the table (its
100
+ * learned_workflow, learned-workflow.ts), which the gate passes like the rest. */
101
+ export function hostTools(run, names, context, results, coding = CodingTools.tools ?? [], gated, extra = []) {
102
+ // The coding source gives the coding tools and nothing else: the network tools are this machine's own, below.
103
+ const stray = coding.map((tool) => tool.name).filter((name) => !BOXED_TOOLS.includes(name));
104
+ if (stray.length)
105
+ throw new Error(`the coding source holds ${stray.join(", ")}, which is no coding tool`);
106
+ // Their paid requests (Parallel's) are booked under the call, in the run's store, as pi's are (paid-calls.ts).
107
+ const web = [webFetchTool(process.env), webFetchTool(process.env, FETCH_PAGE_TOOL), webSearchTool(process.env)].map(booking);
108
+ // monid's, only for a run that names one: its key is the one this process was handed over its pipe (secrets.ts),
109
+ // never in its environment, and its long answers go in the run's work/, the claim's as pi's (`where.work`), read at
110
+ // the call. They are outside the coding source, which holds the coding tools only.
111
+ const monid = names.some((name) => name.startsWith("monid.")) ? monidTools(withSecrets(process.env), () => run.claim.work) : [];
112
+ // `extra`: the run's own tools beyond the table, its learned_workflow (learned-workflow.ts) when its pin names one.
113
+ const tools = new Map([...coding, ...web, ...monid, ...extra].map((tool) => [tool.name, tool]));
114
+ return names.flatMap((name) => {
115
+ // The registrations are keyed by their wire names: the same name for every tool here but monid's.
116
+ const tool = tools.get(wireName(name));
117
+ const replay = REPLAY[name];
118
+ if (!tool || !replay)
119
+ return [];
120
+ const host = {
121
+ name: tool.name,
122
+ description: tool.description,
123
+ inputSchema: tool.parameters,
124
+ replay,
125
+ async call(args, { callId, signal }) {
126
+ const refused = await gated?.gate.enter(name, args, callId, gated.park);
127
+ if (refused) {
128
+ const answer = { text: refused.text, isError: refused.isError };
129
+ results.set(callId, answer);
130
+ return answer;
131
+ }
132
+ const out = bounded(tool.outputLimits);
133
+ const notes = [];
134
+ const env = await run.env({ conversationId: ROOT_CONVERSATION_ID, read: undefined }, context);
135
+ // The call's id and the run's store, as pi's: a paid call marks and books its charge there (monid.ts).
136
+ const api = { env, callId, commit: (change, at) => run.harness.commit(change, at), output: (chunk) => out.push(chunk), outputWindow: undefined, retainedOutput: () => out.retained(), diagnostic: (note) => void notes.push(note.message) };
137
+ // A tool that throws (bash on a non-zero exit or a timeout) still answers with its output, as pi's harness does;
138
+ // monid's answer a failure as an error result, which is kept as it is.
139
+ const result = await tool.execute(args, api, withAbortSignal(signal, context)).catch((error) => ({ failed: error.message, isError: true }));
140
+ // pi 1.1 names the result's blocks `content`, pi 1.2 and later `output`; pi 1.2's bash answers its exit as a
141
+ // result's diagnostic, where 1.1 threw it.
142
+ const given = result;
143
+ const said = [textOf(given.content ?? given.output) || out.text(), given.failed, ...notes, ...(given.diagnostics ?? []).map((note) => note.message)].filter((part) => part).join("\n\n");
144
+ const isError = given.isError === true;
145
+ const work = env.cwd;
146
+ const works = typeof work === "string" ? [work, realOf(work)] : [];
147
+ const answer = { text: isError || SAYS_PATH.has(name) ? workspaceRelative(said, works) : said, isError };
148
+ results.set(callId, answer);
149
+ return answer;
150
+ },
151
+ };
152
+ return [host];
153
+ });
154
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { statfs } from "node:fs/promises";
2
+ /** Memory the server keeps for itself, before any run, in MiB. Measured with RUN_MIB (harness.ts): the server's anon
3
+ * 3 s after its start, 32 starts at limits of 512M to 2048M, was 58 to 81 MB, with no peak at the start over that;
4
+ * reserved for the high end, 81, plus 47 (+58%), since what it holds grows with the agents and runs it keeps. That is
5
+ * with the pinned binaries' sha256 checked a chunk at a time: a start that reads the codex binary (294 MB) and the
6
+ * claude-agent CLI (230 MB) whole sat at 341 to 348 MB on a host of 1 GB or less. */
7
+ export declare const SERVER_MIB = 128;
8
+ /** Free disk under the data directory below which health fails, unless the server says otherwise. */
9
+ export declare const MIN_FREE_MIB = 64;
10
+ /** The memory this server may use: its container's limit when it has one (cgroup), else the machine's. */
11
+ export declare function hostMemory(): number;
12
+ /** The memory runs may hold on a host of `memory` bytes, in MiB: all of it less the server's own. */
13
+ export declare const runsMemoryMib: (memory: number) => number;
14
+ /** What a run of `harness` reserves, in MiB. A harness outside the table (no saved revision names one) reserves the most. */
15
+ export declare const runMibOf: (harness: string | undefined) => number;
16
+ /** How many runs of `harness` alone fit on a host of `memory` bytes. pi, the default, always has one place, as before
17
+ * runs were admitted by memory: a server too small for even that still runs one at a time. */
18
+ export declare function runsThatFit(harness: string, memory: number): number;
19
+ /** The default cap on how many runs at once: as many pi runs, the smallest, as fit. */
20
+ export declare const defaultMaxRuns: (memory: number) => number;
21
+ /** Why no run of `harness` can ever start on a host of `memory` bytes, in words; undefined when one fits. */
22
+ export declare function neverFits(harness: string, memory: number): string | undefined;
23
+ /** Why a run of `harness` cannot start now, with `heldMib` of the memory for runs held: the memory runs hold, in words. */
24
+ export declare function memoryFull(harness: string, memory: number, heldMib: number): string;
25
+ /** The cap on how many runs at once: `given`, else `AGENTRUN_MAX_RUNS`, else the default for this host's memory. The
26
+ * memory each run reserves is checked beside it (runs.ts): both apply. */
27
+ export declare function maxRunsOf(env: NodeJS.ProcessEnv, given?: number): number;
28
+ export type Health = {
29
+ status: "ok" | "failing";
30
+ checks: {
31
+ store: "ok" | "does_not_open";
32
+ disk: "ok" | "below_floor" | "cannot_check";
33
+ };
34
+ };
35
+ /** Whether the store in `data` opens for a read, and its disk has `minFreeBytes` free; a disk it cannot measure fails.
36
+ * Says no path and no number. `fsStat` is node's statfs unless a test gives another. */
37
+ export declare function healthOf(data: string, minFreeBytes: number, fsStat?: typeof statfs): Promise<Health>;
38
+ /** Whether `--open` opens a browser here: not in CI, and on Linux or FreeBSD only with a display. */
39
+ export declare const canOpen: (env: NodeJS.ProcessEnv, platform?: NodeJS.Platform) => boolean;
package/dist/host.js ADDED
@@ -0,0 +1,85 @@
1
+ // What one host can hold, and whether it can work now. Runs are admitted by memory: each run is a process of its own,
2
+ // and each reserves what a run of its harness takes (RUN_MIB, harness.ts) out of the memory the host has less the
3
+ // server's own (SERVER_MIB). Health reads the agent store and the free disk under the data directory. A start here opens
4
+ // a browser only where there is one to open.
5
+ import { statfs } from "node:fs/promises";
6
+ import { totalmem } from "node:os";
7
+ import { openStoreReader } from "@parcha/pi-durable-agent";
8
+ import { REQUEST_BUSY_MS, whenFree } from "./agents.js";
9
+ import { DEFAULT_HARNESS, HARNESSES, RUN_MIB } from "./harness.js";
10
+ const MiB = 2 ** 20;
11
+ /** Memory the server keeps for itself, before any run, in MiB. Measured with RUN_MIB (harness.ts): the server's anon
12
+ * 3 s after its start, 32 starts at limits of 512M to 2048M, was 58 to 81 MB, with no peak at the start over that;
13
+ * reserved for the high end, 81, plus 47 (+58%), since what it holds grows with the agents and runs it keeps. That is
14
+ * with the pinned binaries' sha256 checked a chunk at a time: a start that reads the codex binary (294 MB) and the
15
+ * claude-agent CLI (230 MB) whole sat at 341 to 348 MB on a host of 1 GB or less. */
16
+ export const SERVER_MIB = 128;
17
+ /** Free disk under the data directory below which health fails, unless the server says otherwise. */
18
+ export const MIN_FREE_MIB = 64;
19
+ /** The memory this server may use: its container's limit when it has one (cgroup), else the machine's. */
20
+ export function hostMemory() {
21
+ const total = totalmem();
22
+ const limit = process.constrainedMemory?.() ?? 0;
23
+ return limit > 0 && limit < total ? limit : total;
24
+ }
25
+ /** The memory runs may hold on a host of `memory` bytes, in MiB: all of it less the server's own. */
26
+ export const runsMemoryMib = (memory) => Math.floor(memory / MiB) - SERVER_MIB;
27
+ /** What a run of `harness` reserves, in MiB. A harness outside the table (no saved revision names one) reserves the most. */
28
+ export const runMibOf = (harness) => RUN_MIB[(harness ?? DEFAULT_HARNESS)] ?? Math.max(...Object.values(RUN_MIB));
29
+ /** How many runs of `harness` alone fit on a host of `memory` bytes. pi, the default, always has one place, as before
30
+ * runs were admitted by memory: a server too small for even that still runs one at a time. */
31
+ export function runsThatFit(harness, memory) {
32
+ const fit = Math.max(0, Math.floor(runsMemoryMib(memory) / runMibOf(harness)));
33
+ return harness === DEFAULT_HARNESS ? Math.max(1, fit) : fit;
34
+ }
35
+ /** The default cap on how many runs at once: as many pi runs, the smallest, as fit. */
36
+ export const defaultMaxRuns = (memory) => runsThatFit(DEFAULT_HARNESS, memory);
37
+ const sizeOf = (mib) => `${Math.round(mib)} MB`;
38
+ /** "a pi run", "an opencode run". */
39
+ const aRun = (harness) => `${/^[aeiou]/i.test(harness) ? "an" : "a"} ${harness} run`;
40
+ /** "pi", "pi and codex", "pi, claude-agent and codex". */
41
+ const listed = (names) => (names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names.join(""));
42
+ /** Why no run of `harness` can ever start on a host of `memory` bytes, in words; undefined when one fits. */
43
+ export function neverFits(harness, memory) {
44
+ if (runsThatFit(harness, memory) > 0)
45
+ return undefined;
46
+ const fit = HARNESSES.filter((id) => runsThatFit(id, memory) > 0);
47
+ return `This server has ${sizeOf(memory / MiB)} of memory and keeps ${sizeOf(SERVER_MIB)} for itself; ${aRun(harness)} needs about ${sizeOf(runMibOf(harness))} more, so it can't start here. ${listed(fit)} runs fit.`;
48
+ }
49
+ /** Why a run of `harness` cannot start now, with `heldMib` of the memory for runs held: the memory runs hold, in words. */
50
+ export function memoryFull(harness, memory, heldMib) {
51
+ const free = Math.max(0, runsMemoryMib(memory) - heldMib);
52
+ return `This server's memory is held by the runs it has going: ${aRun(harness)} needs about ${sizeOf(runMibOf(harness))}, and ${sizeOf(free)} of the ${sizeOf(runsMemoryMib(memory))} it has for runs is free; start this one when another ends.`;
53
+ }
54
+ /** The cap on how many runs at once: `given`, else `AGENTRUN_MAX_RUNS`, else the default for this host's memory. The
55
+ * memory each run reserves is checked beside it (runs.ts): both apply. */
56
+ export function maxRunsOf(env, given) {
57
+ const value = given ?? (env.AGENTRUN_MAX_RUNS ? Number(env.AGENTRUN_MAX_RUNS) : defaultMaxRuns(hostMemory()));
58
+ if (!Number.isSafeInteger(value) || value < 1)
59
+ throw new Error(`max runs is a positive integer (--max-runs, AGENTRUN_MAX_RUNS), not ${given ?? env.AGENTRUN_MAX_RUNS}`);
60
+ return value;
61
+ }
62
+ /** Whether the store in `data` opens for a read, and its disk has `minFreeBytes` free; a disk it cannot measure fails.
63
+ * Says no path and no number. `fsStat` is node's statfs unless a test gives another. */
64
+ export async function healthOf(data, minFreeBytes, fsStat = statfs) {
65
+ let store = "ok";
66
+ try {
67
+ await whenFree(() => {
68
+ const reader = openStoreReader(data, { busyTimeoutMs: 0 });
69
+ try {
70
+ reader.listAgents();
71
+ }
72
+ finally {
73
+ reader.close();
74
+ }
75
+ }, REQUEST_BUSY_MS);
76
+ }
77
+ catch {
78
+ store = "does_not_open";
79
+ }
80
+ const free = await fsStat(data).then((fs) => fs.bavail * fs.bsize, () => undefined);
81
+ const disk = free === undefined ? "cannot_check" : free >= minFreeBytes ? "ok" : "below_floor";
82
+ return { status: store === "ok" && disk === "ok" ? "ok" : "failing", checks: { store, disk } };
83
+ }
84
+ /** Whether `--open` opens a browser here: not in CI, and on Linux or FreeBSD only with a display. */
85
+ export const canOpen = (env, platform = process.platform) => !env.CI && (!["linux", "freebsd"].includes(platform) || Boolean(env.DISPLAY || env.WAYLAND_DISPLAY));
@@ -0,0 +1,27 @@
1
+ import type { Models } from "@earendil-works/pi-ai";
2
+ import { type Search } from "./web-search.js";
3
+ export declare const HOSTED_MAX_USES = 5;
4
+ /** One search's results billed as input: about 25,000 tokens, a working estimate. */
5
+ export declare const SEARCH_INPUT_TOKENS = 25000;
6
+ /** What the request may read into its input beyond its context, for the run's cap: each of its searches' results. */
7
+ export declare const HOSTED_SEARCH_ALLOWANCE_TOKENS: number;
8
+ export declare const ANTHROPIC_SEARCH_TOOL: Readonly<{
9
+ type: "web_search_20250305";
10
+ name: "web_search";
11
+ max_uses: 5;
12
+ }>;
13
+ export declare const OPENAI_SEARCH_TOOL: Readonly<{
14
+ type: "web_search";
15
+ }>;
16
+ /** OpenAI's hosted search has no per-tool limit: the Responses API's `max_tool_calls` caps the built-in tool calls of the
17
+ * request at the HOSTED_MAX_USES its fee is reserved for, as Anthropic's tool's `max_uses` does. */
18
+ export declare const OPENAI_SEARCH_LIMIT: Readonly<{
19
+ max_tool_calls: 5;
20
+ }>;
21
+ /** $10 per 1,000 searches (Anthropic) or calls (OpenAI). */
22
+ export declare const SEARCH_USD = 0.01;
23
+ /** The run's models, marked and capped, handed over by the run's app before its tools are bound. */
24
+ export declare function searchOn(models: Models): void;
25
+ /** `query` searched by `ref`'s provider (`provider/model-id`, the model the server resolved web_search on) through the
26
+ * run's models, at most `n` results: a Search. `models`: the run's (searchOn). */
27
+ export declare function hostedSearch(query: string, n: number, ref: string | undefined, signal?: AbortSignal, models?: Models | undefined): Promise<Search>;
@@ -0,0 +1,133 @@
1
+ import { clip, TITLE_CAP } from "./fetch-page.js";
2
+ import { sideRequests } from "./cap.js";
3
+ import { ANSWER_MAX, snippetOf } from "./web-search.js";
4
+ export const HOSTED_MAX_USES = 5;
5
+ /** One search's results billed as input: about 25,000 tokens, a working estimate. */
6
+ export const SEARCH_INPUT_TOKENS = 25_000;
7
+ /** What the request may read into its input beyond its context, for the run's cap: each of its searches' results. */
8
+ export const HOSTED_SEARCH_ALLOWANCE_TOKENS = HOSTED_MAX_USES * SEARCH_INPUT_TOKENS;
9
+ export const ANTHROPIC_SEARCH_TOOL = Object.freeze({ type: "web_search_20250305", name: "web_search", max_uses: HOSTED_MAX_USES });
10
+ export const OPENAI_SEARCH_TOOL = Object.freeze({ type: "web_search" });
11
+ /** OpenAI's hosted search has no per-tool limit: the Responses API's `max_tool_calls` caps the built-in tool calls of the
12
+ * request at the HOSTED_MAX_USES its fee is reserved for, as Anthropic's tool's `max_uses` does. */
13
+ export const OPENAI_SEARCH_LIMIT = Object.freeze({ max_tool_calls: HOSTED_MAX_USES });
14
+ /** $10 per 1,000 searches (Anthropic) or calls (OpenAI). */
15
+ export const SEARCH_USD = 0.01;
16
+ /** OpenAI's models that bill each call's search content as a fixed block of 8,000 input tokens apart from the response's
17
+ * usage: the block is added to the fee at the model's input price. */
18
+ const BLOCK_BILLED = /^gpt-(?:4o|4\.1)-mini(?:-|$)/;
19
+ const ANSWER_TOKENS = 2_048;
20
+ /** As Exa's and Parallel's searches stop. */
21
+ const TIMEOUT_MS = 60_000;
22
+ let runModels;
23
+ /** The run's models, marked and capped, handed over by the run's app before its tools are bound. */
24
+ export function searchOn(models) {
25
+ runModels = models;
26
+ }
27
+ const list = (value) => (Array.isArray(value) ? value.filter((item) => typeof item === "object" && item !== null) : []);
28
+ const text = (value) => (typeof value === "string" ? value : undefined);
29
+ /** What a provider's events say of the search: its results by URL, first seen first, and how many searches it ran. */
30
+ function reader(anthropic) {
31
+ const hits = new Map();
32
+ const add = (url, found) => {
33
+ if (typeof url !== "string" || !URL.canParse(url))
34
+ return;
35
+ const hit = hits.get(url) ?? {};
36
+ hits.set(url, { ...found, ...Object.fromEntries(Object.entries(hit).filter(([, value]) => value)) });
37
+ };
38
+ let reported;
39
+ let calls = 0;
40
+ let failed;
41
+ const anthropicEvent = (event) => {
42
+ const block = event.content_block;
43
+ if (event.type === "content_block_start" && block?.type === "server_tool_use" && block.name === "web_search")
44
+ calls += 1;
45
+ if (event.type === "content_block_start" && block?.type === "web_search_tool_result") {
46
+ if (!Array.isArray(block.content))
47
+ failed = text(block.content?.error_code) ?? "the search failed";
48
+ for (const result of list(block.content))
49
+ if (result.type === "web_search_result")
50
+ add(result.url, { title: text(result.title), published: text(result.page_age) });
51
+ }
52
+ const citation = event.delta?.type === "citations_delta" ? event.delta.citation : undefined;
53
+ if (citation)
54
+ add(citation.url, { title: text(citation.title), snippet: text(citation.cited_text) });
55
+ const used = event.usage?.server_tool_use?.web_search_requests;
56
+ if (event.type === "message_delta" && typeof used === "number")
57
+ reported = used;
58
+ };
59
+ const openaiEvent = (event) => {
60
+ const item = event.item;
61
+ if (event.type === "response.output_item.done" && item?.type === "web_search_call") {
62
+ calls += 1;
63
+ for (const source of list(item.action?.sources))
64
+ add(source.url, {});
65
+ }
66
+ if (event.type === "response.output_item.done" && item?.type === "message") {
67
+ for (const part of list(item.content)) {
68
+ const said = text(part.text) ?? "";
69
+ for (const note of list(part.annotations)) {
70
+ if (note.type !== "url_citation")
71
+ continue;
72
+ // The sentence the citation follows: OpenAI marks the cited source after the claim it supports.
73
+ const before = said.slice(0, typeof note.start_index === "number" ? note.start_index : 0).trimEnd();
74
+ add(note.url, { title: text(note.title), snippet: before.slice(Math.max(before.lastIndexOf(". "), before.lastIndexOf("\n")) + 1).trim() });
75
+ }
76
+ }
77
+ }
78
+ const used = (event.response?.tool_usage?.web_search)?.num_requests;
79
+ if ((event.type === "response.completed" || event.type === "response.incomplete") && typeof used === "number")
80
+ reported = used;
81
+ };
82
+ return {
83
+ event: (event) => (anthropic ? anthropicEvent : openaiEvent)((event ?? {})),
84
+ /** The searches the provider reported, else the search calls its answer held. */
85
+ searches: () => reported ?? calls,
86
+ failed: () => (hits.size ? undefined : failed),
87
+ hits: () => [...hits].map(([url, hit]) => ({ url, title: clip(hit.title ?? "", TITLE_CAP), snippet: snippetOf(hit.snippet ?? ""), ...(hit.published ? { published: hit.published } : {}) })),
88
+ };
89
+ }
90
+ /** `query` searched by `ref`'s provider (`provider/model-id`, the model the server resolved web_search on) through the
91
+ * run's models, at most `n` results: a Search. `models`: the run's (searchOn). */
92
+ export async function hostedSearch(query, n, ref, signal, models = runModels) {
93
+ const slash = ref?.indexOf("/") ?? -1;
94
+ const provider = ref && slash > 0 ? ref.slice(0, slash) : undefined;
95
+ const id = ref && slash > 0 ? ref.slice(slash + 1) : undefined;
96
+ // The name as written, else Anthropic's own id for it (dots as dashes, as claude-agent prepares a dotted name:
97
+ // adapters.ts claudeModelId), the one the run's models hold.
98
+ const model = models && provider && id ? (models.getModel(provider, id) ?? (provider === "anthropic" ? models.getModel(provider, id.replaceAll(".", "-")) : undefined)) : undefined;
99
+ if (!models || !model)
100
+ return { error: `web_search has no model to search on in this run${ref ? ` (${ref})` : ""}` };
101
+ const anthropic = model.api === "anthropic-messages";
102
+ if (!anthropic && model.api !== "openai-responses")
103
+ return { error: `web_search: ${ref} has no hosted web search here` };
104
+ const read = reader(anthropic);
105
+ const context = { messages: [{ role: "user", content: [{ type: "text", text: `Search the web for: ${query}\n\nAnswer briefly from what the search finds, and name each source by its URL.` }], timestamp: Date.now() }] };
106
+ const block = BLOCK_BILLED.test(model.id) ? (8_000 * (model.cost?.input ?? 0)) / 1e6 : 0;
107
+ sideRequests.set(context, { label: "web_search", extraInputTokens: HOSTED_SEARCH_ALLOWANCE_TOKENS, maxFeeUsd: HOSTED_MAX_USES * (SEARCH_USD + block), feeUsd: () => read.searches() * (SEARCH_USD + block) });
108
+ let answer;
109
+ try {
110
+ answer = await models.completeSimple(model, context, {
111
+ maxTokens: ANSWER_TOKENS,
112
+ maxRetries: 0,
113
+ timeoutMs: TIMEOUT_MS,
114
+ ...(signal ? { signal } : {}),
115
+ // The hosted tool, exactly, and no other: the context offers none of its own.
116
+ onPayload: (payload) => {
117
+ const body = payload;
118
+ return anthropic ? { ...body, tools: [ANTHROPIC_SEARCH_TOOL] } : { ...body, ...OPENAI_SEARCH_LIMIT, tools: [OPENAI_SEARCH_TOOL], include: [...(Array.isArray(body.include) ? body.include : []), "web_search_call.action.sources"] };
119
+ },
120
+ onProviderStreamEvent: (event) => read.event(event),
121
+ });
122
+ }
123
+ catch (error) {
124
+ return { error: `the provider's search failed: ${String(error?.message ?? error).slice(0, 300)}` };
125
+ }
126
+ if (answer.stopReason === "error" || answer.stopReason === "aborted")
127
+ return { error: answer.stopReason === "aborted" ? "the search was stopped" : `the provider's search failed: ${(answer.errorMessage ?? "no detail").slice(0, 300)}` };
128
+ const failed = read.failed();
129
+ if (failed)
130
+ return { error: `the provider's search failed: ${failed}` };
131
+ const said = answer.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("").trim();
132
+ return { provider: "native", query, results: read.hits().slice(0, n), ...(said ? { text: clip(said, ANSWER_MAX) } : {}) };
133
+ }
@@ -0,0 +1,104 @@
1
+ export declare const SOURCES: readonly ["claude-code", "codex", "pi"];
2
+ export type Source = (typeof SOURCES)[number];
3
+ /** The harness of serve that runs what each source ran. */
4
+ export declare const HARNESS_OF: Record<Source, string>;
5
+ export type ToolCall = {
6
+ type: "toolCall";
7
+ id: string;
8
+ name: string;
9
+ arguments: Record<string, unknown>;
10
+ };
11
+ /** A request's tokens as pi counts them: `input` is the input neither read from nor written to the cache;
12
+ * `cacheWrite1h`, the part of `cacheWrite` kept for an hour, which Anthropic prices higher. */
13
+ export type Usage = {
14
+ input: number;
15
+ output: number;
16
+ cacheRead: number;
17
+ cacheWrite: number;
18
+ cacheWrite1h?: number;
19
+ };
20
+ /** An assistant turn is one model request: `model` the one it ran on ("provider/model"), `effort` the effort or
21
+ * thinking level it ran at, `usage` its tokens, each absent when the source does not say; `error`, why it failed. A
22
+ * note is a line the harness itself wrote in the conversation: no request, nor the person's. */
23
+ export type Turn = ({
24
+ role: "user";
25
+ text: string;
26
+ at: number;
27
+ } | {
28
+ role: "note";
29
+ author: string;
30
+ text: string;
31
+ at: number;
32
+ } | {
33
+ role: "assistant";
34
+ text: string;
35
+ calls: ToolCall[];
36
+ at: number;
37
+ costUsd?: number;
38
+ key?: string;
39
+ model?: string;
40
+ effort?: string;
41
+ usage?: Usage;
42
+ error?: string;
43
+ } | {
44
+ role: "toolResult";
45
+ callId: string;
46
+ name: string;
47
+ text: string;
48
+ isError: boolean;
49
+ at: number;
50
+ }) & {
51
+ /** The source's own ids of the records the turn was read from (Claude Code's uuids): a later import counts them once. */
52
+ uuids?: string[];
53
+ };
54
+ export type Ended = "completed" | "failed" | "stopped";
55
+ /** The longest gap between two records counted as time at work, as WakaTime counts it: a longer gap is a session left
56
+ * open and counts nothing. Claude Code's Bash tool runs a call for up to 10 minutes with nothing written. */
57
+ export declare const ACTIVE_GAP_MS: number;
58
+ export type Session = {
59
+ source: Source;
60
+ /** The source's own id for the session. */
61
+ id: string;
62
+ file: string;
63
+ cwd?: string;
64
+ /** "provider/model", from the session's latest model. */
65
+ model?: string;
66
+ startedAt?: string;
67
+ endedAt?: string;
68
+ state: Ended;
69
+ /** The whole session's cost, when the source records it; absent is unknown. */
70
+ costUsd?: number;
71
+ firstPrompt?: string;
72
+ /** A subagent's or another session's child: not imported as a run; its usage is its parent's. */
73
+ child: boolean;
74
+ /** A child's parent session, when its file names it (Codex's parent thread). */
75
+ parent?: string;
76
+ /** Read only when asked for: a dry run reads none. */
77
+ turns: Turn[];
78
+ users: number;
79
+ /** Time at work: the gaps between its records of at most ACTIVE_GAP_MS each. */
80
+ activeMs: number;
81
+ /** Records it holds that were read already (in an earlier file of the import, or earlier in this one): copies. */
82
+ copies: number;
83
+ /** The effort or thinking level most of its requests ran at, as the source names it; with its turns only. */
84
+ effort?: string;
85
+ };
86
+ /** The session files of `source` under `home`, never through a link. */
87
+ export declare function sessionFiles(home: string, source: Source): Promise<string[]>;
88
+ /** Claude Code's subagents' session files under `home`, in <session id>/subagents/ (a workflow's a folder deeper), each
89
+ * with the session file it ran under (`of`): the one beside the folder it sits in. A session moved to another project
90
+ * folder keeps its id there, with copies of its subagents' files: each folder's are its own file's. Never through a
91
+ * link. */
92
+ export declare function childFiles(home: string): Promise<{
93
+ file: string;
94
+ of: string;
95
+ }[]>;
96
+ /** One session file of `source`, read whole; `turns: false` keeps only what a listing shows. `seen`: the records and
97
+ * responses an import has read already, across its files; a record in it (a copy a resumed session's file carries) adds
98
+ * nothing, and this file's are added to it. */
99
+ export declare function readSession(file: string, source: Source, { turns: keep, seen }?: {
100
+ turns?: boolean;
101
+ seen?: Set<string>;
102
+ }): Promise<Session>;
103
+ /** The effort most of `turns`' requests ran at, as the model of most requests is a run's model: the first seen of a tie. */
104
+ export declare function mostEffortOf(turns: readonly Turn[]): string | undefined;