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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +560 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +1724 -0
  5. package/dist/adapters.d.ts +205 -0
  6. package/dist/adapters.js +459 -0
  7. package/dist/agents.d.ts +124 -0
  8. package/dist/agents.js +302 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +324 -0
  11. package/dist/bound-files.d.ts +4 -0
  12. package/dist/bound-files.js +164 -0
  13. package/dist/box/record.d.ts +6 -0
  14. package/dist/box/record.js +41 -0
  15. package/dist/box/sweep.d.ts +53 -0
  16. package/dist/box/sweep.js +193 -0
  17. package/dist/box-image.d.ts +98 -0
  18. package/dist/box-image.js +283 -0
  19. package/dist/box-relay.d.ts +42 -0
  20. package/dist/box-relay.js +222 -0
  21. package/dist/boxes.d.ts +54 -0
  22. package/dist/boxes.js +182 -0
  23. package/dist/cap.d.ts +224 -0
  24. package/dist/cap.js +721 -0
  25. package/dist/catalog.d.ts +20 -0
  26. package/dist/catalog.js +53 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +167 -0
  29. package/dist/coding-tools.d.ts +31 -0
  30. package/dist/coding-tools.js +81 -0
  31. package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
  32. package/dist/console/assets/index-BN7oVcO4.js +445 -0
  33. package/dist/console/assets/index-By-jkqki.css +1 -0
  34. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  35. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  36. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  37. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  38. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  39. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  40. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  41. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  42. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  53. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  54. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  57. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  58. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  59. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  60. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  61. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  62. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  63. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  64. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  65. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  66. package/dist/console/index.html +15 -0
  67. package/dist/daytona-api.d.ts +21 -0
  68. package/dist/daytona-api.js +101 -0
  69. package/dist/decision-rows.d.ts +11 -0
  70. package/dist/decision-rows.js +116 -0
  71. package/dist/decisions.d.ts +94 -0
  72. package/dist/decisions.js +184 -0
  73. package/dist/effort-guidance.d.ts +5 -0
  74. package/dist/effort-guidance.js +14 -0
  75. package/dist/environment.d.ts +5 -0
  76. package/dist/environment.js +11 -0
  77. package/dist/errors.d.ts +72 -0
  78. package/dist/errors.js +66 -0
  79. package/dist/exa-keyless.d.ts +35 -0
  80. package/dist/exa-keyless.js +202 -0
  81. package/dist/fetch-page.d.ts +114 -0
  82. package/dist/fetch-page.js +182 -0
  83. package/dist/files.d.ts +60 -0
  84. package/dist/files.js +153 -0
  85. package/dist/grade.d.ts +96 -0
  86. package/dist/grade.js +348 -0
  87. package/dist/graph-view.d.ts +100 -0
  88. package/dist/graph-view.js +212 -0
  89. package/dist/harness-app.d.ts +38 -0
  90. package/dist/harness-app.js +626 -0
  91. package/dist/harness.d.ts +53 -0
  92. package/dist/harness.js +74 -0
  93. package/dist/home-path.d.ts +27 -0
  94. package/dist/home-path.js +78 -0
  95. package/dist/host-tools.d.ts +20 -0
  96. package/dist/host-tools.js +140 -0
  97. package/dist/host.d.ts +39 -0
  98. package/dist/host.js +81 -0
  99. package/dist/hosted-search.d.ts +27 -0
  100. package/dist/hosted-search.js +129 -0
  101. package/dist/import-sources.d.ts +104 -0
  102. package/dist/import-sources.js +629 -0
  103. package/dist/import-summary.d.ts +25 -0
  104. package/dist/import-summary.js +75 -0
  105. package/dist/import-worker.d.ts +26 -0
  106. package/dist/import-worker.js +41 -0
  107. package/dist/import.d.ts +145 -0
  108. package/dist/import.js +1221 -0
  109. package/dist/index.d.ts +7 -0
  110. package/dist/index.js +6 -0
  111. package/dist/key-check.d.ts +36 -0
  112. package/dist/key-check.js +108 -0
  113. package/dist/key-refusal.d.ts +51 -0
  114. package/dist/key-refusal.js +187 -0
  115. package/dist/learn/check.d.ts +99 -0
  116. package/dist/learn/check.js +259 -0
  117. package/dist/learn/grade.d.ts +79 -0
  118. package/dist/learn/grade.js +433 -0
  119. package/dist/learn/index.d.ts +7 -0
  120. package/dist/learn/index.js +11 -0
  121. package/dist/learn/invisible.d.ts +5 -0
  122. package/dist/learn/invisible.js +42 -0
  123. package/dist/learn/notes.d.ts +59 -0
  124. package/dist/learn/notes.js +146 -0
  125. package/dist/learn/reflect.d.ts +49 -0
  126. package/dist/learn/reflect.js +167 -0
  127. package/dist/learn/secrets.d.ts +18 -0
  128. package/dist/learn/secrets.js +111 -0
  129. package/dist/learn/skills.d.ts +84 -0
  130. package/dist/learn/skills.js +198 -0
  131. package/dist/learning-routes.d.ts +196 -0
  132. package/dist/learning-routes.js +609 -0
  133. package/dist/learning-run.d.ts +304 -0
  134. package/dist/learning-run.js +797 -0
  135. package/dist/learning-words.d.ts +73 -0
  136. package/dist/learning-words.js +171 -0
  137. package/dist/learning.d.ts +377 -0
  138. package/dist/learning.js +801 -0
  139. package/dist/llm.d.ts +40 -0
  140. package/dist/llm.js +37 -0
  141. package/dist/llms.txt +37 -0
  142. package/dist/mcp-servers.d.ts +115 -0
  143. package/dist/mcp-servers.js +445 -0
  144. package/dist/mcp.d.ts +51 -0
  145. package/dist/mcp.js +392 -0
  146. package/dist/model.d.ts +184 -0
  147. package/dist/model.js +484 -0
  148. package/dist/monid.d.ts +74 -0
  149. package/dist/monid.js +277 -0
  150. package/dist/openapi/agentrun-v2.openapi.json +4805 -0
  151. package/dist/openapi.d.ts +10 -0
  152. package/dist/openapi.js +1417 -0
  153. package/dist/owner.d.ts +55 -0
  154. package/dist/owner.js +222 -0
  155. package/dist/packs.d.ts +71 -0
  156. package/dist/packs.js +180 -0
  157. package/dist/page.d.ts +32 -0
  158. package/dist/page.js +133 -0
  159. package/dist/paid-calls.d.ts +46 -0
  160. package/dist/paid-calls.js +110 -0
  161. package/dist/pause.d.ts +68 -0
  162. package/dist/pause.js +97 -0
  163. package/dist/pdf-pages.d.ts +44 -0
  164. package/dist/pdf-pages.js +147 -0
  165. package/dist/place.d.ts +46 -0
  166. package/dist/place.js +105 -0
  167. package/dist/print.d.ts +20 -0
  168. package/dist/print.js +29 -0
  169. package/dist/propose.d.ts +38 -0
  170. package/dist/propose.js +82 -0
  171. package/dist/quiet-sqlite-warning.d.ts +1 -0
  172. package/dist/quiet-sqlite-warning.js +14 -0
  173. package/dist/request-start.d.ts +14 -0
  174. package/dist/request-start.js +226 -0
  175. package/dist/result.d.ts +3 -0
  176. package/dist/result.js +5 -0
  177. package/dist/rows.d.ts +46 -0
  178. package/dist/rows.js +121 -0
  179. package/dist/run-box.d.ts +134 -0
  180. package/dist/run-box.js +440 -0
  181. package/dist/run-manifest.d.ts +27 -0
  182. package/dist/run-manifest.js +60 -0
  183. package/dist/runnable.d.ts +80 -0
  184. package/dist/runnable.js +162 -0
  185. package/dist/runs.d.ts +840 -0
  186. package/dist/runs.js +2279 -0
  187. package/dist/secret-cut.d.ts +27 -0
  188. package/dist/secret-cut.js +109 -0
  189. package/dist/secrets.d.ts +50 -0
  190. package/dist/secrets.js +140 -0
  191. package/dist/server-lock.d.ts +44 -0
  192. package/dist/server-lock.js +140 -0
  193. package/dist/server.d.ts +626 -0
  194. package/dist/server.js +1756 -0
  195. package/dist/sessions.d.ts +4 -0
  196. package/dist/sessions.js +105 -0
  197. package/dist/skills.d.ts +31 -0
  198. package/dist/skills.js +68 -0
  199. package/dist/stats.d.ts +101 -0
  200. package/dist/stats.js +82 -0
  201. package/dist/tool-keys.d.ts +151 -0
  202. package/dist/tool-keys.js +273 -0
  203. package/dist/tool-plane.d.ts +143 -0
  204. package/dist/tool-plane.js +242 -0
  205. package/dist/tools.d.ts +147 -0
  206. package/dist/tools.js +253 -0
  207. package/dist/turn-end.d.ts +23 -0
  208. package/dist/turn-end.js +14 -0
  209. package/dist/turns.d.ts +34 -0
  210. package/dist/turns.js +202 -0
  211. package/dist/uploads.d.ts +104 -0
  212. package/dist/uploads.js +474 -0
  213. package/dist/usage.d.ts +29 -0
  214. package/dist/usage.js +58 -0
  215. package/dist/validate.d.ts +55 -0
  216. package/dist/validate.js +175 -0
  217. package/dist/web-fetch.d.ts +64 -0
  218. package/dist/web-fetch.js +262 -0
  219. package/dist/web-search.d.ts +54 -0
  220. package/dist/web-search.js +136 -0
  221. package/dist/webhooks.d.ts +182 -0
  222. package/dist/webhooks.js +487 -0
  223. package/dist/workspace-paths.d.ts +33 -0
  224. package/dist/workspace-paths.js +104 -0
  225. package/dist/workspace.d.ts +88 -0
  226. package/dist/workspace.js +369 -0
  227. package/launcher/agentrun-serve +109 -0
  228. package/package.json +96 -1
  229. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,226 @@
