@parcha/agentrun-serve 0.1.0-beta.50 → 0.1.0-beta.52

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 (232) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +236 -30
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +17 -7
  8. package/dist/api-only.d.ts +6 -3
  9. package/dist/api-only.js +8 -5
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/capacity.d.ts +50 -0
  13. package/dist/capacity.js +49 -0
  14. package/dist/cli-learning/claude-wire.d.ts +41 -0
  15. package/dist/cli-learning/claude-wire.js +258 -0
  16. package/dist/cli-learning/cli.d.ts +11 -0
  17. package/dist/cli-learning/cli.js +241 -0
  18. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  19. package/dist/cli-learning/codex-worktree.js +119 -0
  20. package/dist/cli-learning/connections.d.ts +62 -0
  21. package/dist/cli-learning/connections.js +87 -0
  22. package/dist/cli-learning/entry.d.ts +1 -0
  23. package/dist/cli-learning/entry.js +4 -0
  24. package/dist/cli-learning/evidence.d.ts +78 -0
  25. package/dist/cli-learning/evidence.js +492 -0
  26. package/dist/cli-learning/hook.d.ts +33 -0
  27. package/dist/cli-learning/hook.js +544 -0
  28. package/dist/cli-learning/install.d.ts +33 -0
  29. package/dist/cli-learning/install.js +335 -0
  30. package/dist/cli-learning/observation-proof.d.ts +14 -0
  31. package/dist/cli-learning/observation-proof.js +10 -0
  32. package/dist/cli-learning/policy.d.ts +48 -0
  33. package/dist/cli-learning/policy.js +363 -0
  34. package/dist/cli-learning/schema.d.ts +16 -0
  35. package/dist/cli-learning/schema.js +27 -0
  36. package/dist/cli-learning/state.d.ts +23 -0
  37. package/dist/cli-learning/state.js +61 -0
  38. package/dist/cli.js +24 -2
  39. package/dist/computer-setting.d.ts +8 -0
  40. package/dist/computer-setting.js +11 -0
  41. package/dist/computers.d.ts +6 -2
  42. package/dist/computers.js +2 -2
  43. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  44. package/dist/console/assets/{index-D0mr9wfZ.css → index-DlQepP2J.css} +1 -1
  45. package/dist/console/index.html +2 -2
  46. package/dist/email/email-faux.d.ts +3 -1
  47. package/dist/email/email-faux.js +3 -2
  48. package/dist/email/routes.js +22 -12
  49. package/dist/fal-price.d.ts +76 -0
  50. package/dist/fal-price.js +368 -0
  51. package/dist/harness-install.d.ts +6 -2
  52. package/dist/harness-install.js +40 -8
  53. package/dist/harness.d.ts +1 -1
  54. package/dist/harness.js +2 -2
  55. package/dist/learn/commit.d.ts +5 -0
  56. package/dist/learn/commit.js +4 -1
  57. package/dist/learn/compile.d.ts +13 -5
  58. package/dist/learn/compile.js +24 -7
  59. package/dist/learn/delete.d.ts +12 -6
  60. package/dist/learn/delete.js +17 -11
  61. package/dist/learn/folder.d.ts +11 -0
  62. package/dist/learn/folder.js +20 -3
  63. package/dist/learn/learning-of.d.ts +8 -0
  64. package/dist/learn/learning-of.js +8 -0
  65. package/dist/learn/learning.sh +14 -1
  66. package/dist/learn/promote.d.ts +51 -7
  67. package/dist/learn/promote.js +51 -8
  68. package/dist/learn/secrets.js +14 -3
  69. package/dist/learning-reset.d.ts +18 -0
  70. package/dist/learning-reset.js +115 -0
  71. package/dist/learning-routes.d.ts +1 -1
  72. package/dist/learning-words.d.ts +6 -1
  73. package/dist/learning-words.js +6 -1
  74. package/dist/learning.d.ts +8 -6
  75. package/dist/learning.js +5 -4
  76. package/dist/llms.txt +1 -0
  77. package/dist/mcp-gateway.d.ts +39 -2
  78. package/dist/mcp-gateway.js +41 -10
  79. package/dist/mcp-pin-first.js +3 -2
  80. package/dist/mcp-private-hosts.d.ts +24 -3
  81. package/dist/mcp-private-hosts.js +53 -3
  82. package/dist/mcp-servers-store.d.ts +1 -0
  83. package/dist/mcp-servers-store.js +2 -1
  84. package/dist/media-duration.d.ts +2 -0
  85. package/dist/media-duration.js +136 -0
  86. package/dist/model-gateway.d.ts +2 -0
  87. package/dist/model-gateway.js +3 -1
  88. package/dist/native/runtimes.d.ts +2 -0
  89. package/dist/native/runtimes.js +2 -0
  90. package/dist/observation/learning.d.ts +32 -0
  91. package/dist/observation/learning.js +66 -0
  92. package/dist/observation/observer.d.ts +8 -1
  93. package/dist/observation/observer.js +89 -9
  94. package/dist/observation/schema.js +12 -4
  95. package/dist/observation/usage-identity.d.ts +9 -0
  96. package/dist/observation/usage-identity.js +11 -0
  97. package/dist/openapi.js +133 -24
  98. package/dist/provider.d.ts +8 -0
  99. package/dist/provider.js +14 -2
  100. package/dist/refusal-words.d.ts +0 -3
  101. package/dist/refusal-words.js +0 -3
  102. package/dist/request-metadata.d.ts +20 -0
  103. package/dist/request-metadata.js +24 -0
  104. package/dist/run-launch.d.ts +27 -4
  105. package/dist/run-launch.js +18 -3
  106. package/dist/run-learning-served.d.ts +2 -2
  107. package/dist/run-usage.d.ts +48 -4
  108. package/dist/run-usage.js +156 -39
  109. package/dist/run-view.d.ts +2 -0
  110. package/dist/run-view.js +8 -7
  111. package/dist/runner/adapter-loop.d.ts +3 -1
  112. package/dist/runner/adapter-loop.js +41 -35
  113. package/dist/runner/adapter-run-spec.d.ts +1 -1
  114. package/dist/runner/adapter-run-spec.js +15 -15
  115. package/dist/runner/audit.d.ts +8 -3
  116. package/dist/runner/audit.js +21 -6
  117. package/dist/runner/beside.d.ts +13 -0
  118. package/dist/runner/beside.js +27 -8
  119. package/dist/runner/claim-secrets.d.ts +2 -1
  120. package/dist/runner/claim-secrets.js +5 -3
  121. package/dist/runner/cli-run-spec.d.ts +1 -1
  122. package/dist/runner/cli-run-spec.js +14 -13
  123. package/dist/runner/conformance/harness.js +4 -2
  124. package/dist/runner/disk-free.d.ts +44 -0
  125. package/dist/runner/disk-free.js +96 -0
  126. package/dist/runner/dispatch.js +4 -2
  127. package/dist/runner/feedback-round.d.ts +12 -8
  128. package/dist/runner/feedback-round.js +16 -30
  129. package/dist/runner/harness-loops.js +8 -3
  130. package/dist/runner/journal-kinds.d.ts +4 -1
  131. package/dist/runner/learning-end.d.ts +2 -1
  132. package/dist/runner/learning-end.js +51 -22
  133. package/dist/runner/main.d.ts +17 -6
  134. package/dist/runner/main.js +187 -45
  135. package/dist/runner/mcp-claim.js +1 -1
  136. package/dist/runner/mcp-run.d.ts +9 -0
  137. package/dist/runner/mcp-run.js +16 -1
  138. package/dist/runner/model-route.js +7 -4
  139. package/dist/runner/presence.d.ts +11 -2
  140. package/dist/runner/presence.js +31 -3
  141. package/dist/runner/promotion.d.ts +40 -21
  142. package/dist/runner/promotion.js +130 -59
  143. package/dist/runner/run-child-host.d.ts +12 -15
  144. package/dist/runner/run-child-host.js +52 -112
  145. package/dist/runner/run-errors.js +2 -0
  146. package/dist/runner/runner-check.d.ts +51 -0
  147. package/dist/runner/runner-check.js +206 -0
  148. package/dist/runner/runner-metrics.d.ts +19 -0
  149. package/dist/runner/runner-metrics.js +49 -0
  150. package/dist/runner/runner.d.ts +37 -0
  151. package/dist/runner/runner.js +58 -6
  152. package/dist/runner/sdk-loop.d.ts +2 -2
  153. package/dist/runner/sdk-loop.js +37 -25
  154. package/dist/runner/store-port.d.ts +3 -0
  155. package/dist/runner/workflow-spec.js +3 -3
  156. package/dist/runs-over-store.d.ts +13 -3
  157. package/dist/runs-over-store.js +71 -16
  158. package/dist/sdk/check.d.ts +6 -5
  159. package/dist/sdk/check.js +17 -16
  160. package/dist/sdk/runs.d.ts +22 -2
  161. package/dist/sdk/runs.js +167 -82
  162. package/dist/server.d.ts +3 -0
  163. package/dist/server.js +230 -43
  164. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  165. package/dist/start-switches.js +2 -0
  166. package/dist/stats.d.ts +4 -0
  167. package/dist/stats.js +1 -1
  168. package/dist/store/agent-body.d.ts +16 -0
  169. package/dist/store/agent-body.js +20 -3
  170. package/dist/store/dialect.d.ts +2 -0
  171. package/dist/store/dialect.js +1 -0
  172. package/dist/store/index.d.ts +3 -3
  173. package/dist/store/index.js +2 -2
  174. package/dist/store/journal/storage.d.ts +2 -0
  175. package/dist/store/journal/storage.js +2 -1
  176. package/dist/store/postgres/connection.d.ts +5 -2
  177. package/dist/store/postgres/connection.js +19 -7
  178. package/dist/store/postgres/dialect.js +1 -0
  179. package/dist/store/postgres/migrate.d.ts +30 -0
  180. package/dist/store/postgres/migrate.js +72 -5
  181. package/dist/store/postgres/migration-lint.d.ts +8 -0
  182. package/dist/store/postgres/migration-lint.js +119 -0
  183. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  184. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  185. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  186. package/dist/store/postgres/store.d.ts +8 -3
  187. package/dist/store/postgres/store.js +31 -11
  188. package/dist/store/schema.d.ts +32 -2
  189. package/dist/store/schema.js +74 -5
  190. package/dist/store/sqlite/run-launch.d.ts +31 -1
  191. package/dist/store/sqlite/run-launch.js +111 -2
  192. package/dist/store/sqlite/run-patch.d.ts +2 -1
  193. package/dist/store/sqlite/run-patch.js +4 -3
  194. package/dist/store/sqlite/store.d.ts +17 -0
  195. package/dist/store/sqlite/store.js +226 -37
  196. package/dist/store/store-schema.d.ts +34 -0
  197. package/dist/store/store-schema.js +125 -0
  198. package/dist/store/store.d.ts +120 -5
  199. package/dist/store/store.js +13 -0
  200. package/dist/store-reads/analytics.d.ts +3 -2
  201. package/dist/store-reads/analytics.js +20 -8
  202. package/dist/store-reads/learning.d.ts +12 -8
  203. package/dist/store-reads/learning.js +33 -24
  204. package/dist/store-reads/loop.d.ts +4 -3
  205. package/dist/store-reads/loop.js +7 -5
  206. package/dist/store-view.d.ts +4 -3
  207. package/dist/store-view.js +11 -7
  208. package/dist/template-eval.js +4 -4
  209. package/dist/templates.d.ts +6 -2
  210. package/dist/templates.js +7 -5
  211. package/dist/timeline/labels.js +1 -1
  212. package/dist/tool-gate.d.ts +4 -2
  213. package/dist/tools.js +1 -1
  214. package/dist/unified-usage.d.ts +24 -0
  215. package/dist/unified-usage.js +400 -0
  216. package/dist/uploads-archil.d.ts +100 -0
  217. package/dist/uploads-archil.js +431 -0
  218. package/dist/uploads.d.ts +52 -1
  219. package/dist/uploads.js +186 -108
  220. package/dist/validate.js +5 -1
  221. package/dist/web-save.d.ts +3 -0
  222. package/dist/web-save.js +17 -2
  223. package/dist/workspace/archil-disk.d.ts +6 -5
  224. package/dist/workspace/archil-disk.js +27 -12
  225. package/dist/workspace/archil-exec.js +1 -1
  226. package/dist/workspace/archil.js +4 -3
  227. package/dist/workspace/revision-skills.js +24 -11
  228. package/dist/workspace/synced-folder.d.ts +3 -3
  229. package/dist/workspace/synced-folder.js +7 -6
  230. package/package.json +10 -10
  231. package/skills/agentrun-serve/SKILL.md +52 -7
  232. package/dist/console/assets/index-D7G6o-1E.js +0 -720
