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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +78 -46
  3. package/dist/adapters.d.ts +0 -3
  4. package/dist/adapters.js +0 -7
  5. package/dist/agents.d.ts +1 -1
  6. package/dist/api-only.d.ts +14 -0
  7. package/dist/api-only.js +33 -0
  8. package/dist/archil-routes.d.ts +1 -1
  9. package/dist/box-egress-vm.d.ts +0 -8
  10. package/dist/box-egress-vm.js +0 -10
  11. package/dist/box-egress.d.ts +0 -4
  12. package/dist/box-egress.js +1 -16
  13. package/dist/box-paths.d.ts +25 -2
  14. package/dist/box-paths.js +79 -11
  15. package/dist/box-relay.d.ts +0 -11
  16. package/dist/box-relay.js +0 -20
  17. package/dist/box-settings.d.ts +46 -0
  18. package/dist/box-settings.js +107 -0
  19. package/dist/boxes.d.ts +4 -1
  20. package/dist/browser-cost.js +2 -1
  21. package/dist/browser-person.d.ts +0 -2
  22. package/dist/browser-person.js +0 -2
  23. package/dist/budget.d.ts +0 -4
  24. package/dist/budget.js +0 -7
  25. package/dist/cap.d.ts +0 -7
  26. package/dist/cap.js +0 -22
  27. package/dist/cli.js +23 -8
  28. package/dist/computers.d.ts +1 -1
  29. package/dist/console/assets/index-Dn0ngwG9.js +535 -0
  30. package/dist/console/assets/index-DvW6Aled.css +1 -0
  31. package/dist/console/index.html +2 -2
  32. package/dist/daytona-api.d.ts +0 -11
  33. package/dist/daytona-api.js +1 -82
  34. package/dist/docker-host-addresses.d.ts +37 -0
  35. package/dist/docker-host-addresses.js +110 -0
  36. package/dist/files.d.ts +0 -8
  37. package/dist/files.js +0 -17
  38. package/dist/github-connection.d.ts +1 -1
  39. package/dist/github-connection.js +1 -1
  40. package/dist/harness-install.d.ts +23 -0
  41. package/dist/harness-install.js +99 -4
  42. package/dist/harness.d.ts +4 -3
  43. package/dist/harness.js +16 -1
  44. package/dist/import.js +52 -13
  45. package/dist/learn/secrets.d.ts +2 -1
  46. package/dist/learn/secrets.js +19 -6
  47. package/dist/learned-workflow.d.ts +5 -4
  48. package/dist/learned-workflow.js +6 -3
  49. package/dist/learning-routes.d.ts +9 -46
  50. package/dist/learning-routes.js +25 -29
  51. package/dist/learning-run.d.ts +4 -231
  52. package/dist/learning-run.js +7 -651
  53. package/dist/live/translate.js +1 -1
  54. package/dist/mcp-gateway.d.ts +0 -3
  55. package/dist/mcp-gateway.js +0 -13
  56. package/dist/mcp-probe.d.ts +2 -2
  57. package/dist/mcp-probe.js +2 -2
  58. package/dist/mcp-servers-store.js +1 -1
  59. package/dist/openapi.js +3 -3
  60. package/dist/page.js +3 -1
  61. package/dist/paid-calls.js +3 -2
  62. package/dist/pause.d.ts +0 -2
  63. package/dist/pause.js +1 -8
  64. package/dist/place.d.ts +0 -5
  65. package/dist/place.js +0 -10
  66. package/dist/print.d.ts +2 -1
  67. package/dist/print.js +4 -2
  68. package/dist/run-db.d.ts +0 -2
  69. package/dist/run-db.js +0 -4
  70. package/dist/run-learning-served.d.ts +38 -0
  71. package/dist/run-learning-served.js +9 -0
  72. package/dist/run-secrets.d.ts +33 -0
  73. package/dist/run-secrets.js +53 -0
  74. package/dist/run-timeline-served.js +5 -2
  75. package/dist/run-view.d.ts +5 -9
  76. package/dist/run-view.js +4 -22
  77. package/dist/runner/adapter-loop.d.ts +8 -2
  78. package/dist/runner/adapter-loop.js +44 -12
  79. package/dist/runner/adapter-run-spec.d.ts +8 -0
  80. package/dist/runner/adapter-run-spec.js +6 -5
  81. package/dist/runner/adapters/pi.d.ts +4 -0
  82. package/dist/runner/adapters/pi.js +4 -1
  83. package/dist/runner/beside.js +19 -8
  84. package/dist/runner/claim-secrets.js +1 -1
  85. package/dist/runner/cli-run-spec.js +15 -1
  86. package/dist/runner/journal-kinds.d.ts +6 -0
  87. package/dist/runner/live-ticker.d.ts +1 -1
  88. package/dist/runner/live-ticker.js +28 -4
  89. package/dist/runner/loop-contract.d.ts +3 -2
  90. package/dist/runner/main.d.ts +11 -4
  91. package/dist/runner/main.js +39 -10
  92. package/dist/runner/mcp-claim.d.ts +1 -1
  93. package/dist/runner/mcp-claim.js +1 -1
  94. package/dist/runner/model-route.js +21 -2
  95. package/dist/runner/redact.d.ts +8 -2
  96. package/dist/runner/redact.js +11 -2
  97. package/dist/runner/workflow-spec.js +5 -9
  98. package/dist/runs-over-store.d.ts +1 -1
  99. package/dist/runs-over-store.js +16 -5
  100. package/dist/seal-key.d.ts +54 -15
  101. package/dist/seal-key.js +272 -84
  102. package/dist/sealed-settings.d.ts +2 -2
  103. package/dist/sealed-settings.js +3 -10
  104. package/dist/secrets.d.ts +2 -10
  105. package/dist/secrets.js +21 -17
  106. package/dist/server-secrets-store.js +1 -1
  107. package/dist/server-secrets.js +3 -0
  108. package/dist/server.d.ts +10 -6
  109. package/dist/server.js +89 -41
  110. package/dist/store/index.d.ts +1 -1
  111. package/dist/store/index.js +1 -1
  112. package/dist/store/open.d.ts +12 -2
  113. package/dist/store/open.js +23 -3
  114. package/dist/store/postgres/migrate.js +18 -1
  115. package/dist/store/sqlite/store.js +23 -8
  116. package/dist/store/store.d.ts +3 -0
  117. package/dist/store-reads/journal.d.ts +16 -0
  118. package/dist/store-reads/journal.js +82 -6
  119. package/dist/store-view.js +38 -5
  120. package/dist/tool-keys.d.ts +4 -3
  121. package/dist/tool-keys.js +7 -4
  122. package/dist/tools.d.ts +1 -1
  123. package/dist/tools.js +4 -1
  124. package/dist/trigger-schedule.js +2 -1
  125. package/dist/trigger-secrets-shown.js +5 -1
  126. package/dist/workspace/computer-deps.d.ts +29 -0
  127. package/dist/workspace/computer-deps.js +48 -1
  128. package/dist/workspace/computer-for-claim.d.ts +7 -3
  129. package/dist/workspace/computer-for-claim.js +1 -1
  130. package/dist/workspace/computer-providers.d.ts +6 -2
  131. package/dist/workspace/computer-providers.js +1 -1
  132. package/dist/workspace/index.d.ts +1 -1
  133. package/dist/workspace/index.js +1 -1
  134. package/dist/workspace.d.ts +0 -3
  135. package/dist/workspace.js +0 -3
  136. package/launcher/agentrun-serve +6 -33
  137. package/package.json +14 -14
  138. package/templates/inbound-lead/agent.md +1 -1
  139. package/templates/kyb/agent.md +1 -1
  140. package/dist/app.d.ts +0 -5
  141. package/dist/app.js +0 -514
  142. package/dist/bounds.d.ts +0 -26
  143. package/dist/bounds.js +0 -137
  144. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  145. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  146. package/dist/content-filter.d.ts +0 -7
  147. package/dist/content-filter.js +0 -23
  148. package/dist/disk.d.ts +0 -33
  149. package/dist/disk.js +0 -85
  150. package/dist/door-line.d.ts +0 -23
  151. package/dist/door-line.js +0 -83
  152. package/dist/harness-app.d.ts +0 -69
  153. package/dist/harness-app.js +0 -1162
  154. package/dist/request-start.d.ts +0 -27
  155. package/dist/request-start.js +0 -381
  156. package/dist/run-box.d.ts +0 -205
  157. package/dist/run-box.js +0 -661
  158. package/dist/run-holder.d.ts +0 -52
  159. package/dist/run-holder.js +0 -139
  160. package/dist/runs.d.ts +0 -1200
  161. package/dist/runs.js +0 -4103
  162. package/dist/served-only.d.ts +0 -5
  163. package/dist/served-only.js +0 -12