1
+ // A pi run's model request is marked on the run's root before it leaves (REQUEST_STARTED), and again if its stream
2
+ // ends aborted (REQUEST_ENDED). pi writes a request's entry when it answers or fails, and when it is aborted only if
3
+ // content had streamed, so one cut before that (a stop, a crash) would leave nothing to count; with the marks, the
4
+ // timeline counts it and reads the run's cost unknown, while a request still in flight reads as the sum so far.
5
+ //
6
+ // pi's compaction summary is a paid request too (`completeSimple`), and pi books its usage in its own usage document,
7
+ // never as an entry the run's timeline sums. So it is marked the same way (`request: "compaction"`), and its answer's
8
+ // cost is written as REQUEST_COST: the run's total, and /usage with it, include it, and one cut before its answer reads
9
+ // unknown. Both are wrapped here: `streamSimple` for the generation's requests, `completeSimple` for the summary. A
10
+ // tool's own request on the run's models (web_search's, hosted-search.ts) is a side request the same way, under its own
11
+ // label (sideRequests), and its cost is its tokens' plus the fee its tool names.
12
+ //
13
+ // Under a cap (cap.ts), each request comes with the worst case the cap held for it, and its start mark carries that
14
+ // figure (`heldUsd`), as does the end mark of a summary that failed: the cap counts a request a crash cut at it, in a
15
+ // later process too. The end mark of one stopped before its end carries what the cap counts it at given what it streamed
16
+ // (cap.ts stoppedFigure: what it streamed and an allowance, never more than its worst case). The timeline does not read it, so the run's shown cost
17
+ // is unknown as before. A request the cap refused gets a start mark of its own (`capRefused`), written before pi writes
18
+ // its error entry, so that entry answers its own mark and never stands for an earlier request a stop or a crash cut.
19
+ import { existsSync } from "node:fs";
20
+ import { join } from "node:path";
21
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
22
+ import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
23
+ import { REQUEST_COST, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED } from "@parcha/pi-durable-agent/timeline";
24
+ import { CAP_REFUSED_FIELD, CLAMP, HELD_FIELD, HELD_USD, MARK_NOT_WRITTEN, markResponseBegan, sideRequests, STOPPED_USD } from "./cap.js";
25
+ import { RUN_CANCELLED } from "./files.js";
26
+ /** Whether the run in `root` (its directory) was cancelled: the mark serve's cancel writes there first. */
27
+ export const cancelledIn = (root) => () => existsSync(join(root, RUN_CANCELLED));
28
+ /** How long a request's result waits for its end mark to be written, so it lands before pi's entry for the request. */
29
+ export const END_MARK_WAIT_MS = 1_000;
30
+ /** `models` with each generation request marked before it leaves, once `open` hands over the run (its Harness). Once
31
+ * `cancelled` says the run was cancelled, no request is sent: each is refused here, before it is marked, or after its
32
+ * mark when the cancel came while the mark waited, and then its start is withdrawn (an end mark, `unsent`). */
33
+ export async function markRequests(models, cancelled = () => false) {
34
+ const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
35
+ let open;
36
+ // A request a resumed turn sends before the app's open waits for it: the mark needs the run's store.
37
+ const opened = new Promise((resolve) => (open = resolve));
38
+ const mark = async (kind, data = {}) => {
39
+ const run = await opened;
40
+ await run.harness.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind, data })), BACKGROUND_CONTEXT);
41
+ };
42
+ const failed = (model, why) => ({
43
+ role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(),
44
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
45
+ errorMessage: why,
46
+ });
47
+ const reason = (error) => String(error?.message ?? error).slice(0, 200);
48
+ /** Until `work` settles, or `ms` pass. */
49
+ const within = (work, ms) => new Promise((resolve) => {
50
+ const timer = setTimeout(resolve, ms);
51
+ void work.finally(() => (clearTimeout(timer), resolve()));
52
+ });
53
+ /** What the run's cap held for a request (its options' HELD_USD), as an end mark's field; none without a cap. */
54
+ const heldOf = (options) => {
55
+ const held = options?.[HELD_USD];
56
+ return typeof held === "number" && Number.isFinite(held) ? { [HELD_FIELD]: held } : {};
57
+ };
58
+ /** What the run's cap counts a request stopped before its end at, given the answer it had streamed (its options'
59
+ * STOPPED_USD), as an end mark's field; its worst case when the cap gave no such figure; none without a cap. */
60
+ const stoppedOf = (options, message) => {
61
+ const stopped = options?.[STOPPED_USD];
62
+ const figure = typeof stopped === "function" ? stopped(message) : undefined;
63
+ return typeof figure === "number" && Number.isFinite(figure) ? { [HELD_FIELD]: figure } : heldOf(options);
64
+ };
65
+ /** A start mark's figures: its worst case, and what the cap limited its output to when it did (CLAMP), so a reply cut
66
+ * short there says so on the run's timeline. */
67
+ const startOf = (options) => {
68
+ const clamp = options?.[CLAMP];
69
+ const kept = clamp && typeof clamp.tokens === "number" && typeof clamp.leftUsd === "number" && typeof clamp.capUsd === "number" ? { clamp: { tokens: clamp.tokens, leftUsd: clamp.leftUsd, capUsd: clamp.capUsd } } : {};
70
+ return { ...heldOf(options), ...kept };
71
+ };
72
+ /** A cancelled run's request, never sent. It waits for the cancel to reach the run (the request's abort), and then ends
73
+ * as aborted, as a request the cancel cut does: the turn, or a workflow's node, stops, never failing on the refusal.
74
+ * serve's cancel aborts a live run's turn and then stops its process, so the wait is short. Its bound, a minute, is a
75
+ * backstop for a process the cancel never reaches (an orphan of a server that died in between): it then ends as an
76
+ * error, and `markRefusal` lets the timeline skip pi's entry for it. */
77
+ const refuse = async (model, what, signal, markRefusal) => {
78
+ if (signal && !signal.aborted) {
79
+ await new Promise((resolve) => {
80
+ const timer = setTimeout(resolve, 60_000);
81
+ signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
82
+ });
83
+ }
84
+ if (signal?.aborted)
85
+ return { ...failed(model, ""), stopReason: "aborted", errorMessage: undefined };
86
+ if (markRefusal)
87
+ await mark(REQUEST_REFUSED).catch(() => undefined);
88
+ return failed(model, `the run was cancelled: the ${what} was not sent`);
89
+ };
90
+ const streamSimple = (model, context, options) => {
91
+ const outer = createAssistantMessageEventStream();
92
+ const refused = async () => {
93
+ const message = await refuse(model, "model request", options?.signal, true);
94
+ outer.push({ type: "error", reason: message.stopReason === "aborted" ? "aborted" : "error", error: message });
95
+ outer.end(message);
96
+ };
97
+ void (async () => {
98
+ if (cancelled())
99
+ return refused();
100
+ try {
101
+ await mark(REQUEST_STARTED, startOf(options));
102
+ }
103
+ catch (error) {
104
+ const message = failed(model, `${MARK_NOT_WRITTEN} (${reason(error)})`);
105
+ outer.push({ type: "error", reason: "error", error: message });
106
+ outer.end(message);
107
+ return;
108
+ }
109
+ if (cancelled()) {
110
+ await mark(REQUEST_ENDED, { unsent: true }).catch(() => undefined);
111
+ return refused();
112
+ }
113
+ let result;
114
+ // Whether the provider's response had begun (an event came in) by the time the request ended.
115
+ let began = false;
116
+ // The stream's error event, passed on once the request's end is marked (below): the outer stream's result, which
117
+ // pi writes as the entry and the cap counts, settles on that event.
118
+ let failure;
119
+ try {
120
+ const inner = models.streamSimple(model, context, options);
121
+ for await (const event of inner) {
122
+ if (event.type === "error") {
123
+ failure = event;
124
+ continue;
125
+ }
126
+ began = true;
127
+ outer.push(event);
128
+ }
129
+ result = await inner.result();
130
+ }
131
+ catch (error) {
132
+ // A stream that throws instead of ending on an error event still ends the request, as an error, never a hang.
133
+ result = failed(model, `the model request failed: ${reason(error)}`);
134
+ failure = { type: "error", reason: "error", error: result };
135
+ }
136
+ // An answer or a failure gets pi's own entry; an abort may get none, so its end is marked, with the provider's id
137
+ // for the request when it named one before the cut (the request joins its record by it). A store that cannot
138
+ // take the mark leaves the request unended, which the timeline also reads as cut, at an unknown cost: the
139
+ // conservative reading, so the failure is swallowed here.
140
+ let ending;
141
+ if (result.stopReason === "aborted") {
142
+ const responseId = result.responseId;
143
+ ending = mark(REQUEST_ENDED, { ...(typeof responseId === "string" ? { responseId } : {}), ...stoppedOf(options, result) });
144
+ }
145
+ else if (result.stopReason === "error" && began) {
146
+ // An error after its response began (an overload part way, a reset): its usage is what had streamed, not what the
147
+ // provider can have billed. Its message is recorded (markResponseBegan), which the cap counts at its hold in this
148
+ // process, and its end is marked with the hold (`error`), which the spend read back counts. One before any event
149
+ // (a 429, a 5xx) is refused unbilled, and counts at its own usage.
150
+ markResponseBegan(result);
151
+ if (failure?.type === "error")
152
+ markResponseBegan(failure.error);
153
+ ending = mark(REQUEST_ENDED, { error: true, ...heldOf(options) });
154
+ }
155
+ // The end mark goes in before pi has the result, so the store holds it before pi's entry; a store that refuses it, or
156
+ // has not answered in END_MARK_WAIT_MS, does not hold the turn: the result goes on, and the mark lands when it can.
157
+ if (ending)
158
+ await within(ending.catch(() => undefined), END_MARK_WAIT_MS);
159
+ if (failure)
160
+ outer.push(failure);
161
+ outer.end(result);
162
+ })();
163
+ return outer;
164
+ };
165
+ const completeSimple = async (model, context, options) => {
166
+ const side = sideRequests.get(context);
167
+ const COMPACTION = { request: side?.label ?? "compaction" };
168
+ const what = side ? `${side.label} request` : "summary request";
169
+ // A cancelled run sends no summary either; pi writes no entry for a failed summary, so nothing needs marking.
170
+ if (cancelled())
171
+ return refuse(model, what, options?.signal, false);
172
+ try {
173
+ await mark(REQUEST_STARTED, { ...COMPACTION, ...heldOf(options) });
174
+ }
175
+ catch (error) {
176
+ return failed(model, `${MARK_NOT_WRITTEN} (${reason(error)})`);
177
+ }
178
+ if (cancelled()) {
179
+ await mark(REQUEST_ENDED, { ...COMPACTION, unsent: true }).catch(() => undefined);
180
+ return refuse(model, what, options?.signal, false);
181
+ }
182
+ let result;
183
+ try {
184
+ result = await models.completeSimple(model, context, options);
185
+ }
186
+ catch (error) {
187
+ await mark(REQUEST_ENDED, { ...COMPACTION, ...heldOf(options) }).catch(() => undefined);
188
+ throw error;
189
+ }
190
+ // Its cost closes it; an abort, as for a generation's request, closes it unpriced. A store that cannot take either
191
+ // leaves it open, which reads as cut, at an unknown cost.
192
+ if (result.stopReason === "aborted")
193
+ await mark(REQUEST_ENDED, { ...COMPACTION, ...stoppedOf(options, result) }).catch(() => undefined);
194
+ else {
195
+ const total = result.usage?.cost?.total;
196
+ // A side request's fee is its cost too, on the answer as well: the cap counts the answer's total (cap.ts).
197
+ const usd = typeof total === "number" ? total + (side?.feeUsd() ?? 0) : null;
198
+ if (side && usd !== null)
199
+ result.usage.cost.total = usd;
200
+ // Its tokens, in pi's shape, when pi counted any: zeros are no count.
201
+ const u = result.usage;
202
+ const usage = u && u.input + u.output + u.cacheRead + u.cacheWrite > 0 ? { input: u.input, output: u.output, cacheRead: u.cacheRead, cacheWrite: u.cacheWrite } : undefined;
203
+ // One that ended on an error after its response began (it holds content or a token count; a summary has no events
204
+ // to read) counts at its hold: it says so, and carries it. One before any of that counts at its own usage.
205
+ const began = result.stopReason === "error" && (usage !== undefined || result.content.length > 0);
206
+ if (began)
207
+ markResponseBegan(result);
208
+ const failure = began ? { failed: true, ...heldOf(options) } : {};
209
+ await mark(REQUEST_COST, usage ? { ...COMPACTION, usd, usage: usage, ...failure } : { ...COMPACTION, usd, ...failure }).catch(() => undefined);
210
+ }
211
+ return result;
212
+ };
213
+ const proxy = new Proxy(models, {
214
+ get: (target, key) => {
215
+ if (key === "streamSimple")
216
+ return streamSimple;
217
+ if (key === "completeSimple")
218
+ return completeSimple;
219
+ const value = Reflect.get(target, key, target);
220
+ return typeof value === "function" ? value.bind(target) : value;
221
+ },
222
+ });
223
+ // The start mark of a generation request the cap refused (capModels), which never left: pi's error entry answers it.
224
+ const refused = () => mark(REQUEST_STARTED, { [CAP_REFUSED_FIELD]: true });
225
+ return { models: proxy, open, refused };
226
+ }
@@ -0,0 +1,3 @@
1
+ import type { ToolExecutionResult } from "@earendil-works/pi-durable";
2
+ /** `text` under both keys, with any other fields of the result. */
3
+ export declare const forModel: (text: string, fields?: Omit<ToolExecutionResult, "content" | "output">) => ToolExecutionResult;
package/dist/result.js ADDED
@@ -0,0 +1,5 @@
1
+ /** `text` under both keys, with any other fields of the result. */
2
+ export const forModel = (text, fields = {}) => {
3
+ const blocks = [{ type: "text", text }];
4
+ return { ...fields, content: blocks, output: blocks };
5
+ };
package/dist/rows.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import type { TimelineEvent } from "@parcha/pi-durable-agent/timeline";
2
+ export type Row = TimelineEvent & {
3
+ seq: number;
4
+ };
5
+ /** One server's change numbers: they start at its start time in microseconds, so a cursor from before a restart is below
6
+ * every number it hands out, and increase strictly across its runs. */
7
+ export declare class ChangeClock {
8
+ readonly base: number;
9
+ private counter;
10
+ next(): number;
11
+ get current(): number;
12
+ }
13
+ export type Page = {
14
+ reset: boolean;
15
+ rows: Row[];
16
+ drop: string[];
17
+ next_after: number;
18
+ unchanged: boolean;
19
+ has_more: boolean;
20
+ };
21
+ export declare class RowLog {
22
+ private readonly clock;
23
+ private readonly slots;
24
+ private readonly uses;
25
+ private seq;
26
+ /** The last change of this run: rows, drops and its status. */
27
+ last: number;
28
+ private stateChange;
29
+ private state;
30
+ private readonly waiters;
31
+ constructor(clock: ChangeClock);
32
+ private next;
33
+ /** Make the served rows equal `rows`: new ids are added after every row served so far, changed ones keep their seq,
34
+ * and ids no longer there are dropped, except those `keep` says stay (a row a committed entry made: the timeline only
35
+ * grows). Returns whether anything changed. */
36
+ sync(rows: readonly TimelineEvent[], keep?: (id: string) => boolean): boolean;
37
+ /** The run's status and state, as one more change when they move. */
38
+ setState(value: string): boolean;
39
+ rows(): Row[];
40
+ /** The changes after `after`, at most `limit` rows. A cursor from before this process, ahead of this run, or 0
41
+ * answers every row with `reset`. */
42
+ page(after: number, limit: number): Page;
43
+ /** Resolves on the next change, or after `ms`. */
44
+ changed(ms: number): Promise<void>;
45
+ private touch;
46
+ }
package/dist/rows.js ADDED
@@ -0,0 +1,121 @@
1
+ let latest = 0;
2
+ /** One server's change numbers: they start at its start time in microseconds, so a cursor from before a restart is below
3
+ * every number it hands out, and increase strictly across its runs. */
4
+ export class ChangeClock {
5
+ base = Math.max(Date.now() * 1000, latest + 1);
6
+ counter = this.base;
7
+ next() {
8
+ latest = Math.max(latest, ++this.counter);
9
+ return this.counter;
10
+ }
11
+ get current() {
12
+ return this.counter;
13
+ }
14
+ }
15
+ const SEQ_FREE = (row) => JSON.stringify({ ...row, seq: undefined, id: undefined });
16
+ export class RowLog {
17
+ clock;
18
+ slots = new Map();
19
+ uses = new Map();
20
+ seq = 0;
21
+ /** The last change of this run: rows, drops and its status. */
22
+ last;
23
+ stateChange;
24
+ state = "";
25
+ waiters = new Set();
26
+ constructor(clock) {
27
+ this.clock = clock;
28
+ this.last = clock.base;
29
+ this.stateChange = clock.base;
30
+ }
31
+ next() {
32
+ return this.clock.next();
33
+ }
34
+ /** Make the served rows equal `rows`: new ids are added after every row served so far, changed ones keep their seq,
35
+ * and ids no longer there are dropped, except those `keep` says stay (a row a committed entry made: the timeline only
36
+ * grows). Returns whether anything changed. */
37
+ sync(rows, keep) {
38
+ let changed = false;
39
+ const present = new Set();
40
+ for (const row of rows) {
41
+ present.add(row.id);
42
+ const text = SEQ_FREE(row);
43
+ const slot = this.slots.get(row.id);
44
+ if (slot && !slot.dropped) {
45
+ if (slot.text === text)
46
+ continue;
47
+ slot.text = text;
48
+ slot.row = { ...row, id: slot.id, seq: slot.seq };
49
+ slot.change = this.next();
50
+ changed = true;
51
+ continue;
52
+ }
53
+ const use = (this.uses.get(row.id) ?? 0) + 1;
54
+ this.uses.set(row.id, use);
55
+ const id = use === 1 ? row.id : `${row.id}~${use}`;
56
+ if (slot)
57
+ this.slots.set(`${row.id}\0${slot.change}`, slot);
58
+ const seq = this.seq++;
59
+ this.slots.set(row.id, { id, source: row.id, seq, row: { ...row, id, seq }, change: this.next(), dropped: false, text });
60
+ changed = true;
61
+ }
62
+ for (const [key, slot] of this.slots) {
63
+ if (slot.dropped || key !== slot.source || present.has(slot.source) || keep?.(slot.source))
64
+ continue;
65
+ slot.dropped = true;
66
+ slot.change = this.next();
67
+ changed = true;
68
+ }
69
+ // The usage row stays last: one served after it moves it to the end.
70
+ const shown = [...this.slots.values()].filter((s) => !s.dropped);
71
+ const usage = shown.find((s) => s.row.kind === "usage");
72
+ if (usage && shown.some((s) => s.seq > usage.seq)) {
73
+ usage.seq = this.seq++;
74
+ usage.row = { ...usage.row, seq: usage.seq };
75
+ usage.change = this.next();
76
+ changed = true;
77
+ }
78
+ if (changed)
79
+ this.touch();
80
+ return changed;
81
+ }
82
+ /** The run's status and state, as one more change when they move. */
83
+ setState(value) {
84
+ if (value === this.state)
85
+ return false;
86
+ this.state = value;
87
+ this.stateChange = this.next();
88
+ this.touch();
89
+ return true;
90
+ }
91
+ rows() {
92
+ return [...this.slots.values()].filter((s) => !s.dropped).map((s) => s.row).sort((a, b) => a.seq - b.seq);
93
+ }
94
+ /** The changes after `after`, at most `limit` rows. A cursor from before this process, ahead of this run, or 0
95
+ * answers every row with `reset`. */
96
+ page(after, limit) {
97
+ const reset = after <= 0 || after < this.clock.base || after > this.last;
98
+ const slots = [...this.slots.values()];
99
+ const changed = slots.filter((s) => !s.dropped && (reset || s.change > after)).sort((a, b) => a.change - b.change);
100
+ const has_more = changed.length > limit;
101
+ const taken = changed.slice(0, limit);
102
+ const upto = has_more ? taken.at(-1).change : this.last;
103
+ const drop = reset ? [] : slots.filter((s) => s.dropped && s.change > after && s.change <= upto).map((s) => s.id);
104
+ const rows = taken.map((s) => s.row).sort((a, b) => a.seq - b.seq);
105
+ const unchanged = !reset && rows.length === 0 && drop.length === 0 && this.stateChange <= after;
106
+ return { reset, rows, drop, next_after: upto, unchanged, has_more };
107
+ }
108
+ /** Resolves on the next change, or after `ms`. */
109
+ changed(ms) {
110
+ return new Promise((resolve) => {
111
+ const done = () => (clearTimeout(timer), this.waiters.delete(done), resolve());
112
+ const timer = setTimeout(done, ms);
113
+ this.waiters.add(done);
114
+ });
115
+ }
116
+ touch() {
117
+ this.last = this.clock.current;
118
+ for (const wake of [...this.waiters])
119
+ wake();
120
+ }
121
+ }
@@ -0,0 +1,134 @@
1
+ import type { Context } from "@earendil-works/chord";
2
+ import type { ExecutionEnv } from "@earendil-works/pi-durable/env";
3
+ import type { BoxProvider, BoxSpec } from "@parcha/pi-transport";
4
+ import type { PullReceipt } from "@parcha/pi-transport/sync";
5
+ import { type Place } from "./place.js";
6
+ /** The label a run's box carries: the run's id. */
7
+ export declare const RUN_LABEL = "agentrun.run";
8
+ /** And this one, the same on every run's box, which the start's sweep lists them by. */
9
+ export declare const KIND_LABEL = "agentrun.box";
10
+ /** The whole environment of a box's programs: a constant, never this process's. */
11
+ export declare const BOX_ENV: Readonly<Record<string, string>>;
12
+ /** How long a box lives whatever happens to the server: a bound on a leaked box, never its clean end. */
13
+ export declare const BOX_LIFETIME_MS: number;
14
+ /** A bash command's timeout when the model names none. */
15
+ export declare const BASH_TIMEOUT_MS = 300000;
16
+ /** The image a Docker box starts from (box-image.ts, where the server makes it ready). */
17
+ export { DEFAULT_DOCKER_IMAGE, DOCKER_IMAGE_ENV } from "./box-image.js";
18
+ /** The settings that bound a Docker box; unset, their defaults: enough for a build, and safe on a laptop, where one run's
19
+ * runaway build or fork bomb would otherwise starve everything else. */
20
+ export declare const BOX_CPUS_ENV = "AGENTRUN_BOX_CPUS";
21
+ export declare const BOX_MEMORY_ENV = "AGENTRUN_BOX_MEMORY";
22
+ export declare const BOX_PIDS_ENV = "AGENTRUN_BOX_PIDS";
23
+ /** 2 CPUs' time: a CFS quota (pi-transport's Docker provider), which holds whatever CPU count Docker's VM has. */
24
+ export declare const DEFAULT_BOX_CPUS = 2;
25
+ /** 4 GiB, swap included (--memory-swap the same). */
26
+ export declare const DEFAULT_BOX_MEMORY = "4g";
27
+ /** Processes and threads at once. */
28
+ export declare const DEFAULT_BOX_PIDS = 1024;
29
+ /** A Docker box's limits, as pi-transport's Docker provider takes them. */
30
+ export type BoxLimits = {
31
+ cpus: number;
32
+ memory: string;
33
+ pidsLimit: number;
34
+ };
35
+ /** A Docker box's limits from `env`: each setting's value, or its default when unset or empty. A value that is not one, or
36
+ * that every create would fail on (less than a 1 ms quota, less memory than Docker gives, more processes than the kernel
37
+ * allows), throws, naming its setting: the start checks them (startServe), so no run meets one. */
38
+ export declare function boxLimitsOf(env: NodeJS.ProcessEnv): BoxLimits;
39
+ /** Under `--faux` only: a module whose default export, given the data root, is the provider runs' boxes come from in
40
+ * place of Docker (the tests' faux box). */
41
+ export declare const FAUX_BOX_ENV = "AGENTRUN_SERVE_FAUX_BOX";
42
+ /** A remote box's sync mark in its run's directory: the box's id and the listing its seed or last pull left. The
43
+ * server alone writes it. */
44
+ export declare const BOX_SYNC_FILE = "box-sync.json";
45
+ /** What the run's process copied into its remote box after the seed (a file its host tools filed in work/): one JSON line
46
+ * per file, `{path, sha256, bytes}`, appended by that process alone. The mark has one writer, the server, so the
47
+ * process never writes it; a pull folds these lines into the mark it compares against, for paths the mark lacks, so
48
+ * the box's later edit of such a file comes back instead of reading as a change the server made. */
49
+ export declare const BOX_MIRRORED_FILE = "box-mirrored.jsonl";
50
+ type Mount = NonNullable<BoxSpec["mounts"]>[number];
51
+ /** `source`, when it is below `root` through no link and is its own canonical path; else a refusal naming the link.
52
+ * `root`, the data root, is canonical already (startServe), so a link above it is the operator's choice. */
53
+ export declare function mountSource(root: string, source: string): Promise<string>;
54
+ /** Every mount a run's box gets, each through mountSource: its work/ only, read-write, at BOX_WORK. A run's home joins
55
+ * this list (read-only parts included) when it comes; nothing else of the data root does. */
56
+ export declare function boxMounts(root: string, runDir: string, place: Place): Promise<Mount[]>;
57
+ /** The provider runs' boxes come from, and what a create of its box waits on first (`ready`, run-box below). */
58
+ export type RunBoxes = BoxProvider & {
59
+ ready?: BoxReady;
60
+ };
61
+ /** The provider runs' boxes come from: under `--faux` with a faux box, its module's; else Docker on this machine, run as
62
+ * this process's user (serve's: a run's process is its child), so what a box writes in work/ stays serve's, within the
63
+ * box limits the server's settings give (boxLimitsOf), and whose create first waits while the server pulls its image
64
+ * (box-image.ts). */
65
+ export declare function runBoxProvider(place: Place, env: NodeJS.ProcessEnv, root: string): Promise<RunBoxes>;
66
+ /** What a run's box create waits on first, `note` taking its one timeline row: the server's pull of the Docker image
67
+ * (box-image.ts). A faux box has no image, so none. */
68
+ export type BoxReady = (context: Context, note: (summary: string) => Promise<void> | void) => Promise<void>;
69
+ /** The tests' faux box provider, from its module. */
70
+ export declare const fauxBoxes: (module: string, root: string) => Promise<BoxProvider>;
71
+ /** A run's box, as its tools' environment: found by its label or made on the first call, once; made again on the call
72
+ * after it was lost. A box that cannot be had fails that call; nothing falls back to this machine. Before a local box is
73
+ * made, its provider's `ready` is waited on (its image), and the call that opens it gives the `note` for its timeline
74
+ * row; a remote box is the server's to make (ensureRemoteBox), and never waits on that. `mirror`, on a remote box: copies
75
+ * a file the run's host tools filed in work/ (at `path`, relative to it) into the box, now when the box is open, else at
76
+ * its open. */
77
+ export type RunBox = {
78
+ env(context: Context, note?: (summary: string) => Promise<void> | void): Promise<ExecutionEnv>;
79
+ hostWork: string;
80
+ bound(): Promise<boolean>;
81
+ leftEnded(context: Context): Promise<void>;
82
+ mirror?: (path: string, data: string | Uint8Array) => Promise<void>;
83
+ };
84
+ /** Where a run's box comes from: a provider of this process's own (Docker, or the tests' faux box), or, for a remote box,
85
+ * the server's relay in data root `relay`. A bare function is a provider of this process's own. */
86
+ export type BoxSource = {
87
+ provider: () => Promise<RunBoxes>;
88
+ } | {
89
+ relay: string;
90
+ };
91
+ export declare function runBox(given: BoxSource | (() => Promise<RunBoxes>), run: {
92
+ id: string;
93
+ root: string;
94
+ dir: string;
95
+ place: Place;
96
+ }): RunBox;
97
+ /** The server's side of a remote box: run `run`'s box, found by its label or made, with its work/ seeded once (its mark
98
+ * says so); its id, and whether it was made now. A found box whose network is not closed is destroyed and made again;
99
+ * a box whose seed fails is destroyed, and the call fails. */
100
+ export declare function ensureRemoteBox(boxes: BoxProvider, run: {
101
+ id: string;
102
+ dir: string;
103
+ }, context: Context, wake?: () => Promise<number>): Promise<{
104
+ id: string;
105
+ made: boolean;
106
+ }>;
107
+ /** What a pull of a remote box brought back; undefined when the run has no box (none made, or it is gone). */
108
+ export type RemotePull = {
109
+ -readonly [K in "changed" | "files" | "bytes" | "removed"]: PullReceipt[K];
110
+ };
111
+ /** A pull that did not bring the box's work/ back whole: what it wrote is kept, with its mark, and the box must stay.
112
+ * `lasting`: a stop another pull will meet again (an archive the extractor cannot read, or a limit a pull that wrote
113
+ * nothing reached); else the copy failed, and a later pull may land. */
114
+ export declare class PullIncomplete extends Error {
115
+ readonly lasting: boolean;
116
+ /** The box that keeps what did not come back. */
117
+ readonly box: string;
118
+ constructor(message: string, lasting: boolean, box: string);
119
+ }
120
+ /** The server's side of a remote box: what changed in the box's work/ since its mark, pulled into the run's work/ by the
121
+ * safe extractor (nothing outside work/, no link, safe names only). A file this machine changed since the mark stays
122
+ * (`if_unchanged`), and what the box removed is removed here too. A pull a limit stopped after it wrote something is
123
+ * followed by another, which asks only for the rest. Throws when the copy fails (the mark kept), and PullIncomplete when
124
+ * it is not whole: a caller then keeps the box. */
125
+ export declare function pullRemoteBox(boxes: BoxProvider, run: {
126
+ id: string;
127
+ dir: string;
128
+ }, context: Context, wake?: () => Promise<number>): Promise<RemotePull | undefined>;
129
+ /** Destroys every box labelled with run `runId`; how many it destroyed. */
130
+ export declare function destroyRunBoxes(boxes: BoxProvider, runId: string, context: Context): Promise<number>;
131
+ /** The start's sweep: destroys every run's box whose run `ended` says is over, once `before` (a remote box's pull) for its
132
+ * run says it may go. A box of a run this server does not know is left to its lifetime: another server's, or one being
133
+ * made. */
134
+ export declare function sweepRunBoxes(boxes: BoxProvider, ended: (runId: string) => boolean, context: Context, before?: (runId: string, boxId: string) => Promise<boolean>): Promise<number>;