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

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 (106) hide show
  1. package/CHANGELOG.md +26 -9
  2. package/README.md +104 -22
  3. package/dist/agent-delete.d.ts +3 -2
  4. package/dist/agent-delete.js +29 -4
  5. package/dist/api-only.d.ts +7 -10
  6. package/dist/api-only.js +9 -11
  7. package/dist/compute-cost.d.ts +101 -0
  8. package/dist/compute-cost.js +250 -0
  9. package/dist/console/assets/{index-CR2ZGei1.css → index-D0mr9wfZ.css} +1 -1
  10. package/dist/console/assets/index-D7G6o-1E.js +720 -0
  11. package/dist/console/index.html +2 -2
  12. package/dist/eval-previous.d.ts +52 -0
  13. package/dist/eval-previous.js +164 -0
  14. package/dist/file-types.d.ts +2 -0
  15. package/dist/file-types.js +3 -1
  16. package/dist/harness.js +2 -1
  17. package/dist/learn/check.d.ts +8 -5
  18. package/dist/learn/check.js +25 -24
  19. package/dist/learn/repick.d.ts +22 -13
  20. package/dist/learn/repick.js +57 -56
  21. package/dist/learn/workflow-draft.d.ts +4 -0
  22. package/dist/learn/workflow-draft.js +10 -7
  23. package/dist/learned-workflow.js +8 -8
  24. package/dist/learning-setting.js +2 -2
  25. package/dist/openapi.js +25 -17
  26. package/dist/paid-calls.d.ts +13 -6
  27. package/dist/paid-calls.js +14 -8
  28. package/dist/run-launch.d.ts +2 -2
  29. package/dist/run-launch.js +2 -1
  30. package/dist/run-timeline-served.js +5 -3
  31. package/dist/run-usage.d.ts +23 -8
  32. package/dist/run-usage.js +100 -18
  33. package/dist/runner/adapter-loop.d.ts +4 -0
  34. package/dist/runner/adapter-loop.js +15 -1
  35. package/dist/runner/adapter-run-spec.d.ts +8 -3
  36. package/dist/runner/adapter-run-spec.js +13 -6
  37. package/dist/runner/big-writes.d.ts +33 -0
  38. package/dist/runner/big-writes.js +105 -0
  39. package/dist/runner/cli-run-spec.js +14 -6
  40. package/dist/runner/held.d.ts +4 -1
  41. package/dist/runner/learning-end.js +9 -4
  42. package/dist/runner/metrics.d.ts +4 -0
  43. package/dist/runner/metrics.js +9 -0
  44. package/dist/runner/run-child-host.d.ts +15 -2
  45. package/dist/runner/run-child-host.js +24 -8
  46. package/dist/runner/run-child.js +3 -0
  47. package/dist/runner/save-slots.d.ts +9 -0
  48. package/dist/runner/save-slots.js +91 -0
  49. package/dist/sdk/runs.d.ts +3 -4
  50. package/dist/sdk/runs.js +10 -7
  51. package/dist/sdk/runtimes.d.ts +19 -0
  52. package/dist/sdk/runtimes.js +23 -0
  53. package/dist/sdk/schema.d.ts +14 -8
  54. package/dist/sdk/schema.js +18 -6
  55. package/dist/server.d.ts +4 -0
  56. package/dist/server.js +3 -3
  57. package/dist/store/agent-body.d.ts +2 -3
  58. package/dist/store/agent-body.js +3 -2
  59. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  60. package/dist/store/schema.d.ts +8 -3
  61. package/dist/store/schema.js +12 -2
  62. package/dist/store/sqlite/connection.d.ts +3 -3
  63. package/dist/store/sqlite/connection.js +3 -3
  64. package/dist/store/sqlite/store.d.ts +2 -4
  65. package/dist/store/sqlite/store.js +95 -85
  66. package/dist/store/store.d.ts +8 -1
  67. package/dist/store-reads/cap.d.ts +9 -5
  68. package/dist/store-reads/cap.js +28 -2
  69. package/dist/store-reads/decisions.d.ts +21 -0
  70. package/dist/store-reads/decisions.js +22 -0
  71. package/dist/store-reads/journal.d.ts +8 -2
  72. package/dist/store-reads/journal.js +27 -8
  73. package/dist/store-view.d.ts +5 -1
  74. package/dist/store-view.js +37 -18
  75. package/dist/template-eval.d.ts +15 -1
  76. package/dist/template-eval.js +92 -13
  77. package/dist/templates.d.ts +1 -1
  78. package/dist/templates.js +4 -3
  79. package/dist/timeline/labels.js +17 -0
  80. package/dist/tool-list.js +1 -0
  81. package/dist/tools.d.ts +6 -2
  82. package/dist/tools.js +13 -1
  83. package/dist/trigger-targets.d.ts +21 -5
  84. package/dist/trigger-targets.js +13 -10
  85. package/dist/web-fake.d.ts +25 -0
  86. package/dist/web-fake.js +38 -1
  87. package/dist/web-save.d.ts +75 -0
  88. package/dist/web-save.js +235 -0
  89. package/dist/workspace/archil-claim.d.ts +5 -2
  90. package/dist/workspace/archil-claim.js +5 -2
  91. package/dist/workspace/archil-disk.d.ts +10 -1
  92. package/dist/workspace/archil-disk.js +19 -1
  93. package/dist/workspace/archil.d.ts +3 -0
  94. package/dist/workspace/archil.js +101 -16
  95. package/dist/workspace/computer-for-claim.d.ts +14 -0
  96. package/dist/workspace/computer-for-claim.js +46 -7
  97. package/dist/workspace/computer-intervals.d.ts +9 -3
  98. package/dist/workspace/computer-intervals.js +17 -8
  99. package/dist/workspace/pieced.d.ts +14 -0
  100. package/dist/workspace/pieced.js +23 -0
  101. package/dist/workspace/run-disk.js +32 -12
  102. package/dist/workspace/run-workspace.d.ts +1 -1
  103. package/dist/workspace/run-workspace.js +11 -6
  104. package/package.json +10 -10
  105. package/templates/README.md +36 -7
  106. package/dist/console/assets/index-Bzn4eUYF.js +0 -715