package/dist/uploads.js CHANGED
@@ -3,10 +3,11 @@
3
3
  // for it at its start and copied into its workspace at its claim. Each file is `<data>/files/<file_id>/`: its bytes
4
4
  // (`bytes`) and its record (`file.json`, the contract's File), both 0600, the record written whole. A ready file's bytes
5
5
  // never change, and a run gets a copy of them through its Workspace, never a link: nothing a run does reaches the upload.
6
- import { createHash, randomBytes } from "node:crypto";
6
+ import { createHash } from "node:crypto";
7
7
  import { copyFile, link, lstat, mkdir, open, readdir, readFile, rename, rm, unlink } from "node:fs/promises";
8
8
  import { DISK_DIR } from "./server-fs.js";
9
9
  import { dirname, join } from "node:path";
10
+ import { uuidv7 } from "./agents-store.js";
10
11
  import { ApiError, invalid } from "./errors.js";
11
12
  import { typeOf } from "./file-types.js";
12
13
  import { readJson, serialBy, tempOf, writeDurable } from "./files.js";
@@ -59,16 +60,6 @@ export const uploadUrl = (id) => `/v2/files/${id}`;
59
60
  /** Test seams, tests only: as a run's copy starts, with the run's Workspace, before any file is copied; and as a file
60
61
  * sent in one call writes its record, with the file's folder, its bytes in place. */