@@ -1,27 +0,0 @@
1
- import type { Models } from "@earendil-works/pi-ai";
2
- import { type DurableRun } from "@parcha/pi-durable-disk";
3
- import { type RefusalFigures } from "./cap.js";
4
- /** Whether the run in `root` (its directory) was cancelled: the mark serve's cancel writes there first. */
5
- export declare const cancelledIn: (root: string) => () => boolean;
6
- /** How long a mark that carries a hold (a lost or failed request's end, an unreadable cost's) may take to reach the store
7
- * before the request fails loudly (END_NOT_WRITTEN): 15 s. A lost mark is waited for before the retry is sent, so a
8
- * commit queued behind a large entry on a slow disk (seconds) past 1 s let the retry leave, and its answer reach pi,
9
- * with no mark in the store: a crash then read the request at the answer's own usage. Such a mark is written only on a
10
- * path already lost or failed, so the wait costs latency there and nowhere else; 15 s holds such a commit with room to
11
- * spare, and still fails a store that has stopped within a turn's patience, never a turn held without bound. */
12
- export declare const END_MARK_WAIT_MS = 15000;
13
- /** `models` with each generation request marked before it leaves, once `open` hands over the run (its Harness). Once
14
- * `cancelled` says the run was cancelled, no request is sent: each is refused here, before it is marked, or after its
15
- * mark when the cancel came while the mark waited, and then its start is withdrawn (an end mark, `unsent`). */
16
- export declare function markRequests<M extends Models>(models: M, cancelled?: () => boolean, { holdMarkWaitMs }?: {
17
- holdMarkWaitMs?: number;
18
- }): Promise<{
19
- models: M;
20
- open(run: DurableRun): void;
21
- refused(figures?: RefusalFigures): Promise<void>;
22
- wrapUp(data: {
23
- capUsd: number;
24
- leftUsd: number;
25
- words: string;
26
- }): void;
27
- }>;
@@ -1,381 +0,0 @@
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 { randomUUID } from "node:crypto";
20
- import { existsSync } from "node:fs";
21
- import { join } from "node:path";
22
- import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
23
- import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
24
- import { CAP_WRAPUP, REQUEST_COST, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED } from "@parcha/pi-durable-agent/timeline";
25
- import { BARRIER, syncNow } from "@parcha/pi-durable-disk";
26
- import { anyAttemptLost, ATTEMPTS, attemptLost, BOUND_FIELD, BOUND_USD, CAP_REFUSED_FIELD, END_NOT_WRITTEN, CLAMP, HELD_FIELD, HELD_USD, MARK_NOT_WRITTEN, markResponseBegan, piEnded, refusalFields, sideRequests, STOPPED_USD } from "./cap.js";
27
- import { RUN_CANCELLED } from "./files.js";
28
- import { noStoreToSync } from "./paid-calls.js";
29
- import { isConnectCode, isGatewayTimeout } from "@parcha/agentrun-kernel";
30
- /** Whether the run in `root` (its directory) was cancelled: the mark serve's cancel writes there first. */
31
- export const cancelledIn = (root) => () => existsSync(join(root, RUN_CANCELLED));
32
- /** How long a mark that carries a hold (a lost or failed request's end, an unreadable cost's) may take to reach the store
33
- * before the request fails loudly (END_NOT_WRITTEN): 15 s. A lost mark is waited for before the retry is sent, so a
34
- * commit queued behind a large entry on a slow disk (seconds) past 1 s let the retry leave, and its answer reach pi,
35
- * with no mark in the store: a crash then read the request at the answer's own usage. Such a mark is written only on a
36
- * path already lost or failed, so the wait costs latency there and nowhere else; 15 s holds such a commit with room to
37
- * spare, and still fails a store that has stopped within a turn's patience, never a turn held without bound. */
38
- export const END_MARK_WAIT_MS = 15_000;
39
- /** How long a stop's mark is waited for before pi has the stopped result: a stop's mark needs no fatal wait (without it
40
- * the request reads as cut, at its hold, never less), so a slow store costs a stop at most this. */
41
- const STOP_MARK_WAIT_MS = 1_000;
42
- /** `models` with each generation request marked before it leaves, once `open` hands over the run (its Harness). Once
43
- * `cancelled` says the run was cancelled, no request is sent: each is refused here, before it is marked, or after its
44
- * mark when the cancel came while the mark waited, and then its start is withdrawn (an end mark, `unsent`). */
45
- export async function markRequests(models, cancelled = () => false, { holdMarkWaitMs = END_MARK_WAIT_MS } = {}) {
46
- const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
47
- let open;
48
- // A request a resumed turn sends before the app's open waits for it: the mark needs the run's store.
49
- const opened = new Promise((resolve) => (open = resolve));
50
- const mark = async (kind, data = {}) => {
51
- const run = await opened;
52
- await run.harness.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind, data })), BACKGROUND_CONTEXT);
53
- };
54
- /** A request's start mark, then the run journal's barrier (pi-durable-disk barriers.ts, modelRequestStarted): the mark,
55
- * with the hold and bound a crash is read at, is on disk before the request is sent. A failure fails the request
56
- * unsent (MARK_NOT_WRITTEN): with no store to sync, no mark is written (paid-calls.ts noStoreToSync); a sync that fails
57
- * after the mark is answered by `unsent`, its end mark (best effort), so the store never holds a start that did not
58
- * leave. */
59
- const markStarted = async (data, unsent) => {
60
- const run = await opened;
61
- if (noStoreToSync(run.store))
62
- throw new Error("the run's store is not open, so its start mark cannot be made durable");
63
- await mark(REQUEST_STARTED, data);
64
- try {
65
- await syncNow(run.store, BARRIER.modelRequestStarted);
66
- }
67
- catch (error) {
68
- await mark(REQUEST_ENDED, unsent).catch(() => undefined);
69
- throw new Error(`written, but it could not be made durable: ${reason(error)}`);
70
- }
71
- };
72
- const failed = (model, why) => ({
73
- role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(),
74
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
75
- errorMessage: why,
76
- });
77
- const reason = (error) => String(error?.message ?? error).slice(0, 200);
78
- /** Whether `work` (a mark's write) is in the store within `holdMarkWaitMs` (END_MARK_WAIT_MS, a test's own when it
79
- * gives one): undefined when it is, else why not (its refusal, or the wait run out). */
80
- const landed = (work) => new Promise((resolve) => {
81
- const timer = setTimeout(() => resolve(new Error(`the store had not taken it in ${holdMarkWaitMs} ms`)), holdMarkWaitMs);
82
- work.then(() => (clearTimeout(timer), resolve(undefined)), (error) => (clearTimeout(timer), resolve(error ?? new Error("refused"))));
83
- });
84
- /** Until `work` settles, or `ms` pass. */
85
- const within = (work, ms) => new Promise((resolve) => {
86
- const timer = setTimeout(resolve, ms);
87
- void work.finally(() => (clearTimeout(timer), resolve()));
88
- });
89
- /** What the run's cap held for a request (its options' HELD_USD), as an end mark's field; none without a cap. */
90
- const heldOf = (options) => {
91
- const held = options?.[HELD_USD];
92
- return typeof held === "number" && Number.isFinite(held) ? { [HELD_FIELD]: held } : {};
93
- };
94
- /** Whether a request the cap watched is lost (piEnded, from the attempts its cap recorded): an error before any event
95
- * that left, or an answer after an attempt that was lost. It can have been billed, so it counts at its hold. Only a
96
- * request the cap watched (a hold, and its attempts, or null on an API it cannot watch): another is read as before. */
97
- const lostOf = (options, message) => {
98
- const record = options;
99
- if (typeof record?.[HELD_USD] !== "number" || !record || !(ATTEMPTS in record))
100
- return false;
101
- return piEnded(message, false, record[ATTEMPTS] ?? undefined).end === "lost";
102
- };
103
- /** `options` whose fetch writes the request's end mark at its hold (`lost`), once, the moment an attempt is known lost:
104
- * a rejection once it could have left (any code but a connect one, and not the run's own stop) or a gateway's timeout
105
- * (504, 524), as that attempt's fetch ends; an answer pi-ai then tries again (a 2xx that was not the last), before the
106
- * next attempt is sent, since only the retry says so. Whatever follows (a retry's answer, a stop while pi-ai waits to
107
- * retry, an error), the provider can have billed the lost attempt, and the mark is in the store before pi's entry for
108
- * the request can be, so a later process reads the hold this one books, with no window between them. `options` as
109
- * given on a request the cap does not watch. */
110
- const watchingLost = (options, markLost) => {
111
- const record = options;
112
- const attempts = record && ATTEMPTS in record ? record[ATTEMPTS] : null;
113
- if (!attempts || typeof record?.[HELD_USD] !== "number" || typeof record.fetch !== "function")
114
- return options;
115
- const inner = record.fetch;
116
- let marked = false;
117
- const markOnce = async () => {
118
- if (marked)
119
- return;
120
- marked = true;
121
- await markLost().catch(() => undefined);
122
- };
123
- /** Whether the attempt the fetch just recorded is lost as it ends, whatever comes after it. */
124
- const lostNow = () => {
125
- const last = attempts.at(-1);
126
- return last !== undefined && ("code" in last ? !last.aborted && !isConnectCode(last.code) : isGatewayTimeout(last.status));
127
- };
128
- return { ...record, fetch: (async (input, init) => {
129
- // An answer pi-ai tries again: lost, as the retry shows.
130
- if (attempts.some((attempt) => attemptLost(attempt, false)))
131
- await markOnce();
132
- let response;
133
- try {
134
- response = await inner(input, init);
135
- }
136
- catch (error) {
137
- if (lostNow())
138
- await markOnce();
139
- throw error;
140
- }
141
- if (lostNow())
142
- await markOnce();
143
- return response;
144
- }) };
145
- };
146
- /** What the run's cap counts a request stopped before its end at, given the answer it had streamed (its options'
147
- * STOPPED_USD), as an end mark's field; its worst case when the cap gave no such figure, or when an attempt before the
148
- * stop was lost (anyAttemptLost: it can have been billed, and the cap counts it at its hold in this process too); none
149
- * without a cap. The one figure every stop's end mark carries, a generation's and a summary's. */
150
- const stoppedOf = (options, message) => {
151
- const attempts = options?.[ATTEMPTS];
152
- if (anyAttemptLost(attempts ?? undefined))
153
- return heldOf(options);
154
- const stopped = options?.[STOPPED_USD];
155
- const figure = typeof stopped === "function" ? stopped(message) : undefined;
156
- return typeof figure === "number" && Number.isFinite(figure) ? { [HELD_FIELD]: figure } : heldOf(options);
157
- };
158
- /** A request's bound (BOUND_FIELD, when above 0: the run's cost serves it while the request is in flight), as its
159
- * start mark keeps it. */
160
- const boundOf = (options) => {
161
- const bound = options?.[BOUND_USD];
162
- return typeof bound === "number" && Number.isFinite(bound) && bound > 0 ? { [BOUND_FIELD]: bound } : {};
163
- };
164
- /** A start mark's figures: what the cap held it at, its bound, and what the cap limited its output to when it did
165
- * (CLAMP), so a reply cut short there says so on the run's timeline. */
166
- const startOf = (options) => {
167
- const clamp = options?.[CLAMP];
168
- 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 } } : {};
169
- return { ...heldOf(options), ...boundOf(options), ...kept };
170
- };
171
- /** A cancelled run's request, never sent. It waits for the cancel to reach the run (the request's abort), and then ends
172
- * as aborted, as a request the cancel cut does: the turn, or a workflow's node, stops, never failing on the refusal.
173
- * 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
174
- * backstop for a process the cancel never reaches (an orphan of a server that died in between): it then ends as an
175
- * error, and `markRefusal` lets the timeline skip pi's entry for it. */
176
- const refuse = async (model, what, signal, markRefusal) => {
177
- if (signal && !signal.aborted) {
178
- await new Promise((resolve) => {
179
- const timer = setTimeout(resolve, 60_000);
180
- signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
181
- });
182
- }
183
- if (signal?.aborted)
184
- return { ...failed(model, ""), stopReason: "aborted", errorMessage: undefined };
185
- if (markRefusal)
186
- await mark(REQUEST_REFUSED).catch(() => undefined);
187
- return failed(model, `the run was cancelled: the ${what} was not sent`);
188
- };
189
- const streamSimple = (model, context, options) => {
190
- const outer = createAssistantMessageEventStream();
191
- const refused = async () => {
192
- const message = await refuse(model, "model request", options?.signal, true);
193
- outer.push({ type: "error", reason: message.stopReason === "aborted" ? "aborted" : "error", error: message });
194
- outer.end(message);
195
- };
196
- void (async () => {
197
- if (cancelled())
198
- return refused();
199
- try {
200
- await markStarted(startOf(options), { unsent: true });
201
- }
202
- catch (error) {
203
- const message = failed(model, `${MARK_NOT_WRITTEN} (${reason(error)})`);
204
- outer.push({ type: "error", reason: "error", error: message });
205
- outer.end(message);
206
- return;
207
- }
208
- if (cancelled()) {
209
- await mark(REQUEST_ENDED, { unsent: true }).catch(() => undefined);
210
- return refused();
211
- }
212
- let result;
213
- // Whether the provider's response had begun (an event came in) by the time the request ended.
214
- let began = false;
215
- // The stream's error event, passed on once the request's end is marked (below): the outer stream's result, which
216
- // pi writes as the entry and the cap counts, settles on that event.
217
- let failure;
218
- // Its done event, held the same way: the stream's result settles on it too, so pi has an answer only once its mark
219
- // that carries a hold (a lost or unpriced request's) is in the store, and its entry always comes after that mark.
220
- let done;
221
- // Marked lost before pi-ai tries again (watchingLost): its end mark is in the store before its answer can be.
222
- let lostMarked = false;
223
- // Its write refused: the request's end is not recorded, and the request fails saying so (END_NOT_WRITTEN).
224
- let lostRefused;
225
- const sent = watchingLost(options, async () => {
226
- lostMarked = true;
227
- lostRefused = await landed(mark(REQUEST_ENDED, { lost: true, ...heldOf(options) }));
228
- });
229
- try {
230
- const inner = models.streamSimple(model, context, sent);
231
- for await (const event of inner) {
232
- if (event.type === "error") {
233
- failure = event;
234
- continue;
235
- }
236
- began = true;
237
- if (event.type === "done") {
238
- done = event;
239
- continue;
240
- }
241
- outer.push(event);
242
- }
243
- result = await inner.result();
244
- }
245
- catch (error) {
246
- // A stream that throws instead of ending on an error event still ends the request, as an error, never a hang.
247
- result = failed(model, `the model request failed: ${reason(error)}`);
248
- failure = { type: "error", reason: "error", error: result };
249
- }
250
- // 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
251
- // for the request when it named one before the cut (the request joins its record by it). A store that cannot
252
- // take the mark leaves the request unended, which the timeline also reads as cut, at an unknown cost: the
253
- // conservative reading, so the failure is swallowed here.
254
- let ending;
255
- // Whether `ending` carries the hold a later process must read (an error's or a lost request's): it is in the store
256
- // before pi has the result, however long the store takes, and a refused one fails the request loudly. A stop's
257
- // mark keeps its bound: without it the request stays open, read at its hold, which is never less.
258
- let holding = false;
259
- // An answer whose cost cannot be read counts at its hold (the booking rule), in this process and in a later one: its
260
- // end mark carries the hold (`unpriced`), in the store before pi has the answer, as a lost request's does.
261
- const total = result.usage?.cost?.total;
262
- const unpriced = result.stopReason !== "error" && result.stopReason !== "aborted" && !(typeof total === "number" && Number.isFinite(total)) && Object.keys(heldOf(options)).length > 0;
263
- // A request marked lost before its retry was sent has its end in the store already, at its hold: nothing more.
264
- if (lostMarked) {
265
- if (result.stopReason === "error" && failure?.type === "error")
266
- markResponseBegan(failure.error);
267
- }
268
- else if (result.stopReason === "aborted") {
269
- // Reached only with no lost attempt: watchingLost sets `lostMarked` synchronously, before it awaits the mark, the
270
- // moment an attempt is lost, and that mark lands before pi-ai's retry sleep, so a stop in the sleep finds it set.
271
- const responseId = result.responseId;
272
- ending = mark(REQUEST_ENDED, { ...(typeof responseId === "string" ? { responseId } : {}), ...stoppedOf(options, result) });
273
- }
274
- else if (result.stopReason === "error" && (began || lostOf(options, result))) {
275
- // An error after its response began (an overload part way, a reset): its usage is what had streamed, not what the
276
- // provider can have billed. Its message is recorded (markResponseBegan), which the cap counts at its hold in this
277
- // process, and its end is marked with the hold (`error`), which the spend read back counts. One before any event
278
- // (a 429, a 5xx) is refused unbilled, and counts at its own usage.
279
- markResponseBegan(result);
280
- if (failure?.type === "error")
281
- markResponseBegan(failure.error);
282
- ending = mark(REQUEST_ENDED, { error: true, ...heldOf(options) });
283
- holding = true;
284
- }
285
- else if (unpriced) {
286
- ending = mark(REQUEST_ENDED, { unpriced: true, ...heldOf(options) });
287
- holding = true;
288
- }
289
- // The end mark goes in before pi has the result, so the store holds it before pi's entry; a store that has not taken
290
- // it in END_MARK_WAIT_MS does not hold the turn. One that carries a hold and is not in the store by then (refused, or
291
- // still being written) fails the request loudly (END_NOT_WRITTEN): pi's entry for it then leaves its start open, read
292
- // at its hold (spentIn), so no store's pace stands between a crash and a request read at less than it can have cost.
293
- // A stop's mark needs none of that: without it the request reads as cut, at its hold, which is never less.
294
- let unrecorded = lostRefused;
295
- if (ending && holding)
296
- unrecorded = await landed(ending);
297
- else if (ending)
298
- await within(ending.catch(() => undefined), STOP_MARK_WAIT_MS);
299
- if (unrecorded !== undefined && result.stopReason !== "aborted") {
300
- result = failed(model, `${END_NOT_WRITTEN} (${reason(unrecorded)})`);
301
- failure = { type: "error", reason: "error", error: result };
302
- }
303
- // A request whose end could not be recorded fails loudly (failure, above) in place of its answer.
304
- if (failure)
305
- outer.push(failure);
306
- else if (done)
307
- outer.push(done);
308
- outer.end(result);
309
- })();
310
- return outer;
311
- };
312
- const completeSimple = async (model, context, options) => {
313
- const side = sideRequests.get(context);
314
- // Its label, and an id of its own: such requests run inside tool calls, which pi runs side by side, so its marks name
315
- // it (bounds.ts closes its bound by it).
316
- const COMPACTION = { request: side?.label ?? "compaction", requestId: randomUUID() };
317
- const what = side ? `${side.label} request` : "summary request";
318
- // A cancelled run sends no summary either; pi writes no entry for a failed summary, so nothing needs marking.
319
- if (cancelled())
320
- return refuse(model, what, options?.signal, false);
321
- try {
322
- await markStarted({ ...COMPACTION, ...heldOf(options), ...boundOf(options) }, { ...COMPACTION, unsent: true });
323
- }
324
- catch (error) {
325
- return failed(model, `${MARK_NOT_WRITTEN} (${reason(error)})`);
326
- }
327
- if (cancelled()) {
328
- await mark(REQUEST_ENDED, { ...COMPACTION, unsent: true }).catch(() => undefined);
329
- return refuse(model, what, options?.signal, false);
330
- }
331
- let result;
332
- try {
333
- result = await models.completeSimple(model, context, options);
334
- }
335
- catch (error) {
336
- await mark(REQUEST_ENDED, { ...COMPACTION, ...heldOf(options) }).catch(() => undefined);
337
- throw error;
338
- }
339
- // Its cost closes it; an abort, as for a generation's request, closes it unpriced. A store that cannot take either
340
- // leaves it open, which reads as cut, at an unknown cost.
341
- if (result.stopReason === "aborted")
342
- await mark(REQUEST_ENDED, { ...COMPACTION, ...stoppedOf(options, result) }).catch(() => undefined);
343
- else {
344
- const total = result.usage?.cost?.total;
345
- // A side request's fee is its cost too, on the answer as well: the cap counts the answer's total (cap.ts).
346
- const usd = typeof total === "number" ? total + (side?.feeUsd() ?? 0) : null;
347
- if (side && usd !== null)
348
- result.usage.cost.total = usd;
349
- // Its tokens, in pi's shape, when pi counted any: zeros are no count.
350
- const u = result.usage;
351
- 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;
352
- // One that ended on an error after its response began (it holds content or a token count; a summary has no events
353
- // to read) counts at its hold: it says so, and carries it. One before any of that counts at its own usage.
354
- const began = result.stopReason === "error" && (usage !== undefined || result.content.length > 0);
355
- if (began)
356
- markResponseBegan(result);
357
- // Failed before any response, it counts at its hold too unless it provably never left (piEnded): the same figure the
358
- // cap books in this process, which a later process reads from this mark.
359
- // An answer whose cost cannot be read counts at its hold too (the booking rule), which its mark carries.
360
- const failure = began || lostOf(options, result) ? { failed: true, ...heldOf(options) } : result.stopReason !== "error" && !(typeof usd === "number" && Number.isFinite(usd)) && Object.keys(heldOf(options)).length > 0 ? { unpriced: true, ...heldOf(options) } : {};
361
- await mark(REQUEST_COST, usage ? { ...COMPACTION, usd, usage: usage, ...failure } : { ...COMPACTION, usd, ...failure }).catch(() => undefined);
362
- }
363
- return result;
364
- };
365
- const proxy = new Proxy(models, {
366
- get: (target, key) => {
367
- if (key === "streamSimple")
368
- return streamSimple;
369
- if (key === "completeSimple")
370
- return completeSimple;
371
- const value = Reflect.get(target, key, target);
372
- return typeof value === "function" ? value.bind(target) : value;
373
- },
374
- });
375
- // The start mark of a generation request the cap refused (capModels), which never left: pi's error entry answers it. A
376
- // refusal for room keeps its figures on it (what the cap counted as taken, and the least the request needed).
377
- const refused = (figures) => mark(REQUEST_STARTED, { [CAP_REFUSED_FIELD]: true, ...refusalFields(figures) });
378
- // The wrap-up's row (cap.ts capModels' `wrapUp`): what the run's model was told near its cap, on the root.
379
- const wrapUp = (data) => void mark(CAP_WRAPUP, data).catch(() => undefined);
380
- return { models: proxy, open, refused, wrapUp };
381
- }
package/dist/run-box.d.ts DELETED
@@ -1,205 +0,0 @@
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 BoxEgress, type DockerNetwork, egressBlockedBy } from "./box-egress.js";
6
- import { type Place } from "./place.js";
7
- /** The label a run's box carries: the run's id. */
8
- export declare const RUN_LABEL = "agentrun.run";
9
- /** And, on a box made with a network list, this one: the list's hash (netLabelOf). A box with none carries no such label,
10
- * so its `docker run` is as it was. */
11
- export declare const NET_LABEL = "agentrun.net";
12
- /** The network label's value for a list: the same hosts give the same label, in whatever order and case the setting
13
- * names them, each once. */
14
- export declare const netLabelOf: (allow: readonly string[]) => string;
15
- /** And this one, the same on every run's box, which the start's sweep lists them by. */
16
- export declare const KIND_LABEL = "agentrun.box";
17
- /** And, on a Docker box, the epoch of the run's claim its process held when it made it (runs.ts launch, RUN_EPOCH_ENV). */
18
- export declare const EPOCH_LABEL = "agentrun.epoch";
19
- /** What a run's model is told, once, after its process made a new box in place of the one an earlier process left: the
20
- * run's files are the same, but whatever the old box held outside them is not. */
21
- export declare const BOX_REPLACED_NOTE = "this run's box was replaced after a restart: /workspace is kept; packages installed outside it and /tmp are gone; reinstall what you need";
22
- /** The whole environment of a box's programs: a constant, never this process's. */
23
- export declare const BOX_ENV: Readonly<Record<string, string>>;
24
- /** How long a box lives whatever happens to the server: a bound on a leaked box, never its clean end. */
25
- export declare const BOX_LIFETIME_MS: number;
26
- /** A box command's deadline when its call names none: bash's own default (coding-tools.ts BASH_DEFAULT_TIMEOUT_S), which
27
- * bash always names, so this is the backstop for any other command. */
28
- export declare const BASH_TIMEOUT_MS = 120000;
29
- /** The image a Docker box starts from (box-image.ts, where the server makes it ready). */
30
- export { DEFAULT_DOCKER_IMAGE, DOCKER_IMAGE_ENV } from "./box-image.js";
31
- /** The settings that bound a Docker box; unset, their defaults: enough for a build, and safe on a laptop, where one run's
32
- * runaway build or fork bomb would otherwise starve everything else. */
33
- export declare const BOX_CPUS_ENV = "AGENTRUN_BOX_CPUS";
34
- export declare const BOX_MEMORY_ENV = "AGENTRUN_BOX_MEMORY";
35
- export declare const BOX_PIDS_ENV = "AGENTRUN_BOX_PIDS";
36
- /** 2 CPUs' time: a CFS quota (pi-transport's Docker provider), which holds whatever CPU count Docker's VM has. */
37
- export declare const DEFAULT_BOX_CPUS = 2;
38
- /** 4 GiB, swap included (--memory-swap the same). */
39
- export declare const DEFAULT_BOX_MEMORY = "4g";
40
- /** Processes and threads at once. */
41
- export declare const DEFAULT_BOX_PIDS = 1024;
42
- /** A Docker box's limits, as pi-transport's Docker provider takes them. */
43
- export type BoxLimits = {
44
- cpus: number;
45
- memory: string;
46
- pidsLimit: number;
47
- };
48
- /** 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
49
- * that every create would fail on (less than a 1 ms quota, less memory than Docker gives, more processes than the kernel
50
- * allows), throws, naming its setting: the start checks them (startServe), so no run meets one. */
51
- export declare function boxLimitsOf(env: NodeJS.ProcessEnv): BoxLimits;
52
- /** The setting that names the hosts a box may reach: a comma list of hosts, each a name or `*.` and a name, which
53
- * replaces the default list; `none` for no network at all. Unset or empty, the default. */
54
- export declare const BOX_ALLOW_ENV = "AGENTRUN_BOX_ALLOW";
55
- /** The hosts a box reaches when the setting names none: the package registries pip and npm (and yarn) install from, and
56
- * GitHub for a clone or an archive. */
57
- export declare const DEFAULT_BOX_ALLOW: readonly string[];
58
- /** The most hosts the list may hold: Daytona's own limit on a sandbox's domain list. */
59
- export declare const MAX_BOX_ALLOW = 100;
60
- /** The hosts a box may reach, from `env`'s AGENTRUN_BOX_ALLOW: its list, lower-cased, each host once; the default list when
61
- * unset or empty; `none` for no network. `*`, an IP address, a CIDR, a port, a URL, or more than 100 hosts throws, saying
62
- * what the setting takes: the start checks it (startServe), so no run meets one. */
63
- export declare function boxAllowOf(env: NodeJS.ProcessEnv): readonly string[] | "none";
64
- /** What a server's Docker boxes reach, resolved once at its start: the setting's list (boxAllowOf) where egressBlockedBy
65
- * (box-egress.ts) finds the daemon is this Linux machine's own, else none with the reason; `none` from the setting, with
66
- * it as the reason. */
67
- export declare function boxNetworkOf(env: NodeJS.ProcessEnv, options?: Parameters<typeof egressBlockedBy>[1]): Promise<DockerNetwork>;
68
- /** Under `--faux` only: a module whose default export, given the data root, is the provider runs' boxes come from in
69
- * place of Docker (the tests' faux box). */
70
- export declare const FAUX_BOX_ENV = "AGENTRUN_SERVE_FAUX_BOX";
71
- /** 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
72
- * server alone writes it. */
73
- export declare const BOX_SYNC_FILE = "box-sync.json";
74
- /** What the run's process copied into its remote box after the seed (a file its host tools filed in work/): one JSON line
75
- * per file, `{path, sha256, bytes}`, appended by that process alone. The mark has one writer, the server, so the
76
- * process never writes it; a pull folds these lines into the mark it compares against, for paths the mark lacks, so
77
- * the box's later edit of such a file comes back instead of reading as a change the server made. */
78
- export declare const BOX_MIRRORED_FILE = "box-mirrored.jsonl";
79
- /** In a run's directory while the box the server destroyed for a new one has no successor yet (ensureRemoteBox): the
80
- * attempt that makes one says the box was replaced, though the one that destroyed the old box failed after it. */
81
- export declare const BOX_REPLACED_FILE = "box-replaced";
82
- type Mount = NonNullable<BoxSpec["mounts"]>[number];
83
- /** `source`, when it is below `root` through no link and is its own canonical path; else a refusal naming the link.
84
- * `root`, the data root, is canonical already (startServe), so a link above it is the operator's choice. */
85
- export declare function mountSource(root: string, source: string): Promise<string>;
86
- /** Every mount a run's box gets, each through mountSource: its work/ only, read-write, at BOX_WORK. A run's home joins
87
- * this list (read-only parts included) when it comes; nothing else of the data root does. */
88
- export declare function boxMounts(root: string, runDir: string, place: Place): Promise<Mount[]>;
89
- /** The provider runs' boxes come from, what a create of its box waits on first (`ready`, run-box below), and, for a box
90
- * that reaches the server's host list, where it finds its egress proxy (`egress`, box-egress.ts). */
91
- export type RunBoxes = BoxProvider & {
92
- ready?: BoxReady;
93
- egress?: BoxEgress;
94
- net?: string;
95
- };
96
- /** The provider runs' boxes come from: under `--faux` with a faux box, its module's; else Docker on this machine, run as
97
- * 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
98
- * box limits the server's settings give (boxLimitsOf), and whose create first waits while the server pulls its image
99
- * (box-image.ts). */
100
- export declare function runBoxProvider(place: Place, env: NodeJS.ProcessEnv, root: string): Promise<RunBoxes>;
101
- /** What a run's box create waits on first, `note` taking its one timeline row: the server's pull of the Docker image
102
- * (box-image.ts). A faux box has no image, so none. */
103
- export type BoxReady = (context: Context, note: (summary: string) => Promise<void> | void) => Promise<void>;
104
- /** The tests' faux box provider, from its module. */
105
- export declare const fauxBoxes: (module: string, root: string) => Promise<BoxProvider>;
106
- /** A run's box, as its tools' environment: found by its label or made on the first call, once; made again on the call
107
- * after it was lost. A box that cannot be had fails that call; nothing falls back to this machine. Before a local box is
108
- * made, its provider's `ready` is waited on (its image), and the call that opens it gives the `note` for its timeline
109
- * row; a remote box is the server's to make (ensureRemoteBox), and never waits on that. `mirror`, on a remote box: copies
110
- * 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
111
- * its open. */
112
- export type RunBox = {
113
- env(context: Context, note?: (summary: string) => Promise<void> | void): Promise<ExecutionEnv>;
114
- hostWork: string;
115
- bound(): Promise<boolean>;
116
- leftEnded(context: Context): Promise<void>;
117
- mirror?: (path: string, data: string | Uint8Array) => Promise<void>; /** BOX_REPLACED_NOTE once, after this process replaced an earlier process's box; else nothing. */
118
- replaced(): string | undefined;
119
- };
120
- /** 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,
121
- * the server's relay in data root `relay`. A bare function is a provider of this process's own. */
122
- export type BoxSource = {
123
- provider: () => Promise<RunBoxes>;
124
- } | {
125
- relay: string;
126
- };
127
- export declare function runBox(given: BoxSource | (() => Promise<RunBoxes>), run: {
128
- id: string;
129
- root: string;
130
- dir: string;
131
- place: Place;
132
- epoch: number;
133
- }): RunBox;
134
- /** A remote box's limits, where its provider takes them (the VM box: CPUs and memory, from the same settings as a Docker
135
- * box's, boxLimitsOf). */
136
- export type RemoteLimits = {
137
- cpus?: number;
138
- memoryMb?: number;
139
- };
140
- /** A Docker size (boxLimitsOf's memory) in MiB, the fraction dropped. */
141
- export declare const memoryMbOf: (memory: string) => number;
142
- /** 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
143
- * says so); its id, and whether it was made now. A box is made with the host list `allow` names, or with no network when
144
- * it is `none`; a create the provider refuses for its list (NO_LIST) is said to `onNoList` at once, with its refusal's
145
- * code and words (so a closed box or a seed that then fails leaves it said), and made again with no network, never open.
146
- * A found box is kept when it has no network, or the list asked (the same hosts, in any order, as its provider reads
147
- * them); any other (open, unknown, another list or one it does not say, or a list when `none` was asked) is copied back
148
- * whole, then destroyed and made again, so a narrower list holds after a restart. One whose copy back fails or is not
149
- * whole is kept, and the call fails. A box whose seed fails is destroyed, and the call fails. */
150
- /** What ensureRemoteBox takes beyond the run: the wake of a box Daytona stopped, the hosts the box may reach (`none` for
151
- * none), who hears a refused list, and the copy back a found box gets before it is replaced (pullRemoteBox). */
152
- export type RemoteBoxOptions = {
153
- wake?: () => Promise<number>;
154
- allow?: readonly string[] | "none";
155
- onNoList?: (code: string, message: string) => void;
156
- pull?: (boxes: BoxProvider, run: {
157
- id: string;
158
- dir: string;
159
- }, context: Context, wake?: () => Promise<number>) => Promise<unknown>;
160
- /** The box's limits, where its provider takes them (remoteSpec). */
161
- limits?: RemoteLimits;
162
- };
163
- export declare function ensureRemoteBox(boxes: BoxProvider, run: {
164
- id: string;
165
- dir: string;
166
- }, context: Context, options?: RemoteBoxOptions): Promise<{
167
- id: string;
168
- made: boolean;
169
- replaced?: boolean;
170
- }>;
171
- /** What a pull of a remote box brought back; undefined when the run has no box (none made, or it is gone). */
172
- export type RemotePull = {
173
- -readonly [K in "changed" | "files" | "bytes" | "removed"]: PullReceipt[K];
174
- };
175
- /** 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.
176
- * `lasting`: a stop another pull will meet again (an archive the extractor cannot read, or a limit a pull that wrote
177
- * nothing reached); else the copy failed, and a later pull may land. */
178
- export declare class PullIncomplete extends Error {
179
- readonly lasting: boolean;
180
- /** The box that keeps what did not come back. */
181
- readonly box: string;
182
- constructor(message: string, lasting: boolean, box: string);
183
- }
184
- /** 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
185
- * safe extractor (nothing outside work/, no link, safe names only). A file this machine changed since the mark stays
186
- * (`if_unchanged`), and what the box removed is removed here too. A pull a limit stopped after it wrote something is
187
- * followed by another, which asks only for the rest. Throws when the copy fails (the mark kept), and PullIncomplete when
188
- * it is not whole: a caller then keeps the box. */
189
- export declare function pullRemoteBox(boxes: BoxProvider, run: {
190
- id: string;
191
- dir: string;
192
- }, context: Context, wake?: () => Promise<number>): Promise<RemotePull | undefined>;
193
- /** The fence of a run's boxes for a process under claim epoch `run.epoch`: every box of the run whose epoch is lower (or
194
- * that has none: made before boxes had one) is destroyed; how many. One of a higher epoch is a later process's: this
195
- * one is not the run's holder, so it throws, and makes and destroys nothing. */
196
- export declare function fenceRunBoxes(boxes: BoxProvider, run: {
197
- id: string;
198
- epoch: number;
199
- }, context: Context): Promise<number>;
200
- /** Destroys every box labelled with run `runId`; how many it destroyed. */
201
- export declare function destroyRunBoxes(boxes: BoxProvider, runId: string, context: Context): Promise<number>;
202
- /** The start's sweep: destroys every run's box whose run `ended` says is over, once `before` (a remote box's pull) for its
203
- * 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
204
- * made. */
205
- export declare function sweepRunBoxes(boxes: BoxProvider, ended: (runId: string) => boolean, context: Context, before?: (runId: string, boxId: string) => Promise<boolean>): Promise<number>;