@@ -0,0 +1,75 @@
1
+ import type { JsonValue } from "@earendil-works/chord/json";
2
+ import type { TSchema } from "typebox";
3
+ import { type ToolRegistration } from "@earendil-works/pi-durable";
4
+ import type { PublicFetchOptions } from "@parcha/pi-browser";
5
+ import { type Workspace } from "./workspace/index.js";
6
+ export declare const WEB_SAVE_TOOL = "web_save";
7
+ /** The most bytes a saved file may have. */
8
+ export declare const SAVE_MAX_BYTES: number;
9
+ /** One deadline for a whole download: a 200 MiB file at about 350 KB/s. A page's 30 s (web-fetch-direct.ts) would cut a
10
+ * large file on any link under about 7 MB/s. */
11
+ export declare const SAVE_TIMEOUT_MS = 600000;
12
+ /** The folder a bare name is saved in. */
13
+ export declare const MEDIA_DIR = "media";
14
+ /** The longest path web_save takes, and the most characters of a declared type and of a failure's words an answer
15
+ * carries: with the URL's URL_MAX, they bound every answer (host-bounds.test.mjs). */
16
+ export declare const PATH_MAX_CHARS = 1024;
17
+ export declare const TYPE_MAX_CHARS = 255;
18
+ export declare const WORDS_MAX_CHARS = 2000;
19
+ export type Saved = {
20
+ ok: true;
21
+ path: string;
22
+ bytes: number;
23
+ content_type: string;
24
+ url: string;
25
+ };
26
+ export type Unsaved = {
27
+ ok: false;
28
+ url: string;
29
+ path?: string;
30
+ refused: string;
31
+ } | {
32
+ ok: false;
33
+ url: string;
34
+ path?: string;
35
+ error: string;
36
+ };
37
+ /** The guard's resolver and fetch (a test's, or the fakes'), the caller's signal, a lower cap, and other slots than the
38
+ * server's (a test's). */
39
+ export type SaveOptions = Omit<PublicFetchOptions, "maxBytes"> & {
40
+ maxBytes?: number;
41
+ timeoutMs?: number;
42
+ slots?: SaveSlots;
43
+ };
44
+ /** The most web_save downloads at once per runner, across its runs (SERVER_SLOTS); the rest wait under their own
45
+ * deadline. Each holds its file in memory until its one write: its size when its host states its length, about twice
46
+ * that at the peak when it does not (publicDownload). So a runner's downloads hold at most 800 MiB at 200 MiB a file,
47
+ * about 1.6 GiB when no host states a length; Mode 2's pieced writes (runner/big-writes.ts) can add 800 MiB more. */
48
+ export declare const SAVE_CONCURRENCY = 4;
49
+ /** Slots for downloads, handed out first come first served. `take` answers the slot's release (once), or rejects with
50
+ * the signal's reason if it aborts first, leaving the queue. */
51
+ export type SaveSlots = {
52
+ readonly size: number;
53
+ readonly busy: number;
54
+ readonly waiting: number;
55
+ take(signal: AbortSignal): Promise<() => void>;
56
+ };
57
+ export declare function saveSlots(size: number): SaveSlots;
58
+ /** The runner's one gate: at most SAVE_CONCURRENCY downloads at once per runner, across its runs. A run in the runner's
59
+ * own process takes it here; a run in a process of its own takes it over its channel (runner/save-slots.ts). */
60
+ export declare const SERVER_SLOTS: SaveSlots;
61
+ /** The type `bytes` are saved as at `path`, the host having declared `declared`, or why they are refused. */
62
+ export declare function typeFor(bytes: Uint8Array, declared: string, path: string): {
63
+ type: string;
64
+ } | {
65
+ refused: string;
66
+ };
67
+ /** Where `path` is saved: as given, or under media/ when it names no folder. */
68
+ export declare const savePath: (path: string) => string;
69
+ /** `args.url` downloaded and saved at `args.path` in `work`: what was saved, or why nothing was. Never throws. */
70
+ export declare function webSave(args: unknown, work: Workspace, options?: SaveOptions): Promise<Saved | Unsaved>;
71
+ /** The words the model reads: the answer's JSON. */
72
+ export declare const savedText: (answer: Saved | Unsaved) => string;
73
+ /** web_save on `work`, its download through `guard` (a test's or the fakes' resolver and fetch, none for the network), its
74
+ * slots `slots` (none: SERVER_SLOTS). */
75
+ export declare function webSaveTool(work: () => Promise<Workspace> | Workspace, guard: () => Promise<Omit<PublicFetchOptions, "maxBytes" | "signal">> | Omit<PublicFetchOptions, "maxBytes" | "signal">, slots?: SaveSlots): ToolRegistration<TSchema, JsonValue>;
@@ -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,18 @@ 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. */
66
+ export declare class ArchilDiskMissing extends Error {
67
+ readonly disk: string;
68
+ readonly region: string;
69
+ constructor(disk: string, region: string, words: string, options?: ErrorOptions);
70
+ }
63
71
  /**
64
72
  * 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).
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.
66
75
  */