61
62
  export const uploadTestHooks = {};
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
- * sort by creation time. The store mints its own inside it and exports no minter. */
64
- function uuidv7(now = Date.now()) {
65
- const bytes = randomBytes(16);
66
- bytes.writeUIntBE(now, 0, 6);
67
- bytes[6] = (bytes[6] & 0x0f) | 0x70;
68
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
69
- const hex = bytes.toString("hex");
70
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
71
- }
72
63
  /** Why `path` is not the contract's FilePathString (relative, `/` between segments, no empty segment and none that starts
73
64
  * with `.`, no backslash or NUL, at most 1024 characters), or a segment is longer than a name on disk; undefined when it
74
65
  * is one. */
@@ -192,9 +183,8 @@ export class Uploads {
192
183
  await rm(join(this.root, id), { recursive: true, force: true });
193
184
  });
194
185
  }
195
- /** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
196
186
  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() } };
187
+ return answerOf(file);
198
188
  }
199
189
  /** POST /v2/files?path=...: the body is the file's bytes, whatever its type but a multipart form (415, with the call
200
190
  * that works). The query takes `path`, and `content_type` and `sha256` when given; the length is the body's and the hash
@@ -202,28 +192,7 @@ export class Uploads {
202
192
  * else the path's extension's, else octet-stream. The bytes stream to a dot-named file of their own under the root,
203
193
  * never held whole; over MAX_UPLOAD_BYTES is 413, a `sha256` they do not have 422. Nothing is made until `commit`. */
204
194
  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";
195
+ const { path, sha, contentType } = sentInOneCall(query, requestType, (path) => this.problemOf(path));
227
196
  await mkdir(this.root, { recursive: true, mode: 0o700 });
228
197
  const temp = tempOf(join(this.root, ".incoming"));
229
198
  const handle = await open(temp, "wx", 0o600);
