@parcha/agentrun-serve 0.1.0-beta.50 → 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 (146) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +142 -17
  3. package/dist/agents-store.js +7 -3
  4. package/dist/api-only.d.ts +2 -1
  5. package/dist/api-only.js +3 -2
  6. package/dist/capacity.d.ts +50 -0
  7. package/dist/capacity.js +49 -0
  8. package/dist/cli-learning/claude-wire.d.ts +41 -0
  9. package/dist/cli-learning/claude-wire.js +258 -0
  10. package/dist/cli-learning/cli.d.ts +11 -0
  11. package/dist/cli-learning/cli.js +241 -0
  12. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  13. package/dist/cli-learning/codex-worktree.js +119 -0
  14. package/dist/cli-learning/connections.d.ts +62 -0
  15. package/dist/cli-learning/connections.js +87 -0
  16. package/dist/cli-learning/entry.d.ts +1 -0
  17. package/dist/cli-learning/entry.js +4 -0
  18. package/dist/cli-learning/evidence.d.ts +78 -0
  19. package/dist/cli-learning/evidence.js +492 -0
  20. package/dist/cli-learning/hook.d.ts +33 -0
  21. package/dist/cli-learning/hook.js +544 -0
  22. package/dist/cli-learning/install.d.ts +33 -0
  23. package/dist/cli-learning/install.js +335 -0
  24. package/dist/cli-learning/observation-proof.d.ts +14 -0
  25. package/dist/cli-learning/observation-proof.js +10 -0
  26. package/dist/cli-learning/policy.d.ts +48 -0
  27. package/dist/cli-learning/policy.js +363 -0
  28. package/dist/cli-learning/schema.d.ts +16 -0
  29. package/dist/cli-learning/schema.js +27 -0
  30. package/dist/cli-learning/state.d.ts +23 -0
  31. package/dist/cli-learning/state.js +61 -0
  32. package/dist/cli.js +24 -2
  33. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  34. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  35. package/dist/console/index.html +2 -2
  36. package/dist/email/email-faux.d.ts +3 -1
  37. package/dist/email/email-faux.js +3 -2
  38. package/dist/email/routes.js +22 -12
  39. package/dist/harness-install.d.ts +6 -2
  40. package/dist/harness-install.js +40 -8
  41. package/dist/harness.d.ts +1 -1
  42. package/dist/harness.js +2 -2
  43. package/dist/learn/secrets.js +14 -3
  44. package/dist/learning-words.d.ts +1 -1
  45. package/dist/learning-words.js +1 -1
  46. package/dist/mcp-pin-first.js +2 -1
  47. package/dist/mcp-private-hosts.d.ts +24 -3
  48. package/dist/mcp-private-hosts.js +53 -3
  49. package/dist/model-gateway.d.ts +2 -0
  50. package/dist/model-gateway.js +3 -1
  51. package/dist/native/runtimes.d.ts +2 -0
  52. package/dist/native/runtimes.js +2 -0
  53. package/dist/observation/learning.d.ts +32 -0
  54. package/dist/observation/learning.js +66 -0
  55. package/dist/observation/observer.d.ts +8 -1
  56. package/dist/observation/observer.js +89 -9
  57. package/dist/observation/schema.js +12 -4
  58. package/dist/observation/usage-identity.d.ts +9 -0
  59. package/dist/observation/usage-identity.js +11 -0
  60. package/dist/openapi.js +89 -13
  61. package/dist/run-launch.d.ts +14 -0
  62. package/dist/run-launch.js +4 -0
  63. package/dist/run-view.d.ts +2 -0
  64. package/dist/run-view.js +12 -7
  65. package/dist/runner/adapter-loop.js +29 -26
  66. package/dist/runner/adapter-run-spec.js +2 -2
  67. package/dist/runner/beside.d.ts +13 -0
  68. package/dist/runner/beside.js +27 -8
  69. package/dist/runner/cli-run-spec.js +2 -2
  70. package/dist/runner/disk-free.d.ts +44 -0
  71. package/dist/runner/disk-free.js +96 -0
  72. package/dist/runner/feedback-round.d.ts +12 -8
  73. package/dist/runner/feedback-round.js +16 -30
  74. package/dist/runner/harness-loops.js +3 -1
  75. package/dist/runner/journal-kinds.d.ts +1 -1
  76. package/dist/runner/learning-end.js +4 -0
  77. package/dist/runner/main.d.ts +17 -6
  78. package/dist/runner/main.js +187 -45
  79. package/dist/runner/presence.d.ts +11 -2
  80. package/dist/runner/presence.js +31 -3
  81. package/dist/runner/run-child-host.d.ts +12 -15
  82. package/dist/runner/run-child-host.js +46 -108
  83. package/dist/runner/run-errors.js +2 -0
  84. package/dist/runner/runner-check.d.ts +51 -0
  85. package/dist/runner/runner-check.js +206 -0
  86. package/dist/runner/runner-metrics.d.ts +19 -0
  87. package/dist/runner/runner-metrics.js +49 -0
  88. package/dist/runner/runner.d.ts +37 -0
  89. package/dist/runner/runner.js +43 -3
  90. package/dist/runner/sdk-loop.js +34 -22
  91. package/dist/runs-over-store.d.ts +8 -1
  92. package/dist/runs-over-store.js +57 -9
  93. package/dist/sdk/runs.d.ts +22 -2
  94. package/dist/sdk/runs.js +103 -34
  95. package/dist/server.d.ts +3 -0
  96. package/dist/server.js +149 -26
  97. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  98. package/dist/start-switches.js +2 -0
  99. package/dist/stats.d.ts +4 -0
  100. package/dist/stats.js +1 -1
  101. package/dist/store/agent-body.d.ts +12 -0
  102. package/dist/store/agent-body.js +16 -2
  103. package/dist/store/dialect.d.ts +2 -0
  104. package/dist/store/dialect.js +1 -0
  105. package/dist/store/index.d.ts +3 -3
  106. package/dist/store/index.js +2 -2
  107. package/dist/store/postgres/connection.d.ts +5 -2
  108. package/dist/store/postgres/connection.js +19 -7
  109. package/dist/store/postgres/dialect.js +1 -0
  110. package/dist/store/postgres/migrate.d.ts +30 -0
  111. package/dist/store/postgres/migrate.js +72 -5
  112. package/dist/store/postgres/migration-lint.d.ts +8 -0
  113. package/dist/store/postgres/migration-lint.js +119 -0
  114. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  115. package/dist/store/postgres/store.d.ts +8 -3
  116. package/dist/store/postgres/store.js +31 -11
  117. package/dist/store/schema.d.ts +18 -1
  118. package/dist/store/schema.js +33 -2
  119. package/dist/store/sqlite/run-launch.d.ts +9 -1
  120. package/dist/store/sqlite/run-launch.js +44 -0
  121. package/dist/store/sqlite/store.d.ts +17 -0
  122. package/dist/store/sqlite/store.js +87 -10
  123. package/dist/store/store-schema.d.ts +34 -0
  124. package/dist/store/store-schema.js +125 -0
  125. package/dist/store/store.d.ts +53 -1
  126. package/dist/store/store.js +13 -0
  127. package/dist/store-reads/analytics.d.ts +3 -2
  128. package/dist/store-reads/analytics.js +20 -8
  129. package/dist/store-view.d.ts +4 -3
  130. package/dist/store-view.js +11 -7
  131. package/dist/templates.d.ts +3 -2
  132. package/dist/tool-gate.d.ts +4 -2
  133. package/dist/unified-usage.d.ts +24 -0
  134. package/dist/unified-usage.js +400 -0
  135. package/dist/uploads-archil.d.ts +100 -0
  136. package/dist/uploads-archil.js +430 -0
  137. package/dist/uploads.d.ts +55 -1
  138. package/dist/uploads.js +185 -98
  139. package/dist/validate.js +1 -1
  140. package/dist/workspace/archil-disk.d.ts +6 -5
  141. package/dist/workspace/archil-disk.js +27 -12
  142. package/dist/workspace/archil.js +3 -2
  143. package/package.json +10 -10
  144. package/skills/agentrun-serve/SKILL.md +52 -7
  145. package/dist/console/assets/index-D0mr9wfZ.css +0 -1
  146. package/dist/console/assets/index-D7G6o-1E.js +0 -720
