@parcha/agentrun-serve 0.1.0-beta.49 → 0.1.0-beta.51

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 (216) hide show
  1. package/CHANGELOG.md +173 -9
  2. package/README.md +246 -39
  3. package/dist/agent-delete.d.ts +3 -2
  4. package/dist/agent-delete.js +29 -4
  5. package/dist/agents-store.js +7 -3
  6. package/dist/api-only.d.ts +8 -10
  7. package/dist/api-only.js +11 -12
  8. package/dist/capacity.d.ts +50 -0
  9. package/dist/capacity.js +49 -0
  10. package/dist/cli-learning/claude-wire.d.ts +41 -0
  11. package/dist/cli-learning/claude-wire.js +258 -0
  12. package/dist/cli-learning/cli.d.ts +11 -0
  13. package/dist/cli-learning/cli.js +241 -0
  14. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  15. package/dist/cli-learning/codex-worktree.js +119 -0
  16. package/dist/cli-learning/connections.d.ts +62 -0
  17. package/dist/cli-learning/connections.js +87 -0
  18. package/dist/cli-learning/entry.d.ts +1 -0
  19. package/dist/cli-learning/entry.js +4 -0
  20. package/dist/cli-learning/evidence.d.ts +78 -0
  21. package/dist/cli-learning/evidence.js +492 -0
  22. package/dist/cli-learning/hook.d.ts +33 -0
  23. package/dist/cli-learning/hook.js +544 -0
  24. package/dist/cli-learning/install.d.ts +33 -0
  25. package/dist/cli-learning/install.js +335 -0
  26. package/dist/cli-learning/observation-proof.d.ts +14 -0
  27. package/dist/cli-learning/observation-proof.js +10 -0
  28. package/dist/cli-learning/policy.d.ts +48 -0
  29. package/dist/cli-learning/policy.js +363 -0
  30. package/dist/cli-learning/schema.d.ts +16 -0
  31. package/dist/cli-learning/schema.js +27 -0
  32. package/dist/cli-learning/state.d.ts +23 -0
  33. package/dist/cli-learning/state.js +61 -0
  34. package/dist/cli.js +24 -2
  35. package/dist/compute-cost.d.ts +101 -0
  36. package/dist/compute-cost.js +250 -0
  37. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  38. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/email/email-faux.d.ts +3 -1
  41. package/dist/email/email-faux.js +3 -2
  42. package/dist/email/routes.js +22 -12
  43. package/dist/eval-previous.d.ts +52 -0
  44. package/dist/eval-previous.js +164 -0
  45. package/dist/file-types.d.ts +2 -0
  46. package/dist/file-types.js +3 -1
  47. package/dist/harness-install.d.ts +6 -2
  48. package/dist/harness-install.js +40 -8
  49. package/dist/harness.d.ts +1 -1
  50. package/dist/harness.js +3 -2
  51. package/dist/learn/check.d.ts +8 -5
  52. package/dist/learn/check.js +25 -24
  53. package/dist/learn/repick.d.ts +22 -13
  54. package/dist/learn/repick.js +57 -56
  55. package/dist/learn/secrets.js +14 -3
  56. package/dist/learn/workflow-draft.d.ts +4 -0
  57. package/dist/learn/workflow-draft.js +10 -7
  58. package/dist/learned-workflow.js +8 -8
  59. package/dist/learning-setting.js +2 -2
  60. package/dist/learning-words.d.ts +1 -1
  61. package/dist/learning-words.js +1 -1
  62. package/dist/mcp-pin-first.js +2 -1
  63. package/dist/mcp-private-hosts.d.ts +24 -3
  64. package/dist/mcp-private-hosts.js +53 -3
  65. package/dist/model-gateway.d.ts +2 -0
  66. package/dist/model-gateway.js +3 -1
  67. package/dist/native/runtimes.d.ts +2 -0
  68. package/dist/native/runtimes.js +2 -0
  69. package/dist/observation/learning.d.ts +32 -0
  70. package/dist/observation/learning.js +66 -0
  71. package/dist/observation/observer.d.ts +8 -1
  72. package/dist/observation/observer.js +89 -9
  73. package/dist/observation/schema.js +12 -4
  74. package/dist/observation/usage-identity.d.ts +9 -0
  75. package/dist/observation/usage-identity.js +11 -0
  76. package/dist/openapi.js +113 -29
  77. package/dist/paid-calls.d.ts +13 -6
  78. package/dist/paid-calls.js +14 -8
  79. package/dist/run-launch.d.ts +16 -2
  80. package/dist/run-launch.js +6 -1
  81. package/dist/run-timeline-served.js +5 -3
  82. package/dist/run-usage.d.ts +23 -8
  83. package/dist/run-usage.js +100 -18
  84. package/dist/run-view.d.ts +2 -0
  85. package/dist/run-view.js +12 -7
  86. package/dist/runner/adapter-loop.d.ts +4 -0
  87. package/dist/runner/adapter-loop.js +44 -27
  88. package/dist/runner/adapter-run-spec.d.ts +8 -3
  89. package/dist/runner/adapter-run-spec.js +15 -8
  90. package/dist/runner/beside.d.ts +13 -0
  91. package/dist/runner/beside.js +27 -8
  92. package/dist/runner/big-writes.d.ts +33 -0
  93. package/dist/runner/big-writes.js +105 -0
  94. package/dist/runner/cli-run-spec.js +16 -8
  95. package/dist/runner/disk-free.d.ts +44 -0
  96. package/dist/runner/disk-free.js +96 -0
  97. package/dist/runner/feedback-round.d.ts +12 -8
  98. package/dist/runner/feedback-round.js +16 -30
  99. package/dist/runner/harness-loops.js +3 -1
  100. package/dist/runner/held.d.ts +4 -1
  101. package/dist/runner/journal-kinds.d.ts +1 -1
  102. package/dist/runner/learning-end.js +13 -4
  103. package/dist/runner/main.d.ts +17 -6
  104. package/dist/runner/main.js +187 -45
  105. package/dist/runner/metrics.d.ts +4 -0
  106. package/dist/runner/metrics.js +9 -0
  107. package/dist/runner/presence.d.ts +11 -2
  108. package/dist/runner/presence.js +31 -3
  109. package/dist/runner/run-child-host.d.ts +27 -17
  110. package/dist/runner/run-child-host.js +70 -116
  111. package/dist/runner/run-child.js +3 -0
  112. package/dist/runner/run-errors.js +2 -0
  113. package/dist/runner/runner-check.d.ts +51 -0
  114. package/dist/runner/runner-check.js +206 -0
  115. package/dist/runner/runner-metrics.d.ts +19 -0
  116. package/dist/runner/runner-metrics.js +49 -0
  117. package/dist/runner/runner.d.ts +37 -0
  118. package/dist/runner/runner.js +43 -3
  119. package/dist/runner/save-slots.d.ts +9 -0
  120. package/dist/runner/save-slots.js +91 -0
  121. package/dist/runner/sdk-loop.js +34 -22
  122. package/dist/runs-over-store.d.ts +8 -1
  123. package/dist/runs-over-store.js +57 -9
  124. package/dist/sdk/runs.d.ts +25 -6
  125. package/dist/sdk/runs.js +107 -35
  126. package/dist/sdk/runtimes.d.ts +19 -0
  127. package/dist/sdk/runtimes.js +23 -0
  128. package/dist/sdk/schema.d.ts +14 -8
  129. package/dist/sdk/schema.js +18 -6
  130. package/dist/server.d.ts +7 -0
  131. package/dist/server.js +151 -28
  132. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  133. package/dist/start-switches.js +2 -0
  134. package/dist/stats.d.ts +4 -0
  135. package/dist/stats.js +1 -1
  136. package/dist/store/agent-body.d.ts +13 -2
  137. package/dist/store/agent-body.js +19 -4
  138. package/dist/store/dialect.d.ts +2 -0
  139. package/dist/store/dialect.js +1 -0
  140. package/dist/store/index.d.ts +3 -3
  141. package/dist/store/index.js +2 -2
  142. package/dist/store/postgres/connection.d.ts +5 -2
  143. package/dist/store/postgres/connection.js +19 -7
  144. package/dist/store/postgres/dialect.js +1 -0
  145. package/dist/store/postgres/migrate.d.ts +30 -0
  146. package/dist/store/postgres/migrate.js +72 -5
  147. package/dist/store/postgres/migration-lint.d.ts +8 -0
  148. package/dist/store/postgres/migration-lint.js +119 -0
  149. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  150. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  151. package/dist/store/postgres/store.d.ts +8 -3
  152. package/dist/store/postgres/store.js +31 -11
  153. package/dist/store/schema.d.ts +26 -4
  154. package/dist/store/schema.js +45 -4
  155. package/dist/store/sqlite/connection.d.ts +3 -3
  156. package/dist/store/sqlite/connection.js +3 -3
  157. package/dist/store/sqlite/run-launch.d.ts +9 -1
  158. package/dist/store/sqlite/run-launch.js +44 -0
  159. package/dist/store/sqlite/store.d.ts +19 -4
  160. package/dist/store/sqlite/store.js +180 -93
  161. package/dist/store/store-schema.d.ts +34 -0
  162. package/dist/store/store-schema.js +125 -0
  163. package/dist/store/store.d.ts +61 -2
  164. package/dist/store/store.js +13 -0
  165. package/dist/store-reads/analytics.d.ts +3 -2
  166. package/dist/store-reads/analytics.js +20 -8
  167. package/dist/store-reads/cap.d.ts +9 -5
  168. package/dist/store-reads/cap.js +28 -2
  169. package/dist/store-reads/decisions.d.ts +21 -0
  170. package/dist/store-reads/decisions.js +22 -0
  171. package/dist/store-reads/journal.d.ts +8 -2
  172. package/dist/store-reads/journal.js +27 -8
  173. package/dist/store-view.d.ts +9 -4
  174. package/dist/store-view.js +48 -25
  175. package/dist/template-eval.d.ts +15 -1
  176. package/dist/template-eval.js +92 -13
  177. package/dist/templates.d.ts +4 -3
  178. package/dist/templates.js +4 -3
  179. package/dist/timeline/labels.js +17 -0
  180. package/dist/tool-gate.d.ts +4 -2
  181. package/dist/tool-list.js +1 -0
  182. package/dist/tools.d.ts +6 -2
  183. package/dist/tools.js +13 -1
  184. package/dist/trigger-targets.d.ts +21 -5
  185. package/dist/trigger-targets.js +13 -10
  186. package/dist/unified-usage.d.ts +24 -0
  187. package/dist/unified-usage.js +400 -0
  188. package/dist/uploads-archil.d.ts +100 -0
  189. package/dist/uploads-archil.js +430 -0
  190. package/dist/uploads.d.ts +55 -1
  191. package/dist/uploads.js +185 -98
  192. package/dist/validate.js +1 -1
  193. package/dist/web-fake.d.ts +25 -0
  194. package/dist/web-fake.js +38 -1
  195. package/dist/web-save.d.ts +75 -0
  196. package/dist/web-save.js +235 -0
  197. package/dist/workspace/archil-claim.d.ts +5 -2
  198. package/dist/workspace/archil-claim.js +5 -2
  199. package/dist/workspace/archil-disk.d.ts +11 -1
  200. package/dist/workspace/archil-disk.js +43 -10
  201. package/dist/workspace/archil.d.ts +3 -0
  202. package/dist/workspace/archil.js +102 -16
  203. package/dist/workspace/computer-for-claim.d.ts +14 -0
  204. package/dist/workspace/computer-for-claim.js +46 -7
  205. package/dist/workspace/computer-intervals.d.ts +9 -3
  206. package/dist/workspace/computer-intervals.js +17 -8
  207. package/dist/workspace/pieced.d.ts +14 -0
  208. package/dist/workspace/pieced.js +23 -0
  209. package/dist/workspace/run-disk.js +32 -12
  210. package/dist/workspace/run-workspace.d.ts +1 -1
  211. package/dist/workspace/run-workspace.js +11 -6
  212. package/package.json +10 -10
  213. package/skills/agentrun-serve/SKILL.md +52 -7
  214. package/templates/README.md +36 -7
  215. package/dist/console/assets/index-Bzn4eUYF.js +0 -715
  216. package/dist/console/assets/index-CR2ZGei1.css +0 -1
