@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
@@ -0,0 +1,431 @@
1
+ // Uploads in Mode 2 (Archil settings set): kept on the server's own Archil disk, never on its data directory, and copied
2
+ // into a run's folder by the server when it starts the run, so a runner reads no upload and needs no disk of the server's.
3
+ //
4
+ // - The uploads disk: one per server, named agentrun-<server id>-files (uploadsDiskName; an agent's is
5
+ // agentrun-<server id>-i-<agent id>, workspace/run-disk.ts), made by the first upload (POST /v2/files) and found by
6
+ // name after. Reads (GET, DELETE, a run's file_ids) never make it: with none there, this server keeps no file.
7
+ // - Each file is files/<file_id>/ on it, as Mode 1 keeps <data>/files/<file_id>/ (uploads.ts): its bytes (`bytes`) and
8
+ // its record (`file.json`, the contract's File), the record written after the bytes, so a file with no record is none.
9
+ // Each run started with it leaves a mark, files/<file_id>/runs/<run id> (the time it was made), which retention reads.
10
+ // - At a run's start with file_ids (placeRunFiles), before its row is written: the run's disk is resolved as its claim
11
+ // resolves it (workspace/run-disk.ts runDiskOf: the launch's, else its agent's, made when the agent has none), and each
12
+ // file is copied into the run's folder at work/inputs/<path> as a claim copies it in Mode 1 (uploads.ts
13
+ // copyFilesInto), PLACE_CONCURRENCY at a time across every start on the server, all within PLACE_TIMEOUT_MS. A copy
14
+ // that fails, or runs past that, refuses the start in words, and what it wrote is removed. The launch then says so
15
+ // (RunLaunch.filesPlaced) and names the disk, so the claim mounts that disk and copies nothing.
16
+ // - Retention (sweepUploads): a file older than the retention (AGENTRUN_UPLOAD_RETENTION, default 7d; "off" keeps every
17
+ // file) that no run in the store names is deleted. A mark of a run the store no longer has, or keeps only as a deleted
18
+ // run's tombstone (runKeepsUploads), does not count, but a mark younger than MARK_GRACE_MS does: its run may be
19
+ // starting now, its row not yet written.
20
+ //
21
+ // Mode 1 is uploads.ts alone, unchanged.
22
+ import { loadArchilSettings, serverIdOf } from "./archil-settings.js";
23
+ import { ApiError, invalid } from "./errors.js";
24
+ import { serialBy } from "./files.js";
25
+ import { createHash } from "node:crypto";
26
+ import { ID } from "./validate.js";
27
+ import { ArchilClaimRefused } from "./workspace/archil-claim.js";
28
+ import { archilDisk } from "./workspace/archil-disk.js";
29
+ import { availableDisk, diskNamed, ensureDisk } from "./workspace/archil-disks.js";
30
+ import { archilApiKey } from "./workspace/archil-key.js";
31
+ import { archilWorkspace } from "./workspace/archil.js";
32
+ import { agentDirName, runKey } from "./workspace/paths.js";
33
+ import { runDiskOf } from "./workspace/run-disk.js";
34
+ import { isWorkspaceError, WorkspaceError } from "./workspace/index.js";
35
+ import { answerOf, copyFilesInto, INPUTS_DIR, isUploadedFile, MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, mismatchOf, pathProblem, readyFilesOf, reservation, sentInOneCall, slots, } from "./uploads.js";
36
+ import { uuidv7 } from "./agents-store.js";
37
+ /** The folder of the uploads disk the files are kept under. */
38
+ export const UPLOADS_KEY = "files";
39
+ const RECORD = "file.json";
40
+ const BYTES = "bytes";
41
+ /** Each file's marks of the runs started with it. */
42
+ const MARKS = "runs";
43
+ /** How many files the server copies into run folders at once, across every start: its one HTTP/2 connection to
44
+ * Archil's S3 host carries them all, and with 3 or more 10 MiB writes in flight Archil's gateway resets their streams
45
+ * (NGHTTP2_ENHANCE_YOUR_CALM), measured live. Two at a time copied 20 files of 10 MiB in 11 to 14 s. */
46
+ export const PLACE_CONCURRENCY = 2;
47
+ /** How long a start may spend copying its files (and making its agent's disk, when it has none) before it is refused:
48
+ * well inside a client's read timeout of a start (grep reads one for 90 s). */
49
+ export const PLACE_TIMEOUT_MS = 45_000;
50
+ /** A mark younger than this keeps its file whether or not its run is in the store yet. */
51
+ export const MARK_GRACE_MS = 60 * 60_000;
52
+ /** The retention of uploaded files no run names, when AGENTRUN_UPLOAD_RETENTION is not set: 7 days. */
53
+ export const DEFAULT_UPLOAD_RETENTION_MS = 7 * 24 * 60 * 60_000;
54
+ export const UPLOAD_RETENTION_ENV = "AGENTRUN_UPLOAD_RETENTION";
55
+ /** How often the server sweeps the uploads disk. */
56
+ export const UPLOAD_SWEEP_EVERY_MS = 60 * 60_000;
57
+ /** The longest key Archil's S3 gateway takes, in bytes. */
58
+ const KEY_MAX = 1024;
59
+ /** A run's copy of a file on its disk at most: the agent's folder name (agentDirName: up to 128 characters, a dash and 16
60
+ * hex digits), a run id of up to 128 characters, and room for a suffix on each segment (uploads.ts copyFilesInto). */
61
+ const RUN_KEY_ROOM = `agents/${"x".repeat(128 + 17)}/runs/${"x".repeat(128)}/work/${INPUTS_DIR}/`;
62
+ const SUFFIX_ROOM = `-${MAX_FILES_PER_RUN + 1}`.length;
63
+ /** The uploads disk's name: agentrun-<server id>-files. No agent's disk is named so (diskNameOf: -i- or -h- before the
64
+ * agent's part). */
65
+ export const uploadsDiskName = (serverId) => `agentrun-${serverId}-files`;
66
+ /** AGENTRUN_UPLOAD_RETENTION as milliseconds: a whole number and a unit (ms, s, m, h, d), or "off" (undefined: every file
67
+ * is kept). Not set: DEFAULT_UPLOAD_RETENTION_MS. Anything else throws, naming the variable. */
68
+ export function uploadRetentionMs(value) {
69
+ if (value === undefined || value.trim() === "")
70
+ return DEFAULT_UPLOAD_RETENTION_MS;
71
+ if (value.trim() === "off")
72
+ return undefined;
73
+ const m = /^(\d+)(ms|s|m|h|d)$/.exec(value.trim());
74
+ if (!m || Number(m[1]) <= 0)
75
+ throw new Error(`${UPLOAD_RETENTION_ENV} is ${JSON.stringify(value)}: give a duration such as 7d, 36h or 90m, or "off"`);
76
+ return Number(m[1]) * { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
77
+ }
78
+ /** Why `path` cannot be an upload's path on an Archil disk: not the contract's FilePathString, or a run's copy of it
79
+ * (agents/<agent>/runs/<run>/work/inputs/<path>, suffixes included) longer than a key Archil takes. */
80
+ export function archilPathProblem(path) {
81
+ const problem = pathProblem(path);
82
+ if (problem)
83
+ return problem;
84
+ const longest = Buffer.byteLength(`${RUN_KEY_ROOM}${path}`) + path.split("/").length * SUFFIX_ROOM;
85
+ return longest > KEY_MAX ? `path is too long for a run's folder on Archil: a run's copy of it would take a key of up to ${longest} bytes, over ${KEY_MAX}` : undefined;
86
+ }
87
+ /** Reads `body` whole, up to MAX_UPLOAD_BYTES kept (the rest read and dropped, so the client gets the refusal, not a
88
+ * reset): its bytes, its length and its SHA-256. */
89
+ async function readBody(body, keep) {
90
+ const hash = createHash("sha256");
91
+ const chunks = [];
92
+ let size = 0;
93
+ for await (const chunk of body) {
94
+ size += chunk.length;
95
+ hash.update(chunk);
96
+ if (size <= keep)
97
+ chunks.push(chunk);
98
+ }
99
+ return { bytes: size <= keep ? Buffer.concat(chunks, size) : Buffer.alloc(0), size, sha256: hash.digest("hex") };
100
+ }
101
+ const tooLarge = () => new ApiError("payload_too_large", `the body is over ${MAX_UPLOAD_BYTES} bytes, this server's largest upload`, { details: { limit: "max_upload_bytes" } });
102
+ /** Uploads kept in a Workspace: `<file_id>/bytes`, `<file_id>/file.json` and `<file_id>/runs/<run id>` at its root (the
103
+ * uploads disk's files/ folder). The routes' rules are Mode 1's (uploads.ts): the same checks, words and answers. */
104
+ export class WorkspaceUploads {
105
+ workspace;
106
+ commits;
107
+ /** `commits`: each file's commit or delete in progress, one at a time per file as Mode 1's. Shared by every store over
108
+ * the same uploads disk (archilUploads keeps one per disk), so two requests on one file take turns. */
109
+ constructor(workspace, commits = new Map()) {
110
+ this.workspace = workspace;
111
+ this.commits = commits;
112
+ }
113
+ exclusive(id, work) {
114
+ return serialBy(this.commits, id, work);
115
+ }
116
+ async get(id) {
117
+ if (!ID.test(id))
118
+ return null;
119
+ let text;
120
+ try {
121
+ text = Buffer.from(await this.workspace.read(`${id}/${RECORD}`)).toString("utf8");
122
+ }
123
+ catch (error) {
124
+ if (isWorkspaceError(error, "NOT_FOUND"))
125
+ return null;
126
+ throw error;
127
+ }
128
+ let record;
129
+ try {
130
+ record = JSON.parse(text);
131
+ }
132
+ catch {
133
+ return null;
134
+ }
135
+ return isUploadedFile(record) && record.file_id === id ? record : null;
136
+ }
137
+ async ids() {
138
+ const entries = await this.workspace.list("").catch((error) => {
139
+ if (isWorkspaceError(error, "NOT_FOUND"))
140
+ return [];
141
+ throw error;
142
+ });
143
+ return entries.filter((entry) => entry.kind === "dir" && ID.test(entry.name)).map((entry) => entry.name).sort().reverse();
144
+ }
145
+ async remove(id) {
146
+ await this.exclusive(id, async () => {
147
+ if (!(await this.get(id)))
148
+ throw new ApiError("not_found", `no file ${id}: GET /v2/files lists the files this server keeps`);
149
+ await this.workspace.remove(id, { recursive: true, force: true });
150
+ });
151
+ }
152
+ /** A file's folder, gone whole: what a failed make leaves is never a file the API cannot list or delete. */
153
+ async drop(id) {
154
+ await this.workspace.remove(id, { recursive: true, force: true }).catch(() => undefined);
155
+ }
156
+ async take(query, requestType, body) {
157
+ const { path, sha, contentType } = sentInOneCall(query, requestType, archilPathProblem);
158
+ const { bytes, size, sha256 } = await readBody(body, MAX_UPLOAD_BYTES);
159
+ if (size > MAX_UPLOAD_BYTES)
160
+ throw tooLarge();
161
+ if (sha !== null && sha !== sha256)
162
+ throw invalid([{ field: "sha256", reason: "invalid", message: `The body's SHA-256 is ${sha256}; the query names ${sha}.` }]);
163
+ return {
164
+ fingerprint: { sent_in_one_call: true, path, content_type: contentType, size_bytes: size, sha256 },
165
+ commit: async () => {
166
+ const now = Date.now();
167
+ 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 };
168
+ try {
169
+ await this.workspace.write(`${file.file_id}/${BYTES}`, bytes);
170
+ await this.workspace.write(`${file.file_id}/${RECORD}`, `${JSON.stringify(file)}\n`);
171
+ }
172
+ catch (error) {
173
+ await this.drop(file.file_id);
174
+ throw error;
175
+ }
176
+ return answerOf(file);
177
+ },
178
+ // The bytes were never written anywhere but memory.
179
+ discard: async () => undefined,
180
+ };
181
+ }
182
+ async reserve(body) {
183
+ const file = reservation(body, archilPathProblem);
184
+ await this.workspace.write(`${file.file_id}/${RECORD}`, `${JSON.stringify(file)}\n`);
185
+ return answerOf(file);
186
+ }
187
+ async receive(id, body) {
188
+ const file = await this.get(id);
189
+ if (!file)
190
+ throw new ApiError("not_found", `no file ${id}`);
191
+ const { bytes, size, sha256 } = await readBody(body, file.status === "pending" ? file.size_bytes : 0);
192
+ if (size > MAX_UPLOAD_BYTES)
193
+ throw tooLarge();
194
+ const wrong = mismatchOf(file, size, sha256);
195
+ if (wrong)
196
+ throw wrong;
197
+ return await this.exclusive(id, async () => {
198
+ // Read again: another PUT may have made it ready meanwhile, or a DELETE removed it.
199
+ const now = await this.get(id);
200
+ if (!now)
201
+ throw new ApiError("not_found", `no file ${id}: it was deleted while its bytes arrived`);
202
+ if (now.status === "ready") {
203
+ const other = mismatchOf(now, size, sha256);
204
+ if (other)
205
+ throw other;
206
+ return now;
207
+ }
208
+ await this.workspace.write(`${id}/${BYTES}`, bytes);
209
+ const ready = { ...now, sha256, status: "ready" };
210
+ await this.workspace.write(`${id}/${RECORD}`, `${JSON.stringify(ready)}\n`);
211
+ return ready;
212
+ });
213
+ }
214
+ readyFiles(ids) {
215
+ return readyFilesOf(ids, (id) => this.get(id), archilPathProblem);
216
+ }
217
+ /** File `file`'s bytes. */
218
+ async bytes(file) {
219
+ return await this.workspace.read(`${file.file_id}/${BYTES}`);
220
+ }
221
+ /** Marks each of `ids` as named by run `runId`, at `now`. */
222
+ async mark(ids, runId, now = Date.now()) {
223
+ await Promise.all(ids.map((id) => this.workspace.write(`${id}/${MARKS}/${runId}`, `${JSON.stringify({ at: new Date(now).toISOString() })}\n`)));
224
+ }
225
+ /** Whether a run keeps file `id`: a mark of a run the store has (`hasRun`), or one younger than MARK_GRACE_MS. */
226
+ async named(id, hasRun, now) {
227
+ const marks = await this.workspace.list(`${id}/${MARKS}`).catch((error) => {
228
+ if (isWorkspaceError(error, "NOT_FOUND"))
229
+ return [];
230
+ throw error;
231
+ });
232
+ for (const mark of marks) {
233
+ if (mark.kind !== "file" || !ID.test(mark.name))
234
+ continue;
235
+ const at = await this.workspace.read(`${id}/${MARKS}/${mark.name}`).then((raw) => Date.parse(JSON.parse(Buffer.from(raw).toString("utf8")).at ?? ""), () => Number.NaN);
236
+ // A mark whose time can't be read is taken as new: a file is kept while a run might be starting with it.
237
+ if (!(now - at >= MARK_GRACE_MS))
238
+ return true;
239
+ if (await hasRun(mark.name))
240
+ return true;
241
+ }
242
+ return false;
243
+ }
244
+ /** Deletes each file made more than `retentionMs` before `now` that no run keeps (named): the ids deleted. A file a
245
+ * record can't be read for (a make that failed between its bytes and its record) is deleted once its folder is that
246
+ * old by the id's own time (a UUIDv7's milliseconds). */
247
+ async sweep(retentionMs, hasRun, now = Date.now()) {
248
+ const deleted = [];
249
+ for (const id of await this.ids()) {
250
+ const made = await this.get(id).then((file) => (file ? Date.parse(file.created_at) : timeOfId(id)), () => Number.NaN);
251
+ if (!(now - made > retentionMs))
252
+ continue;
253
+ if (await this.named(id, hasRun, now))
254
+ continue;
255
+ await this.exclusive(id, async () => {
256
+ await this.workspace.remove(id, { recursive: true, force: true });
257
+ deleted.push(id);
258
+ });
259
+ }
260
+ return deleted;
261
+ }
262
+ }
263
+ /** The time a UUIDv7 id was made at (its first 48 bits), or NaN for another id. */
264
+ function timeOfId(id) {
265
+ const hex = id.replace(/-/g, "");
266
+ return /^[0-9a-f]{32}$/.test(hex) && hex[12] === "7" ? Number.parseInt(hex.slice(0, 12), 16) : Number.NaN;
267
+ }
268
+ /** Whether run `runId` keeps the uploads it was started with, for retention (sweep's hasRun): the store has it and it
269
+ * was not deleted. A deleted run's row stays as a tombstone (purgedAt set), which keeps no upload. */
270
+ export const runKeepsUploads = (store) => async (runId) => {
271
+ const run = await store.runs.get(runId);
272
+ return run !== undefined && run.purgedAt === null;
273
+ };
274
+ /** Mode 2's uploads for one server: the uploads store (`here`), a start's placing of its files (`place`), and the sweep.
275
+ * Every call reads the Archil settings first: with none (Mode 1), `here` and `place` answer undefined, and the caller
276
+ * uses uploads.ts. */
277
+ export function archilUploads(options) {
278
+ const { store, sealKey, env = {} } = options;
279
+ /** The uploads disk's id by the settings it was found under (its region, S3 URL and account key), once found or made. */
280
+ const disks = new Map();
281
+ /** Each uploads disk's per-file turns (WorkspaceUploads commits), by its id: one map for every request on it. */
282
+ const turns = new Map();
283
+ /** The copy slots every start's placing shares (PLACE_CONCURRENCY). */
284
+ const copying = slots(PLACE_CONCURRENCY);
285
+ const turnsOf = (diskId) => {
286
+ let held = turns.get(diskId);
287
+ if (!held)
288
+ turns.set(diskId, (held = new Map()));
289
+ return held;
290
+ };
291
+ /** The settings and the account key, or undefined in Mode 1. A key that can't be read is 503 in words naming what to
292
+ * save, never a value. */
293
+ async function opened() {
294
+ const settings = await loadArchilSettings(store, env);
295
+ if (settings === undefined)
296
+ return undefined;
297
+ let key;
298
+ try {
299
+ key = (await archilApiKey({ env, keys: store.sealedKeys, sealKey })).value;
300
+ }
301
+ catch (error) {
302
+ throw new ApiError("unavailable", `This server keeps uploads on Archil, and its Archil key can't be read: ${error.message}`);
303
+ }
304
+ const control = { region: settings.region, key: () => key, ...(options.control?.baseUrl ? { baseUrl: options.control.baseUrl } : {}), ...(options.control?.fetch ? { fetch: options.control.fetch } : {}) };
305
+ return { settings, key, control };
306
+ }
307
+ const diskOf = (settings, key, diskId) => (options.control?.makeDisk ?? archilDisk)({ disk: diskId, region: settings.region, s3BaseUrl: settings.s3Url, key: () => key });
308
+ /** The uploads disk's id: found by its name, or made when `make` (the first upload); undefined when it is not there and
309
+ * not to be made. Archil's refusal is 424 in its words, the key scrubbed. */
310
+ async function uploadsDiskId(settings, key, control, make) {
311
+ // By the account too (a hash of its key, never the key): a key of another account in the same region has its own
312
+ // uploads disk, which is looked up again, never the old account's id.
313
+ const at = `${settings.region} ${settings.s3Url} ${createHash("sha256").update(key).digest("hex").slice(0, 16)}`;
314
+ const known = disks.get(at);
315
+ if (known !== undefined)
316
+ return known;
317
+ const name = uploadsDiskName(await serverIdOf(store));
318
+ try {
319
+ // Two first uploads at once both make it: Archil's make is idempotent by name (archil-disks.ts ensureDisk).
320
+ const there = await diskNamed(control, name);
321
+ if (there === undefined && !make)
322
+ return undefined;
323
+ const id = there?.id ?? (await ensureDisk(control, name)).id;
324
+ if (there?.status !== "available")
325
+ await availableDisk(control, id, { timeoutMs: options.placeTimeoutMs ?? PLACE_TIMEOUT_MS });
326
+ disks.set(at, id);
327
+ return id;
328
+ }
329
+ catch (error) {
330
+ throw new ApiError("upstream_failed", `This server's uploads disk ${name} on Archil can't be ${make ? "made or read" : "read"}: ${String(error?.message ?? error).split(key).join("[the key]")}`);
331
+ }
332
+ }
333
+ /** The uploads store in Mode 2, undefined in Mode 1. `make`: an upload, which makes the uploads disk when there is none;
334
+ * otherwise, with none, a store of no files. */
335
+ async function here(make) {
336
+ const open = await opened();
337
+ if (open === undefined)
338
+ return undefined;
339
+ const diskId = await uploadsDiskId(open.settings, open.key, open.control, make);
340
+ return diskId === undefined ? new WorkspaceUploads(emptyWorkspace) : new WorkspaceUploads(archilWorkspace(diskOf(open.settings, open.key, diskId), UPLOADS_KEY), turnsOf(diskId));
341
+ }
342
+ /** In Mode 2, run `runId`'s files (`launch.files`, checked ready) copied into its folder before its row is written: its
343
+ * disk resolved as its claim resolves it, then each file at work/inputs/<path>, and each marked as the run's. Undefined
344
+ * in Mode 1 (the claim copies them, uploads.ts). A disk that can't be had, a file that can't be read or written, or a
345
+ * copy past the time allowed refuses the start in words (424), what it wrote removed. */
346
+ async function place(runId, agentId, launch) {
347
+ const ids = launch.files ?? [];
348
+ if (!ids.length)
349
+ return undefined;
350
+ const open = await opened();
351
+ if (open === undefined)
352
+ return undefined;
353
+ const timeoutMs = options.placeTimeoutMs ?? PLACE_TIMEOUT_MS;
354
+ const signal = AbortSignal.timeout(timeoutMs);
355
+ const refused = (why) => new ApiError("upstream_failed", `The run's files could not be copied into its folder on Archil, so it was not started: ${why.split(open.key).join("[the key]")}`);
356
+ const late = `it took longer than ${timeoutMs / 1000} s`;
357
+ /** The run's folder's parent on its disk, once the disk is resolved: what undo removes the run's folder from. */
358
+ let runs;
359
+ let disk;
360
+ // All of the placing (the records read, the run's disk, the marks, the copy) is one piece of work, raced against the
361
+ // deadline: the start answers by then whatever a call to Archil is still waiting on.
362
+ const work = (async () => {
363
+ const uploads = (await here(false));
364
+ const files = await uploads.readyFiles(ids);
365
+ try {
366
+ // The claim's resolver, without the run (its row is not written yet): the disk then rides the launch, so every
367
+ // claim of the run mounts this one.
368
+ disk = await runDiskOf({ store, agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), control: open.control, signal, availableMs: timeoutMs });
369
+ }
370
+ catch (error) {
371
+ throw refused(error instanceof ArchilClaimRefused ? error.message : signal.aborted ? `its disk was not ready: ${late}` : String(error?.message ?? error));
372
+ }
373
+ signal.throwIfAborted();
374
+ const runDisk = diskOf(open.settings, open.key, disk.diskId);
375
+ runs = archilWorkspace(runDisk, `agents/${agentDirName(agentId)}/runs`, { queueMs: 5_000 });
376
+ await uploads.mark(ids, runId);
377
+ await copyFilesInto(archilWorkspace(runDisk, runKey(agentId, runId)), files, (file) => uploads.bytes(file), { concurrency: PLACE_CONCURRENCY, turn: copying, signal });
378
+ })();
379
+ /** Removes what the placing wrote, once every read and write it started has settled, so none lands after. */
380
+ const undo = async () => {
381
+ await work.catch(() => undefined);
382
+ await runs?.remove(runId, { recursive: true, force: true }).catch(() => undefined);
383
+ };
384
+ try {
385
+ await new Promise((resolve, reject) => {
386
+ const onAbort = () => reject(signal.reason);
387
+ signal.addEventListener("abort", onAbort, { once: true });
388
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
389
+ });
390
+ // A copy that ended just as the deadline passed is late all the same: its start has been given up on.
391
+ signal.throwIfAborted();
392
+ }
393
+ catch (error) {
394
+ if (signal.aborted) {
395
+ // Answered now; what is still in flight is removed once it settles.
396
+ void undo();
397
+ throw refused(`the copy of its files: ${late}`);
398
+ }
399
+ await undo();
400
+ throw error instanceof ApiError ? error : refused(String(error?.message ?? error));
401
+ }
402
+ const launchDisk = launch.archilDisk ?? { diskId: disk.diskId, kind: disk.kind };
403
+ return { launch: { ...launch, archilDisk: launchDisk, filesPlaced: true }, undo };
404
+ }
405
+ /** One sweep of the uploads disk (WorkspaceUploads.sweep), in Mode 2 with the disk there: the ids deleted. */
406
+ async function sweep(retentionMs, hasRun, now = Date.now()) {
407
+ const uploads = await here(false);
408
+ return uploads === undefined ? [] : await uploads.sweep(retentionMs, hasRun, now);
409
+ }
410
+ return { here, place, sweep };
411
+ }
412
+ const noDisk = async () => {
413
+ throw new WorkspaceError("REFUSED", "this server has made no uploads disk yet: its first upload makes it");
414
+ };
415
+ /** The uploads store's folder while the uploads disk is not made: nothing in it, and nothing written to it. */
416
+ const emptyWorkspace = {
417
+ read: async (path) => {
418
+ throw new WorkspaceError("NOT_FOUND", `${path} is not there: this server has made no uploads disk yet`, { path });
419
+ },
420
+ stat: async () => undefined,
421
+ list: async () => [],
422
+ grep: noDisk,
423
+ write: noDisk,
424
+ append: noDisk,
425
+ mkdir: noDisk,
426
+ remove: async () => undefined,
427
+ exec: noDisk,
428
+ process: { start: noDisk, read: noDisk, write: noDisk, signal: noDisk, wait: noDisk, list: noDisk },
429
+ mountSpec: noDisk,
430
+ attach: noDisk,
431
+ };
package/dist/uploads.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ApiError } from "./errors.js";
1
2
  import { type Json } from "./validate.js";