67
76
  export interface ArchilDisk {
68
77
  readonly id: string;
@@ -16,6 +16,19 @@ 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. */
22
+ export class ArchilDiskMissing extends Error {
23
+ disk;
24
+ region;
25
+ constructor(disk, region, words, options) {
26
+ super(`the Archil disk ${disk} is not there in region ${region}: ${words}`, options);
27
+ this.disk = disk;
28
+ this.region = region;
29
+ this.name = "ArchilDiskMissing";
30
+ }
31
+ }
19
32
  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
33
  /** The S3 endpoint, checked: https on an Archil host whose name carries the region ("aws-us-east-1" → "…​.us-east-1.aws.
21
34
  * …archil.com"), or, when the control plane is a loopback one too (a test), http(s) to this machine's loopback. */
@@ -143,7 +156,12 @@ class SdkArchilDisk {
143
156
  const { region, baseUrl } = this.#options;
144
157
  const { Archil } = await import("disk");
145
158
  const client = new Archil({ apiKey, region, s3BaseUrl: this.#s3, ...(baseUrl === undefined ? {} : { baseUrl }) });
146
- return { client, disk: await client.disks.get(this.id) };
159
+ const disk = await client.disks.get(this.id).catch((error) => {
160
+ if (error?.status !== 404)
161
+ throw error;
162
+ throw new ArchilDiskMissing(this.id, region, String(error?.message ?? error), { cause: error });
163
+ });
164
+ return { client, disk };
147
165
  })();
148
166
  // A failed start (the key refused, the disk not found) is tried again by the next call.
149
167
  ready.catch(() => { if (this.#ready === ready) {
@@ -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,17 @@ 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
+ // 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.
305
+ const kind = statusOf(error) === 404
306
+ ? await this.#kind(rel).catch((lookup) => {
307
+ if (lookup instanceof ArchilDiskMissing)
308
+ throw failed(lookup, rel, "read");
309
+ return undefined;
310
+ })
311
+ : undefined;
312
+ if (kind === "dir")
250
313
  throw new WorkspaceError("REFUSED", `${show(rel)} is a directory`, { path: rel, cause: error });
251
- }
252
314
  if (statusOf(error) === 501) {
253
315
  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
316
  }
@@ -269,7 +331,7 @@ class ArchilWorkspace {
269
331
  const bytes = bytesOf(data);
270
332
  const rel = ArchilWorkspace.#below(path, "a file").join("/");
271
333
  try {
272
- await this.#write(rel, () => this.#disk.putObject(this.#key(rel), bytes));
334
+ await this.#put(this.#key(rel), () => this.#disk.putObject(this.#key(rel), bytes));
273
335
  }
274
336
  catch (error) {
275
337
  throw await this.#writeFailed(error, rel, "file", "write");
@@ -290,26 +352,31 @@ class ArchilWorkspace {
290
352
  // land in order.
291
353
  for (let at = 0; at === 0 || at < bytes.length; at += APPEND_MAX) {
292
354
  const part = bytes.subarray(at, at + APPEND_MAX);
293
- await this.#write(rel, () => this.#disk.appendObject(this.#key(rel), part));
355
+ await this.#put(this.#key(rel), () => this.#disk.appendObject(this.#key(rel), part));
294
356
  landed += part.length;
295
357
  }
296
358
  }
297
359
  catch (error) {
298
360
  const why = await this.#writeFailed(error, rel, "file", "append");
299
361
  const status = statusOf(error);
300
- const refused = status !== undefined && status >= 400 && status < 500;
362
+ // A disk that is not there took nothing either.
363
+ // So did a put refused for a folder that could not be made.
364
+ const refused = error instanceof ArchilDiskMissing || error instanceof FolderNotMade || (status !== undefined && status >= 400 && status < 500);
301
365
  if (chunks === 1) {
302
366
  // A refusal (4xx) applied nothing; any other failure may have come after the bytes were committed.
303
367
  if (refused)
304
368
  throw why;
305
369
  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
370
  }
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.
371
+ // Part of it may be on the disk. Only what is known is said: the size read back, or else what was acknowledged, with
372
+ // the failed chunk's outcome unknown unless it was refused (as one chunk's refusal applied nothing). A chunk may
373
+ // commit and lose its answer, so a count is never a guess.
309
374
  const after = before === undefined ? undefined : await this.#sizeOf(rel).catch(() => undefined);
310
375
  const known = before !== undefined && after !== undefined && after - before >= landed && after - before <= bytes.length
311
376
  ? `${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`;
377
+ : refused
378
+ ? `${landed} of ${bytes.length} bytes were appended (the chunk that failed was refused, so none of it landed)`
379
+ : `at least ${landed} of ${bytes.length} bytes were appended; the failed chunk may also have landed: unknown, re-read the file before retrying`;
313
380
  throw new WorkspaceError(why.code, `${known} to ${show(rel)} before it failed: ${why.message}`, { path: rel, cause: error });
314
381
  }
315
382
  }
@@ -385,13 +452,29 @@ class ArchilWorkspace {
385
452
  async mkdir(dir) {
386
453
  const rel = relativeSegments(dir).join("/");
387
454
  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)));
455
+ // A directory is a key ending in "/"; a parent that is not there is made first (#put), and one already there is
456
+ // left as it is.
457
+ await this.#put(`${this.#key(rel)}/`, () => this.#disk.putObject(`${this.#key(rel)}/`, new Uint8Array(0)));
390
458
  }
391
459
  catch (error) {
392
460
  throw await this.#writeFailed(error, rel, "dir", "mkdir");
393
461
  }
394
462
  }