package/dist/uploads.js CHANGED
@@ -61,7 +61,7 @@ export const uploadUrl = (id) => `/v2/files/${id}`;
61
61
  export const uploadTestHooks = {};
62
62
  /** A UUIDv7, the form of the agent store's agent and run ids: 48 bits of Unix milliseconds, then random bits, so ids
63
63
  * sort by creation time. The store mints its own inside it and exports no minter. */
64
- function uuidv7(now = Date.now()) {
64
+ export function uuidv7(now = Date.now()) {
65
65
  const bytes = randomBytes(16);
66
66
  bytes.writeUIntBE(now, 0, 6);
67
67
  bytes[6] = (bytes[6] & 0x0f) | 0x70;
@@ -192,9 +192,8 @@ export class Uploads {
192
192
  await rm(join(this.root, id), { recursive: true, force: true });
193
193
  });
194
194
  }
195
- /** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
196
195
  answer(file) {
197
- return { file, upload: { method: "PUT", url: uploadUrl(file.file_id), expires_at: new Date(Date.parse(file.created_at) + UPLOAD_WINDOW_MS).toISOString() } };
196
+ return answerOf(file);
198
197
  }
199
198
  /** POST /v2/files?path=...: the body is the file's bytes, whatever its type but a multipart form (415, with the call
200
199
  * that works). The query takes `path`, and `content_type` and `sha256` when given; the length is the body's and the hash
@@ -202,28 +201,7 @@ export class Uploads {
202
201
  * else the path's extension's, else octet-stream. The bytes stream to a dot-named file of their own under the root,
203
202
  * never held whole; over MAX_UPLOAD_BYTES is 413, a `sha256` they do not have 422. Nothing is made until `commit`. */