2
3
  import { type Workspace } from "./workspace/index.js";
3
4
  /** `limits.max_upload_bytes`: the largest file a reservation names and a PUT sends. */
@@ -83,7 +84,6 @@ export declare class Uploads {
83
84
  /** Deletes the file `id`, pending or ready, or 404. A run that copied it keeps its copy. In turn with a PUT's commit, so
84
85
  * a PUT that ends after the delete answers 404 and makes nothing. */
85
86
  remove(id: string): Promise<void>;
86
- /** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
87
87
  private answer;
88
88
  /** POST /v2/files?path=...: the body is the file's bytes, whatever its type but a multipart form (415, with the call
89
89
  * that works). The query takes `path`, and `content_type` and `sha256` when given; the length is the body's and the hash
@@ -126,6 +126,57 @@ export declare class Uploads {
126
126
  /** The run ids that hold files here (hold), for a start's sweep of the holds of runs that ended. */
127
127
  holders(): Promise<string[]>;
128
128
  }
129
+ /** What the files routes and a run's start ask of the place uploads are kept: this server's data directory (Uploads,
130
+ * Mode 1), or its uploads disk on Archil (uploads-archil.ts WorkspaceUploads, Mode 2). */
131
+ export interface UploadStore {
132
+ get(id: string): Promise<UploadedFile | null>;
133
+ ids(): Promise<string[]>;
134
+ remove(id: string): Promise<void>;
135
+ take(query: URLSearchParams, requestType: string | undefined, body: AsyncIterable<Buffer>): Promise<Received>;
136
+ reserve(body: Json): Promise<FileUploadAnswer>;
137
+ receive(id: string, body: AsyncIterable<Buffer>): Promise<UploadedFile>;
138
+ readyFiles(ids: readonly unknown[]): Promise<UploadedFile[]>;
139
+ }
140
+ /** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
141
+ export declare const answerOf: (file: UploadedFile) => FileUploadAnswer;
142
+ /** Whether `value` reads as a File record. */
143
+ export declare const isUploadedFile: (value: Json | null) => value is UploadedFile;
144
+ /** A file sent in one call, its query and request type checked (Uploads.take): its path, the hash the query names (or
145
+ * null) and its type. `problemOf`: why a path cannot be a file's path in this store. */
146
+ export declare function sentInOneCall(query: URLSearchParams, requestType: string | undefined, problemOf: (path: string) => string | undefined): {
147
+ path: string;
148
+ sha: string | null;
149
+ contentType: string;
150
+ };
151
+ /** POST /v2/files's JSON body checked as the contract's FileCreate (Uploads.reserve): the pending file it makes, not yet
152
+ * written. */
153
+ export declare function reservation(body: Json, problemOf: (path: string) => string | undefined): UploadedFile;
154
+ /** A body's bytes against the file `held` was reserved or made as: the 422 at the field that differs, or undefined. */
155
+ export declare function mismatchOf(held: UploadedFile, size: number, sha256: string): ApiError | undefined;
156
+ /** A run's `file_ids` (Uploads.readyFiles): each a file `get` finds ready, none twice, at most MAX_FILES_PER_RUN, or 422
157
+ * at `file_ids`. `problemOf`: why a ready file's path cannot be copied into a run of this store. */
158
+ export declare function readyFilesOf(ids: readonly unknown[], get: (id: string) => Promise<UploadedFile | null>, problemOf: (path: string) => string | undefined): Promise<UploadedFile[]>;
159
+ /** Copies `files` into the workspace's `inputs/` (Uploads.copyInto), each at its `path` with its folders: a name taken
160
+ * already (the same path twice, a file where another's folder goes, or what the folder held before) gets the next free
161
+ * suffix (`notes-2.txt`, `docs-2/`), the same for the same files in the same order, every name chosen before the first
162
+ * byte is written. Each copy is a new file written whole by the Workspace. `read`: a file's bytes. `concurrency`: how
163
+ * many files are read and written at once (default 1, one after another); `turn`: each file's read and write runs
164
+ * inside it, as a limit shared with other copies (slots) takes them; `signal`: stops the copy before its next file,
165
+ * rejecting with the signal's reason. */
166
+ export declare function copyFilesInto(workspace: Workspace, files: readonly UploadedFile[], read: (file: UploadedFile) => Promise<Uint8Array>, { concurrency, turn, signal }?: {
167
+ readonly concurrency?: number;
168
+ readonly turn?: (copy: () => Promise<void>) => Promise<void>;
169
+ readonly signal?: AbortSignal;
170
+ }): Promise<void>;
171
+ /** At most `size` of the calls given to it running at once, the rest waiting in the order they came: a slot a call
172
+ * leaves goes straight to the next one waiting. */
173
+ export declare function slots(size: number): <T>(work: () => Promise<T>) => Promise<T>;
174
+ /** The files a run's claim copies in (placeRunInputs): its launch's, unless the server already placed them in its folder
175
+ * when it started the run (Mode 2, RunLaunch.filesPlaced), when the claim reads no upload at all. */
176
+ export declare const filesToCopy: (launch: {
177
+ readonly files?: readonly string[];
178
+ readonly filesPlaced?: true;
179
+ }) => readonly string[];
129
180
  /** The words a run fails in when its files cannot be copied into its workspace at its claim. */
130
181
  export declare const notCopied: (why: string) => string;
131
182
  /** At a run's claim: its opening message (`message`, the start's text content) saved as inputs/message.md