@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
@@ -0,0 +1,235 @@
1
+ // web_save: one public file saved into the run's Workspace (a bare name under media/), so a link that expires becomes a
2
+ // file the run keeps. It downloads through the public-host guard's bytes variant (pi-browser publicDownload, web_fetch's
3
+ // hop loop) and writes once through the Workspace, never over a path in use, a media type only when its bytes agree.
4
+ import { extname } from "node:path";
5
+ import { defineTool } from "@earendil-works/pi-durable";
6
+ import { extensionOf, typeOf } from "./file-types.js";
7
+ import { clip, URL_MAX } from "./web-fetch-direct.js";
8
+ import { forModel } from "./result.js";
9
+ import { isWorkspaceError, workspaceErrorWords } from "./workspace/index.js";
10
+ export const WEB_SAVE_TOOL = "web_save";
11
+ /** The most bytes a saved file may have. */
12
+ export const SAVE_MAX_BYTES = 200 * 1024 * 1024;
13
+ /** 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
14
+ * large file on any link under about 7 MB/s. */
15
+ export const SAVE_TIMEOUT_MS = 600_000;
16
+ /** The folder a bare name is saved in. */
17
+ export const MEDIA_DIR = "media";
18
+ /** The longest path web_save takes, and the most characters of a declared type and of a failure's words an answer
19
+ * carries: with the URL's URL_MAX, they bound every answer (host-bounds.test.mjs). */
20
+ export const PATH_MAX_CHARS = 1_024;
21
+ export const TYPE_MAX_CHARS = 255;
22
+ export const WORDS_MAX_CHARS = 2_000;
23
+ /** The most web_save downloads at once per runner, across its runs (SERVER_SLOTS); the rest wait under their own
24
+ * deadline. Each holds its file in memory until its one write: its size when its host states its length, about twice
25
+ * that at the peak when it does not (publicDownload). So a runner's downloads hold at most 800 MiB at 200 MiB a file,
26
+ * about 1.6 GiB when no host states a length; Mode 2's pieced writes (runner/big-writes.ts) can add 800 MiB more. */
27
+ export const SAVE_CONCURRENCY = 4;
28
+ export function saveSlots(size) {
29
+ let busy = 0;
30
+ const queue = [];
31
+ const releaser = () => {
32
+ let done = false;
33
+ return () => {
34
+ if (done)
35
+ return;
36
+ done = true;
37
+ // The slot goes straight to the next waiter, so busy only drops when no one waits.
38
+ const next = queue.shift();
39
+ if (next)
40
+ next();
41
+ else
42
+ busy--;
43
+ };
44
+ };
45
+ return {
46
+ size,
47
+ get busy() { return busy; },
48
+ get waiting() { return queue.length; },
49
+ take(signal) {
50
+ if (signal.aborted)
51
+ return Promise.reject(signal.reason);
52
+ if (busy < size) {
53
+ busy++;
54
+ return Promise.resolve(releaser());
55
+ }
56
+ return new Promise((resolve, reject) => {
57
+ const leave = () => {
58
+ queue.splice(queue.indexOf(grant), 1);
59
+ reject(signal.reason);
60
+ };
61
+ const grant = () => {
62
+ signal.removeEventListener("abort", leave);
63
+ resolve(releaser());
64
+ };
65
+ queue.push(grant);
66
+ signal.addEventListener("abort", leave, { once: true });
67
+ });
68
+ },
69
+ };
70
+ }
71
+ /** The runner's one gate: at most SAVE_CONCURRENCY downloads at once per runner, across its runs. A run in the runner's
72
+ * own process takes it here; a run in a process of its own takes it over its channel (runner/save-slots.ts). */
73
+ export const SERVER_SLOTS = saveSlots(SAVE_CONCURRENCY);
74
+ const ascii = (b, at, text) => b.length >= at + text.length && [...text].every((c, i) => b[at + i] === c.charCodeAt(0));
75
+ const MEDIA = [
76
+ { types: ["image/png"], test: (b) => b.length >= 8 && [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((x, i) => b[i] === x) },
77
+ { types: ["image/jpeg"], test: (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
78
+ { types: ["image/gif"], test: (b) => ascii(b, 0, "GIF87a") || ascii(b, 0, "GIF89a") },
79
+ { types: ["image/webp"], test: (b) => ascii(b, 0, "RIFF") && ascii(b, 8, "WEBP") },
80
+ { types: ["audio/wav"], test: (b) => ascii(b, 0, "RIFF") && ascii(b, 8, "WAVE") },
81
+ // An ID3 tag, or an MPEG audio frame's sync: eleven set bits, then a layer that is not the reserved 00 (which is AAC's).
82
+ { types: ["audio/mpeg"], test: (b) => ascii(b, 0, "ID3") || (b.length >= 2 && b[0] === 0xff && (b[1] & 0xe0) === 0xe0 && (b[1] & 0x06) !== 0) },
83
+ { types: ["audio/ogg"], test: (b) => ascii(b, 0, "OggS") },
84
+ // ISO media: an ftyp box first. Its brand says audio (M4A, M4B) or not; either type may be declared or named.
85
+ { types: ["video/mp4", "audio/mp4"], test: (b) => ascii(b, 4, "ftyp") && !(ascii(b, 8, "M4A ") || ascii(b, 8, "M4B ")) },
86
+ { types: ["audio/mp4", "video/mp4"], test: (b) => ascii(b, 4, "ftyp") },
87
+ // EBML: WebM (and Matroska).
88
+ { types: ["video/webm", "audio/webm"], test: (b) => b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3 },
89
+ ];
90
+ /** Every type MEDIA checks: one of these declared must carry its signature. */
91
+ const MEDIA_TYPES = new Set(MEDIA.flatMap((kind) => kind.types));
92
+ /** Names hosts give some of those types besides the one file-types.ts serves. */
93
+ const ALIASES = new Map([["image/jpg", "image/jpeg"], ["image/pjpeg", "image/jpeg"], ["audio/mp3", "audio/mpeg"], ["audio/x-wav", "audio/wav"], ["audio/wave", "audio/wav"], ["audio/vnd.wave", "audio/wav"], ["audio/x-m4a", "audio/mp4"], ["audio/m4a", "audio/mp4"]]);
94
+ /** Declared types that say nothing about the bytes. */
95
+ const UNTYPED = new Set(["", "application/octet-stream", "binary/octet-stream", "application/binary"]);
96
+ /** A Content-Type as its bare type, lower case, its parameters dropped and its aliases resolved. */
97
+ const bare = (type) => {
98
+ const plain = (type ?? "").split(";")[0].trim().toLowerCase();
99
+ return ALIASES.get(plain) ?? plain;
100
+ };
101
+ /** The type `bytes` are saved as at `path`, the host having declared `declared`, or why they are refused. */
102
+ export function typeFor(bytes, declared, path) {
103
+ if (declared.length > TYPE_MAX_CHARS)
104
+ return { refused: `refused: the host's Content-Type is longer than ${TYPE_MAX_CHARS} characters` };
105
+ const said = bare(declared);
106
+ const named = typeOf(path) === undefined ? undefined : bare(typeOf(path));
107
+ const ext = path.slice(path.lastIndexOf("/") + 1).includes(".") ? path.slice(path.lastIndexOf(".")) : "";
108
+ const kind = MEDIA.find((one) => one.test(bytes));
109
+ if (kind) {
110
+ const sniffed = kind.types[0];
111
+ if (!UNTYPED.has(said) && !kind.types.includes(said))
112
+ return { refused: `refused: the host says ${said}, but the bytes are ${sniffed}` };
113
+ if (named && !kind.types.includes(named))
114
+ return { refused: `refused: the path's extension ${ext} is ${named}, but the bytes are ${sniffed}; save it under an extension of that type` };
115
+ if (!named) {
116
+ const type = kind.types.includes(said) ? said : sniffed;
117
+ // audio/webm has no extension of its own; .webm (video/webm) holds it.
118
+ return { refused: `refused: ${path} has no extension of ${type}; save it as ${path.slice(0, path.length - extname(path).length)}.${extensionOf(type) ?? extensionOf(sniffed)}` };
119
+ }
120
+ return { type: named };
121
+ }
122
+ if (MEDIA_TYPES.has(said))
123
+ return { refused: `refused: the host says ${said}, but the bytes are not ${said}` };
124
+ if (named !== undefined && named === said)
125
+ return { type: said };
126
+ return { refused: `refused: ${said ? `${said} is` : "a file with no type is"} not a media type this server plays${named ? `, and the path's extension ${ext} says ${named}` : ", and the path's extension does not say it is"}` };
127
+ }
128
+ /** A failure's words, at most WORDS_MAX_CHARS. */
129
+ const wordsOf = (error) => clip(String(error?.message ?? error), WORDS_MAX_CHARS);
130
+ /** Where `path` is saved: as given, or under media/ when it names no folder. */
131
+ export const savePath = (path) => (path.includes("/") ? path : `${MEDIA_DIR}/${path}`);
132
+ /** `args.url` downloaded and saved at `args.path` in `work`: what was saved, or why nothing was. Never throws. */
133
+ export async function webSave(args, work, options = {}) {
134
+ const { url, path } = (args && typeof args === "object" ? args : {});
135
+ const shown = typeof url === "string" ? clip(url, URL_MAX) : "";
136
+ if (typeof url !== "string" || !URL.canParse(url))
137
+ return { ok: false, url: shown, error: "url is not an absolute URL" };
138
+ if (url.length > URL_MAX)
139
+ return { ok: false, url: shown, error: `url is longer than ${URL_MAX.toLocaleString("en-US")} characters` };
140
+ if (typeof path !== "string" || path === "")
141
+ return { ok: false, url: shown, error: "path is required: where in the run's folder to save the file (a bare name goes under media/)" };
142
+ if (path.length > PATH_MAX_CHARS)
143
+ return { ok: false, url: shown, error: `path is longer than ${PATH_MAX_CHARS.toLocaleString("en-US")} characters` };
144
+ const at = savePath(path);
145
+ const failed = (error) => {
146
+ const words = workspaceErrorWords(error);
147
+ if (words)
148
+ return isWorkspaceError(error, "ESCAPE") || isWorkspaceError(error, "REFUSED") || isWorkspaceError(error, "EXISTS") ? { ok: false, url: shown, path: at, refused: clip(`refused: ${words}`, WORDS_MAX_CHARS) } : { ok: false, url: shown, path: at, error: clip(words, WORDS_MAX_CHARS) };
149
+ return { ok: false, url: shown, path: at, error: wordsOf(error) };
150
+ };
151
+ const taken = async () => {
152
+ const there = await work.stat(at);
153
+ return there ? { ok: false, url: shown, path: at, refused: `refused: ${at} already holds a ${there.kind === "dir" ? "folder" : there.kind === "link" ? "link" : "file"}; web_save never overwrites, so pick another path` } : undefined;
154
+ };
155
+ try {
156
+ const before = await taken();
157
+ if (before)
158
+ return before;
159
+ }
160
+ catch (error) {
161
+ return failed(error);
162
+ }
163
+ const { BrowserFailureError, publicDownload } = await import("@parcha/pi-browser");
164
+ const { timeoutMs = SAVE_TIMEOUT_MS, maxBytes = SAVE_MAX_BYTES, slots = SERVER_SLOTS, ...guard } = options;
165
+ const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(guard.signal ? [guard.signal] : [])]);
166
+ const cut = (error, waited) => {
167
+ const name = error?.name;
168
+ if (name === "TimeoutError" && !guard.signal?.aborted)
169
+ return { ok: false, url: shown, path: at, error: `the download did not finish in ${timeoutMs / 1000} s${waited}` };
170
+ return { ok: false, url: shown, path: at, error: wordsOf(error) };
171
+ };
172
+ let release;
173
+ try {
174
+ release = await slots.take(signal);
175
+ }
176
+ catch (error) {
177
+ return cut(error, `: it waited all that time for a free download slot (at most ${slots.size} at once)`);
178
+ }
179
+ // The slot is held while the bytes are in memory: through the download, the type check and the write.
180
+ try {
181
+ let file;
182
+ try {
183
+ file = await publicDownload(url, { ...guard, maxBytes, signal });
184
+ }
185
+ catch (error) {
186
+ if (error instanceof BrowserFailureError && error.failure.code === "refused")
187
+ return { ok: false, url: shown, path: at, refused: clip(error.message, WORDS_MAX_CHARS) };
188
+ return cut(error, "");
189
+ }
190
+ const final = clip(file.url, URL_MAX);
191
+ if (file.bytes === null)
192
+ return { ok: false, url: final, path: at, error: `the host answered ${file.status}` };
193
+ const typed = typeFor(file.bytes, file.contentType, at);
194
+ if ("refused" in typed)
195
+ return { ok: false, url: final, path: at, refused: clip(typed.refused, WORDS_MAX_CHARS) };
196
+ try {
197
+ // Again just before the write: a file made at the path while the download ran is kept, not replaced.
198
+ const after = await taken();
199
+ if (after)
200
+ return { ...after, url: final };
201
+ await work.write(at, file.bytes);
202
+ }
203
+ catch (error) {
204
+ return { ...failed(error), url: final };
205
+ }
206
+ return { ok: true, path: at, bytes: file.bytes.length, content_type: typed.type, url: final };
207
+ }
208
+ finally {
209
+ release();
210
+ }
211
+ }
212
+ /** The words the model reads: the answer's JSON. */
213
+ export const savedText = (answer) => JSON.stringify(answer);
214
+ /** web_save on `work`, its download through `guard` (a test's or the fakes' resolver and fetch, none for the network), its
215
+ * slots `slots` (none: SERVER_SLOTS). */
216
+ export function webSaveTool(work, guard, slots) {
217
+ return defineTool({
218
+ 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.`,
220
+ parameters: {
221
+ type: "object",
222
+ additionalProperties: false,
223
+ properties: {
224
+ url: { type: "string", description: "The file's absolute http(s) URL." },
225
+ path: { type: "string", description: `Where to save it in the run's folder, e.g. ${MEDIA_DIR}/cat.png; a bare name goes under ${MEDIA_DIR}/.` },
226
+ },
227
+ required: ["url", "path"],
228
+ },
229
+ replay: "unsafe",
230
+ execute: async (args, _api, context) => {
231
+ const answer = await webSave(args, await work(), { ...(await guard()), ...(context?.abortSignal ? { signal: context.abortSignal } : {}), ...(slots ? { slots } : {}) });
232
+ return forModel(savedText(answer), { details: answer });
233
+ },
234
+ });
235
+ }
@@ -27,12 +27,15 @@ export interface ArchilClaimOptions {
27
27
  readonly makeDisk?: (options: ArchilDiskOptions) => ArchilDisk;
28
28
  /** The run's mount credential, minted when a mount first asks: the run and this claim's epoch (its token user's
29
29
  * nickname, agentrun:<run>:<epoch>, so a reclaim removes an earlier claim's first) and its ttl (the run's lifetime
30
- * bound, the safety net if the remove never comes); a loopback control plane and its fetch in a test. Absent: a mount
31
- * is refused in words. */
30
+ * bound, the safety net if the remove never comes). Absent: a mount is refused in words. */
32
31
  readonly mount?: {
33
32
  readonly runId: string;
34
33
  readonly epoch: number;
35
34
  readonly ttlMs: number;
35
+ };
36
+ /** Archil's control plane, where the run's disk is read (and made) and its mount credential minted: a loopback fake
37
+ * and its fetch in a test. Absent: the region's own. */
38
+ readonly control?: {
36
39
  readonly baseUrl?: string;
37
40
  readonly fetch?: typeof fetch;
38
41
  };
