@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.58

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 (108) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +64 -33
  3. package/dist/api-only.d.ts +2 -4
  4. package/dist/api-only.js +2 -4
  5. package/dist/box-paths.d.ts +4 -3
  6. package/dist/box-paths.js +7 -4
  7. package/dist/claude-login-token.d.ts +117 -0
  8. package/dist/claude-login-token.js +737 -0
  9. package/dist/claude-login.d.ts +52 -12
  10. package/dist/claude-login.js +164 -39
  11. package/dist/cli.js +7 -41
  12. package/dist/computer-attach.d.ts +35 -17
  13. package/dist/computer-attach.js +301 -49
  14. package/dist/computers.d.ts +10 -10
  15. package/dist/computers.js +5 -5
  16. package/dist/console/assets/{backend-DVhHzJX2.js → backend-CSAWUqtZ.js} +1 -1
  17. package/dist/console/assets/index-DPh29cyz.js +747 -0
  18. package/dist/console/index.html +1 -1
  19. package/dist/dial-relay.d.ts +25 -4
  20. package/dist/dial-relay.js +129 -1
  21. package/dist/env-switch.d.ts +1 -3
  22. package/dist/env-switch.js +1 -3
  23. package/dist/fal-price.d.ts +1 -3
  24. package/dist/fal-price.js +77 -26
  25. package/dist/learn/ledger.d.ts +170 -0
  26. package/dist/learn/ledger.js +218 -0
  27. package/dist/learn/promote.d.ts +3 -3
  28. package/dist/learn/promote.js +1 -1
  29. package/dist/learning-cost.d.ts +22 -20
  30. package/dist/learning-cost.js +15 -21
  31. package/dist/live-reach.d.ts +2 -0
  32. package/dist/live-reach.js +2 -0
  33. package/dist/mcp-api-only-origins.d.ts +8 -3
  34. package/dist/mcp-api-only-origins.js +17 -17
  35. package/dist/micro.d.ts +2 -0
  36. package/dist/micro.js +2 -0
  37. package/dist/model.d.ts +5 -4
  38. package/dist/model.js +7 -6
  39. package/dist/monid.d.ts +14 -1
  40. package/dist/monid.js +103 -26
  41. package/dist/openapi.js +34 -12
  42. package/dist/place-offers.d.ts +4 -0
  43. package/dist/place-offers.js +7 -4
  44. package/dist/provider.d.ts +2 -2
  45. package/dist/provider.js +9 -5
  46. package/dist/run-learning-served.d.ts +2 -2
  47. package/dist/run-view.d.ts +1 -2
  48. package/dist/run-view.js +2 -1
  49. package/dist/runner/adapter-loop.js +3 -16
  50. package/dist/runner/adapter-run-spec.d.ts +20 -13
  51. package/dist/runner/adapter-run-spec.js +57 -48
  52. package/dist/runner/beside.d.ts +9 -2
  53. package/dist/runner/beside.js +24 -7
  54. package/dist/runner/claim-secrets.d.ts +17 -15
  55. package/dist/runner/claim-secrets.js +32 -34
  56. package/dist/runner/cli-run-spec.js +21 -9
  57. package/dist/runner/held.d.ts +16 -4
  58. package/dist/runner/main.d.ts +11 -6
  59. package/dist/runner/main.js +12 -7
  60. package/dist/runner/mcp-claim.js +3 -2
  61. package/dist/runner/mcp-run.d.ts +3 -6
  62. package/dist/runner/mcp-run.js +3 -4
  63. package/dist/runner/presence.d.ts +11 -1
  64. package/dist/runner/presence.js +7 -0
  65. package/dist/runner/reflect-hook.js +1 -1
  66. package/dist/runner/run-child-host.d.ts +19 -8
  67. package/dist/runner/run-child-host.js +80 -34
  68. package/dist/runner/runner.d.ts +3 -0
  69. package/dist/runner/runner.js +1 -1
  70. package/dist/runner/save-slots.js +2 -1
  71. package/dist/runner/subagent.d.ts +11 -0
  72. package/dist/runner/subagent.js +17 -3
  73. package/dist/runner/workflow-first.d.ts +27 -14
  74. package/dist/runner/workflow-first.js +29 -22
  75. package/dist/runner/workflow-spec.js +1 -1
  76. package/dist/server.d.ts +18 -7
  77. package/dist/server.js +150 -64
  78. package/dist/slots.d.ts +9 -0
  79. package/dist/slots.js +45 -0
  80. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  81. package/dist/store/schema.d.ts +17 -0
  82. package/dist/store/schema.js +47 -1
  83. package/dist/store/sqlite/run-patch.d.ts +11 -1
  84. package/dist/store/sqlite/run-patch.js +29 -1
  85. package/dist/store/sqlite/store.js +72 -9
  86. package/dist/store/store.d.ts +14 -0
  87. package/dist/store-reads/learning.d.ts +81 -124
  88. package/dist/store-reads/learning.js +207 -286
  89. package/dist/template-eval.d.ts +19 -0
  90. package/dist/template-eval.js +92 -43
  91. package/dist/template-import.d.ts +0 -10
  92. package/dist/template-import.js +5 -10
  93. package/dist/timeline/web-calls.d.ts +12 -14
  94. package/dist/timeline/web-calls.js +14 -30
  95. package/dist/web-save.d.ts +4 -9
  96. package/dist/web-save.js +4 -43
  97. package/dist/workspace/attached-computers.d.ts +32 -9
  98. package/dist/workspace/attached-computers.js +77 -13
  99. package/dist/workspace/computer-deps.d.ts +6 -1
  100. package/dist/workspace/computer-deps.js +1 -1
  101. package/dist/workspace/computer-for-claim.js +6 -3
  102. package/dist/workspace/paired-route.d.ts +91 -0
  103. package/dist/workspace/paired-route.js +153 -0
  104. package/dist/wrapped.d.ts +8 -2
  105. package/dist/wrapped.js +21 -6
  106. package/package.json +12 -12
  107. package/templates/README.md +3 -3
  108. package/dist/console/assets/index-okP-y8PK.js +0 -747