package/dist/uploads.js CHANGED
@@ -61,7 +61,7 @@ export const uploadUrl = (id) => `/v2/files/${id}`;
61
61
  export const uploadTestHooks = {};
62
62
  /** A UUIDv7, the form of the agent store's agent and run ids: 48 bits of Unix milliseconds, then random bits, so ids
63
63
  * sort by creation time. The store mints its own inside it and exports no minter. */
64
- function uuidv7(now = Date.now()) {
64
+ export function uuidv7(now = Date.now()) {
65
65
  const bytes = randomBytes(16);
66
66
  bytes.writeUIntBE(now, 0, 6);
67
67
  bytes[6] = (bytes[6] & 0x0f) | 0x70;
@@ -192,9 +192,8 @@ export class Uploads {
192
192
  await rm(join(this.root, id), { recursive: true, force: true });
193
193
  });
194
194
  }
195
- /** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
196
195
  answer(file) {
197
- return { file, upload: { method: "PUT", url: uploadUrl(file.file_id), expires_at: new Date(Date.parse(file.created_at) + UPLOAD_WINDOW_MS).toISOString() } };
196
+ return answerOf(file);
198
197
  }
199
198
  /** POST /v2/files?path=...: the body is the file's bytes, whatever its type but a multipart form (415, with the call
200
199
  * that works). The query takes `path`, and `content_type` and `sha256` when given; the length is the body's and the hash
@@ -202,28 +201,7 @@ export class Uploads {
202
201
  * else the path's extension's, else octet-stream. The bytes stream to a dot-named file of their own under the root,
203
202
  * never held whole; over MAX_UPLOAD_BYTES is 413, a `sha256` they do not have 422. Nothing is made until `commit`. */