@@ -244,13 +213,13 @@ export class Uploads {
244
213
  throw invalid([{ field: "sha256", reason: "invalid", message: `The body's SHA-256 is ${sha256}; the query names ${sha}.` }]);
245
214
  await handle.sync();
246
215
  await handle.close();
247
- const fingerprint = { sent_in_one_call: true, path: path, content_type: contentType, size_bytes: size, sha256 };
216
+ const fingerprint = { sent_in_one_call: true, path, content_type: contentType, size_bytes: size, sha256 };
248
217
  let made = false;
249
218
  return {
250
219
  fingerprint,
251
220
  commit: async () => {
252
221
  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 };
222
+ 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
223
  const dir = join(this.root, file.file_id);
255
224
  await mkdir(dir, { mode: 0o700 });
256
225
  try {
@@ -280,34 +249,7 @@ export class Uploads {
280
249
  }
281
250
  /** POST /v2/files: the body checked as the contract's FileCreate, then a pending file; with where to send its bytes. */
282
251
  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
- };
252
+ const file = reservation(body, (path) => this.problemOf(path));
311
253
  await mkdir(this.root, { recursive: true, mode: 0o700 });
312
254
  await mkdir(join(this.root, file.file_id), { mode: 0o700 });
313
255
  await writeDurable(join(this.root, file.file_id, RECORD), `${JSON.stringify(file)}\n`);
@@ -401,34 +343,7 @@ export class Uploads {
401
343
  }
402
344
  /** 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
345
  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;
346
+ return readyFilesOf(ids, (id) => this.get(id), (path) => this.problemOf(path));
432
347
  }
433
348
  /** Copies `files` into the run's `inputs/` through its Workspace, each at its `path` with its folders, in order, before
434
349
  * 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 +352,7 @@ export class Uploads {
437
352
  * the copy (ESCAPE), and nothing is written through it. `bytesOf`: where each file's bytes are read (its upload's own,
438
353
  * or the run's hold of them, `held`). */
439
354
  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
- }
355
+ await copyFilesInto(workspaceAt(work), files, (file) => readFile(bytesOf(file)));
455
356
  }