463
+ /** The root made on the disk when it is not there yet; one already there is not put again, so a computer whose mount
464
+ * holds it (Archil's write delegation refuses a put there) never stands in the way. A failure throws, in Archil's words. */
465
+ async ensureRoot() {
466
+ const marker = `${this.#root}/`;
467
+ try {
468
+ for await (const page of this.#pages(this.#root, false)) {
469
+ if (page.commonPrefixes.includes(marker) || page.objects.some((o) => o.key === marker))
470
+ return;
471
+ }
472
+ await this.#put(marker, () => this.#disk.putObject(marker, new Uint8Array(0)));
473
+ }
474
+ catch (error) {
475
+ throw failed(error, "", "mkdir");
476
+ }
477
+ }
395
478
  async grep(pattern, options = {}) {
396
479
  try {
397
480
  new RegExp(pattern);
@@ -662,7 +745,7 @@ class ArchilWorkspace {
662
745
  * exec queue, so it does not wait for it. */
663
746
  async #makeRoot() {
664
747
  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"); });
748
+ await this.#put(`${folder}/`, () => this.#disk.putObject(`${folder}/`, new Uint8Array(0)), true).catch((error) => { throw failed(error, "", "mkdir"); });
666
749
  }
667
750
  this.#rooted = true;
668
751
  }
@@ -753,7 +836,9 @@ class ArchilWorkspace {
753
836
  const wrote = async (path, what, call) => {
754
837
  try {
755
838
  const rel = relativeSegments(path).join("/");
756
- await this.#write(rel, () => call(this.#key(rel)));
839
+ const key = this.#key(rel);
840
+ // A put or a folder makes the folders above it that are not there; a remove makes none.
841
+ await (what === "remove" ? this.#write(rel, () => call(key)) : this.#put(what === "mkdir" ? `${key}/` : key, () => call(key)));
757
842
  return { ok: true, value: undefined };
758
843
  }
759
844
  catch (error) {
@@ -767,7 +852,7 @@ class ArchilWorkspace {
767
852
  remove: (path, type) => wrote(path, "remove", (key) => this.#disk.deleteObject(type === "dir" ? `${key}/` : key)),
768
853
  meta: async (folder) => {
769
854
  try {
770
- await this.#write("", () => this.#disk.putObject(meta, Buffer.from(JSON.stringify(folder))));
855
+ await this.#put(meta, () => this.#disk.putObject(meta, Buffer.from(JSON.stringify(folder))));
771
856
  return { ok: true, value: undefined };
772
857
  }
773
858
  catch (error) {