204
203
  async take(query, requestType, body) {
205
- const type = String(requestType ?? "").trim();
206
- if (/^multipart\//i.test(type))
207
- throw new ApiError("unsupported_media_type", "A multipart form is not taken: send the file's bytes as the body, as `curl --data-binary @plan.md \"$AGENTRUN_BASE_URL/files?path=plan.md\"` does.");
208
- const issues = [...new Set(query.keys())].filter((key) => !QUERY.includes(key)).map((key) => ({ field: key, reason: "not_allowed", message: `A file sent in one call takes path, content_type and sha256 in the query; ${key} is not one.` }));
209
- for (const key of QUERY)
210
- if (query.getAll(key).length > 1)
211
- issues.push({ field: key, reason: "duplicate", message: `${key} is given more than once` });
212
- const path = query.get("path");
213
- // An empty one is none.
214
- const named = query.get("content_type") || null;
215
- const sha = query.get("sha256");
216
- if (path === null)
217
- issues.push({ field: "path", reason: "missing", message: "Name the file: POST /v2/files?path=<its path> with its bytes as the body, or a JSON reservation {path, size_bytes} and then PUT /v2/files/<id>.", fix: "Add ?path=<the file's name> to the URL." });
218
- if (sha !== null && !SHA256.test(sha))
219
- issues.push({ field: "sha256", reason: "bad_format", message: "sha256 is 64 lowercase hex digits" });
220
- if (issues.length)
221
- throw invalid(issues);
222
- const problem = this.problemOf(path);
223
- if (problem)
224
- throw new ApiError("invalid_file_path", problem);
225
- const given = type && !GENERIC_TYPES.has(type.split(";")[0].trim().toLowerCase()) ? type : undefined;
226
- const contentType = named ?? given ?? typeOf(path) ?? "application/octet-stream";
204
+ const { path, sha, contentType } = sentInOneCall(query, requestType, (path) => this.problemOf(path));
227
205
  await mkdir(this.root, { recursive: true, mode: 0o700 });
228
206
  const temp = tempOf(join(this.root, ".incoming"));
229
207
  const handle = await open(temp, "wx", 0o600);
@@ -244,13 +222,13 @@ export class Uploads {
244
222
  throw invalid([{ field: "sha256", reason: "invalid", message: `The body's SHA-256 is ${sha256}; the query names ${sha}.` }]);
245
223
  await handle.sync();
246
224
  await handle.close();
247
- const fingerprint = { sent_in_one_call: true, path: path, content_type: contentType, size_bytes: size, sha256 };
225
+ const fingerprint = { sent_in_one_call: true, path, content_type: contentType, size_bytes: size, sha256 };
248
226
  let made = false;
249
227
  return {
250
228
  fingerprint,
251
229
  commit: async () => {
252
230
  const now = Date.now();
253
- const file = { file_id: uuidv7(now), path: path, size_bytes: size, content_type: contentType, sha256, status: "ready", created_at: new Date(now).toISOString(), expires_at: null };
231
+ const file = { file_id: uuidv7(now), path, size_bytes: size, content_type: contentType, sha256, status: "ready", created_at: new Date(now).toISOString(), expires_at: null };
254
232
  const dir = join(this.root, file.file_id);
255
233
  await mkdir(dir, { mode: 0o700 });
256
234
  try {
@@ -280,34 +258,7 @@ export class Uploads {
280
258
  }
281
259
  /** POST /v2/files: the body checked as the contract's FileCreate, then a pending file; with where to send its bytes. */
282
260
  async reserve(body) {
283
- const issues = unknownFields(body, FIELDS);
284
- if (typeof body.path !== "string")
285
- issues.push({ field: "path", reason: body.path === undefined ? "missing" : "wrong_type", message: "path is the file's relative path, a string" });
286
- if (!(Number.isSafeInteger(body.size_bytes) && body.size_bytes >= 0))
287
- issues.push({ field: "size_bytes", reason: body.size_bytes === undefined ? "missing" : "wrong_type", message: "size_bytes is the file's length in bytes, an integer 0 or more" });
288
- if (body.content_type !== undefined && typeof body.content_type !== "string")
289
- issues.push({ field: "content_type", reason: "wrong_type", message: "content_type is a string" });
290
- if (body.sha256 !== undefined && !(typeof body.sha256 === "string" && SHA256.test(body.sha256)))
291
- issues.push({ field: "sha256", reason: typeof body.sha256 === "string" ? "bad_format" : "wrong_type", message: "sha256 is 64 lowercase hex digits" });
292
- if (issues.length)
293
- throw invalid(issues);
294
- const problem = this.problemOf(body.path);
295
- if (problem)
296
- throw new ApiError("invalid_file_path", problem);
297
- if (body.size_bytes > MAX_UPLOAD_BYTES)
298
- throw new ApiError("payload_too_large", `size_bytes is over ${MAX_UPLOAD_BYTES}, this server's largest upload`, { details: { limit: "max_upload_bytes" } });
299
- const now = Date.now();
300
- const file = {
301
- file_id: uuidv7(now),
302
- path: body.path,
303
- size_bytes: body.size_bytes,
304
- // Named, or by the path's extension as a run's files are served (`plan.md` is text/markdown), else octet-stream.
305
- content_type: body.content_type ?? typeOf(body.path) ?? "application/octet-stream",
306
- sha256: body.sha256 ?? null,
307
- status: "pending",
308
- created_at: new Date(now).toISOString(),
309
- expires_at: null,
310
- };
261
+ const file = reservation(body, (path) => this.problemOf(path));
311
262
  await mkdir(this.root, { recursive: true, mode: 0o700 });
312
263
  await mkdir(join(this.root, file.file_id), { mode: 0o700 });
313
264
  await writeDurable(join(this.root, file.file_id, RECORD), `${JSON.stringify(file)}\n`);
@@ -401,34 +352,7 @@ export class Uploads {
401
352
  }
402
353
  /** A run's `file_ids`: each a file that is ready, none twice, at most MAX_FILES_PER_RUN, or 422 at `file_ids`. */
403
354
  async readyFiles(ids) {
404
- const issues = [];
405
- if (ids.length > MAX_FILES_PER_RUN)
406
- issues.push({ field: "file_ids", reason: "too_many", message: `A run names at most ${MAX_FILES_PER_RUN} files here (limits.max_files_per_run); this names ${ids.length}.` });
407
- else if (new Set(ids).size !== ids.length)
408
- issues.push({ field: "file_ids", reason: "duplicate", message: "file_ids names one file twice" });
409
- if (issues.length)
410
- throw invalid(issues);
411
- const files = [];
412
- for (const [i, id] of ids.entries()) {
413
- const field = `file_ids[${i}]`;
414
- if (typeof id !== "string" || !ID.test(id)) {
415
- issues.push({ field, reason: "wrong_type", message: `${field} is ${shown(id)}, not a file id: use the file_id an upload answered (POST /v2/files answers it under file.file_id).` });
416
- continue;
417
- }
418
- const file = await this.get(id);
419
- const problem = file?.status === "ready" ? this.problemOf(file.path) : undefined;
420
- if (!file)
421
- issues.push({ field, reason: "not_an_option", message: `There is no file ${id}: reserve it with POST /v2/files.` });
422
- else if (file.status !== "ready")
423
- issues.push({ field, reason: "invalid", message: `The file ${id} is not ready: send its bytes with PUT /v2/files/${id} first.` });
424
- else if (problem)
425
- issues.push({ field, reason: "invalid", message: `The file ${id} cannot be copied into a run here: ${problem}.` });
426
- else
427
- files.push(file);
428
- }
429
- if (issues.length)
430
- throw invalid(issues);
431
- return files;
355
+ return readyFilesOf(ids, (id) => this.get(id), (path) => this.problemOf(path));
432
356
  }
433
357
  /** Copies `files` into the run's `inputs/` through its Workspace, each at its `path` with its folders, in order, before
434
358
  * the run's first turn: a name taken already (the same path twice, a file where another's folder goes, or what the
@@ -437,21 +361,7 @@ export class Uploads {
437
361
  * the copy (ESCAPE), and nothing is written through it. `bytesOf`: where each file's bytes are read (its upload's own,
438
362
  * or the run's hold of them, `held`). */
439
363
  async copyInto(work, files, bytesOf = (file) => join(this.root, file.file_id, BYTES)) {
440
- const workspace = workspaceAt(work);
441
- await uploadTestHooks.beforeCopy?.(workspace);
442
- const names = takenNames(workspace);
443
- // inputs/message.md is the run's message's (MESSAGE_FILE), never an upload's.
444
- const top = await names(INPUTS_DIR);
445
- if (!top.has(MESSAGE_FILE))
446
- top.set(MESSAGE_FILE, "file");
447
- for (const file of files) {
448
- const segments = file.path.split("/");
449
- let dir = INPUTS_DIR;
450
- for (const segment of segments.slice(0, -1))
451
- dir = `${dir}/${free(await names(dir), segment, "dir")}`;
452
- const name = free(await names(dir), segments.at(-1), "file");
453
- await workspace.write(`${dir}/${name}`, await readFile(bytesOf(file)));
454
- }
364
+ await copyFilesInto(workspaceAt(work), files, (file) => readFile(bytesOf(file)));
455
365
  }
456
366
  /** At a run's start, before its row is written: each of its files (`ids`, ready) held for it under
457
367
  * `<root>/.held/<run id>/`, its record and its bytes (a hard link to the upload's, which never change once ready; a
@@ -501,6 +411,183 @@ export class Uploads {
501
411
  return (await readdir(join(this.root, HELD_DIR)).catch(() => [])).filter((name) => ID.test(name));
502
412
  }
503
413
  }
414
+ /** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
415
+ export const answerOf = (file) => ({ file, upload: { method: "PUT", url: uploadUrl(file.file_id), expires_at: new Date(Date.parse(file.created_at) + UPLOAD_WINDOW_MS).toISOString() } });
416
+ /** Whether `value` reads as a File record. */
417
+ export const isUploadedFile = isFile;
418
+ /** A file sent in one call, its query and request type checked (Uploads.take): its path, the hash the query names (or
419
+ * null) and its type. `problemOf`: why a path cannot be a file's path in this store. */
420
+ export function sentInOneCall(query, requestType, problemOf) {
421
+ const type = String(requestType ?? "").trim();
422
+ if (/^multipart\//i.test(type))
423
+ throw new ApiError("unsupported_media_type", "A multipart form is not taken: send the file's bytes as the body, as `curl --data-binary @plan.md \"$AGENTRUN_BASE_URL/files?path=plan.md\"` does.");
424
+ const issues = [...new Set(query.keys())].filter((key) => !QUERY.includes(key)).map((key) => ({ field: key, reason: "not_allowed", message: `A file sent in one call takes path, content_type and sha256 in the query; ${key} is not one.` }));
425
+ for (const key of QUERY)
426
+ if (query.getAll(key).length > 1)
427
+ issues.push({ field: key, reason: "duplicate", message: `${key} is given more than once` });
428
+ const path = query.get("path");
429
+ // An empty one is none.
430
+ const named = query.get("content_type") || null;
431
+ const sha = query.get("sha256");
432
+ if (path === null)
433
+ issues.push({ field: "path", reason: "missing", message: "Name the file: POST /v2/files?path=<its path> with its bytes as the body, or a JSON reservation {path, size_bytes} and then PUT /v2/files/<id>.", fix: "Add ?path=<the file's name> to the URL." });
434
+ if (sha !== null && !SHA256.test(sha))
435
+ issues.push({ field: "sha256", reason: "bad_format", message: "sha256 is 64 lowercase hex digits" });
436
+ if (issues.length)
437
+ throw invalid(issues);
438
+ const problem = problemOf(path);
439
+ if (problem)
440
+ throw new ApiError("invalid_file_path", problem);
441
+ const given = type && !GENERIC_TYPES.has(type.split(";")[0].trim().toLowerCase()) ? type : undefined;
442
+ return { path: path, sha, contentType: named ?? given ?? typeOf(path) ?? "application/octet-stream" };
443
+ }
444
+ /** POST /v2/files's JSON body checked as the contract's FileCreate (Uploads.reserve): the pending file it makes, not yet
445
+ * written. */
446
+ export function reservation(body, problemOf) {
447
+ const issues = unknownFields(body, FIELDS);
448
+ if (typeof body.path !== "string")
449
+ issues.push({ field: "path", reason: body.path === undefined ? "missing" : "wrong_type", message: "path is the file's relative path, a string" });
450
+ if (!(Number.isSafeInteger(body.size_bytes) && body.size_bytes >= 0))
451
+ issues.push({ field: "size_bytes", reason: body.size_bytes === undefined ? "missing" : "wrong_type", message: "size_bytes is the file's length in bytes, an integer 0 or more" });
452
+ if (body.content_type !== undefined && typeof body.content_type !== "string")
453
+ issues.push({ field: "content_type", reason: "wrong_type", message: "content_type is a string" });
454
+ if (body.sha256 !== undefined && !(typeof body.sha256 === "string" && SHA256.test(body.sha256)))
455
+ issues.push({ field: "sha256", reason: typeof body.sha256 === "string" ? "bad_format" : "wrong_type", message: "sha256 is 64 lowercase hex digits" });
456
+ if (issues.length)
457
+ throw invalid(issues);
458
+ const problem = problemOf(body.path);
459
+ if (problem)
460
+ throw new ApiError("invalid_file_path", problem);
461
+ if (body.size_bytes > MAX_UPLOAD_BYTES)
462
+ throw new ApiError("payload_too_large", `size_bytes is over ${MAX_UPLOAD_BYTES}, this server's largest upload`, { details: { limit: "max_upload_bytes" } });
463
+ const now = Date.now();
464
+ return {
465
+ file_id: uuidv7(now),
466
+ path: body.path,
467
+ size_bytes: body.size_bytes,
468
+ // Named, or by the path's extension as a run's files are served (`plan.md` is text/markdown), else octet-stream.
469
+ content_type: body.content_type ?? typeOf(body.path) ?? "application/octet-stream",
470
+ sha256: body.sha256 ?? null,
471
+ status: "pending",
472
+ created_at: new Date(now).toISOString(),
473
+ expires_at: null,
474
+ };
475
+ }
476
+ /** A body's bytes against the file `held` was reserved or made as: the 422 at the field that differs, or undefined. */
477
+ export function mismatchOf(held, size, sha256) {
478
+ return size !== held.size_bytes
479
+ ? invalid([{ field: "size_bytes", reason: "invalid", message: `The body is ${size} bytes; the file was reserved with size_bytes ${held.size_bytes}.` }])
480
+ : held.sha256 !== null && held.sha256 !== sha256
481
+ ? invalid([{ field: "sha256", reason: "invalid", message: `The body's SHA-256 is ${sha256}; the file ${held.status === "ready" ? "is ready with" : "was reserved with"} ${held.sha256}.` }])
482
+ : undefined;
483
+ }
484
+ /** A run's `file_ids` (Uploads.readyFiles): each a file `get` finds ready, none twice, at most MAX_FILES_PER_RUN, or 422
485
+ * at `file_ids`. `problemOf`: why a ready file's path cannot be copied into a run of this store. */
486
+ export async function readyFilesOf(ids, get, problemOf) {
487
+ const issues = [];
488
+ if (ids.length > MAX_FILES_PER_RUN)
489
+ issues.push({ field: "file_ids", reason: "too_many", message: `A run names at most ${MAX_FILES_PER_RUN} files here (limits.max_files_per_run); this names ${ids.length}.` });
490
+ else if (new Set(ids).size !== ids.length)
491
+ issues.push({ field: "file_ids", reason: "duplicate", message: "file_ids names one file twice" });
492
+ if (issues.length)
493
+ throw invalid(issues);
494
+ const files = [];
495
+ // Every record read at once (each a round trip to the disk in Mode 2), then judged in order.
496
+ const found = await Promise.all(ids.map((id) => (typeof id === "string" && ID.test(id) ? get(id) : Promise.resolve(null))));
497
+ for (const [i, id] of ids.entries()) {
498
+ const field = `file_ids[${i}]`;
499
+ if (typeof id !== "string" || !ID.test(id)) {
500
+ issues.push({ field, reason: "wrong_type", message: `${field} is ${shown(id)}, not a file id: use the file_id an upload answered (POST /v2/files answers it under file.file_id).` });
501
+ continue;
502
+ }
503
+ const file = found[i];
504
+ const problem = file?.status === "ready" ? problemOf(file.path) : undefined;
505
+ if (!file)
506
+ issues.push({ field, reason: "not_an_option", message: `There is no file ${id}: reserve it with POST /v2/files.` });
507
+ else if (file.status !== "ready")
508
+ issues.push({ field, reason: "invalid", message: `The file ${id} is not ready: send its bytes with PUT /v2/files/${id} first.` });
509
+ else if (problem)
510
+ issues.push({ field, reason: "invalid", message: `The file ${id} cannot be copied into a run here: ${problem}.` });
511
+ else
512
+ files.push(file);
513
+ }
514
+ if (issues.length)
515
+ throw invalid(issues);
516
+ return files;
517
+ }
518
+ /** Copies `files` into the workspace's `inputs/` (Uploads.copyInto), each at its `path` with its folders: a name taken
519
+ * already (the same path twice, a file where another's folder goes, or what the folder held before) gets the next free
520
+ * suffix (`notes-2.txt`, `docs-2/`), the same for the same files in the same order, every name chosen before the first
521
+ * byte is written. Each copy is a new file written whole by the Workspace. `read`: a file's bytes. `concurrency`: how
522
+ * many files are read and written at once (default 1, one after another); `turn`: each file's read and write runs
523
+ * inside it, as a limit shared with other copies (slots) takes them; `signal`: stops the copy before its next file,
524
+ * rejecting with the signal's reason. */
525
+ export async function copyFilesInto(workspace, files, read, { concurrency = 1, turn = (copy) => copy(), signal } = {}) {
526
+ await uploadTestHooks.beforeCopy?.(workspace);
527
+ const names = takenNames(workspace);
528
+ // inputs/message.md is the run's message's (MESSAGE_FILE), never an upload's.
529
+ const top = await names(INPUTS_DIR);
530
+ if (!top.has(MESSAGE_FILE))
531
+ top.set(MESSAGE_FILE, "file");
532
+ const targets = [];
533
+ for (const file of files) {
534
+ const segments = file.path.split("/");
535
+ let dir = INPUTS_DIR;
536
+ for (const segment of segments.slice(0, -1))
537
+ dir = `${dir}/${free(await names(dir), segment, "dir")}`;
538
+ targets.push({ file, to: `${dir}/${free(await names(dir), segments.at(-1), "file")}` });
539
+ }
540
+ let next = 0;
541
+ // One file that fails stops the others before their next file: nothing more is written once the copy has failed.
542
+ let failed = false;
543
+ const worker = async () => {
544
+ while (!failed && next < targets.length) {
545
+ const { file, to } = targets[next++];
546
+ try {
547
+ // Checked once the turn is had too: a file that waited for one past the deadline is not started.
548
+ signal?.throwIfAborted();
549
+ await turn(async () => {
550
+ signal?.throwIfAborted();
551
+ await workspace.write(to, await read(file));
552
+ });
553
+ }
554
+ catch (error) {
555
+ failed = true;
556
+ throw error;
557
+ }
558
+ }
559
+ };
560
+ // Every worker settles before the copy answers, so nothing it started is still writing once a caller cleans up.
561
+ const settled = await Promise.allSettled(Array.from({ length: Math.max(1, Math.min(concurrency, targets.length)) }, worker));
562
+ const first = settled.find((one) => one.status === "rejected");
563
+ if (first)
564
+ throw first.reason;
565
+ }
566
+ /** At most `size` of the calls given to it running at once, the rest waiting in the order they came: a slot a call
567
+ * leaves goes straight to the next one waiting. */
568
+ export function slots(size) {
569
+ let running = 0;
570
+ const waiting = [];
571
+ return async (work) => {
572
+ if (running < size)
573
+ running++;
574
+ else
575
+ await new Promise((resolve) => waiting.push(resolve));
576
+ try {
577
+ return await work();
578
+ }
579
+ finally {
580
+ const next = waiting.shift();
581
+ if (next)
582
+ next();
583
+ else
584
+ running--;
585
+ }
586
+ };
587
+ }
588
+ /** The files a run's claim copies in (placeRunInputs): its launch's, unless the server already placed them in its folder
589
+ * when it started the run (Mode 2, RunLaunch.filesPlaced), when the claim reads no upload at all. */
590
+ export const filesToCopy = (launch) => (launch.filesPlaced ? [] : (launch.files ?? []));
504
591
  /** The words a run fails in when its files cannot be copied into its workspace at its claim. */
505
592
  export const notCopied = (why) => `The run's files could not be copied into its workspace: ${why}`;
506
593
  /** At a run's claim: its opening message (`message`, the start's text content) saved as inputs/message.md
package/dist/validate.js CHANGED
@@ -18,7 +18,7 @@ export const isObject = (value) => typeof value === "object" && value !== null &
18
18
  /** How long an Idempotency-Key answers with its first answer (capabilities' limits.idempotency_ttl_s). */
19
19
  export const IDEMPOTENCY_TTL_S = 86_400;
20
20
  export const stable = (value) => Array.isArray(value) ? `[${value.map(stable).join(",")}]` : isObject(value) ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stable(value[k])}`).join(",")}}` : JSON.stringify(value);
21
- export const DEFINITION_FIELDS = ["id", "version", "name", "description", "instructions", "workflow", "model", "model_tiers", "thinking", "harness", "place", "computer", "learning", "skills", "tools", "tool_settings", "approvals", "max_cost_usd", "input_schema", "output_schema", "checkout", "native", "sdk"];
21
+ export const DEFINITION_FIELDS = ["id", "version", "name", "description", "instructions", "workflow", "model", "model_tiers", "thinking", "harness", "place", "computer", "learning", "skills", "tools", "tool_settings", "approvals", "max_cost_usd", "input_schema", "output_schema", "checkout", "native", "sdk", "cli_learning"];
22
22
  /** What an agentic definition may ask the server to check out in each run's folder before its first turn
23
23
  * (runner/pr-checkout.ts): `pull_request`, the pull request the run's GitHub event names, at its head, read-only, in
24
24
  * `repo/`; `none` clears it on an edit. */
@@ -2,6 +2,7 @@ import { type Page, type Part } from "./web-fetch-direct.js";
2
2
  import { type WebPage } from "./web-fetch.js";
3
3
  import { type Hit, type Search } from "./web-search.js";
4
4
  import type { Plane } from "./tool-plane.js";
5
+ import type { PublicFetchOptions } from "@parcha/pi-browser";
5
6
  export type SearchAnswer = {
6
7
  query: string;
7
8
  results: Hit[];
@@ -18,6 +19,21 @@ export type FetchAnswer = {
18
19
  url: string;
19
20
  error: string;
20
21
  };
22
+ /** A saved file's answer: its body as text or as base64, its declared type and status. */
23
+ export type FileBody = {
24
+ status?: number;
25
+ content_type?: string;
26
+ } & ({
27
+ text: string;
28
+ } | {
29
+ base64: string;
30
+ });
31
+ export type SaveAnswer = ({
32
+ url: string;
33
+ } & FileBody) | {
34
+ url: string;
35
+ error: string;
36
+ };
21
37
  export type WebFixture = {
22
38
  search: {
23
39
  answers: SearchAnswer[];
@@ -37,6 +53,12 @@ export type WebFixture = {
37
53
  error: string;
38
54
  };
39
55
  };
56
+ save?: {
57
+ answers: SaveAnswer[];
58
+ default?: FileBody | {
59
+ error: string;
60
+ };
61
+ };
40
62
  };
41
63
  /** A case's web fake: every web call failing, or a fixture. */
42
64
  export type WebFake = "unavailable" | WebFixture;
@@ -51,6 +73,9 @@ export declare function fakeSearch(fake: WebFake, args: Record<string, unknown>,
51
73
  export declare function fakeFetch(fake: WebFake, url: unknown, part?: Part & {
52
74
  signal?: AbortSignal;
53
75
  }): Promise<WebPage | Page>;
76
+ /** The guard's resolver and fetch for web_save in `fake`: every name a public address, each file answered from the
77
+ * fixture's `save` (by exact URL, else its default), every other URL a refused connection, as a host that is down. */
78
+ export declare function fakeSaveOptions(fake: WebFake): Pick<PublicFetchOptions, "lookup" | "fetchImpl">;
54
79
  /** A faked run's plane: web_search never a harness's own search (Claude's or Codex's, which would answer in its stead), so
55
80
  * the run's own web_search tool, the one the fake answers through, is the one its harness offers. */
56
81
  export declare function fakedPlane(plane: Plane | undefined): Plane | undefined;
package/dist/web-fake.js CHANGED
@@ -4,7 +4,10 @@
4
4
  // RATE_LIMITED), and every page fails as a fetch whose connection is refused does (the guarded direct fetch's own words,
5
5
  // web-fetch-direct.ts readDirect). A fixture: each search answered by the first answer whose `query` (a regular
6
6
  // expression, case-insensitive) matches the query, else its default; each page by the answer for exactly its URL, else
7
- // its default, read through the guarded direct fetch's own path (its URL, port and status checks, its parts).
7
+ // its default, read through the guarded direct fetch's own path (its URL, port and status checks, its parts). web_save's
8
+ // files (web-save.ts) answer from the fixture's optional `save`: each file by the answer for exactly its URL, else its
9
+ // default, else a refused connection, downloaded through web_save's own guarded path (every hop checked, the cap, the type
10
+ // checked against the bytes); `unavailable` refuses every connection.
8
11
  //
9
12
  // Only the eval's own in-process runner binds it (runner/beside.ts `evalFakes`, by the agent the eval made for the run):
10
13
  // no package field, API field, setting or environment variable reaches it, so no other server's runs ever see a fake.
@@ -55,6 +58,22 @@ export function webFixtureOf(value, at, bad) {
55
58
  });
56
59
  if (!pageOk(fetch.default, false))
57
60
  say("fetch.default is {status?, title?, text} or {error}");
61
+ const statusOk = (status) => status === undefined || (Number.isInteger(status) && status >= 200 && status <= 599);
62
+ const fileOk = (answer, keyed) => isObject(answer) && (!keyed || (isText(answer.url) && URL.canParse(answer.url)))
63
+ && (isText(answer.error) ? answer.text === undefined && answer.base64 === undefined : (isText(answer.text) !== isText(answer.base64)) && (answer.text === undefined || isText(answer.text)) && (answer.base64 === undefined || isText(answer.base64)) && statusOk(answer.status) && (answer.content_type === undefined || isText(answer.content_type)));
64
+ if (value.save !== undefined) {
65
+ const save = value.save;
66
+ if (!isObject(save) || !Array.isArray(save.answers))
67
+ say("save is {answers, default?}, answers a list of {url, content_type?, status?, text | base64} or {url, error}");
68
+ else {
69
+ save.answers.forEach((answer, i) => {
70
+ if (!fileOk(answer, true))
71
+ say(`save.answers.${i} is {url, content_type?, status?, text | base64} or {url, error}, its url absolute and its status 200 to 599`);
72
+ });
73
+ if (save.default !== undefined && !fileOk(save.default, false))
74
+ say("save.default is {content_type?, status?, text | base64} or {error}");
75
+ }
76
+ }
58
77
  for (const problem of problems)
59
78
  bad(problem);
60
79
  return problems.length ? undefined : value;
@@ -95,6 +114,24 @@ export async function fakeFetch(fake, url, part = {}) {
95
114
  // A page served as text has no title of its own: the fixture's.
96
115
  return page.ok && answer && !("error" in answer) && answer.title ? { ...page, title: clip(answer.title, TITLE_CAP) } : page;
97
116
  }
117
+ /** The guard's resolver and fetch for web_save in `fake`: every name a public address, each file answered from the
118
+ * fixture's `save` (by exact URL, else its default), every other URL a refused connection, as a host that is down. */
119
+ export function fakeSaveOptions(fake) {
120
+ return {
121
+ lookup: async () => [PUBLIC_ADDRESS],
122
+ fetchImpl: async (url) => {
123
+ const save = fake === "unavailable" ? undefined : fake.save;
124
+ const answer = save?.answers.find((one) => one.url === String(url)) ?? save?.default;
125
+ if (answer === undefined)
126
+ throw new TypeError("fetch failed", { cause: Object.assign(new Error("connect ECONNREFUSED"), { code: "ECONNREFUSED" }) });
127
+ if ("error" in answer)
128
+ throw new TypeError(answer.error);
129
+ const status = answer.status ?? 200;
130
+ const body = "base64" in answer ? Buffer.from(answer.base64, "base64") : answer.text;
131
+ return new Response(NULL_BODY.has(status) ? null : body, { status, headers: answer.content_type ? { "content-type": answer.content_type } : {} });
132
+ },
133
+ };
134
+ }
98
135
  /** A faked run's plane: web_search never a harness's own search (Claude's or Codex's, which would answer in its stead), so
99
136
  * the run's own web_search tool, the one the fake answers through, is the one its harness offers. */
100
137
  export function fakedPlane(plane) {
@@ -0,0 +1,75 @@
1
+ import type { JsonValue } from "@earendil-works/chord/json";
2
+ import type { TSchema } from "typebox";
3
+ import { type ToolRegistration } from "@earendil-works/pi-durable";
4
+ import type { PublicFetchOptions } from "@parcha/pi-browser";
5
+ import { type Workspace } from "./workspace/index.js";
6
+ export declare const WEB_SAVE_TOOL = "web_save";
7
+ /** The most bytes a saved file may have. */
8
+ export declare const SAVE_MAX_BYTES: number;
9
+ /** One deadline for a whole download: a 200 MiB file at about 350 KB/s. A page's 30 s (web-fetch-direct.ts) would cut a
10
+ * large file on any link under about 7 MB/s. */
11
+ export declare const SAVE_TIMEOUT_MS = 600000;
12
+ /** The folder a bare name is saved in. */
13
+ export declare const MEDIA_DIR = "media";
14
+ /** The longest path web_save takes, and the most characters of a declared type and of a failure's words an answer
15
+ * carries: with the URL's URL_MAX, they bound every answer (host-bounds.test.mjs). */
16
+ export declare const PATH_MAX_CHARS = 1024;
17
+ export declare const TYPE_MAX_CHARS = 255;
18
+ export declare const WORDS_MAX_CHARS = 2000;
19
+ export type Saved = {
20
+ ok: true;
21
+ path: string;
22
+ bytes: number;
23
+ content_type: string;
24
+ url: string;
25
+ };
26
+ export type Unsaved = {
27
+ ok: false;
28
+ url: string;
29
+ path?: string;
30
+ refused: string;
31
+ } | {
32
+ ok: false;
33
+ url: string;
34
+ path?: string;
35
+ error: string;
36
+ };
37
+ /** The guard's resolver and fetch (a test's, or the fakes'), the caller's signal, a lower cap, and other slots than the
38
+ * server's (a test's). */
39
+ export type SaveOptions = Omit<PublicFetchOptions, "maxBytes"> & {
40
+ maxBytes?: number;
41
+ timeoutMs?: number;
42
+ slots?: SaveSlots;
43
+ };
44
+ /** The most web_save downloads at once per runner, across its runs (SERVER_SLOTS); the rest wait under their own
45
+ * deadline. Each holds its file in memory until its one write: its size when its host states its length, about twice
46
+ * that at the peak when it does not (publicDownload). So a runner's downloads hold at most 800 MiB at 200 MiB a file,
47
+ * about 1.6 GiB when no host states a length; Mode 2's pieced writes (runner/big-writes.ts) can add 800 MiB more. */
48
+ export declare const SAVE_CONCURRENCY = 4;
49
+ /** Slots for downloads, handed out first come first served. `take` answers the slot's release (once), or rejects with
50
+ * the signal's reason if it aborts first, leaving the queue. */
51
+ export type SaveSlots = {
52
+ readonly size: number;
53
+ readonly busy: number;
54
+ readonly waiting: number;
55
+ take(signal: AbortSignal): Promise<() => void>;
56
+ };
57
+ export declare function saveSlots(size: number): SaveSlots;
58
+ /** The runner's one gate: at most SAVE_CONCURRENCY downloads at once per runner, across its runs. A run in the runner's
59
+ * own process takes it here; a run in a process of its own takes it over its channel (runner/save-slots.ts). */
60
+ export declare const SERVER_SLOTS: SaveSlots;
61
+ /** The type `bytes` are saved as at `path`, the host having declared `declared`, or why they are refused. */
62
+ export declare function typeFor(bytes: Uint8Array, declared: string, path: string): {
63
+ type: string;
64
+ } | {
65
+ refused: string;
66
+ };
67
+ /** Where `path` is saved: as given, or under media/ when it names no folder. */
68
+ export declare const savePath: (path: string) => string;
69
+ /** `args.url` downloaded and saved at `args.path` in `work`: what was saved, or why nothing was. Never throws. */
70
+ export declare function webSave(args: unknown, work: Workspace, options?: SaveOptions): Promise<Saved | Unsaved>;
71
+ /** The words the model reads: the answer's JSON. */
72
+ export declare const savedText: (answer: Saved | Unsaved) => string;
73
+ /** web_save on `work`, its download through `guard` (a test's or the fakes' resolver and fetch, none for the network), its
74
+ * slots `slots` (none: SERVER_SLOTS). */
75
+ export declare function webSaveTool(work: () => Promise<Workspace> | Workspace, guard: () => Promise<Omit<PublicFetchOptions, "maxBytes" | "signal">> | Omit<PublicFetchOptions, "maxBytes" | "signal">, slots?: SaveSlots): ToolRegistration<TSchema, JsonValue>;