456
357
  /** At a run's start, before its row is written: each of its files (`ids`, ready) held for it under
457
358
  * `<root>/.held/<run id>/`, its record and its bytes (a hard link to the upload's, which never change once ready; a
@@ -501,6 +402,183 @@ export class Uploads {
501
402
  return (await readdir(join(this.root, HELD_DIR)).catch(() => [])).filter((name) => ID.test(name));
502
403
  }
503
404
  }
405
+ /** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
406
+ 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() } });
407
+ /** Whether `value` reads as a File record. */
408
+ export const isUploadedFile = isFile;
409
+ /** A file sent in one call, its query and request type checked (Uploads.take): its path, the hash the query names (or
410
+ * null) and its type. `problemOf`: why a path cannot be a file's path in this store. */
411
+ export function sentInOneCall(query, requestType, problemOf) {
412
+ const type = String(requestType ?? "").trim();
413
+ if (/^multipart\//i.test(type))
414
+ 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.");
415
+ 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.` }));
416
+ for (const key of QUERY)
417
+ if (query.getAll(key).length > 1)
418
+ issues.push({ field: key, reason: "duplicate", message: `${key} is given more than once` });
419
+ const path = query.get("path");
420
+ // An empty one is none.
421
+ const named = query.get("content_type") || null;
422
+ const sha = query.get("sha256");
423
+ if (path === null)
424
+ 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." });
425
+ if (sha !== null && !SHA256.test(sha))
426
+ issues.push({ field: "sha256", reason: "bad_format", message: "sha256 is 64 lowercase hex digits" });
427
+ if (issues.length)
428
+ throw invalid(issues);
429
+ const problem = problemOf(path);
430
+ if (problem)
431
+ throw new ApiError("invalid_file_path", problem);
432
+ const given = type && !GENERIC_TYPES.has(type.split(";")[0].trim().toLowerCase()) ? type : undefined;
433
+ return { path: path, sha, contentType: named ?? given ?? typeOf(path) ?? "application/octet-stream" };
434
+ }
435
+ /** POST /v2/files's JSON body checked as the contract's FileCreate (Uploads.reserve): the pending file it makes, not yet
436
+ * written. */
437
+ export function reservation(body, problemOf) {
438
+ const issues = unknownFields(body, FIELDS);
439
+ if (typeof body.path !== "string")
440
+ issues.push({ field: "path", reason: body.path === undefined ? "missing" : "wrong_type", message: "path is the file's relative path, a string" });
441
+ if (!(Number.isSafeInteger(body.size_bytes) && body.size_bytes >= 0))
442
+ 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" });
443
+ if (body.content_type !== undefined && typeof body.content_type !== "string")
444
+ issues.push({ field: "content_type", reason: "wrong_type", message: "content_type is a string" });
445
+ if (body.sha256 !== undefined && !(typeof body.sha256 === "string" && SHA256.test(body.sha256)))
446
+ issues.push({ field: "sha256", reason: typeof body.sha256 === "string" ? "bad_format" : "wrong_type", message: "sha256 is 64 lowercase hex digits" });
447
+ if (issues.length)
448
+ throw invalid(issues);
449
+ const problem = problemOf(body.path);
450
+ if (problem)
451
+ throw new ApiError("invalid_file_path", problem);
452
+ if (body.size_bytes > MAX_UPLOAD_BYTES)
453
+ throw new ApiError("payload_too_large", `size_bytes is over ${MAX_UPLOAD_BYTES}, this server's largest upload`, { details: { limit: "max_upload_bytes" } });
454
+ const now = Date.now();
455
+ return {
456
+ file_id: uuidv7(now),
457
+ path: body.path,
458
+ size_bytes: body.size_bytes,
459
+ // Named, or by the path's extension as a run's files are served (`plan.md` is text/markdown), else octet-stream.
460
+ content_type: body.content_type ?? typeOf(body.path) ?? "application/octet-stream",
461
+ sha256: body.sha256 ?? null,
462
+ status: "pending",
463
+ created_at: new Date(now).toISOString(),
464
+ expires_at: null,
465
+ };
466
+ }
467
+ /** A body's bytes against the file `held` was reserved or made as: the 422 at the field that differs, or undefined. */
468
+ export function mismatchOf(held, size, sha256) {
469
+ return size !== held.size_bytes
470
+ ? invalid([{ field: "size_bytes", reason: "invalid", message: `The body is ${size} bytes; the file was reserved with size_bytes ${held.size_bytes}.` }])
471
+ : held.sha256 !== null && held.sha256 !== sha256
472
+ ? 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}.` }])
473
+ : undefined;
474
+ }
475
+ /** A run's `file_ids` (Uploads.readyFiles): each a file `get` finds ready, none twice, at most MAX_FILES_PER_RUN, or 422
476
+ * at `file_ids`. `problemOf`: why a ready file's path cannot be copied into a run of this store. */
477
+ export async function readyFilesOf(ids, get, problemOf) {
478
+ const issues = [];
479
+ if (ids.length > MAX_FILES_PER_RUN)
480
+ 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}.` });
481
+ else if (new Set(ids).size !== ids.length)
482
+ issues.push({ field: "file_ids", reason: "duplicate", message: "file_ids names one file twice" });
483
+ if (issues.length)
484
+ throw invalid(issues);
485
+ const files = [];
486
+ // Every record read at once (each a round trip to the disk in Mode 2), then judged in order.
487
+ const found = await Promise.all(ids.map((id) => (typeof id === "string" && ID.test(id) ? get(id) : Promise.resolve(null))));
488
+ for (const [i, id] of ids.entries()) {
489
+ const field = `file_ids[${i}]`;
490
+ if (typeof id !== "string" || !ID.test(id)) {
491
+ 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).` });
492
+ continue;
493
+ }
494
+ const file = found[i];
495
+ const problem = file?.status === "ready" ? problemOf(file.path) : undefined;
496
+ if (!file)
497
+ issues.push({ field, reason: "not_an_option", message: `There is no file ${id}: reserve it with POST /v2/files.` });
498
+ else if (file.status !== "ready")
499
+ issues.push({ field, reason: "invalid", message: `The file ${id} is not ready: send its bytes with PUT /v2/files/${id} first.` });
500
+ else if (problem)
501
+ issues.push({ field, reason: "invalid", message: `The file ${id} cannot be copied into a run here: ${problem}.` });
502
+ else
503
+ files.push(file);
504
+ }
505
+ if (issues.length)
506
+ throw invalid(issues);
507
+ return files;
508
+ }
509
+ /** Copies `files` into the workspace's `inputs/` (Uploads.copyInto), each at its `path` with its folders: a name taken
510
+ * already (the same path twice, a file where another's folder goes, or what the folder held before) gets the next free
511
+ * suffix (`notes-2.txt`, `docs-2/`), the same for the same files in the same order, every name chosen before the first
512
+ * byte is written. Each copy is a new file written whole by the Workspace. `read`: a file's bytes. `concurrency`: how
513
+ * many files are read and written at once (default 1, one after another); `turn`: each file's read and write runs
514
+ * inside it, as a limit shared with other copies (slots) takes them; `signal`: stops the copy before its next file,
515
+ * rejecting with the signal's reason. */
516
+ export async function copyFilesInto(workspace, files, read, { concurrency = 1, turn = (copy) => copy(), signal } = {}) {
517
+ await uploadTestHooks.beforeCopy?.(workspace);
518
+ const names = takenNames(workspace);
519
+ // inputs/message.md is the run's message's (MESSAGE_FILE), never an upload's.
520
+ const top = await names(INPUTS_DIR);
521
+ if (!top.has(MESSAGE_FILE))
522
+ top.set(MESSAGE_FILE, "file");
523
+ const targets = [];
524
+ for (const file of files) {
525
+ const segments = file.path.split("/");
526
+ let dir = INPUTS_DIR;
527
+ for (const segment of segments.slice(0, -1))
528
+ dir = `${dir}/${free(await names(dir), segment, "dir")}`;
529
+ targets.push({ file, to: `${dir}/${free(await names(dir), segments.at(-1), "file")}` });
530
+ }
531
+ let next = 0;
532
+ // One file that fails stops the others before their next file: nothing more is written once the copy has failed.
533
+ let failed = false;
534
+ const worker = async () => {
535
+ while (!failed && next < targets.length) {
536
+ const { file, to } = targets[next++];
537
+ try {
538
+ // Checked once the turn is had too: a file that waited for one past the deadline is not started.
539
+ signal?.throwIfAborted();
540
+ await turn(async () => {
541
+ signal?.throwIfAborted();
542
+ await workspace.write(to, await read(file));
543
+ });
544
+ }
545
+ catch (error) {
546
+ failed = true;
547
+ throw error;
548
+ }
549
+ }
550
+ };
551
+ // Every worker settles before the copy answers, so nothing it started is still writing once a caller cleans up.
552
+ const settled = await Promise.allSettled(Array.from({ length: Math.max(1, Math.min(concurrency, targets.length)) }, worker));
553
+ const first = settled.find((one) => one.status === "rejected");
554
+ if (first)
555
+ throw first.reason;
556
+ }
557
+ /** At most `size` of the calls given to it running at once, the rest waiting in the order they came: a slot a call
558
+ * leaves goes straight to the next one waiting. */
559
+ export function slots(size) {
560
+ let running = 0;
561
+ const waiting = [];
562
+ return async (work) => {
563
+ if (running < size)
564
+ running++;
565
+ else
566
+ await new Promise((resolve) => waiting.push(resolve));
567
+ try {
568
+ return await work();
569
+ }
570
+ finally {
571
+ const next = waiting.shift();
572
+ if (next)
573
+ next();
574
+ else
575
+ running--;
576
+ }
577
+ };
578
+ }
579
+ /** The files a run's claim copies in (placeRunInputs): its launch's, unless the server already placed them in its folder
580
+ * when it started the run (Mode 2, RunLaunch.filesPlaced), when the claim reads no upload at all. */
581
+ export const filesToCopy = (launch) => (launch.filesPlaced ? [] : (launch.files ?? []));
504
582
  /** The words a run fails in when its files cannot be copied into its workspace at its claim. */
505
583
  export const notCopied = (why) => `The run's files could not be copied into its workspace: ${why}`;
506
584
  /** 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", "max_requests", "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. */
@@ -175,6 +175,10 @@ export function definitionIssues(definition, { at = "definition", creating = tru
175
175
  if (!(typeof d.max_cost_usd === "number" && Number.isFinite(d.max_cost_usd) && d.max_cost_usd >= 0))
176
176
  out.push(issue(`${at}.max_cost_usd`, "wrong_type", `${at}.max_cost_usd is a number of at least 0, in US dollars: above 0 sets the agent's default cap, 0 clears it`));
177
177
  }
178
+ // The agent's own limit on each run's requests on free models, under the server's (AGENTRUN_FREE_MODEL_REQUESTS, which
179
+ // wins when lower): above 0 sets it, 0 clears it, and an edit that leaves it out keeps the agent's (agents-store.ts).
180
+ if (d.max_requests !== undefined && !(typeof d.max_requests === "number" && Number.isSafeInteger(d.max_requests) && d.max_requests >= 0))
181
+ out.push(issue(`${at}.max_requests`, "wrong_type", `${at}.max_requests is a whole number of at least 0: above 0 sets the most requests on free models each run makes (the server's own limit holds when it is lower), 0 clears it`));
178
182
  // The server's checkout before each run's first turn: kept by an edit that leaves it out, cleared by `none`.
179
183
  if (d.checkout !== undefined) {
180
184
  if (d.workflow !== undefined)
@@ -16,11 +16,14 @@ export declare const MEDIA_DIR = "media";
16
16
  export declare const PATH_MAX_CHARS = 1024;
17
17
  export declare const TYPE_MAX_CHARS = 255;
18
18
  export declare const WORDS_MAX_CHARS = 2000;
19
+ /** `duration_s`: an audio or video file's length in seconds (to the millisecond), when its bytes give it (mp3, wav, mp4,
20
+ * m4a, mov: media-duration.ts); absent for any other file, so an agent can time a cut or price a job billed by length. */
19
21
  export type Saved = {
20
22
  ok: true;
21
23
  path: string;
22
24
  bytes: number;
23
25
  content_type: string;
26
+ duration_s?: number;
24
27
  url: string;
25
28
  };
26
29
  export type Unsaved = {
package/dist/web-save.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import { extname } from "node:path";
5
5
  import { defineTool } from "@earendil-works/pi-durable";
6
6
  import { extensionOf, typeOf } from "./file-types.js";
7
+ import { mediaSeconds } from "./media-duration.js";
7
8
  import { clip, URL_MAX } from "./web-fetch-direct.js";
8
9
  import { forModel } from "./result.js";
9
10
  import { isWorkspaceError, workspaceErrorWords } from "./workspace/index.js";
@@ -203,12 +204,26 @@ export async function webSave(args, work, options = {}) {
203
204
  catch (error) {
204
205
  return { ...failed(error), url: final };
205
206
  }
206
- return { ok: true, path: at, bytes: file.bytes.length, content_type: typed.type, url: final };
207
+ const seconds = lengthOf(file.bytes, typed.type);
208
+ return { ok: true, path: at, bytes: file.bytes.length, content_type: typed.type, ...(seconds === undefined ? {} : { duration_s: seconds }), url: final };
207
209
  }
208
210
  finally {
209
211
  release();
210
212
  }
211
213
  }
214
+ /** An audio or video file's length in seconds, rounded to the millisecond; undefined for any other type, or when its bytes
215
+ * don't give it. Never throws: a saved file is answered saved whatever its bytes hold. */
216
+ function lengthOf(bytes, type) {
217
+ if (!/^(audio|video)\//.test(type))
218
+ return undefined;
219
+ try {
220
+ const seconds = mediaSeconds(bytes);
221
+ return seconds === undefined ? undefined : Math.round(seconds * 1000) / 1000;
222
+ }
223
+ catch {
224
+ return undefined;
225
+ }
226
+ }
212
227
  /** The words the model reads: the answer's JSON. */
213
228
  export const savedText = (answer) => JSON.stringify(answer);
214
229
  /** web_save on `work`, its download through `guard` (a test's or the fakes' resolver and fetch, none for the network), its
@@ -216,7 +231,7 @@ export const savedText = (answer) => JSON.stringify(answer);
216
231
  export function webSaveTool(work, guard, slots) {
217
232
  return defineTool({
218
233
  name: WEB_SAVE_TOOL,
219
- description: `Download one file from a public URL into this run's folder, where it stays (the run's Files show and play it): use it for a generated image, audio or video a service answered with a link that expires. path is where to save it, relative to the run's folder; a bare name (cat.png) goes under ${MEDIA_DIR}/. A path that already holds a file is refused, never overwritten. The file must be a type its bytes show: an image (png, jpeg, gif, webp), audio (mp3, wav, ogg, m4a) or video (mp4, webm), and the path must have an extension of that type (cat.png, not cat or cat.bin); any other type (a page, a PDF, text) is saved only to a path whose extension names the type the host declares. At most ${SAVE_MAX_BYTES / (1024 * 1024)} MiB and ${SAVE_TIMEOUT_MS / 60_000} minutes. A private or local address, a port other than 80 or 443, or a scheme other than http(s) is refused, at every redirect too. Answers JSON: { ok: true, path, bytes, content_type, url } (url the final one, after redirects), or { ok: false, url, refused } when it was refused, { ok: false, url, error } when it failed; nothing is left at the path when it does not save.`,
234
+ description: `Download one file from a public URL into this run's folder, where it stays (the run's Files show and play it): use it for a generated image, audio or video a service answered with a link that expires. path is where to save it, relative to the run's folder; a bare name (cat.png) goes under ${MEDIA_DIR}/. A path that already holds a file is refused, never overwritten. The file must be a type its bytes show: an image (png, jpeg, gif, webp), audio (mp3, wav, ogg, m4a) or video (mp4, webm), and the path must have an extension of that type (cat.png, not cat or cat.bin); any other type (a page, a PDF, text) is saved only to a path whose extension names the type the host declares. At most ${SAVE_MAX_BYTES / (1024 * 1024)} MiB and ${SAVE_TIMEOUT_MS / 60_000} minutes. A private or local address, a port other than 80 or 443, or a scheme other than http(s) is refused, at every redirect too. Answers JSON: { ok: true, path, bytes, content_type, duration_s?, url } (url the final one, after redirects; duration_s an audio or video file's length in seconds, when its bytes give it: mp3, wav, mp4, m4a), or { ok: false, url, refused } when it was refused, { ok: false, url, error } when it failed; nothing is left at the path when it does not save.`,
220
235
  parameters: {
221
236
  type: "object",
222
237
  additionalProperties: false,
@@ -60,9 +60,10 @@ export type ArchilExecAnswer = {
60
60
  readonly stdout: string;
61
61
  readonly stderr: string;
62
62
  };
63
- /** The disk itself is not there: Archil's lookup of it, made before the SDK's first call, answered 404 (removed, or the
64
- * key's account or region holds none of that id). Every SDK call fails with it. It carries no HTTP `status`, so no
65
- * caller reads it as a missing file or folder. */
63
+ /** The disk itself is not there: Archil's lookup of it, made before the SDK's first call and again after any call
64
+ * answered 404, answered 404 (removed, at the start or mid-run, or the key's account or region holds none of that id).
65
+ * Every call that meets it fails with it. It carries no HTTP `status`, so no caller reads it as a missing file or
66
+ * folder. */
66
67
  export declare class ArchilDiskMissing extends Error {
67
68
  readonly disk: string;
68
69
  readonly region: string;
@@ -70,8 +71,8 @@ export declare class ArchilDiskMissing extends Error {
70
71
  }
71
72
  /**
72
73
  * An Archil disk, keys relative to its root. A failed call rejects with an error carrying the HTTP `status` when there
73
- * was an answer (the SDK's ArchilS3Error and ArchilApiError do, and so does the ranged read here), or, from every call
74
- * but the ranged read, ArchilDiskMissing when Archil has no such disk.
74
+ * was an answer (the SDK's ArchilS3Error and ArchilApiError do, and so does the ranged read here), or ArchilDiskMissing
75
+ * when Archil has no such disk.
75
76
  */
76
77
  export interface ArchilDisk {
77
78
  readonly id: string;
@@ -16,9 +16,10 @@ export function pinnedImage(image) {
16
16
  }
17
17
  /** The one network an exec is given: no egress. */
18
18
  export const DENY_EGRESS = Object.freeze({ egress: Object.freeze({ default: "deny" }) });
19
- /** The disk itself is not there: Archil's lookup of it, made before the SDK's first call, answered 404 (removed, or the
20
- * key's account or region holds none of that id). Every SDK call fails with it. It carries no HTTP `status`, so no
21
- * caller reads it as a missing file or folder. */
19
+ /** The disk itself is not there: Archil's lookup of it, made before the SDK's first call and again after any call
20
+ * answered 404, answered 404 (removed, at the start or mid-run, or the key's account or region holds none of that id).
21
+ * Every call that meets it fails with it. It carries no HTTP `status`, so no caller reads it as a missing file or
22
+ * folder. */
22
23
  export class ArchilDiskMissing extends Error {
23
24
  disk;
24
25
  region;
@@ -172,6 +173,20 @@ class SdkArchilDisk {
172
173
  this.#readyKey = apiKey;
173
174
  return ready;
174
175
  }
176
+ /** `call` made with the client and the disk. */
177
+ async #call(call) {
178
+ return call(await this.#sdk()).catch((error) => this.#after(error));
179
+ }
180
+ /** Throws `error`. A 404 is a missing key, or the disk itself removed at Archil since #sdk looked it up: the disk is
181
+ * looked up again (one disks.get), so a disk not there fails the call that met it as ArchilDiskMissing. The 404 is
182
+ * kept only once the lookup found the disk; a lookup that failed otherwise is the call's failure. */
183
+ async #after(error) {
184
+ if (error?.status === 404) {
185
+ this.#ready = undefined;
186
+ await this.#sdk();
187
+ }
188
+ throw error;
189
+ }
175
190
  /** The client made and the disk looked up: one disks.get. A key of the wrong kind fails here (401 or 403). */
176
191
  async ready() {
177
192
  await this.#sdk();
@@ -218,25 +233,25 @@ class SdkArchilDisk {
218
233
  await pause(100 * 2 ** attempt);
219
234
  continue;
220
235
  }
221
- throw new RangeReadError(response.status, response.statusText, body);
236
+ return this.#after(new RangeReadError(response.status, response.statusText, body));
222
237
  }
223
238
  }
224
239
  async putObject(key, body) {
225
- await (await this.#sdk()).disk.putObject(key, body);
240
+ await this.#call(({ disk }) => disk.putObject(key, body));
226
241
  }
227
242
  async appendObject(key, body) {
228
- await (await this.#sdk()).disk.appendObject(key, body);
243
+ await this.#call(({ disk }) => disk.appendObject(key, body));
229
244
  }
230
245
  async deleteObject(key) {
231
- await (await this.#sdk()).disk.deleteObject(key);
246
+ await this.#call(({ disk }) => disk.deleteObject(key));
232
247
  }
233
248
  async deleteObjects(keys) {
234
- return (await (await this.#sdk()).disk.deleteObjects([...keys], { quiet: true })).errors;
249
+ return (await this.#call(({ disk }) => disk.deleteObjects([...keys], { quiet: true }))).errors;
235
250
  }
236
251
  async listPage(prefix, options) {
237
- const page = await (await this.#sdk()).disk.listObjects(prefix, {
252
+ const page = await this.#call(({ disk }) => disk.listObjects(prefix, {
238
253
  recursive: options.recursive, singlePage: true, ...(options.token === undefined ? {} : { continuationToken: options.token }),
239
- });
254
+ }));
240
255
  const next = page.isTruncated ? page.nextContinuationToken : undefined;
241
256
  return {
242
257
  objects: page.objects.map(({ key, size, lastModified }) => ({ key, size, ...(lastModified === undefined ? {} : { mtimeMs: lastModified.getTime() }) })),
@@ -244,7 +259,7 @@ class SdkArchilDisk {
244
259
  };
245
260
  }
246
261
  async grep(request) {
247
- const answer = await (await this.#sdk()).disk.grep({ ...request, globs: request.globs === undefined ? undefined : [...request.globs] });
262
+ const answer = await this.#call(({ disk }) => disk.grep({ ...request, globs: request.globs === undefined ? undefined : [...request.globs] }));
248
263
  return { matches: answer.matches.map(({ file, line, text }) => ({ file, line, text })), stoppedReason: answer.stoppedReason };
249
264
  }
250
265
  async exec(request) {
@@ -268,7 +283,7 @@ class SdkArchilDisk {
268
283
  ...(request.network === undefined ? {} : { network: { egress: { default: request.network.egress.default } } }),
269
284
  command: request.command,
270
285
  disks: Object.fromEntries(Object.entries(request.mounts).map(([name, subdirectory]) => [name, { disk: this.id, subdirectory, queueMs: request.queueMs }])),
271
- });
286
+ }).catch((error) => this.#after(error));
272
287
  return { exitCode: answer.exitCode, stdout: answer.stdout, stderr: answer.stderr };
273
288
  }
274
289
  }
@@ -222,7 +222,7 @@ export async function archilExec(disk, job) {
222
222
  };
223
223
  }
224
224
  case "link": throw new WorkspaceError("ESCAPE", `${show(job.cwd)} has a symbolic link on the way, and a workspace follows none`, { path });
225
- case "nocwd": throw new WorkspaceError("NOT_FOUND", `${show(job.cwd)} is not there`, { path });
225
+ case "nocwd": throw new WorkspaceError("NOT_FOUND", `${show(job.cwd)} is not there (exec; Archil: no folder ${job.root}/${path} on disk ${disk.id})`, { path });
226
226
  case "notdir": throw new WorkspaceError("REFUSED", `${show(job.cwd)} is not a directory`, { path });
227
227
  case "noprog": throw new WorkspaceError("NOT_FOUND", `${JSON.stringify(job.argv[0])} is not a program here (PATH ${JSON.stringify(job.env.PATH ?? "")})`, { path });
228
228
  case "noroot": throw new WorkspaceError("UNAVAILABLE", `the workspace's folder ${job.root} or its spill folder was not mounted`, { path });
@@ -300,8 +300,9 @@ class ArchilWorkspace {
300
300
  answer = await this.#disk.getRange(this.#key(rel), `bytes=${offset}-${last}`);
301
301
  }
302
302
  catch (error) {
303
- // A ranged read is no SDK call, so a disk that is not there answers it 404 as a missing file would: the look at what
304
- // is there (an SDK call) is what tells them apart, and its ArchilDiskMissing is the read's failure.
303
+ // The seam looks the disk up again after a ranged read's 404, so a disk gone at Archil, at the start or mid-run, is
304
+ // its ArchilDiskMissing (no status). A 404 left is a file that is not there, or a folder: the look at what is there
305
+ // tells them apart, and a disk removed in between still fails the read as gone.
305
306
  const kind = statusOf(error) === 404
306
307
  ? await this.#kind(rel).catch((lookup) => {
307
308
  if (lookup instanceof ArchilDiskMissing)
@@ -443,7 +444,7 @@ class ArchilWorkspace {
443
444
  if (entries.size === 0 && rel !== "") {
444
445
  const kind = await this.#kind(rel).catch((error) => { throw failed(error, rel, "list"); });
445
446
  if (kind === undefined)
446
- throw new WorkspaceError("NOT_FOUND", `${show(rel)} is not there`, { path: rel });
447
+ throw new WorkspaceError("NOT_FOUND", `${show(rel)} is not there (list; Archil: nothing under ${prefix} on disk ${this.#disk.id})`, { path: rel });
447
448
  if (kind === "file")
448
449
  throw new WorkspaceError("REFUSED", `${show(rel)} is not a directory`, { path: rel });
449
450
  }