@@ -22,6 +22,7 @@ import { archilDisk, pinnedImage } from "./archil-disk.js";
22
22
  import { mintMountToken, nicknameOf, removeMountToken, removeOlderMountTokens, removeRunMountTokens } from "./archil-mount-credential.js";
23
23
  import { COMPUTER_LIFETIME_MS } from "./computer-deps.js";
24
24
  import { heldOrThrow } from "../runner/held.js";
25
+ import { piecedWorkspace } from "./pieced.js";
25
26
  import { runDiskOf } from "./run-disk.js";
26
27
  export { ARCHIL_API_KEY_ROW };
27
28
  /** A claim this step refused, in words a person reads: no Archil call was made. */
@@ -61,7 +62,9 @@ export async function archilWhereHeld(options) {
61
62
  secrets: new Set(),
62
63
  release: () => void given.release().catch(() => undefined),
63
64
  };
64
- HELD_ARCHIL.set(claim, given.workspace);
65
+ // A write bigger than a piece crosses in pieces its runner pulls, and is written there once (runner/big-writes.ts): one
66
+ // call would not fit the channel's frame.
67
+ HELD_ARCHIL.set(claim, piecedWorkspace(given.workspace, given.pieces, options.signal));
65
68
  return claim;
66
69
  }
67
70
  export async function archilClaim(options) {
@@ -84,7 +87,7 @@ export async function archilClaim(options) {
84
87
  held.add(apiKey);
85
88
  // The run's disk first (run-disk.ts): its launch's, else its agent's, made now when it has none; every call below is on
86
89
  // it alone, the run's mount credential minted, revoked and reclaimed there.
87
- const control = { region: settings.region, key: () => apiKey, ...(options.mount?.baseUrl ? { baseUrl: options.mount.baseUrl } : {}), ...(options.mount?.fetch ? { fetch: options.mount.fetch } : {}) };
90
+ const control = { region: settings.region, key: () => apiKey, ...(options.control?.baseUrl ? { baseUrl: options.control.baseUrl } : {}), ...(options.control?.fetch ? { fetch: options.control.fetch } : {}) };
88
91
  let chosen;
89
92
  try {
90
93
  chosen = await runDiskOf({ store: options.run.store, agentId: options.run.agentId, ...(options.mount ? { runId: options.mount.runId } : {}), ...(options.run.launch ? { launch: options.run.launch } : {}), control, signal: options.signal });
@@ -60,9 +60,19 @@ 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 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. */
67
+ export declare class ArchilDiskMissing extends Error {
68
+ readonly disk: string;
69
+ readonly region: string;
70
+ constructor(disk: string, region: string, words: string, options?: ErrorOptions);
71
+ }
63
72
  /**
64
73
  * An Archil disk, keys relative to its root. A failed call rejects with an error carrying the HTTP `status` when there
65
- * was an answer (the SDK's ArchilS3Error and ArchilApiError do, and so does the ranged read here).
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.
66
76
  */
67
77
  export interface ArchilDisk {
68
78
  readonly id: string;
@@ -16,6 +16,20 @@ 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 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. */
23
+ export class ArchilDiskMissing extends Error {
24
+ disk;
25
+ region;
26
+ constructor(disk, region, words, options) {
27
+ super(`the Archil disk ${disk} is not there in region ${region}: ${words}`, options);
28
+ this.disk = disk;
29
+ this.region = region;
30
+ this.name = "ArchilDiskMissing";
31
+ }
32
+ }
19
33
  const LOOPBACK = /^(?:127\.\d+\.\d+\.\d+|localhost|\[::1\])$/; // key-gate: loopback-rule names loopback hosts to allow plain http only to them, in tests
20
34
  /** The S3 endpoint, checked: https on an Archil host whose name carries the region ("aws-us-east-1" → "…​.us-east-1.aws.
21
35
  * …archil.com"), or, when the control plane is a loopback one too (a test), http(s) to this machine's loopback. */
@@ -143,7 +157,12 @@ class SdkArchilDisk {
143
157
  const { region, baseUrl } = this.#options;
144
158
  const { Archil } = await import("disk");
145
159
  const client = new Archil({ apiKey, region, s3BaseUrl: this.#s3, ...(baseUrl === undefined ? {} : { baseUrl }) });
146
- return { client, disk: await client.disks.get(this.id) };
160
+ const disk = await client.disks.get(this.id).catch((error) => {
161
+ if (error?.status !== 404)
162
+ throw error;
163
+ throw new ArchilDiskMissing(this.id, region, String(error?.message ?? error), { cause: error });
164
+ });
165
+ return { client, disk };
147
166
  })();
148
167
  // A failed start (the key refused, the disk not found) is tried again by the next call.
149
168
  ready.catch(() => { if (this.#ready === ready) {
@@ -154,6 +173,20 @@ class SdkArchilDisk {
154
173
  this.#readyKey = apiKey;
155
174
  return ready;
156
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
+ }
157
190
  /** The client made and the disk looked up: one disks.get. A key of the wrong kind fails here (401 or 403). */
158
191
  async ready() {
159
192
  await this.#sdk();
@@ -200,25 +233,25 @@ class SdkArchilDisk {
200
233
  await pause(100 * 2 ** attempt);
201
234
  continue;
202
235
  }
203
- throw new RangeReadError(response.status, response.statusText, body);
236
+ return this.#after(new RangeReadError(response.status, response.statusText, body));
204
237
  }
205
238
  }
206
239
  async putObject(key, body) {
207
- await (await this.#sdk()).disk.putObject(key, body);
240
+ await this.#call(({ disk }) => disk.putObject(key, body));
208
241
  }
209
242
  async appendObject(key, body) {
210
- await (await this.#sdk()).disk.appendObject(key, body);
243
+ await this.#call(({ disk }) => disk.appendObject(key, body));
211
244
  }
212
245
  async deleteObject(key) {
213
- await (await this.#sdk()).disk.deleteObject(key);
246
+ await this.#call(({ disk }) => disk.deleteObject(key));
214
247
  }
215
248
  async deleteObjects(keys) {
216
- return (await (await this.#sdk()).disk.deleteObjects([...keys], { quiet: true })).errors;
249
+ return (await this.#call(({ disk }) => disk.deleteObjects([...keys], { quiet: true }))).errors;
217
250
  }
218
251
  async listPage(prefix, options) {
219
- const page = await (await this.#sdk()).disk.listObjects(prefix, {
252
+ const page = await this.#call(({ disk }) => disk.listObjects(prefix, {
220
253
  recursive: options.recursive, singlePage: true, ...(options.token === undefined ? {} : { continuationToken: options.token }),
221
- });
254
+ }));
222
255
  const next = page.isTruncated ? page.nextContinuationToken : undefined;
223
256
  return {
224
257
  objects: page.objects.map(({ key, size, lastModified }) => ({ key, size, ...(lastModified === undefined ? {} : { mtimeMs: lastModified.getTime() }) })),
@@ -226,7 +259,7 @@ class SdkArchilDisk {
226
259
  };
227
260
  }
228
261
  async grep(request) {
229
- 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] }));
230
263
  return { matches: answer.matches.map(({ file, line, text }) => ({ file, line, text })), stoppedReason: answer.stoppedReason };
231
264
  }
232
265
  async exec(request) {
@@ -250,7 +283,7 @@ class SdkArchilDisk {
250
283
  ...(request.network === undefined ? {} : { network: { egress: { default: request.network.egress.default } } }),
251
284
  command: request.command,
252
285
  disks: Object.fromEntries(Object.entries(request.mounts).map(([name, subdirectory]) => [name, { disk: this.id, subdirectory, queueMs: request.queueMs }])),
253
- });
286
+ }).catch((error) => this.#after(error));
254
287
  return { exitCode: answer.exitCode, stdout: answer.stdout, stderr: answer.stderr };
255
288
  }
256
289
  }
@@ -39,6 +39,9 @@ declare class ArchilWorkspace implements Workspace {
39
39
  stat(path: string): Promise<Stat | undefined>;
40
40
  list(dir: string): Promise<Entry[]>;
41
41
  mkdir(dir: string): Promise<void>;
42
+ /** The root made on the disk when it is not there yet; one already there is not put again, so a computer whose mount
43
+ * holds it (Archil's write delegation refuses a put there) never stands in the way. A failure throws, in Archil's words. */
44
+ ensureRoot(): Promise<void>;
42
45
  grep(pattern: string, options?: GrepOptions): Promise<GrepResult>;
43
46
  remove(path: string, options?: {
44
47
  readonly recursive?: boolean;
@@ -50,7 +50,7 @@
50
50
  // through the file API as the runner keeps it, its files and `dir/` markers, and its modes and links in sync.json beside
51
51
  // the root (syncMetaOf), and attach() with check.sync reads back a synced folder under the claim's epoch instead.
52
52
  import { folderPathProblem } from "@parcha/agentrun-computer";
53
- import { DENY_EGRESS, pinnedImage } from "./archil-disk.js";
53
+ import { ArchilDiskMissing, DENY_EGRESS, pinnedImage } from "./archil-disk.js";
54
54
  import { ArchilEgressRefused, archilExec, COMMAND_MAX_MS, DEFAULT_QUEUE_MS, MAX_EXEC_MS, spillKeys, spillName } from "./archil-exec.js";
55
55
  import { attachedWorkspace, checkReadBack, noProcesses } from "./attach.js";
56
56
  import { globRegex } from "./glob.js";
@@ -73,14 +73,28 @@ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
73
73
  * unhandled rejection. */
74
74
  const quiet = (promise) => { promise.catch(() => undefined); return promise; };
75
75
  const byName = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
76
- /** A disk API failure as a WorkspaceError. */
76
+ /** A put Archil refused (404) for a folder above it that was not there, a folder that then could not be made (`why`):
77
+ * nothing of the put landed. Kept apart from the folder's own failure so an append can say so. */
78
+ class FolderNotMade extends Error {
79
+ why;
80
+ constructor(why) {
81
+ super(why.message, { cause: why });
82
+ this.why = why;
83
+ }
84
+ }
85
+ /** A disk API failure as a WorkspaceError, Archil's words kept. A disk that is not there is UNAVAILABLE, never a file or
86
+ * folder that is not there: no caller takes it for an empty folder. */
77
87
  function failed(error, path, what) {
78
88
  if (error instanceof WorkspaceError)
79
89
  return error;
90
+ if (error instanceof FolderNotMade)
91
+ return error.why;
80
92
  const status = statusOf(error);
81
93
  const at = { path, cause: error };
94
+ if (error instanceof ArchilDiskMissing)
95
+ return new WorkspaceError("UNAVAILABLE", `${what} ${show(path)}: ${error.message}`, at);
82
96
  if (status === 404)
83
- return new WorkspaceError("NOT_FOUND", `${show(path)} is not there`, at);
97
+ return new WorkspaceError("NOT_FOUND", `${show(path)} is not there (${what}; Archil: ${describe(error)})`, at);
84
98
  if (status === 413 || error?.code === "EntityTooLarge")
85
99
  return new WorkspaceError("TOO_LARGE", `${what} ${show(path)}: more than the disk takes in one call`, at);
86
100
  if (status === 401 || status === 403)
@@ -172,6 +186,46 @@ class ArchilWorkspace {
172
186
  await this.#execs;
173
187
  return this.#settle(rel, call);
174
188
  }
189
+ /** Relative path of disk key `key` under the root ("" for the root, or for a folder above or beside it). */
190
+ #relOf(key) {
191
+ return key.startsWith(`${this.#root}/`) ? key.slice(this.#root.length + 1) : "";
192
+ }
193
+ /** Whether folder `key` (a disk key, no trailing "/") is on the disk. */
194
+ async #folderThere(key) {
195
+ for await (const page of this.#pages(key, false)) {
196
+ if (page.commonPrefixes.includes(`${key}/`) || page.objects.some((o) => o.key === `${key}/`))
197
+ return true;
198
+ }
199
+ return false;
200
+ }
201
+ /** `put`, which puts disk key `key` (a file, or a folder ending in "/"), after this workspace's execs (`inExec`: made
202
+ * from inside the exec queue, so not after it). Archil may make no folder above a put (staging's answered 404 for an
203
+ * expert run's `.agents/skills/` on a fresh run folder), so on a 404 each folder above `key` that is not there is
204
+ * made, from the highest down, and `put` is made once more. A folder already there is left as it is. */
205
+ async #put(key, put, inExec = false) {
206
+ const call = (rel, fn) => (inExec ? this.#settle(rel, fn) : this.#write(rel, fn));
207
+ try {
208
+ return await call(this.#relOf(key), put);
209
+ }
210
+ catch (error) {
211
+ if (statusOf(error) !== 404 || error instanceof ArchilDiskMissing)
212
+ throw error;
213
+ }
214
+ const above = key.replace(/\/$/, "").split("/").slice(0, -1);
215
+ let there = above.length;
216
+ while (there > 0 && !(await this.#folderThere(above.slice(0, there).join("/"))))
217
+ there--;
218
+ for (let depth = there + 1; depth <= above.length; depth++) {
219
+ const folder = above.slice(0, depth).join("/");
220
+ try {
221
+ await call(this.#relOf(folder), () => this.#disk.putObject(`${folder}/`, new Uint8Array(0)));
222
+ }
223
+ catch (error) {
224
+ throw new FolderNotMade(failed(error, this.#relOf(folder), "mkdir"));
225
+ }
226
+ }
227
+ return call(this.#relOf(key), put);
228
+ }
175
229
  /** Every page of the listing of `prefix`. */
176
230
  async *#pages(prefix, recursive) {
177
231
  let token;
@@ -246,9 +300,18 @@ class ArchilWorkspace {
246
300
  answer = await this.#disk.getRange(this.#key(rel), `bytes=${offset}-${last}`);
247
301
  }
248
302
  catch (error) {
249
- if (statusOf(error) === 404 && (await this.#kind(rel).catch(() => undefined)) === "dir") {
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.
306
+ const kind = statusOf(error) === 404
307
+ ? await this.#kind(rel).catch((lookup) => {
308
+ if (lookup instanceof ArchilDiskMissing)
309
+ throw failed(lookup, rel, "read");
310
+ return undefined;
311
+ })
312
+ : undefined;
313
+ if (kind === "dir")
250
314
  throw new WorkspaceError("REFUSED", `${show(rel)} is a directory`, { path: rel, cause: error });
251
- }
252
315
  if (statusOf(error) === 501) {
253
316
  throw new WorkspaceError("UNAVAILABLE", `${show(rel)} is a symbolic link (an exec made it): Archil's file API does not read one`, { path: rel, cause: error });
254
317
  }
@@ -269,7 +332,7 @@ class ArchilWorkspace {
269
332
  const bytes = bytesOf(data);
270
333
  const rel = ArchilWorkspace.#below(path, "a file").join("/");
271
334
  try {
272
- await this.#write(rel, () => this.#disk.putObject(this.#key(rel), bytes));
335
+ await this.#put(this.#key(rel), () => this.#disk.putObject(this.#key(rel), bytes));
273
336
  }
274
337
  catch (error) {
275
338
  throw await this.#writeFailed(error, rel, "file", "write");
@@ -290,26 +353,31 @@ class ArchilWorkspace {
290
353
  // land in order.
291
354
  for (let at = 0; at === 0 || at < bytes.length; at += APPEND_MAX) {
292
355
  const part = bytes.subarray(at, at + APPEND_MAX);
293
- await this.#write(rel, () => this.#disk.appendObject(this.#key(rel), part));
356
+ await this.#put(this.#key(rel), () => this.#disk.appendObject(this.#key(rel), part));
294
357
  landed += part.length;
295
358
  }
296
359
  }
297
360
  catch (error) {
298
361
  const why = await this.#writeFailed(error, rel, "file", "append");
299
362
  const status = statusOf(error);
300
- const refused = status !== undefined && status >= 400 && status < 500;
363
+ // A disk that is not there took nothing either.
364
+ // So did a put refused for a folder that could not be made.
365
+ const refused = error instanceof ArchilDiskMissing || error instanceof FolderNotMade || (status !== undefined && status >= 400 && status < 500);
301
366
  if (chunks === 1) {
302
367
  // A refusal (4xx) applied nothing; any other failure may have come after the bytes were committed.
303
368
  if (refused)
304
369
  throw why;
305
370
  throw new WorkspaceError(why.code, `the append to ${show(rel)} may also have landed: unknown, re-read the file before retrying: ${why.message}`, { path: rel, cause: error });
306
371
  }
307
- // Part of it may be on the disk. Only what is known is said: the size read back, or else what was acknowledged,
308
- // with the failed chunk's outcome unknown. A chunk may commit and lose its answer, so a count is never a guess.
372
+ // Part of it may be on the disk. Only what is known is said: the size read back, or else what was acknowledged, with
373
+ // the failed chunk's outcome unknown unless it was refused (as one chunk's refusal applied nothing). A chunk may
374
+ // commit and lose its answer, so a count is never a guess.
309
375
  const after = before === undefined ? undefined : await this.#sizeOf(rel).catch(() => undefined);
310
376
  const known = before !== undefined && after !== undefined && after - before >= landed && after - before <= bytes.length
311
377
  ? `${after - before} of ${bytes.length} bytes were appended (read back from the file: ${after} bytes now, ${before} before)`
312
- : `at least ${landed} of ${bytes.length} bytes were appended; the failed chunk may also have landed: unknown, re-read the file before retrying`;
378
+ : refused
379
+ ? `${landed} of ${bytes.length} bytes were appended (the chunk that failed was refused, so none of it landed)`
380
+ : `at least ${landed} of ${bytes.length} bytes were appended; the failed chunk may also have landed: unknown, re-read the file before retrying`;
313
381
  throw new WorkspaceError(why.code, `${known} to ${show(rel)} before it failed: ${why.message}`, { path: rel, cause: error });
314
382
  }
315
383
  }
@@ -385,13 +453,29 @@ class ArchilWorkspace {
385
453
  async mkdir(dir) {
386
454
  const rel = relativeSegments(dir).join("/");
387
455
  try {
388
- // A directory is a key ending in "/"; its parents are made with it, and one already there is left as it is.
389
- await this.#write(rel, () => this.#disk.putObject(`${this.#key(rel)}/`, new Uint8Array(0)));
456
+ // A directory is a key ending in "/"; a parent that is not there is made first (#put), and one already there is
457
+ // left as it is.
458
+ await this.#put(`${this.#key(rel)}/`, () => this.#disk.putObject(`${this.#key(rel)}/`, new Uint8Array(0)));
390
459
  }
391
460
  catch (error) {
392
461
  throw await this.#writeFailed(error, rel, "dir", "mkdir");
393
462
  }
394
463
  }
464
+ /** The root made on the disk when it is not there yet; one already there is not put again, so a computer whose mount
465
+ * holds it (Archil's write delegation refuses a put there) never stands in the way. A failure throws, in Archil's words. */
466
+ async ensureRoot() {
467
+ const marker = `${this.#root}/`;
468
+ try {
469
+ for await (const page of this.#pages(this.#root, false)) {
470
+ if (page.commonPrefixes.includes(marker) || page.objects.some((o) => o.key === marker))
471
+ return;
472
+ }
473
+ await this.#put(marker, () => this.#disk.putObject(marker, new Uint8Array(0)));
474
+ }
475
+ catch (error) {
476
+ throw failed(error, "", "mkdir");
477
+ }
478
+ }
395
479
  async grep(pattern, options = {}) {
396
480
  try {
397
481
  new RegExp(pattern);
@@ -662,7 +746,7 @@ class ArchilWorkspace {
662
746
  * exec queue, so it does not wait for it. */
663
747
  async #makeRoot() {
664
748
  for (const folder of [this.#root, this.#spill]) {
665
- await this.#settle("", () => this.#disk.putObject(`${folder}/`, new Uint8Array(0))).catch((error) => { throw failed(error, "", "mkdir"); });
749
+ await this.#put(`${folder}/`, () => this.#disk.putObject(`${folder}/`, new Uint8Array(0)), true).catch((error) => { throw failed(error, "", "mkdir"); });
666
750
  }
667
751
  this.#rooted = true;
668
752
  }
@@ -753,7 +837,9 @@ class ArchilWorkspace {
753
837
  const wrote = async (path, what, call) => {
754
838
  try {
755
839
  const rel = relativeSegments(path).join("/");
756
- await this.#write(rel, () => call(this.#key(rel)));
840
+ const key = this.#key(rel);
841
+ // A put or a folder makes the folders above it that are not there; a remove makes none.
842
+ await (what === "remove" ? this.#write(rel, () => call(key)) : this.#put(what === "mkdir" ? `${key}/` : key, () => call(key)));
757
843
  return { ok: true, value: undefined };
758
844
  }
759
845
  catch (error) {
@@ -767,7 +853,7 @@ class ArchilWorkspace {
767
853
  remove: (path, type) => wrote(path, "remove", (key) => this.#disk.deleteObject(type === "dir" ? `${key}/` : key)),
768
854
  meta: async (folder) => {
769
855
  try {
770
- await this.#write("", () => this.#disk.putObject(meta, Buffer.from(JSON.stringify(folder))));
856
+ await this.#put(meta, () => this.#disk.putObject(meta, Buffer.from(JSON.stringify(folder))));
771
857
  return { ok: true, value: undefined };
772
858
  }
773
859
  catch (error) {