204
203
  async take(query, requestType, body) {
205
- const type = String(requestType ?? "").trim();
206
- if (/^multipart\//i.test(type))
207
- throw new ApiError("unsupported_media_type", "A multipart form is not taken: send the file's bytes as the body, as `curl --data-binary @plan.md \"$AGENTRUN_BASE_URL/files?path=plan.md\"` does.");
208
- const issues = [...new Set(query.keys())].filter((key) => !QUERY.includes(key)).map((key) => ({ field: key, reason: "not_allowed", message: `A file sent in one call takes path, content_type and sha256 in the query; ${key} is not one.` }));
209
- for (const key of QUERY)
210
- if (query.getAll(key).length > 1)
211
- issues.push({ field: key, reason: "duplicate", message: `${key} is given more than once` });
212
- const path = query.get("path");
213
- // An empty one is none.
214
- const named = query.get("content_type") || null;
215
- const sha = query.get("sha256");
216
- if (path === null)
217
- issues.push({ field: "path", reason: "missing", message: "Name the file: POST /v2/files?path=<its path> with its bytes as the body, or a JSON reservation {path, size_bytes} and then PUT /v2/files/<id>.", fix: "Add ?path=<the file's name> to the URL." });
218
- if (sha !== null && !SHA256.test(sha))
219
- issues.push({ field: "sha256", reason: "bad_format", message: "sha256 is 64 lowercase hex digits" });
220
- if (issues.length)
221
- throw invalid(issues);
222
- const problem = this.problemOf(path);
223
- if (problem)
224
- throw new ApiError("invalid_file_path", problem);
225
- const given = type && !GENERIC_TYPES.has(type.split(";")[0].trim().toLowerCase()) ? type : undefined;
226
- const contentType = named ?? given ?? typeOf(path) ?? "application/octet-stream";
204
+ const { path, sha, contentType } = sentInOneCall(query, requestType, (path) => this.problemOf(path));
227
205
  await mkdir(this.root, { recursive: true, mode: 0o700 });
228
206
  const temp = tempOf(join(this.root, ".incoming"));
229
207
  const handle = await open(temp, "wx", 0o600);
@@ -244,13 +222,13 @@ export class Uploads {
244
222
  throw invalid([{ field: "sha256", reason: "invalid", message: `The body's SHA-256 is ${sha256}; the query names ${sha}.` }]);
245
223
  await handle.sync();
246
224
  await handle.close();
247
- const fingerprint = { sent_in_one_call: true, path: path, content_type: contentType, size_bytes: size, sha256 };
225
+ const fingerprint = { sent_in_one_call: true, path, content_type: contentType, size_bytes: size, sha256 };
248
226
  let made = false;
249
227
  return {
250
228
  fingerprint,
251
229
  commit: async () => {
252
230
  const now = Date.now();
253
- const file = { file_id: uuidv7(now), path: path, size_bytes: size, content_type: contentType, sha256, status: "ready", created_at: new Date(now).toISOString(), expires_at: null };
231
+ const file = { file_id: uuidv7(now), path, size_bytes: size, content_type: contentType, sha256, status: "ready", created_at: new Date(now).toISOString(), expires_at: null };
254
232
  const dir = join(this.root, file.file_id);
255
233
  await mkdir(dir, { mode: 0o700 });
256
234
  try {
@@ -280,34 +258,7 @@ export class Uploads {
280
258
  }
281
259
  /** POST /v2/files: the body checked as the contract's FileCreate, then a pending file; with where to send its bytes. */
282
260
  async reserve(body) {
283
- const issues = unknownFields(body, FIELDS);
284
- if (typeof body.path !== "string")
285
- issues.push({ field: "path", reason: body.path === undefined ? "missing" : "wrong_type", message: "path is the file's relative path, a string" });
286
- if (!(Number.isSafeInteger(body.size_bytes) && body.size_bytes >= 0))
287
- issues.push({ field: "size_bytes", reason: body.size_bytes === undefined ? "missing" : "wrong_type", message: "size_bytes is the file's length in bytes, an integer 0 or more" });
288
- if (body.content_type !== undefined && typeof body.content_type !== "string")
289
- issues.push({ field: "content_type", reason: "wrong_type", message: "content_type is a string" });
290
- if (body.sha256 !== undefined && !(typeof body.sha256 === "string" && SHA256.test(body.sha256)))
291
- issues.push({ field: "sha256", reason: typeof body.sha256 === "string" ? "bad_format" : "wrong_type", message: "sha256 is 64 lowercase hex digits" });
292
- if (issues.length)
293
- throw invalid(issues);
294
- const problem = this.problemOf(body.path);
295
- if (problem)
296
- throw new ApiError("invalid_file_path", problem);
297
- if (body.size_bytes > MAX_UPLOAD_BYTES)
298
- throw new ApiError("payload_too_large", `size_bytes is over ${MAX_UPLOAD_BYTES}, this server's largest upload`, { details: { limit: "max_upload_bytes" } });
299
- const now = Date.now();
300
- const file = {
301
- file_id: uuidv7(now),
302
- path: body.path,
303
- size_bytes: body.size_bytes,
304
- // Named, or by the path's extension as a run's files are served (`plan.md` is text/markdown), else octet-stream.
305
- content_type: body.content_type ?? typeOf(body.path) ?? "application/octet-stream",
306
- sha256: body.sha256 ?? null,
307
- status: "pending",
308
- created_at: new Date(now).toISOString(),
309
- expires_at: null,
310
- };
261
+ const file = reservation(body, (path) => this.problemOf(path));
311
262
  await mkdir(this.root, { recursive: true, mode: 0o700 });
312
263
  await mkdir(join(this.root, file.file_id), { mode: 0o700 });
313
264
  await writeDurable(join(this.root, file.file_id, RECORD), `${JSON.stringify(file)}\n`);
@@ -401,34 +352,7 @@ export class Uploads {
401
352
  }
402
353
  /** A run's `file_ids`: each a file that is ready, none twice, at most MAX_FILES_PER_RUN, or 422 at `file_ids`. */
403
354
  async readyFiles(ids) {
404
- const issues = [];
405
- if (ids.length > MAX_FILES_PER_RUN)
406
- issues.push({ field: "file_ids", reason: "too_many", message: `A run names at most ${MAX_FILES_PER_RUN} files here (limits.max_files_per_run); this names ${ids.length}.` });
407
- else if (new Set(ids).size !== ids.length)
408
- issues.push({ field: "file_ids", reason: "duplicate", message: "file_ids names one file twice" });
409
- if (issues.length)
410
- throw invalid(issues);
411
- const files = [];
412
- for (const [i, id] of ids.entries()) {
413
- const field = `file_ids[${i}]`;
414
- if (typeof id !== "string" || !ID.test(id)) {
415
- issues.push({ field, reason: "wrong_type", message: `${field} is ${shown(id)}, not a file id: use the file_id an upload answered (POST /v2/files answers it under file.file_id).` });
416
- continue;
417
- }
418
- const file = await this.get(id);
419
- const problem = file?.status === "ready" ? this.problemOf(file.path) : undefined;
420
- if (!file)
421
- issues.push({ field, reason: "not_an_option", message: `There is no file ${id}: reserve it with POST /v2/files.` });
422
- else if (file.status !== "ready")
423
- issues.push({ field, reason: "invalid", message: `The file ${id} is not ready: send its bytes with PUT /v2/files/${id} first.` });
424
- else if (problem)
425
- issues.push({ field, reason: "invalid", message: `The file ${id} cannot be copied into a run here: ${problem}.` });
426
- else
427
- files.push(file);
428
- }
429
- if (issues.length)
430
- throw invalid(issues);
431
- return files;
355
+ return readyFilesOf(ids, (id) => this.get(id), (path) => this.problemOf(path));
432
356
  }
433
357
  /** Copies `files` into the run's `inputs/` through its Workspace, each at its `path` with its folders, in order, before
434
358
  * the run's first turn: a name taken already (the same path twice, a file where another's folder goes, or what the
@@ -437,21 +361,7 @@ export class Uploads {
437
361
  * the copy (ESCAPE), and nothing is written through it. `bytesOf`: where each file's bytes are read (its upload's own,
438
362
  * or the run's hold of them, `held`). */
439
363
  async copyInto(work, files, bytesOf = (file) => join(this.root, file.file_id, BYTES)) {
440
- const workspace = workspaceAt(work);
441
- await uploadTestHooks.beforeCopy?.(workspace);
442
- const names = takenNames(workspace);
443
- // inputs/message.md is the run's message's (MESSAGE_FILE), never an upload's.
444
- const top = await names(INPUTS_DIR);
445
- if (!top.has(MESSAGE_FILE))
446
- top.set(MESSAGE_FILE, "file");
447
- for (const file of files) {
448
- const segments = file.path.split("/");
449
- let dir = INPUTS_DIR;
450
- for (const segment of segments.slice(0, -1))
451
- dir = `${dir}/${free(await names(dir), segment, "dir")}`;
452
- const name = free(await names(dir), segments.at(-1), "file");
453
- await workspace.write(`${dir}/${name}`, await readFile(bytesOf(file)));
454
- }
364
+ await copyFilesInto(workspaceAt(work), files, (file) => readFile(bytesOf(file)));
455
365
  }
456
366
  /** At a run's start, before its row is written: each of its files (`ids`, ready) held for it under
457
367
  * `<root>/.held/<run id>/`, its record and its bytes (a hard link to the upload's, which never change once ready; a
@@ -501,6 +411,183 @@ export class Uploads {
501
411
  return (await readdir(join(this.root, HELD_DIR)).catch(() => [])).filter((name) => ID.test(name));
502
412
  }
503
413
  }
414
+ /** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
415
+ export const answerOf = (file) => ({ file, upload: { method: "PUT", url: uploadUrl(file.file_id), expires_at: new Date(Date.parse(file.created_at) + UPLOAD_WINDOW_MS).toISOString() } });
416
+ /** Whether `value` reads as a File record. */
417
+ export const isUploadedFile = isFile;
418
+ /** A file sent in one call, its query and request type checked (Uploads.take): its path, the hash the query names (or
419
+ * null) and its type. `problemOf`: why a path cannot be a file's path in this store. */
420
+ export function sentInOneCall(query, requestType, problemOf) {
421
+ const type = String(requestType ?? "").trim();
422
+ if (/^multipart\//i.test(type))
423
+ throw new ApiError("unsupported_media_type", "A multipart form is not taken: send the file's bytes as the body, as `curl --data-binary @plan.md \"$AGENTRUN_BASE_URL/files?path=plan.md\"` does.");
424
+ const issues = [...new Set(query.keys())].filter((key) => !QUERY.includes(key)).map((key) => ({ field: key, reason: "not_allowed", message: `A file sent in one call takes path, content_type and sha256 in the query; ${key} is not one.` }));
425
+ for (const key of QUERY)
426
+ if (query.getAll(key).length > 1)
427
+ issues.push({ field: key, reason: "duplicate", message: `${key} is given more than once` });
428
+ const path = query.get("path");
429
+ // An empty one is none.
430
+ const named = query.get("content_type") || null;
431
+ const sha = query.get("sha256");
432
+ if (path === null)
433
+ issues.push({ field: "path", reason: "missing", message: "Name the file: POST /v2/files?path=<its path> with its bytes as the body, or a JSON reservation {path, size_bytes} and then PUT /v2/files/<id>.", fix: "Add ?path=<the file's name> to the URL." });
434
+ if (sha !== null && !SHA256.test(sha))
435
+ issues.push({ field: "sha256", reason: "bad_format", message: "sha256 is 64 lowercase hex digits" });
436
+ if (issues.length)
437
+ throw invalid(issues);
438
+ const problem = problemOf(path);
439
+ if (problem)
440
+ throw new ApiError("invalid_file_path", problem);
441
+ const given = type && !GENERIC_TYPES.has(type.split(";")[0].trim().toLowerCase()) ? type : undefined;
442
+ return { path: path, sha, contentType: named ?? given ?? typeOf(path) ?? "application/octet-stream" };
443
+ }
444
+ /** POST /v2/files's JSON body checked as the contract's FileCreate (Uploads.reserve): the pending file it makes, not yet
445
+ * written. */
446
+ export function reservation(body, problemOf) {
447
+ const issues = unknownFields(body, FIELDS);
448
+ if (typeof body.path !== "string")
449
+ issues.push({ field: "path", reason: body.path === undefined ? "missing" : "wrong_type", message: "path is the file's relative path, a string" });
450
+ if (!(Number.isSafeInteger(body.size_bytes) && body.size_bytes >= 0))
451
+ issues.push({ field: "size_bytes", reason: body.size_bytes === undefined ? "missing" : "wrong_type", message: "size_bytes is the file's length in bytes, an integer 0 or more" });
452
+ if (body.content_type !== undefined && typeof body.content_type !== "string")
453
+ issues.push({ field: "content_type", reason: "wrong_type", message: "content_type is a string" });
454
+ if (body.sha256 !== undefined && !(typeof body.sha256 === "string" && SHA256.test(body.sha256)))
455
+ issues.push({ field: "sha256", reason: typeof body.sha256 === "string" ? "bad_format" : "wrong_type", message: "sha256 is 64 lowercase hex digits" });
456
+ if (issues.length)
457
+ throw invalid(issues);
458
+ const problem = problemOf(body.path);
459
+ if (problem)
460
+ throw new ApiError("invalid_file_path", problem);
461
+ if (body.size_bytes > MAX_UPLOAD_BYTES)
462
+ throw new ApiError("payload_too_large", `size_bytes is over ${MAX_UPLOAD_BYTES}, this server's largest upload`, { details: { limit: "max_upload_bytes" } });
463
+ const now = Date.now();
464
+ return {
465
+ file_id: uuidv7(now),
466
+ path: body.path,
467
+ size_bytes: body.size_bytes,
468
+ // Named, or by the path's extension as a run's files are served (`plan.md` is text/markdown), else octet-stream.
469
+ content_type: body.content_type ?? typeOf(body.path) ?? "application/octet-stream",
470
+ sha256: body.sha256 ?? null,
471
+ status: "pending",
472
+ created_at: new Date(now).toISOString(),
473
+ expires_at: null,
474
+ };
475
+ }
476
+ /** A body's bytes against the file `held` was reserved or made as: the 422 at the field that differs, or undefined. */
477
+ export function mismatchOf(held, size, sha256) {
478
+ return size !== held.size_bytes
479
+ ? invalid([{ field: "size_bytes", reason: "invalid", message: `The body is ${size} bytes; the file was reserved with size_bytes ${held.size_bytes}.` }])
480
+ : held.sha256 !== null && held.sha256 !== sha256
481
+ ? invalid([{ field: "sha256", reason: "invalid", message: `The body's SHA-256 is ${sha256}; the file ${held.status === "ready" ? "is ready with" : "was reserved with"} ${held.sha256}.` }])
482
+ : undefined;
483
+ }
484
+ /** A run's `file_ids` (Uploads.readyFiles): each a file `get` finds ready, none twice, at most MAX_FILES_PER_RUN, or 422
485
+ * at `file_ids`. `problemOf`: why a ready file's path cannot be copied into a run of this store. */
486
+ export async function readyFilesOf(ids, get, problemOf) {
487
+ const issues = [];
488
+ if (ids.length > MAX_FILES_PER_RUN)
489
+ issues.push({ field: "file_ids", reason: "too_many", message: `A run names at most ${MAX_FILES_PER_RUN} files here (limits.max_files_per_run); this names ${ids.length}.` });
490
+ else if (new Set(ids).size !== ids.length)
491
+ issues.push({ field: "file_ids", reason: "duplicate", message: "file_ids names one file twice" });
492
+ if (issues.length)
493
+ throw invalid(issues);
494
+ const files = [];
495
+ // Every record read at once (each a round trip to the disk in Mode 2), then judged in order.
496
+ const found = await Promise.all(ids.map((id) => (typeof id === "string" && ID.test(id) ? get(id) : Promise.resolve(null))));
497
+ for (const [i, id] of ids.entries()) {
498
+ const field = `file_ids[${i}]`;
499
+ if (typeof id !== "string" || !ID.test(id)) {
500
+ issues.push({ field, reason: "wrong_type", message: `${field} is ${shown(id)}, not a file id: use the file_id an upload answered (POST /v2/files answers it under file.file_id).` });
501
+ continue;
502
+ }
503
+ const file = found[i];
504
+ const problem = file?.status === "ready" ? problemOf(file.path) : undefined;
505
+ if (!file)
506
+ issues.push({ field, reason: "not_an_option", message: `There is no file ${id}: reserve it with POST /v2/files.` });
507
+ else if (file.status !== "ready")
508
+ issues.push({ field, reason: "invalid", message: `The file ${id} is not ready: send its bytes with PUT /v2/files/${id} first.` });
509
+ else if (problem)
510
+ issues.push({ field, reason: "invalid", message: `The file ${id} cannot be copied into a run here: ${problem}.` });
511
+ else
512
+ files.push(file);
513
+ }
514
+ if (issues.length)
515
+ throw invalid(issues);
516
+ return files;
517
+ }
518
+ /** Copies `files` into the workspace's `inputs/` (Uploads.copyInto), each at its `path` with its folders: a name taken
519
+ * already (the same path twice, a file where another's folder goes, or what the folder held before) gets the next free
520
+ * suffix (`notes-2.txt`, `docs-2/`), the same for the same files in the same order, every name chosen before the first
521
+ * byte is written. Each copy is a new file written whole by the Workspace. `read`: a file's bytes. `concurrency`: how
522
+ * many files are read and written at once (default 1, one after another); `turn`: each file's read and write runs
523
+ * inside it, as a limit shared with other copies (slots) takes them; `signal`: stops the copy before its next file,
524
+ * rejecting with the signal's reason. */
525
+ export async function copyFilesInto(workspace, files, read, { concurrency = 1, turn = (copy) => copy(), signal } = {}) {
526
+ await uploadTestHooks.beforeCopy?.(workspace);
527
+ const names = takenNames(workspace);
528
+ // inputs/message.md is the run's message's (MESSAGE_FILE), never an upload's.
529
+ const top = await names(INPUTS_DIR);
530
+ if (!top.has(MESSAGE_FILE))
531
+ top.set(MESSAGE_FILE, "file");
532
+ const targets = [];
533
+ for (const file of files) {
534
+ const segments = file.path.split("/");
535
+ let dir = INPUTS_DIR;
536
+ for (const segment of segments.slice(0, -1))
537
+ dir = `${dir}/${free(await names(dir), segment, "dir")}`;
538
+ targets.push({ file, to: `${dir}/${free(await names(dir), segments.at(-1), "file")}` });
539
+ }
540
+ let next = 0;
541
+ // One file that fails stops the others before their next file: nothing more is written once the copy has failed.
542
+ let failed = false;
543
+ const worker = async () => {
544
+ while (!failed && next < targets.length) {
545
+ const { file, to } = targets[next++];
546
+ try {
547
+ // Checked once the turn is had too: a file that waited for one past the deadline is not started.
548
+ signal?.throwIfAborted();
549
+ await turn(async () => {
550
+ signal?.throwIfAborted();
551
+ await workspace.write(to, await read(file));
552
+ });
553
+ }
554
+ catch (error) {
555
+ failed = true;
556
+ throw error;
557
+ }
558
+ }
559
+ };
560
+ // Every worker settles before the copy answers, so nothing it started is still writing once a caller cleans up.
561
+ const settled = await Promise.allSettled(Array.from({ length: Math.max(1, Math.min(concurrency, targets.length)) }, worker));
562
+ const first = settled.find((one) => one.status === "rejected");
563
+ if (first)
564
+ throw first.reason;
565
+ }
566
+ /** At most `size` of the calls given to it running at once, the rest waiting in the order they came: a slot a call
567
+ * leaves goes straight to the next one waiting. */
568
+ export function slots(size) {
569
+ let running = 0;
570
+ const waiting = [];
571
+ return async (work) => {
572
+ if (running < size)
573
+ running++;
574
+ else
575
+ await new Promise((resolve) => waiting.push(resolve));
576
+ try {
577
+ return await work();
578
+ }
579
+ finally {
580
+ const next = waiting.shift();
581
+ if (next)
582
+ next();
583
+ else
584
+ running--;
585
+ }
586
+ };
587
+ }
588
+ /** The files a run's claim copies in (placeRunInputs): its launch's, unless the server already placed them in its folder
589
+ * when it started the run (Mode 2, RunLaunch.filesPlaced), when the claim reads no upload at all. */
590
+ export const filesToCopy = (launch) => (launch.filesPlaced ? [] : (launch.files ?? []));
504
591
  /** The words a run fails in when its files cannot be copied into its workspace at its claim. */
505
592
  export const notCopied = (why) => `The run's files could not be copied into its workspace: ${why}`;
506
593
  /** At a run's claim: its opening message (`message`, the start's text content) saved as inputs/message.md
package/dist/validate.js CHANGED
@@ -18,7 +18,7 @@ export const isObject = (value) => typeof value === "object" && value !== null &
18
18
  /** How long an Idempotency-Key answers with its first answer (capabilities' limits.idempotency_ttl_s). */
19
19
  export const IDEMPOTENCY_TTL_S = 86_400;
20
20
  export const stable = (value) => Array.isArray(value) ? `[${value.map(stable).join(",")}]` : isObject(value) ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stable(value[k])}`).join(",")}}` : JSON.stringify(value);
21
- export const DEFINITION_FIELDS = ["id", "version", "name", "description", "instructions", "workflow", "model", "model_tiers", "thinking", "harness", "place", "computer", "learning", "skills", "tools", "tool_settings", "approvals", "max_cost_usd", "input_schema", "output_schema", "checkout", "native", "sdk"];
21
+ export const DEFINITION_FIELDS = ["id", "version", "name", "description", "instructions", "workflow", "model", "model_tiers", "thinking", "harness", "place", "computer", "learning", "skills", "tools", "tool_settings", "approvals", "max_cost_usd", "input_schema", "output_schema", "checkout", "native", "sdk", "cli_learning"];
22
22
  /** What an agentic definition may ask the server to check out in each run's folder before its first turn
23
23
  * (runner/pr-checkout.ts): `pull_request`, the pull request the run's GitHub event names, at its head, read-only, in
24
24
  * `repo/`; `none` clears it on an edit. */
@@ -60,9 +60,10 @@ export type ArchilExecAnswer = {
60
60
  readonly stdout: string;
61
61
  readonly stderr: string;
62
62
  };
63
- /** The disk itself is not there: Archil's lookup of it, made before the SDK's first call, answered 404 (removed, or the
64
- * key's account or region holds none of that id). Every SDK call fails with it. It carries no HTTP `status`, so no
65
- * caller reads it as a missing file or folder. */
63
+ /** The disk itself is not there: Archil's lookup of it, made before the SDK's first call and again after any call
64
+ * answered 404, answered 404 (removed, at the start or mid-run, or the key's account or region holds none of that id).
65
+ * Every call that meets it fails with it. It carries no HTTP `status`, so no caller reads it as a missing file or
66
+ * folder. */
66
67
  export declare class ArchilDiskMissing extends Error {
67
68
  readonly disk: string;
68
69
  readonly region: string;
@@ -70,8 +71,8 @@ export declare class ArchilDiskMissing extends Error {
70
71
  }
71
72
  /**
72
73
  * An Archil disk, keys relative to its root. A failed call rejects with an error carrying the HTTP `status` when there
73
- * was an answer (the SDK's ArchilS3Error and ArchilApiError do, and so does the ranged read here), or, from every call
74
- * but the ranged read, ArchilDiskMissing when Archil has no such disk.
74
+ * was an answer (the SDK's ArchilS3Error and ArchilApiError do, and so does the ranged read here), or ArchilDiskMissing
75
+ * when Archil has no such disk.
75
76
  */
76
77
  export interface ArchilDisk {
77
78
  readonly id: string;
@@ -16,9 +16,10 @@ export function pinnedImage(image) {
16
16
  }
17
17
  /** The one network an exec is given: no egress. */
18
18
  export const DENY_EGRESS = Object.freeze({ egress: Object.freeze({ default: "deny" }) });
19
- /** The disk itself is not there: Archil's lookup of it, made before the SDK's first call, answered 404 (removed, or the
20
- * key's account or region holds none of that id). Every SDK call fails with it. It carries no HTTP `status`, so no
21
- * caller reads it as a missing file or folder. */
19
+ /** The disk itself is not there: Archil's lookup of it, made before the SDK's first call and again after any call
20
+ * answered 404, answered 404 (removed, at the start or mid-run, or the key's account or region holds none of that id).
21
+ * Every call that meets it fails with it. It carries no HTTP `status`, so no caller reads it as a missing file or
22
+ * folder. */
22
23
  export class ArchilDiskMissing extends Error {
23
24
  disk;
24
25
  region;
@@ -172,6 +173,20 @@ class SdkArchilDisk {
172
173
  this.#readyKey = apiKey;
173
174
  return ready;
174
175
  }
176
+ /** `call` made with the client and the disk. */
177
+ async #call(call) {
178
+ return call(await this.#sdk()).catch((error) => this.#after(error));
179
+ }
180
+ /** Throws `error`. A 404 is a missing key, or the disk itself removed at Archil since #sdk looked it up: the disk is
181
+ * looked up again (one disks.get), so a disk not there fails the call that met it as ArchilDiskMissing. The 404 is
182
+ * kept only once the lookup found the disk; a lookup that failed otherwise is the call's failure. */
183
+ async #after(error) {
184
+ if (error?.status === 404) {
185
+ this.#ready = undefined;
186
+ await this.#sdk();
187
+ }
188
+ throw error;
189
+ }
175
190
  /** The client made and the disk looked up: one disks.get. A key of the wrong kind fails here (401 or 403). */
176
191
  async ready() {
177
192
  await this.#sdk();
@@ -218,25 +233,25 @@ class SdkArchilDisk {
218
233
  await pause(100 * 2 ** attempt);
219
234
  continue;
220
235
  }
221
- throw new RangeReadError(response.status, response.statusText, body);
236
+ return this.#after(new RangeReadError(response.status, response.statusText, body));
222
237
  }
223
238
  }
224
239
  async putObject(key, body) {
225
- await (await this.#sdk()).disk.putObject(key, body);
240
+ await this.#call(({ disk }) => disk.putObject(key, body));
226
241
  }
227
242
  async appendObject(key, body) {
228
- await (await this.#sdk()).disk.appendObject(key, body);
243
+ await this.#call(({ disk }) => disk.appendObject(key, body));
229
244
  }
230
245
  async deleteObject(key) {
231
- await (await this.#sdk()).disk.deleteObject(key);
246
+ await this.#call(({ disk }) => disk.deleteObject(key));
232
247
  }
233
248
  async deleteObjects(keys) {
234
- return (await (await this.#sdk()).disk.deleteObjects([...keys], { quiet: true })).errors;
249
+ return (await this.#call(({ disk }) => disk.deleteObjects([...keys], { quiet: true }))).errors;
235
250
  }
236
251
  async listPage(prefix, options) {
237
- const page = await (await this.#sdk()).disk.listObjects(prefix, {
252
+ const page = await this.#call(({ disk }) => disk.listObjects(prefix, {
238
253
  recursive: options.recursive, singlePage: true, ...(options.token === undefined ? {} : { continuationToken: options.token }),
239
- });
254
+ }));
240
255
  const next = page.isTruncated ? page.nextContinuationToken : undefined;
241
256
  return {
242
257
  objects: page.objects.map(({ key, size, lastModified }) => ({ key, size, ...(lastModified === undefined ? {} : { mtimeMs: lastModified.getTime() }) })),
@@ -244,7 +259,7 @@ class SdkArchilDisk {
244
259
  };
245
260
  }
246
261
  async grep(request) {
247
- const answer = await (await this.#sdk()).disk.grep({ ...request, globs: request.globs === undefined ? undefined : [...request.globs] });
262
+ const answer = await this.#call(({ disk }) => disk.grep({ ...request, globs: request.globs === undefined ? undefined : [...request.globs] }));
248
263
  return { matches: answer.matches.map(({ file, line, text }) => ({ file, line, text })), stoppedReason: answer.stoppedReason };
249
264
  }
250
265
  async exec(request) {
@@ -268,7 +283,7 @@ class SdkArchilDisk {
268
283
  ...(request.network === undefined ? {} : { network: { egress: { default: request.network.egress.default } } }),
269
284
  command: request.command,
270
285
  disks: Object.fromEntries(Object.entries(request.mounts).map(([name, subdirectory]) => [name, { disk: this.id, subdirectory, queueMs: request.queueMs }])),
271
- });
286
+ }).catch((error) => this.#after(error));
272
287
  return { exitCode: answer.exitCode, stdout: answer.stdout, stderr: answer.stderr };
273
288
  }
274
289
  }
@@ -300,8 +300,9 @@ class ArchilWorkspace {
300
300
  answer = await this.#disk.getRange(this.#key(rel), `bytes=${offset}-${last}`);
301
301
  }
302
302
  catch (error) {
303
- // A ranged read is no SDK call, so a disk that is not there answers it 404 as a missing file would: the look at what
304
- // is there (an SDK call) is what tells them apart, and its ArchilDiskMissing is the read's failure.
303
+ // The seam looks the disk up again after a ranged read's 404, so a disk gone at Archil, at the start or mid-run, is
304
+ // its ArchilDiskMissing (no status). A 404 left is a file that is not there, or a folder: the look at what is there
305
+ // tells them apart, and a disk removed in between still fails the read as gone.
305
306
  const kind = statusOf(error) === 404
306
307
  ? await this.#kind(rel).catch((lookup) => {
307
308
  if (lookup instanceof ArchilDiskMissing)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-serve",
3
- "version": "0.1.0-beta.50",
3
+ "version": "0.1.0-beta.51",
4
4
  "description": "The AgentRun server: the /v2 API and console over one store, with runners that run your agents; the deployable process of the AgentRun platform.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -62,15 +62,15 @@
62
62
  "@earendil-works/pi-coding-agent": "1.5.2",
63
63
  "@modelcontextprotocol/client": "2.4.0",
64
64
  "@modelcontextprotocol/server": "2.4.0",
65
- "@parcha/agentrun-computer": "0.1.0-beta.50",
66
- "@parcha/agentrun-decisions": "0.1.0-beta.50",
67
- "@parcha/agentrun-dsl": "0.1.0-beta.50",
68
- "@parcha/agentrun-harness-acp": "0.1.0-beta.50",
69
- "@parcha/agentrun-harness-claude": "0.1.0-beta.50",
70
- "@parcha/agentrun-harness-codex": "0.1.0-beta.50",
71
- "@parcha/agentrun-jev": "0.1.0-beta.50",
72
- "@parcha/agentrun-kernel": "0.1.0-beta.50",
73
- "@parcha/pi-browser": "0.1.0-beta.50",
65
+ "@parcha/agentrun-computer": "0.1.0-beta.51",
66
+ "@parcha/agentrun-decisions": "0.1.0-beta.51",
67
+ "@parcha/agentrun-dsl": "0.1.0-beta.51",
68
+ "@parcha/agentrun-harness-acp": "0.1.0-beta.51",
69
+ "@parcha/agentrun-harness-claude": "0.1.0-beta.51",
70
+ "@parcha/agentrun-harness-codex": "0.1.0-beta.51",
71
+ "@parcha/agentrun-jev": "0.1.0-beta.51",
72
+ "@parcha/agentrun-kernel": "0.1.0-beta.51",
73
+ "@parcha/pi-browser": "0.1.0-beta.51",
74
74
  "@secretlint/core": "13.1.0",
75
75
  "@secretlint/profiler": "13.1.0",
76
76
  "@secretlint/secretlint-rule-preset-recommend": "13.1.0",
@@ -30,7 +30,7 @@ Inspect configured models before asking for a key. For an existing setup, follow
30
30
  and history import need no destination model key. Live jobs use the source runtime's existing sign-in.
31
31
 
32
32
  Finish with the first requested run's result and console link, or imported history and counts. Offer optional
33
- self-improvement separately, and verify accepted notes or skills in a fresh later run when requested.
33
+ self-improvement separately, and verify owner corrections in a fresh later run when requested.
34
34
 
35
35
  ## Connect agent
36
36
 
@@ -108,11 +108,56 @@ reported model/harness and activity/usage. CLI `configured` or `delivery_state:
108
108
  delivery. Observed sessions are read-only: idle is not proof of completion, and missing telemetry is not proof of
109
109
  an agent failure. No prompts, transcripts or tool contents are uploaded through this metadata path.
110
110
 
111
- If the user also wants self-improvement for application-owned jobs, follow the supported backend SDK learning
111
+ For independently started **Codex CLI or Claude Code** sessions, use the existing CLI learning path below.
112
+ For SDK application-owned jobs, follow the supported backend SDK learning
112
113
  integration and verify accepted-revision delivery in a fresh run. Observation alone cannot enable it. The current
113
114
  Claude Agent SDK and Codex SDK wrappers are TypeScript integrations; do not claim a Python SDK backend is wrapped
114
115
  by setting OTEL variables. Do not fabricate a runnable native agent or use a copied prompt as proof.
115
116
 
117
+ ### Learning in existing CLI sessions
118
+
119
+ For a connected-session card handoff, read its exact `GET /v2/observations?session_id=...` record.
120
+ On the source machine, resolve `external_session_id` through the collector's private identity map to the
121
+ native session, then inspect that session's actual project through its harness. Never print the identity
122
+ map or credentials, and never select a project from a display name or basename. A verified
123
+ `learning.agent_id` links to the existing shared project/runtime learning profile; reuse it. If the
124
+ source is unavailable, ask the user to open the original session. Run and Edit continue or change that
125
+ original setup, not a managed run or a replacement definition. Delegated children cannot enable independent
126
+ hook learning. Only offer enrollment for the selected root session's project, with its shared scope clear.
127
+
128
+ When requested, use the matching build's `learning connect` on the source machine. This path keeps the
129
+ original CLI in control of task execution and does not require an SDK wrapper. The initial integration
130
+ requires AgentRun on that same machine; identify its loopback port and actual data directory. Do not
131
+ silently replace a remote destination with a new local server. Enrollment uses the local owner credential
132
+ privately and leaves a scoped connection credential for hooks, never an owner key in project files.
133
+
134
+ ```sh
135
+ agentrun-serve learning connect --project /absolute/project --runtime codex \
136
+ --url http://127.0.0.1:7340 --data /absolute/server-data
137
+ ```
138
+
139
+ Use `claude-code` for Claude Code. Scope enrollment to the selected project/runtime. Installation merges
140
+ source hooks without replacing other hooks or changing tools, permissions, instructions or sign-in.
141
+ Codex linked worktrees append exact project-scoped hooks to the corresponding main-checkout
142
+ `.codex/hooks.json`, following native discovery. They keep separate local receipts and a local `.codex`
143
+ directory; disconnect preserves surviving native hook positions. If `learning status` reports `migration-required`,
144
+ rerun the same connect command to migrate unchanged owned hooks without replacing the connection.
145
+ Verify `/hooks`; Codex must trust the current declaration. Project configuration does not hot reload:
146
+ open a new session or close and resume it after the current task finishes. Reloading user settings alone
147
+ does not reload these project hooks. Do not interrupt the user's running task to activate them.
148
+ Do not claim merely writing a configuration file activated a running session. Begin on the next complete
149
+ prompt after activation, without importing earlier conversations or learning from an in-flight turn.
150
+
151
+ The prompt hook supplies pinned owner corrections; completion hooks record bounded role-preserving evidence
152
+ and reported usage. Source dialogue never becomes a standing correction automatically. Source hooks do not
153
+ provide a workflow execution bridge or make extra native reflection calls. Missing policy, truncated evidence
154
+ and cancellation stay explicit. This is not metadata-only observation.
155
+
156
+ Use `learning status` with the same project/runtime/data arguments and open the returned agent's Learning
157
+ tab. Save a correction explicitly, then verify an actual completed source run and its delivery and use
158
+ on a later prompt. Report incomplete evidence accurately. Learning Off controls guidance for future prompts;
159
+ `learning disconnect` revokes enrollment and removes only its installed hooks, retaining prior history.
160
+
116
161
  ### Live connection on this server
117
162
 
118
163
  Verify that the coding agent, source project and AgentRun server are on the same machine. A browser's loopback
@@ -210,11 +255,11 @@ target; duplicates are skipped. The worker does not continuously upload historic
210
255
 
211
256
  ### Optional self-improvement
212
257
 
213
- When requested, verify the imported agent and enable its existing **Self-improving** control. Notes and skills are
214
- additive, pinned to a learning revision for each run. Reflection resumes the exact task session with tools disabled;
215
- the existing checker, grader and merge rules decide what becomes active. Risky proposals await owner review in
216
- Learning Dojo; a connector cannot approve them. Reflection and grading add model usage. Off means later runs
217
- receive and create no AgentRun learning. Do not start a paid run unless authorized, and do not promise enforcement
258
+ When requested, verify the imported agent and enable its existing **Self-improving** control. Owner corrections
259
+ are additive, pinned to a learning revision for each run. Eligible jobs compile into workflow drafts by resuming
260
+ the exact task session with tools disabled; checks and a dry run decide whether to keep a draft. Compilation
261
+ adds model usage. Learned workflows do not serve native runs in this release. Off means later runs receive
262
+ and create no AgentRun learning. Do not start a paid run unless authorized, and do not promise enforcement
218
263
  of native dollar caps, interactive approvals, learned workflows or unsupported desktop tools.
219
264
 
220
265
  ### Historical import into a local store