@@ -271,6 +271,25 @@ export declare function apiOf(baseUrl: string, token: string): Api;
271
271
  export declare const CLAIM_READ_TIMEOUT_MS = 10000;
272
272
  /** The least time between two of those reads of one run. */
273
273
  export declare const CLAIM_READ_EVERY_MS = 5000;
274
+ /** How long that read may take: its wait, and 10 s for the answer to arrive. */
275
+ export declare const PAGE_READ_TIMEOUT_MS: number;
276
+ /** The bound of a read in waitRun made at `now`: `capMs`, or the time left to `deadline` when that is less (`ms`, whole
277
+ * milliseconds and never below 0, as AbortSignal.timeout takes them), and whether the time left is what bounds it
278
+ * (`atDeadline`). */
279
+ export declare function readBound(deadline: number, capMs: number, now: number): {
280
+ ms: number;
281
+ atDeadline: boolean;
282
+ };
283
+ /** A run waited for: its rows until it ends (completed, failed, cancelled) or waits on a person (input_required), or
284
+ * `deadline` passes (then it is cancelled). A stop of the eval (`signal`) cancels it too, and throws. Each of its reads
285
+ * ends at the deadline and at the stop (bounded), so a server that stalls one never holds the wait past either.
286
+ * Exported for its tests. */
287
+ export declare function waitRun(api: Api, runId: string, deadline: number, signal?: AbortSignal, queueTimeoutMs?: number): Promise<{
288
+ status: string;
289
+ rows: Json[];
290
+ waiting?: string;
291
+ why?: string;
292
+ }>;
274
293
  /** A run's tool calls, each named as a grader names it: the gate's own rule (RunGate.enter), its settings key, but a
275
294
  * shell tool held to bash's setting (bash_background, bash_output, ...) keeps its own name, so its grader sees it. A
276
295
  * call on a saved server `toolkits` names ({<saved server>: <the package's toolkit>}, a need an owner's server filled
@@ -1042,17 +1042,41 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1042
1042
  export const CLAIM_READ_TIMEOUT_MS = 10_000;
1043
1043
  /** The least time between two of those reads of one run. */
1044
1044
  export const CLAIM_READ_EVERY_MS = 5_000;
1045
- /** Whether a runner holds the run now (the run read's `claim`); undefined when the read fails, takes over
1046
- * CLAIM_READ_TIMEOUT_MS, runs past the run's `deadline` or is stopped by `signal` (the eval's stop): not known, so never
1047
- * a reason to cancel the run. Its bound ends at the deadline, so a read that stalls never puts the cancel past it. */
1045
+ /** How long a timeline page read asks the server to wait for a new row (its wait_ms). */
1046
+ const PAGE_WAIT_MS = 5_000;
1047
+ /** How long that read may take: its wait, and 10 s for the answer to arrive. */
1048
+ export const PAGE_READ_TIMEOUT_MS = PAGE_WAIT_MS + 10_000;
1049
+ /** The bound of a read in waitRun made at `now`: `capMs`, or the time left to `deadline` when that is less (`ms`, whole
1050
+ * milliseconds and never below 0, as AbortSignal.timeout takes them), and whether the time left is what bounds it
1051
+ * (`atDeadline`). */
1052
+ export function readBound(deadline, capMs, now) {
1053
+ const left = deadline - now;
1054
+ return left < capMs ? { ms: Math.max(0, Math.ceil(left)), atDeadline: true } : { ms: capMs, atDeadline: false };
1055
+ }
1056
+ /** A read in waitRun, bounded as readBound says and by the eval's stop (`stop`): the `signal` its request takes, whether
1057
+ * to `send` it at all (not with no time left), and `byDeadline()`, true once the deadline ended it. The wait takes that
1058
+ * as its end, with no second read of the clock: the timer runs on a monotonic clock in whole milliseconds, and
1059
+ * Date.now() can still read a millisecond short of the deadline when it fires. */
1060
+ function bounded(deadline, capMs, stop) {
1061
+ const { ms, atDeadline } = readBound(deadline, capMs, Date.now());
1062
+ const timeout = AbortSignal.timeout(ms);
1063
+ return { signal: stop ? AbortSignal.any([stop, timeout]) : timeout, send: ms > 0, byDeadline: () => atDeadline && (ms === 0 || timeout.aborted) };
1064
+ }
1065
+ /** Whether a runner holds the run now (the run read's `claim`): "deadline" when the read ran to the run's `deadline`, or
1066
+ * there was no time left to send it; undefined when it fails, takes over CLAIM_READ_TIMEOUT_MS or is stopped by
1067
+ * `signal` (the eval's stop): not known, so never a reason to cancel the run as unheld. */
1048
1068
  async function heldNow(api, runId, deadline, signal) {
1049
- const timeout = AbortSignal.timeout(Math.max(0, Math.min(CLAIM_READ_TIMEOUT_MS, deadline - Date.now())));
1050
- const read = await api("GET", `/runs/${runId}`, undefined, {}, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout }).catch(() => undefined);
1051
- return read?.status === 200 && isObject(read.body) ? isObject(read.body.claim) : undefined;
1069
+ const read = bounded(deadline, CLAIM_READ_TIMEOUT_MS, signal);
1070
+ const answered = read.send ? await api("GET", `/runs/${runId}`, undefined, {}, { signal: read.signal }).catch(() => undefined) : undefined;
1071
+ if (read.byDeadline())
1072
+ return "deadline";
1073
+ return answered?.status === 200 && isObject(answered.body) ? isObject(answered.body.claim) : undefined;
1052
1074
  }
1053
1075
  /** A run waited for: its rows until it ends (completed, failed, cancelled) or waits on a person (input_required), or
1054
- * `deadline` passes (then it is cancelled). A stop of the eval (`signal`) cancels it too, and throws. */
1055
- async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIMEOUT_MS) {
1076
+ * `deadline` passes (then it is cancelled). A stop of the eval (`signal`) cancels it too, and throws. Each of its reads
1077
+ * ends at the deadline and at the stop (bounded), so a server that stalls one never holds the wait past either.
1078
+ * Exported for its tests. */
1079
+ export async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIMEOUT_MS) {
1056
1080
  const view = new Map();
1057
1081
  let after = 0;
1058
1082
  const started = Date.now();
@@ -1062,55 +1086,75 @@ async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIME
1062
1086
  // page asks (at most one read in CLAIM_READ_EVERY_MS): a claim can lapse for a moment on a stalled machine (not renewed
1063
1087
  // in time, then claimed again), so one read that finds none never ends the wait. The run is cancelled only when reads
1064
1088
  // found no runner holding it from the first such read to one queueTimeoutMs later, none between them finding one. A read
1065
- // that doesn't answer (failed, stalled past its bound or the deadline, or stopped) says neither, and the stop and the
1066
- // deadline still end the wait.
1089
+ // that doesn't answer (failed, stalled past its bound, or stopped) says neither.
1067
1090
  let unheldSince = started;
1068
1091
  let everHeld = false;
1069
1092
  let askedAt = -Infinity;
1093
+ let rows = [];
1094
+ let state;
1070
1095
  for (;;) {
1071
1096
  if (signal?.aborted) {
1072
1097
  await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1073
1098
  signal.throwIfAborted();
1074
1099
  }
1075
1100
  // calls=whole: each call's arguments and its output, whole to CALL_RESULT_CHARS (tool_input, tool_result_text), which its graders read.
1076
- // CALLS_PAGE_ROWS rows a page, the most a calls=whole page holds (an older server's default is 500).
1077
- const page = expectOk(`reading run ${runId}'s timeline`, await api("GET", `/runs/${runId}/timeline?after=${after}&wait_ms=5000&calls=whole&limit=${CALLS_PAGE_ROWS}`));
1078
- if (page.reset)
1079
- view.clear();
1080
- for (const id of page.drop ?? [])
1081
- view.delete(id);
1082
- for (const row of page.rows ?? [])
1083
- view.set(String(row.id), row);
1084
- after = Number(page.next_after ?? after);
1085
- const rows = [...view.values()].sort((a, b) => Number(a.seq ?? 0) - Number(b.seq ?? 0));
1086
- const status = String(page.status);
1087
- if (ENDED.includes(status) && page.final && !page.has_more)
1088
- return { status, rows };
1089
- if (status === "input_required" && !page.has_more) {
1090
- const waiting = rows.findLast((row) => row.kind === "waiting");
1091
- return { status, rows, waiting: typeof waiting?.summary === "string" ? waiting.summary : "it waits on a person" };
1092
- }
1093
- if (status === "queued" && (everHeld || Date.now() - started > queueTimeoutMs) && Date.now() - askedAt >= CLAIM_READ_EVERY_MS) {
1094
- askedAt = Date.now();
1095
- const held = await heldNow(api, runId, deadline, signal);
1096
- if (held === true) {
1097
- everHeld = true;
1098
- unheldSince = undefined;
1101
+ // CALLS_PAGE_ROWS rows a page, the most a calls=whole page holds (an older server's default is 500). A page its bound
1102
+ // cut (stalled past PAGE_READ_TIMEOUT_MS, run to the deadline, or stopped) is no page: it is asked again, unless the
1103
+ // stop or the deadline below ends the wait.
1104
+ const read = bounded(deadline, PAGE_READ_TIMEOUT_MS, signal);
1105
+ const answered = read.send
1106
+ ? await api("GET", `/runs/${runId}/timeline?after=${after}&wait_ms=${PAGE_WAIT_MS}&calls=whole&limit=${CALLS_PAGE_ROWS}`, undefined, {}, { signal: read.signal }).catch((error) => {
1107
+ if (read.signal.aborted)
1108
+ return undefined;
1109
+ throw error;
1110
+ })
1111
+ : undefined;
1112
+ let timedOut = read.byDeadline();
1113
+ const page = answered === undefined ? undefined : expectOk(`reading run ${runId}'s timeline`, answered);
1114
+ if (page) {
1115
+ if (page.reset)
1116
+ view.clear();
1117
+ for (const id of page.drop ?? [])
1118
+ view.delete(id);
1119
+ for (const row of page.rows ?? [])
1120
+ view.set(String(row.id), row);
1121
+ after = Number(page.next_after ?? after);
1122
+ rows = [...view.values()].sort((a, b) => Number(a.seq ?? 0) - Number(b.seq ?? 0));
1123
+ state = page.state;
1124
+ const status = String(page.status);
1125
+ if (ENDED.includes(status) && page.final && !page.has_more)
1126
+ return { status, rows };
1127
+ if (status === "input_required" && !page.has_more) {
1128
+ const waiting = rows.findLast((row) => row.kind === "waiting");
1129
+ return { status, rows, waiting: typeof waiting?.summary === "string" ? waiting.summary : "it waits on a person" };
1099
1130
  }
1100
- else if (held === false) {
1101
- unheldSince ??= askedAt;
1102
- if (Date.now() - unheldSince >= queueTimeoutMs) {
1103
- await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1104
- return { status: "timed_out", rows, why: `the run stayed queued for ${Math.round(queueTimeoutMs / 1000)} s with no runner holding it, and it was cancelled` };
1131
+ if (status === "queued" && (everHeld || Date.now() - started > queueTimeoutMs) && Date.now() - askedAt >= CLAIM_READ_EVERY_MS) {
1132
+ askedAt = Date.now();
1133
+ const held = await heldNow(api, runId, deadline, signal);
1134
+ if (held === "deadline")
1135
+ timedOut = true;
1136
+ else if (held === true) {
1137
+ everHeld = true;
1138
+ unheldSince = undefined;
1139
+ }
1140
+ else if (held === false) {
1141
+ unheldSince ??= askedAt;
1142
+ if (Date.now() - unheldSince >= queueTimeoutMs) {
1143
+ await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1144
+ return { status: "timed_out", rows, why: `the run stayed queued for ${Math.round(queueTimeoutMs / 1000)} s with no runner holding it, and it was cancelled` };
1145
+ }
1105
1146
  }
1106
1147
  }
1107
1148
  }
1108
- // At the deadline, not only past it: the claim read's bound ends at the deadline, and may end in its very millisecond.
1109
- if (Date.now() >= deadline) {
1110
- await api("POST", `/runs/${runId}/cancel`, {});
1111
- return { status: "timed_out", rows, why: `the run took longer than ${Math.round((deadline - started) / 1000)} s (state ${String(page.state)} when the wait gave up) and was cancelled` };
1149
+ if (signal?.aborted)
1150
+ continue;
1151
+ // A read the deadline ended, or the clock at the deadline, not only past it. A cancel that fails is sent again once the
1152
+ // wait's answer is settled (settle cancels a run not ended): the wait still ends timed out.
1153
+ if (timedOut || Date.now() >= deadline) {
1154
+ await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1155
+ return { status: "timed_out", rows, why: `the run took longer than ${Math.round((deadline - started) / 1000)} s (state ${String(state ?? "unknown")} when the wait gave up) and was cancelled` };
1112
1156
  }
1113
- if (page.has_more !== true && page.unchanged === true)
1157
+ if (page?.has_more !== true && page?.unchanged === true)
1114
1158
  await sleep(250);
1115
1159
  }
1116
1160
  }
@@ -1239,6 +1283,11 @@ export async function evalTemplate(options) {
1239
1283
  const log = options.log ?? (() => undefined);
1240
1284
  if (options.data !== undefined && options.server)
1241
1285
  throw new Error(ON_DATA_WITH_SERVER);
1286
+ // A NaN bound would never end a wait (no clock reads past it); a fraction of a millisecond is rounded up (readBound).
1287
+ for (const [name, ms] of [["runTimeoutMs", options.runTimeoutMs], ["queueTimeoutMs", options.queueTimeoutMs]]) {
1288
+ if (ms !== undefined && !(Number.isFinite(ms) && ms > 0))
1289
+ throw new RangeError(`${name} is a time in milliseconds over 0, not ${ms}`);
1290
+ }
1242
1291
  const { pkg, cases } = readCases(options.dir, options.cases);
1243
1292
  if (options.graderModel !== undefined && !MODEL_REF.test(options.graderModel))
1244
1293
  throw new CaseError(options.dir, [`--grader-model is "provider/model-id", not ${options.graderModel}`]);
@@ -25,16 +25,6 @@ export declare function loadImported(deps: Pick<TemplateImportDeps, "registry" |
25
25
  /** The uploads served here whose row the store no longer keeps (an agent's purge removed it: Agents.purge), no longer
26
26
  * served. Only the package read before the store is removed, so an upload put in meanwhile stays served. */
27
27
  export declare function dropRemovedUploads(deps: Pick<TemplateImportDeps, "registry" | "store">): Promise<void>;
28
- /** An upload: its files checked as an import's are, its id `upload:<name>` (its manifest's name), its sha the package's
29
- * sha256; a dry run answers it, storing nothing; else it is stored and served (201), in place of the one of its name. */
30
- /** An upload's files ({files} of POST /v2/templates/import) checked as the import checks them, storing nothing: the
31
- * package's bytes by path (each hidden path left out) and the package read from them; else the refusal the route answers
32
- * (422). `agentrun deploy` runs this on the body it is about to send (agentrun-serve check-upload), so a package a target
33
- * refuses is refused before anything is sent, by this one check. */
34
- export declare function checkUpload(raw: unknown): {
35
- files: Map<string, Buffer>;
36
- pkg: Package;
37
- };
38
28
  /** POST /v2/templates/import: the package read at its source's commit and checked; a dry run answers it, storing nothing;
39
29
  * else it is stored and served (201), in place of the one under its id. `signal` ends the read (the request's). An
40
30
  * upload ({files}) is uploadTemplate's. */
@@ -163,23 +163,18 @@ function bodyOf(body, apiOnly) {
163
163
  }
164
164
  /** An upload: its files checked as an import's are, its id `upload:<name>` (its manifest's name), its sha the package's
165
165
  * sha256; a dry run answers it, storing nothing; else it is stored and served (201), in place of the one of its name. */
166
- /** An upload's files ({files} of POST /v2/templates/import) checked as the import checks them, storing nothing: the
167
- * package's bytes by path (each hidden path left out) and the package read from them; else the refusal the route answers
168
- * (422). `agentrun deploy` runs this on the body it is about to send (agentrun-serve check-upload), so a package a target
169
- * refuses is refused before anything is sent, by this one check. */
170
- export function checkUpload(raw) {
166
+ async function uploadTemplate(deps, raw, dryRun) {
167
+ let pkg;
168
+ let files;
171
169
  try {
172
- const files = uploadFiles(raw);
170
+ files = uploadFiles(raw);
173
171
  const name = manifestOf(files.get(MANIFEST)?.toString("utf8") ?? "")?.name;
174
172
  const id = `${UPLOAD_PREFIX}${typeof name === "string" ? name : ""}`;
175
- return { files, pkg: importedPackage(id, { source: id, sha: uploadSha(files), publisher: "" }, files) };
173
+ pkg = importedPackage(id, { source: id, sha: uploadSha(files), publisher: "" }, files);
176
174
  }
177
175
  catch (error) {
178
176
  refusalOf(error);
179
177
  }
180
- }
181
- async function uploadTemplate(deps, raw, dryRun) {
182
- const { files, pkg } = checkUpload(raw);
183
178
  const replaced = deps.registry.get(pkg.id)?.origin?.sha ?? null;
184
179
  if (dryRun)
185
180
  return { status: 200, pkg, trusted: true, replaced };
@@ -1,19 +1,18 @@
1
+ /** The names eachString has tried for a property, counted so a test can bound the work, not time it. */
2
+ export declare const namesTried: {
3
+ count: number;
4
+ };
1
5
  /** A web call's output with each text that gives way cut to `keep` characters (a cut one ending "…"), the rest whole. */
2
6
  export type WebShown = (keep: number) => string;
3
7
  /** Whether a text holds a held value no cut in place takes (key-refusal.ts withheldWhole): `joined` is `parts` joined
4
8
  * by line breaks, for a reader that reads each part by itself too (adapter-run-spec.ts answersCut). */
5
9
  export type WebHolds = (joined: string, parts: readonly string[]) => boolean;
6
- /** Whether `text`, a web call's output, is withheld whole: `holds` (whether a text holds a held value no cut in place
7
- * takes: key-refusal.ts withheldWhole) reads its JSON's strings as they came joined by line breaks, then the lines after
8
- * the JSON: once its values alone, so two values side by side in the output are side by side in the join, and once with
9
- * each property name before its value, so a name and its value are too. Each string is cut on its own wherever the
10
- * output is shown (webCut, webShownOf), and the JSON's punctuation between two strings is no whitespace any view of the
11
- * whole text joins across, so a held value split across two of them is found only here. The strings are read in the
12
- * order the output is written back in (stringsOf: what webCut stores and webShownOf shows), and, where that differs
13
- * (an integer-like name, a name written twice), in the order the text was written too (writtenStrings: what a row's
14
- * preview shows of the text as it came). Every reader of a web call's output asks this first: the runner before it
15
- * stores the answer (adapter-run-spec.ts answersCut), a timeline before its row shows any of it (timeline.ts shownOf,
16
- * resultText). False for an output that is not a web call's JSON. */
10
+ /** Whether `text`, a web call's output, is withheld whole: `holds` (key-refusal.ts withheldWhole) finds a held value in
11
+ * its JSON's strings joined by line breaks (false for an output that is not a web call's JSON). They are read in the
12
+ * order the output is written back in (stringsOf) and, where that differs, in the order it was written (writtenStrings).
13
+ * Every reader asks this first: the runner before it stores the answer (answersCut), a timeline before its row shows.
14
+ * Each string is cut on its own wherever the output is shown, and no view joins across the JSON's punctuation between
15
+ * two strings, so a held value split across two of them is found only here. */
17
16
  export declare function webHeld(tool: string, text: string, holds: WebHolds): boolean;
18
17
  /** `text`, a call of `tool`'s output, with `cut` (the run's redactor) applied to each string of its JSON by itself, its
19
18
  * property names too, and to the lines after it, never to its JSON line whole: the redactor reads a run of more than
@@ -26,9 +25,8 @@ export declare function webCut(tool: string, text: string, cut: (text: string) =
26
25
  /** `text`, a call of `tool`'s output, as a grader reads it (WebShown), each of its strings through `each` first (the
27
26
  * run's redaction, its URLs' query values elided), so a cut never falls inside what that takes out. Undefined for a
28
27
  * tool other than web_search and web_fetch, or an output that is not its JSON. A page's links past a cut are counted
29
- * in `links_cut`. With `holds`, an output it withholds (webHeld: a held value split across two strings, which `each`
30
- * reads one at a time) shows "[redacted]". */
31
- export declare function webShownOf(tool: string, text: string, each?: (text: string) => string, holds?: WebHolds): WebShown | undefined;
28
+ * in `links_cut`. */
29
+ export declare function webShownOf(tool: string, text: string, each?: (text: string) => string): WebShown | undefined;
32
30
  /** `shown` in `room` characters: whole when it fits, else each text that gives way cut to the longest length that
33
31
  * fits, the same for each; past `room` only when its url lists alone pass it, every such text then cut to nothing. */
34
32
  export declare function webWithin(shown: WebShown, room: number): string;
@@ -1,5 +1,7 @@
1
1
  const WEB_SEARCH = "web_search";
2
2
  const WEB_FETCH = "web_fetch";
3
+ /** The names eachString has tried for a property, counted so a test can bound the work, not time it. */
4
+ export const namesTried = { count: 0 };
3
5
  const isObj = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
6
  /** `text` cut to `keep` characters and marked, never splitting a surrogate pair. */
5
7
  function clip(text, keep) {
@@ -9,9 +11,7 @@ function clip(text, keep) {
9
11
  return `${text.slice(0, code >= 0xd800 && code <= 0xdbff ? keep - 1 : keep)}…`;
10
12
  }
11
13
  /** Every string in `value` through `each`, property names too (a tool may write a value as one): two names `each` makes
12
- * one are both kept, the later ones numbered, as the runner's cutDeep keeps them (runner/redact.ts). Each name's next
13
- * number is kept (`next`), so k names that cut to one cost k lookups, not k²/2: no name is ever taken back, so every
14
- * number below it is still taken, and the one it finds is the lowest free one, as a count from 2 finds. */
14
+ * one are both kept, the later ones numbered, as the runner's cutDeep keeps them (runner/redact.ts). */
15
15
  function eachString(value, each) {
16
16
  if (typeof value === "string")
17
17
  return each(value);
@@ -24,13 +24,10 @@ function eachString(value, each) {
24
24
  for (const [key, item] of Object.entries(value)) {
25
25
  const once = each(key);
26
26
  let name = once;
27
- if (Object.hasOwn(out, name)) {
28
- next ??= new Map();
29
- let n = next.get(once) ?? 2;
30
- while (Object.hasOwn(out, `${once} (${n})`))
31
- n++;
27
+ // Each name's count goes on from its last free number: no name is taken back, so every number below it is still taken.
28
+ for (let n = next?.get(once) ?? 2; (namesTried.count++, Object.hasOwn(out, name)); n++) {
32
29
  name = `${once} (${n})`;
33
- next.set(once, n + 1);
30
+ (next ??= new Map()).set(once, n + 1);
34
31
  }
35
32
  Object.defineProperty(out, name, { value: eachString(item, each), enumerable: true, writable: true, configurable: true });
36
33
  }
@@ -81,17 +78,12 @@ function webRead(tool, text) {
81
78
  }
82
79
  return isObj(read) ? { read, end } : undefined;
83
80
  }
84
- /** Whether `text`, a web call's output, is withheld whole: `holds` (whether a text holds a held value no cut in place
85
- * takes: key-refusal.ts withheldWhole) reads its JSON's strings as they came joined by line breaks, then the lines after
86
- * the JSON: once its values alone, so two values side by side in the output are side by side in the join, and once with
87
- * each property name before its value, so a name and its value are too. Each string is cut on its own wherever the
88
- * output is shown (webCut, webShownOf), and the JSON's punctuation between two strings is no whitespace any view of the
89
- * whole text joins across, so a held value split across two of them is found only here. The strings are read in the
90
- * order the output is written back in (stringsOf: what webCut stores and webShownOf shows), and, where that differs
91
- * (an integer-like name, a name written twice), in the order the text was written too (writtenStrings: what a row's
92
- * preview shows of the text as it came). Every reader of a web call's output asks this first: the runner before it
93
- * stores the answer (adapter-run-spec.ts answersCut), a timeline before its row shows any of it (timeline.ts shownOf,
94
- * resultText). False for an output that is not a web call's JSON. */
81
+ /** Whether `text`, a web call's output, is withheld whole: `holds` (key-refusal.ts withheldWhole) finds a held value in
82
+ * its JSON's strings joined by line breaks (false for an output that is not a web call's JSON). They are read in the
83
+ * order the output is written back in (stringsOf) and, where that differs, in the order it was written (writtenStrings).
84
+ * Every reader asks this first: the runner before it stores the answer (answersCut), a timeline before its row shows.
85
+ * Each string is cut on its own wherever the output is shown, and no view joins across the JSON's punctuation between
86
+ * two strings, so a held value split across two of them is found only here. */
95
87
  export function webHeld(tool, text, holds) {
96
88
  const web = webRead(tool, text);
97
89
  return web ? heldIn(web, text, holds) : false;
@@ -112,8 +104,6 @@ function heldIn(web, text, holds) {
112
104
  }
113
105
  /** Whether two lists hold the same strings in the same order. */
114
106
  const sameStrings = (a, b) => a.length === b.length && a.every((one, i) => one === b[i]);
115
- /** What a web call withheld whole shows. */
116
- const WITHHELD = () => "[redacted]";
117
107
  /** How many of `links`, in order, fit in `keep` characters of JSON. */
118
108
  function linksWithin(links, keep) {
119
109
  let used = 0;
@@ -142,21 +132,17 @@ export function webCut(tool, text, cut, holds) {
142
132
  /** `text`, a call of `tool`'s output, as a grader reads it (WebShown), each of its strings through `each` first (the
143
133
  * run's redaction, its URLs' query values elided), so a cut never falls inside what that takes out. Undefined for a
144
134
  * tool other than web_search and web_fetch, or an output that is not its JSON. A page's links past a cut are counted
145
- * in `links_cut`. With `holds`, an output it withholds (webHeld: a held value split across two strings, which `each`
146
- * reads one at a time) shows "[redacted]". */
147
- export function webShownOf(tool, text, each = (part) => part, holds) {
135
+ * in `links_cut`. */
136
+ export function webShownOf(tool, text, each = (part) => part) {
148
137
  const web = webRead(tool, text);
149
138
  if (!web)
150
139
  return undefined;
151
140
  const shown = eachString(web.read, each);
152
141
  const after = web.end < 0 ? "" : each(text.slice(web.end));
153
- const withheld = () => (holds ? heldIn(web, text, holds) : false);
154
142
  if (tool === WEB_SEARCH) {
155
143
  const results = shown.results;
156
144
  if (!Array.isArray(results) || !results.every(isObj))
157
145
  return undefined;
158
- if (withheld())
159
- return WITHHELD;
160
146
  return (keep) => {
161
147
  const hits = results.map((hit) => (typeof hit.snippet === "string" ? { ...hit, snippet: clip(hit.snippet, keep) } : hit));
162
148
  return `${JSON.stringify({ ...shown, ...(typeof shown.text === "string" ? { text: clip(shown.text, keep) } : {}), results: hits })}${after}`;
@@ -166,8 +152,6 @@ export function webShownOf(tool, text, each = (part) => part, holds) {
166
152
  return undefined;
167
153
  const page = shown;
168
154
  const links = Array.isArray(page.links) ? page.links : undefined;
169
- if (withheld())
170
- return WITHHELD;
171
155
  return (keep) => {
172
156
  const kept = links ? linksWithin(links, keep) : 0;
173
157
  const cut = links ? links.length - kept : 0;
@@ -3,6 +3,7 @@ import type { TSchema } from "typebox";
3
3
  import { type ToolRegistration } from "@earendil-works/pi-durable";
4
4
  import type { PublicFetchOptions } from "@parcha/pi-browser";
5
5
  import { type Workspace } from "./workspace/index.js";
6
+ import { type Slots as SaveSlots } from "./slots.js";
6
7
  export declare const WEB_SAVE_TOOL = "web_save";
7
8
  /** The most bytes a saved file may have. */
8
9
  export declare const SAVE_MAX_BYTES: number;
@@ -51,15 +52,9 @@ export type SaveOptions = Omit<PublicFetchOptions, "maxBytes"> & {
51
52
  * that at the peak when it does not (publicDownload). So a runner's downloads hold at most 800 MiB at 200 MiB a file,
52
53
  * about 1.6 GiB when no host states a length; Mode 2's pieced writes (runner/big-writes.ts) can add 800 MiB more. */
53
54
  export declare const SAVE_CONCURRENCY = 4;
54
- /** Slots for downloads, handed out first come first served. `take` answers the slot's release (once), or rejects with
55
- * the signal's reason if it aborts first, leaving the queue. */
56
- export type SaveSlots = {
57
- readonly size: number;
58
- readonly busy: number;
59
- readonly waiting: number;
60
- take(signal: AbortSignal): Promise<() => void>;
61
- };
62
- export declare function saveSlots(size: number): SaveSlots;
55
+ /** Slots for downloads (slots.ts): `take` answers the slot's release, or rejects with the signal's reason if it aborts
56
+ * first. Re-exported here under web_save's names for its callers. */
57
+ export { type Slots as SaveSlots, slots as saveSlots } from "./slots.js";
63
58
  /** The runner's one gate: at most SAVE_CONCURRENCY downloads at once per runner, across its runs. A run in the runner's
64
59
  * own process takes it here; a run in a process of its own takes it over its channel (runner/save-slots.ts). */
65
60
  export declare const SERVER_SLOTS: SaveSlots;
package/dist/web-save.js CHANGED
@@ -8,6 +8,7 @@ import { mediaSeconds } from "./media-duration.js";
8
8
  import { clip, URL_MAX } from "@parcha/agentrun-web";
9
9
  import { forModel } from "./result.js";
10
10
  import { isWorkspaceError, workspaceErrorWords } from "./workspace/index.js";
11
+ import { slots as saveSlots } from "./slots.js";
11
12
  export const WEB_SAVE_TOOL = "web_save";
12
13
  /** The most bytes a saved file may have. */
13
14
  export const SAVE_MAX_BYTES = 200 * 1024 * 1024;
@@ -28,49 +29,9 @@ export const LENGTH_TYPES = "mp3, wav, mp4 or m4a";
28
29
  * that at the peak when it does not (publicDownload). So a runner's downloads hold at most 800 MiB at 200 MiB a file,
29
30
  * about 1.6 GiB when no host states a length; Mode 2's pieced writes (runner/big-writes.ts) can add 800 MiB more. */
30
31
  export const SAVE_CONCURRENCY = 4;
31
- export function saveSlots(size) {
32
- let busy = 0;
33
- const queue = [];
34
- const releaser = () => {
35
- let done = false;
36
- return () => {
37
- if (done)
38
- return;
39
- done = true;
40
- // The slot goes straight to the next waiter, so busy only drops when no one waits.
41
- const next = queue.shift();
42
- if (next)
43
- next();
44
- else
45
- busy--;
46
- };
47
- };
48
- return {
49
- size,
50
- get busy() { return busy; },
51
- get waiting() { return queue.length; },
52
- take(signal) {
53
- if (signal.aborted)
54
- return Promise.reject(signal.reason);
55
- if (busy < size) {
56
- busy++;
57
- return Promise.resolve(releaser());
58
- }
59
- return new Promise((resolve, reject) => {
60
- const leave = () => {
61
- queue.splice(queue.indexOf(grant), 1);
62
- reject(signal.reason);
63
- };
64
- const grant = () => {
65
- signal.removeEventListener("abort", leave);
66
- resolve(releaser());
67
- };
68
- queue.push(grant);
69
- signal.addEventListener("abort", leave, { once: true });
70
- });
71
- },
72
- };
73
- }
32
+ /** Slots for downloads (slots.ts): `take` answers the slot's release, or rejects with the signal's reason if it aborts
33
+ * first. Re-exported here under web_save's names for its callers. */
34
+ export { slots as saveSlots } from "./slots.js";
74
35
  /** The runner's one gate: at most SAVE_CONCURRENCY downloads at once per runner, across its runs. A run in the runner's
75
36
  * own process takes it here; a run in a process of its own takes it over its channel (runner/save-slots.ts). */
76
37
  export const SERVER_SLOTS = saveSlots(SAVE_CONCURRENCY);
@@ -1,5 +1,5 @@
1
1
  import { type AttachHub, type ComputerProvider, type HelloResult, type PairedComputer } from "@parcha/agentrun-computer";
2
- import type { PairedComputerRow } from "../store/index.js";
2
+ import type { Claim, PairedComputerRow } from "../store/index.js";
3
3
  import type { ComputerSettingKind, KindRegistry, ProviderEntry } from "./resolve-computer.js";
4
4
  /** A paired computer's id starts with this; the rest is lowercase letters and digits, so the whole is an id an agent's
5
5
  * computer setting takes as its provider (lowercase letters, digits and dashes). */
@@ -8,21 +8,42 @@ export declare const PAIRED_ID_PREFIX = "cmp-";
8
8
  export declare const ATTACHED_IMAGE = "attached";
9
9
  /** How to start a server so its runs can use a paired computer, in one line: the same words wherever it is said. */
10
10
  export declare const ONE_PROCESS_FIX = "start the image with the server options alone, without server-and-runner (outside the image: agentrun-serve without --no-runner)";
11
- /** The words a run gets when its agent's computer is a paired computer and its runner is not in the server's process. */
12
- export declare const ONE_PROCESS_WORDS = "a paired computer's socket is held by the server process it dialed, and this runner runs in a process of its own: start the image with the server options alone, without server-and-runner (outside the image: agentrun-serve without --no-runner)";
11
+ /** The words a run gets when its agent's computer is a paired computer and its runner, in a process of its own, keeps
12
+ * no relay. */
13
+ export declare const ONE_PROCESS_WORDS = "a paired computer's socket is held by the server process it dialed, and this runner runs in a process of its own and relays no computer's socket: give the runner AGENTRUN_PUBLIC_URL (this server's public address), or start the image with the server options alone, without server-and-runner (outside the image: agentrun-serve without --no-runner)";
13
14
  /** What a pairing code, the pair answer and each paired computer say on a server whose runner runs in a process of its
14
- * own (--no-runner; the image's server-and-runner): the computer pairs, and no run here can use it. */
15
- export declare const RUNNER_APART_WORDS = "no run on this server can use a paired computer: its runner runs in a process of its own, and the computer's socket is held by the server's: start the image with the server options alone, without server-and-runner (outside the image: agentrun-serve without --no-runner)";
15
+ * own (--no-runner; the image's server-and-runner) while no runner relays: the computer pairs, and no run here can use
16
+ * it. */
17
+ export declare const RUNNER_APART_WORDS = "no run on this server can use a paired computer: its runner runs in a process of its own and relays no computer's socket: give the runner AGENTRUN_PUBLIC_URL (this server's public address), or start the image with the server options alone, without server-and-runner (outside the image: agentrun-serve without --no-runner)";
16
18
  /** What a provider whose machines dial this server (the computer package's connectOf "dial": Fly Machines, Cloudflare,
17
19
  * and E2B, Daytona or Modal set to dial) says on such a server: its row in GET /v2/computers and its test. Its
18
20
  * machines' sockets are taken by the server's attach hub, and a runner of its own process has none, so its create
19
21
  * refuses (the computer package's hosted/provider.ts, naming the same fix). */
20
22
  export declare const dialApartWords: (label: string) => string;
23
+ /** A runner's relay of the paired computers (dial-relay.ts pairedRelayOn): its hub, where the server moves a box's
24
+ * socket for a run of this runner (a runner apart's own; the server's, for the runner beside it). `bring` routes the
25
+ * box here for `run` (its hold's end `until`, ms; under `claim`, the run's claim, so a superseded claim's take throws
26
+ * Fenced) and resolves once the box is on the hub; it rejects with code computer_unavailable in words (another run
27
+ * holds it, it is not attached, it did not come in time, its claim was cancelled: `signal`, the create's, which drops
28
+ * the route it took at once), never hanging past PAIRED_BRING_MS. `letGo` ends `hold` (once every remove or KILL it
29
+ * sent has answered), then drops the route where no hold is left. */
30
+ export interface PairedRelay {
31
+ readonly hub: AttachHub;
32
+ bring(row: Pick<PairedComputerRow, "id" | "name">, hold: {
33
+ readonly run: string;
34
+ readonly until: number;
35
+ readonly claim?: Claim;
36
+ readonly signal?: AbortSignal;
37
+ }): Promise<void>;
38
+ letGo(computer: string, hold?: string, run?: string): Promise<void>;
39
+ }
21
40
  /** What the claim reads of the paired computers: the store's rows (removed ones left out), and the server's hub where
22
- * the runner shares its process (absent: a runner of its own process). */
41
+ * the runner shares its process, or the runner's relay where it runs in a process of its own and relays (neither: a
42
+ * runner of its own process with no relay). */
23
43
  export interface AttachedComputers {
24
44
  rows(): Promise<readonly PairedComputerRow[]>;
25
45
  readonly hub?: AttachHub;
46
+ readonly relay?: PairedRelay;
26
47
  }
27
48
  /** The store's row as the hub and attachedProvider take it. */
28
49
  export declare const pairedOf: (row: PairedComputerRow) => PairedComputer;
@@ -42,9 +63,11 @@ export declare function servesNoKind(name: string, hello: Partial<HelloResult>):
42
63
  export declare function pairedEntry(row: PairedComputerRow, registry: Pick<KindRegistry, "SETTING_KINDS" | "servingRefusals">): ProviderEntry;
43
64
  /** `registry` with each paired computer of `rows` as one more provider (pairedEntry). */
44
65
  export declare function withPaired<R extends KindRegistry>(registry: R, rows: readonly PairedComputerRow[]): R;
45
- /** The provider of the paired computer `row`: attachedProvider over the hub, or a refusal in ONE_PROCESS_WORDS where this
46
- * process holds no hub. */
47
- export declare function pairedProvider(row: PairedComputerRow, hub: AttachHub | undefined): ComputerProvider;
66
+ /** The provider of the paired computer `row`: over a relay's hub where the runner has one (`relay`: a runner apart's
67
+ * own, or the server's for the runner beside it), the box brought there before each create and let go after each
68
+ * release (relayedProvider); else attachedProvider over the server's hub (`hub`) with no route; else a refusal in
69
+ * ONE_PROCESS_WORDS. `claim`: the run's claim (ClaimLaunch.claim), which the bring's route takes under. */
70
+ export declare function pairedProvider(row: PairedComputerRow, hub: AttachHub | undefined, relay?: PairedRelay, claim?: Claim): ComputerProvider;
48
71
  /** Why the paired computer `row` cannot be had now, in words that say what to do, or undefined: it must be attached (its
49
72
  * driver dialed this server). Asked at a run's start, as a vendor's readiness is; another run's hold is the claim's. */
50
73
  export declare function pairedRefusal(row: PairedComputerRow, hub: Pick<AttachHub, "online"> | undefined): string | undefined;