@parcha/agentrun-serve 0.1.0-beta.30 → 0.1.0-beta.31

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 (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +182 -26
  3. package/dist/agents.d.ts +8 -3
  4. package/dist/agents.js +4 -1
  5. package/dist/app.js +23 -8
  6. package/dist/background.d.ts +2 -1
  7. package/dist/background.js +41 -20
  8. package/dist/box-egress-vm.d.ts +125 -0
  9. package/dist/box-egress-vm.js +350 -0
  10. package/dist/box-egress.d.ts +3 -2
  11. package/dist/box-relay-vm.d.ts +4 -0
  12. package/dist/box-relay-vm.js +76 -55
  13. package/dist/boxes.d.ts +7 -2
  14. package/dist/boxes.js +30 -11
  15. package/dist/cap.d.ts +2 -1
  16. package/dist/cap.js +2 -1
  17. package/dist/cli.js +30 -4
  18. package/dist/console/assets/{index-34jfpIbQ.js → index-CnJBf7Lc.js} +90 -85
  19. package/dist/console/index.html +1 -1
  20. package/dist/decisions.d.ts +3 -3
  21. package/dist/decisions.js +4 -3
  22. package/dist/files.d.ts +3 -0
  23. package/dist/files.js +3 -0
  24. package/dist/grade.d.ts +5 -2
  25. package/dist/grade.js +13 -5
  26. package/dist/harness-app.js +10 -1
  27. package/dist/host-check.d.ts +12 -0
  28. package/dist/host-check.js +34 -0
  29. package/dist/key-words.d.ts +37 -0
  30. package/dist/key-words.js +40 -0
  31. package/dist/learn/grade.d.ts +3 -0
  32. package/dist/learn/grade.js +3 -1
  33. package/dist/learn/index.d.ts +1 -1
  34. package/dist/learn/index.js +1 -1
  35. package/dist/learn/reflect.js +2 -0
  36. package/dist/learn/skills.d.ts +2 -0
  37. package/dist/learn/skills.js +16 -0
  38. package/dist/learning-routes.d.ts +30 -1
  39. package/dist/learning-routes.js +173 -19
  40. package/dist/learning-run.d.ts +1 -1
  41. package/dist/learning-run.js +25 -4
  42. package/dist/learning-words.d.ts +7 -3
  43. package/dist/learning-words.js +26 -8
  44. package/dist/learning.d.ts +9 -1
  45. package/dist/learning.js +57 -2
  46. package/dist/mcp-gateway.d.ts +96 -0
  47. package/dist/mcp-gateway.js +408 -0
  48. package/dist/mcp-meta.d.ts +17 -0
  49. package/dist/mcp-meta.js +38 -0
  50. package/dist/mcp-servers.d.ts +26 -5
  51. package/dist/mcp-servers.js +53 -10
  52. package/dist/openapi.js +52 -9
  53. package/dist/page.d.ts +2 -0
  54. package/dist/page.js +3 -0
  55. package/dist/place.d.ts +3 -2
  56. package/dist/place.js +11 -3
  57. package/dist/print.d.ts +7 -0
  58. package/dist/print.js +13 -0
  59. package/dist/run-box.js +15 -5
  60. package/dist/runnable.d.ts +8 -1
  61. package/dist/runnable.js +51 -2
  62. package/dist/runs.d.ts +15 -8
  63. package/dist/runs.js +66 -13
  64. package/dist/secrets.d.ts +15 -0
  65. package/dist/secrets.js +20 -2
  66. package/dist/server.d.ts +10 -1
  67. package/dist/server.js +111 -29
  68. package/dist/tool-gate.d.ts +18 -3
  69. package/dist/tool-gate.js +44 -13
  70. package/dist/tool-keys.d.ts +2 -1
  71. package/dist/tool-keys.js +4 -8
  72. package/dist/tool-plane.d.ts +5 -1
  73. package/dist/tool-plane.js +30 -6
  74. package/dist/tools.js +8 -5
  75. package/dist/web-fetch.js +3 -3
  76. package/package.json +12 -16
@@ -16,12 +16,13 @@
16
16
  // the same link rule, so a link at the folder is an error on either, never followed. A text that leaves holding one of
17
17
  // the host's secrets as they are now (a value made secret after it was written) is cut of it, a file's name holding
18
18
  // one reads "[redacted]" whole, and a diff's file holding one is withheld.
19
+ import { existsSync } from "node:fs";
19
20
  import { rm } from "node:fs/promises";
20
21
  import { join } from "node:path";
21
- import { approve, buildIndex, CAPS, checkNote, INDEX_FILE, INDEX_LINES, isHeld, learnedFront, learnedName, learnedPlace, learnedStatus, NOTE_FILE, NOTE_STATUSES, parseNoteFile, printable, released, retire, retiredLearned, SKILLS_DIR, supersede, WORKFLOWS_DIR } from "./learn/index.js";
22
+ import { approve, buildIndex, CAPS, checkNote, frontKeys, INDEX_FILE, INDEX_LINES, isHeld, LEARNED_KEYS, learnedFront, learnedName, learnedPlace, learnedStatus, NOTE_FILE, NOTE_STATUSES, parseNoteFile, printable, released, retire, retiredLearned, skillProblems, SKILLS_DIR, supersede, unstorable, WORKFLOWS_DIR } from "./learn/index.js";
22
23
  import { ApiError, invalid } from "./errors.js";
23
24
  import { homeOf, readJson } from "./files.js";
24
- import { agentFolder, changedOrder, checkOut, detailShown, git, line, mainOf, notesView, openAgentRepo, PROPOSAL, readBlobs, readFolder, readPin, secretsShown, withAgentRepo } from "./learning.js";
25
+ import { agentFolder, checkOut, detailShown, git, line, mainOf, notesView, openAgentRepo, PROPOSAL, readBlobs, readFolder, readPin, secretsShown, withAgentRepo } from "./learning.js";
25
26
  import { isObject } from "./validate.js";
26
27
  /** A file on main larger than this is not read: a note is at most 4 KB (learn/check.ts CAPS.note). */
27
28
  const FILE_CAP = 1 << 20;
@@ -38,6 +39,7 @@ const APPROVED_VIA = "Approved-Via: console";
38
39
  /** What a retire adds to a note, on top of the note cap a retired note may fill (learn/notes.ts retire). */
39
40
  const RETIRED_LINE = Buffer.byteLength("status: retired\n");
40
41
  const utf8 = new TextDecoder("utf-8", { fatal: true });
42
+ const PERSON_KINDS = ["approved", "edited", "created", "retired", "restored"];
41
43
  export { secretsShown } from "./learning.js";
42
44
  /** The few values last kept, by key, oldest dropped first: at most `entries` of them, `bytes` in all by their sizes. */
43
45
  class Recent {
@@ -184,27 +186,75 @@ async function notesAt(home, repo, sha) {
184
186
  const known = parsedAt.get(key);
185
187
  if (known)
186
188
  return known;
187
- const [{ index, notes }, touched] = await Promise.all([readAt(home, repo, sha), changedOrder(home, repo, sha)]);
189
+ const [{ index, notes }, { order: touched, changes }] = await Promise.all([readAt(home, repo, sha), historyAt(home, repo, sha)]);
188
190
  const rank = (note) => (note.status === "active" ? 0 : 1);
189
- const parsed = { index, notes: [...notes.values()].sort((a, b) => rank(a) - rank(b) || (touched.get(a.file) ?? Infinity) - (touched.get(b.file) ?? Infinity) || (a.file < b.file ? -1 : 1)) };
191
+ const parsed = { index, changes, notes: [...notes.values()].sort((a, b) => rank(a) - rank(b) || (touched.get(a.file) ?? Infinity) - (touched.get(b.file) ?? Infinity) || (a.file < b.file ? -1 : 1)) };
190
192
  parsedAt.set(key, parsed, 2 * parsed.notes.reduce((size, note) => size + note.text.length + 256, index.length));
191
193
  return parsed;
192
194
  }
195
+ /** What a commit's change was, as the view says it (LastChange), or undefined for a commit that is neither: a person's
196
+ * names its kind in the fixed prefix of its subject, `learning: <kind> by a person: `; a run's merge carries its Run-Id
197
+ * trailer, `learned`. Nothing else is read (no other part of the subject, no body). */
198
+ function changeOf(at, subject, runId) {
199
+ if (runId.trim())
200
+ return { kind: "learned", by: "run", at };
201
+ for (const kind of PERSON_KINDS)
202
+ if (subject.startsWith(`learning: ${kind} by a person: `))
203
+ return { kind, by: "person", at };
204
+ return undefined;
205
+ }
206
+ /** The log fields changeOf reads (LAST_FORMAT), after the record separator: the commit's time, subject, Changed-By and Run-Id. */
207
+ const LAST_FORMAT = "%cI%x1f%s%x1f%(trailers:key=Run-Id,valueonly,separator=%x2C)";
208
+ /** Folds one record of a LAST_FORMAT walk (newest first) into `out`, for the files it changed. */
209
+ function foldHistory(out, head, files) {
210
+ const [at = "", subject = "", runId = ""] = head.split("\x1f");
211
+ const change = changeOf(at, subject, runId);
212
+ for (const file of files) {
213
+ const known = out.get(file);
214
+ if (!known)
215
+ out.set(file, { at, ...(change ? { last: change } : {}), ...(change?.kind === "retired" ? { retire: change } : {}) });
216
+ else if (!known.retire && change?.kind === "retired")
217
+ known.retire = change;
218
+ }
219
+ }
220
+ /** A retired item's `retired`: its newest retire by a person, else (retired some other way) its newest change's time. */
221
+ const retiredOf = (history) => (history ? (history.retire ? { at: history.retire.at, by: "person" } : { at: history.at, by: "run" }) : undefined);
222
+ /** Commit `sha`'s first-parent history, read in one walk: each file's place by its newest change (0 for the newest
223
+ * commit's, as learning.ts changedOrder orders a run's notes) and that change (changeOf). */
224
+ async function historyAt(home, repo, sha) {
225
+ const order = new Map();
226
+ const changes = new Map();
227
+ recordsOf(await git(home, repo, ["log", "--first-parent", "-z", "--name-only", `--format=%x1e${LAST_FORMAT}`, sha])).forEach(({ head, files }, i) => {
228
+ for (const file of files)
229
+ if (!order.has(file))
230
+ order.set(file, i);
231
+ foldHistory(changes, head, files);
232
+ });
233
+ return { order, changes };
234
+ }
235
+ /** A note as the view shows it, with its last change, and when and by whom it was retired on a retired one. */
236
+ const withChanges = (view, history) => ({
237
+ ...view,
238
+ ...(history?.last ? { last_change: history.last } : {}),
239
+ ...(view.status === "retired" && history ? { retired: retiredOf(history) } : {}),
240
+ });
193
241
  /** By the folder and the commit: its skills and drafts, raw (each answer cuts them of the host's secrets as they are
194
242
  * then), for the 8 commits last read. */
195
243
  const learnedAtCache = new Recent(8, 4 << 20);
196
244
  /** The run whose merge last changed each of commit `sha`'s files under skills/ and workflows/: its first-parent log's
197
245
  * commits with a Run-Id, newest first, read once (a person's approval, which names none, changes no answer). */
198
246
  async function lastRuns(home, repo, sha) {
199
- const out = new Map();
200
- for (const { head, files } of recordsOf(await git(home, repo, ["log", "--first-parent", "-z", "--name-only", "--format=%x1e%(trailers:key=Run-Id,valueonly,separator=%x2C)", sha, "--", SKILLS_DIR, WORKFLOWS_DIR]))) {
201
- const run = head.split(",")[0].trim();
247
+ const runs = new Map();
248
+ const changes = new Map();
249
+ for (const { head, files } of recordsOf(await git(home, repo, ["log", "--first-parent", "-z", "--name-only", `--format=%x1e${LAST_FORMAT}`, sha, "--", SKILLS_DIR, WORKFLOWS_DIR]))) {
250
+ const run = (head.split("\x1f")[2] ?? "").split(",")[0].trim();
251
+ foldHistory(changes, head, files);
202
252
  if (run)
203
253
  for (const file of files)
204
- if (!out.has(file))
205
- out.set(file, run);
254
+ if (!runs.has(file))
255
+ runs.set(file, run);
206
256
  }
207
- return out;
257
+ return { runs, changes };
208
258
  }
209
259
  /** Commit `sha`'s skills and workflow drafts, by name: each skill's SKILL.md and each draft's workflow.json with its
210
260
  * README.md, regular files under FILE_CAP, with what their front matter says. A draft without its README, or a file
@@ -224,7 +274,7 @@ async function learnedAt(home, repo, sha) {
224
274
  }
225
275
  const fronts = new Map([...entries].filter(([path]) => !path.endsWith("/workflow.json")).map(([path, { oid }]) => [path, oid]));
226
276
  // A folder with none reads no history for them.
227
- const [texts, runs] = entries.size ? await Promise.all([textsOf(home, repo, fronts), lastRuns(home, repo, sha)]) : [new Map(), new Map()];
277
+ const [texts, { runs, changes }] = entries.size ? await Promise.all([textsOf(home, repo, fronts), lastRuns(home, repo, sha)]) : [new Map(), { runs: new Map(), changes: new Map() }];
228
278
  const skills = [];
229
279
  const workflows = [];
230
280
  for (const [path, { size }] of entries) {
@@ -237,6 +287,11 @@ async function learnedAt(home, repo, sha) {
237
287
  continue;
238
288
  const said = learnedFront(front.text);
239
289
  const item = { name: place.name, file: path, ...(place.kind === "workflow" ? { readme: held } : {}), description: said?.description ?? "", status: learnedStatus(front.text), run: runs.get(path) ?? null, bytes: size, etag: etagOf(front.oid) };
290
+ const history = changes.get(held);
291
+ if (history?.last)
292
+ item.last_change = history.last;
293
+ if (item.status === "retired")
294
+ item.retired = retiredOf(history);
240
295
  (place.kind === "skill" ? skills : workflows).push(item);
241
296
  }
242
297
  const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
@@ -267,6 +322,47 @@ async function pageRequest(home, repo, query, fallback) {
267
322
  throw new ApiError("bad_request", "cursor is not one this server gave");
268
323
  return { limit, at: { sha: named[1], offset: Number(named[2]) } };
269
324
  }
325
+ /** For tests: how many times a pending count was read from a folder (once per commit of its main). */
326
+ export const pendingTestHooks = { reads: 0 };
327
+ /** By agent: its folder's main commit and how many of its items wait for the owner's OK there. */
328
+ const pendingBy = new Map();
329
+ const pendingReads = new Map();
330
+ /** How many of agent `agentId`'s learned items wait for its owner's OK on its folder's main: notes, skills and workflow
331
+ * drafts held with `status: pending`, as the learning view reads them (notesAt, learnedAt). Read once per commit of
332
+ * main (a list of agents asks for every agent): the commit is resolved each time, the folder only when it moved. A
333
+ * folder never made has none waiting; one that cannot be read is undefined (the caller shows no count). */
334
+ export async function pendingCount(data, agentId) {
335
+ try {
336
+ const { home, repo } = await placeOf(data, agentId);
337
+ // A folder never made (no .git) holds nothing yet: 0. One whose .git git cannot read (an invalid repository, git
338
+ // missing) is unknown: undefined, so the count is left out rather than shown as 0.
339
+ if (existsSync(join(repo, ".git")) && !(await git(home, repo, ["rev-parse", "--git-dir"]).then(() => true, () => false)))
340
+ return undefined;
341
+ const sha = await mainOf(home, repo);
342
+ if (!sha)
343
+ return 0;
344
+ const known = pendingBy.get(agentId);
345
+ if (known?.sha === sha)
346
+ return known.pending;
347
+ // Requests that miss together share one read of the commit (cleared once it settles, so a failure is not kept).
348
+ const key = `${agentId}\0${sha}`;
349
+ let reading = pendingReads.get(key);
350
+ if (!reading) {
351
+ pendingTestHooks.reads += 1;
352
+ reading = Promise.all([notesAt(home, repo, sha), learnedAt(home, repo, sha)]).then(([{ notes }, { skills, workflows }]) => {
353
+ const pending = notes.filter((note) => note.status === "pending").length + [...skills, ...workflows].filter((item) => item.status === "pending").length;
354
+ pendingBy.set(agentId, { sha, pending });
355
+ return pending;
356
+ });
357
+ pendingReads.set(key, reading);
358
+ void reading.finally(() => pendingReads.delete(key)).catch(() => undefined);
359
+ }
360
+ return await reading;
361
+ }
362
+ catch {
363
+ return undefined;
364
+ }
365
+ }
270
366
  /** GET /agents/{id}/learning: main, its index, the first page of its notes and of its log, and how the agent's runs
271
367
  * fared and what learning changed for them (`counts`, `impact`: learning-run.ts, from the runs' rows and the learning
272
368
  * ledger); an agent with no folder (its learning never on) has an empty one. */
@@ -275,8 +371,10 @@ export async function agentLearning(data, agentId, shown, counts, impact) {
275
371
  const sha = await mainOf(home, repo);
276
372
  if (!sha)
277
373
  return { agent: agentId, main: null, index: "", notes: EMPTY, skills: [], workflows: [], log: EMPTY, counts, impact };
278
- const [{ index, notes }, { skills, workflows }, log] = await Promise.all([notesAt(home, repo, sha), learnedAt(home, repo, sha), logPage(home, repo, sha, 0, LOG_PAGE, shown)]);
279
- return { agent: agentId, main: sha, index: shown.text(index), notes: pageOf(notes, sha, 0, NOTES_PAGE, (note) => noteView(note, shown)), skills: skills.map((item) => learnedView(item, shown)), workflows: workflows.map((item) => learnedView(item, shown)), log, counts, impact };
374
+ const [{ index, notes, changes }, { skills, workflows }, log] = await Promise.all([notesAt(home, repo, sha), learnedAt(home, repo, sha), logPage(home, repo, sha, 0, LOG_PAGE, shown)]);
375
+ // Each note's last change, from the notes' walk; a skill's or a draft's is on it (learnedAt). A retired one says when
376
+ // and by whom it was retired, from the same change.
377
+ return { agent: agentId, main: sha, index: shown.text(index), notes: pageOf(notes, sha, 0, NOTES_PAGE, (note) => withChanges(noteView(note, shown), changes.get(note.file))), skills: skills.map((item) => learnedView(item, shown)), workflows: workflows.map((item) => learnedView(item, shown)), log, counts, impact };
280
378
  }
281
379
  /** GET /agents/{id}/learning/notes?cursor=&limit=&status=: a page of the notes, ordered as the view's, from what the
282
380
  * commit's first read kept. */
@@ -289,8 +387,9 @@ export async function learningNotes(data, agentId, query, shown) {
289
387
  const sha = at?.sha ?? (await mainOf(home, repo));
290
388
  if (!sha)
291
389
  return EMPTY;
292
- const { notes } = await notesAt(home, repo, sha);
293
- return pageOf(status === null ? notes : notes.filter((note) => note.status === status), sha, at?.offset ?? 0, limit, (note) => noteView(note, shown));
390
+ const { notes, changes } = await notesAt(home, repo, sha);
391
+ const listed = status === null ? notes : notes.filter((note) => note.status === status);
392
+ return pageOf(listed, sha, at?.offset ?? 0, limit, (note) => withChanges(noteView(note, shown), changes.get(note.file)));
294
393
  }
295
394
  /** GET /agents/{id}/learning/log?cursor=&limit=: a page of the changes on main, newest first, reading only its own. */
296
395
  export async function learningLog(data, agentId, query, shown) {
@@ -322,6 +421,8 @@ function fileOf(raw, use) {
322
421
  throw new ApiError("bad_request", "A workflow is approved by its README.md, the file that says it waits.");
323
422
  if (use === "retire" && place.kind === "workflow")
324
423
  throw new ApiError("bad_request", "A workflow is retired by its README.md, the file that says whether it is in use.");
424
+ if (use === "restore" && place.kind === "workflow")
425
+ throw new ApiError("bad_request", "A workflow is restored by its README.md, the file that says whether it is in use.");
325
426
  return file;
326
427
  }
327
428
  if (file === INDEX_FILE && use !== "read")
@@ -396,6 +497,19 @@ function conditionOf(ifMatch, ifNoneMatch, put) {
396
497
  throw new ApiError("precondition_required", put ? "A write names the version it read: If-Match with the note's ETag to edit it, or If-None-Match: * to create it." : "A retire names the version it read: If-Match with the note's ETag.");
397
498
  return { ...(match?.length ? { match } : {}), absent };
398
499
  }
500
+ /** Whether `file` waited for its owner's OK (status pending) just before a person last retired it on `main`'s line. */
501
+ async function heldBeforeRetire(home, repo, main, file, learned) {
502
+ const retire = line(await git(home, repo, ["log", "--first-parent", "-1", "--format=%H", "--fixed-strings", `--grep=learning: retired by a person: ${file}`, main, "--", file]));
503
+ if (!retire)
504
+ return false;
505
+ const before = await git(home, repo, ["cat-file", "blob", `${retire}^:${file}`]).then((out) => out.toString("utf8"), () => undefined);
506
+ if (before === undefined)
507
+ return false;
508
+ if (learned)
509
+ return learnedStatus(before) === "pending";
510
+ const note = parseNoteFile(file, before);
511
+ return !Array.isArray(note) && note.status === "pending";
512
+ }
399
513
  /** PUT /agents/{id}/learning/files/{file} (`body`, the note's whole text), or POST .../retire or .../approve (`approve`;
400
514
  * no body), as a person: the precondition, then the checks (a retire's and an approve's, the note's format alone: never
401
515
  * its secrets), then one commit on main in the agent's queue, on the folder agentFolder checked: the note, and MEMORY.md
@@ -405,7 +519,7 @@ function conditionOf(ifMatch, ifNoneMatch, put) {
405
519
  * the checks refuse is never written to git. A retire of a note that is not active, and an edit that changes nothing,
406
520
  * commit nothing. `refuse`: the host's secrets. */
407
521
  export async function writeNote(data, agentId, raw, input) {
408
- const file = fileOf(raw, input.approve ? "approve" : input.body === undefined ? "retire" : "write");
522
+ const file = fileOf(raw, input.approve ? "approve" : input.restore ? "restore" : input.body === undefined ? "retire" : "write");
409
523
  // A skill's SKILL.md or a draft's README.md: only ever approved or retired here.
410
524
  const learned = learnedPlace(file);
411
525
  const condition = conditionOf(input.ifMatch, input.ifNoneMatch, input.body !== undefined);
@@ -451,7 +565,47 @@ export async function writeNote(data, agentId, raw, input) {
451
565
  // Beside the note itself: what an approve marks of the notes the approved one supersedes.
452
566
  const also = new Map();
453
567
  const notes = main ? (await readAt(home, repo, main)).notes : new Map();
454
- if (text === undefined && learned && !input.approve) {
568
+ let heldBefore = false;
569
+ if (input.restore) {
570
+ // Restored, a retired note, skill or draft is active again: given to every later run. It is checked again as a
571
+ // new one is (secrets' shapes, the host's values, hidden characters, its format, every file of a skill's or a
572
+ // draft's folder): a retire takes a leaking one out of every run unchecked, and a restore never brings it back.
573
+ // One that waited for its owner's OK before its retire is recorded as their approval too (Approved-Via).
574
+ heldBefore = await heldBeforeRetire(home, repo, main, file, Boolean(learned));
575
+ if (learned) {
576
+ const status = learnedStatus(current.text);
577
+ const kind = learned.kind === "skill" ? "skill" : "workflow";
578
+ if (status !== "retired")
579
+ throw new ApiError("bad_request", `The ${kind} is not retired: it is ${status}.`);
580
+ text = released(current.text);
581
+ const problems = skillProblems(text, learned.name).map((detail) => printable({ rule: kind, path: file, detail }, input.refuse));
582
+ const extra = (frontKeys(text) ?? []).filter((key) => !LEARNED_KEYS.includes(key) && key !== "status");
583
+ if (extra.length)
584
+ problems.push(printable({ rule: "skill_front_matter", path: file, detail: `its front matter sets ${extra.join(", ")}: a learned ${kind} sets name and description alone` }, input.refuse));
585
+ const folder = `${learned.kind === "skill" ? SKILLS_DIR : WORKFLOWS_DIR}/${learned.name}/`;
586
+ const others = (await git(home, repo, ["ls-tree", "-r", "-z", "--name-only", main, "--", folder])).toString("utf8").split("\0").filter((path) => path && path !== file);
587
+ const changes = [{ path: file, status: "modified", bytes: Buffer.from(text, "utf8") }, ...(await Promise.all(others.map(async (path) => ({ path, status: "modified", bytes: await git(home, repo, ["cat-file", "blob", `${main}:${path}`]) }))))];
588
+ problems.push(...unstorable(changes, input.refuse));
589
+ if (problems.length)
590
+ throw refused(problems);
591
+ }
592
+ else {
593
+ const note = parseNoteFile(file, current.text);
594
+ if (Array.isArray(note))
595
+ throw refused(note.map((detail) => printable({ rule: "note", path: file, detail }, input.refuse)));
596
+ if (note.status !== "retired")
597
+ throw new ApiError("bad_request", `The note is not retired: it is ${note.status}.`);
598
+ text = approve(current.text);
599
+ const { problems } = checkNote(file, Buffer.from(text, "utf8"), input.refuse);
600
+ if (problems.length)
601
+ throw refused(problems);
602
+ // What it supersedes, and is active still, is superseded now, as an approval marks it.
603
+ for (const old of note.supersedes)
604
+ if (notes.get(old)?.status === "active")
605
+ also.set(old, supersede(notes.get(old).text, file));
606
+ }
607
+ }
608
+ else if (text === undefined && learned && !input.approve) {
455
609
  // Retired, as a note is: no later run is given it. One already retired is answered as it is; nothing else in
456
610
  // the folder changes.
457
611
  if (learnedStatus(current.text) === "retired")
@@ -502,7 +656,7 @@ export async function writeNote(data, agentId, raw, input) {
502
656
  if (lines > INDEX_LINES)
503
657
  throw refused([{ rule: "index_full", detail: `the index would hold ${lines} lines; it holds at most ${INDEX_LINES}, so retire a note first` }]);
504
658
  const parent = main ?? (await openAgentRepo(home, repo, check));
505
- const subject = `learning: ${input.approve ? "approved" : given === undefined ? "retired" : current ? "edited" : "created"} by a person: ${file}`;
659
+ const subject = `learning: ${input.approve ? "approved" : input.restore ? "restored" : given === undefined ? "retired" : current ? "edited" : "created"} by a person: ${file}`;
506
660
  const env = { GIT_INDEX_FILE: join(repo, ".git", "person.index") };
507
661
  let commit;
508
662
  let oid;
@@ -517,7 +671,7 @@ export async function writeNote(data, agentId, raw, input) {
517
671
  await git(home, repo, ["update-index", "-z", "--index-info"], entries, env);
518
672
  const tree = line(await git(home, repo, ["write-tree"], "", env));
519
673
  // Who approved, and how, in the trailers; the commit's own date is when. Never the note's text.
520
- const trailers = input.approve ? `${BY_USER}\n${APPROVED_VIA}` : BY_USER;
674
+ const trailers = input.approve || heldBefore ? `${BY_USER}\n${APPROVED_VIA}` : BY_USER;
521
675
  commit = line(await git(home, repo, ["commit-tree", tree, "-p", parent, "-m", subject, "-m", trailers]));
522
676
  }
523
677
  finally {
@@ -163,7 +163,7 @@ export declare class LearningRuns {
163
163
  onLoad(row: Pick<RunRow, "id" | "agent" | "state">, dir: string, meta: Run["meta"], save: () => Promise<void>): Promise<void>;
164
164
  /** A run's process launched, handed the secrets named `names`: what each held then, as handover read it, kept beside
165
165
  * the run while its learning is under way (a key replaced since stays refused in its notes). */
166
- onLaunch(run: Run, names: readonly string[]): void;
166
+ onLaunch(run: Run, names: readonly string[], also?: readonly string[]): void;
167
167
  /** A running run read at a start, `live` when its process serves it still. One a server left while its end-of-run turn
168
168
  * ran is finishing with its job's outcome, and nothing opens it again; when its process lives, the turn is asked again
169
169
  * under the same request id, which it takes once, and waited for. */
@@ -86,6 +86,18 @@ export function notesRead(reflect, rows) {
86
86
  }
87
87
  return [...read];
88
88
  }
89
+ /** How much of a grader's answer the host could not read a run keeps: its start and its end, where such an answer goes
90
+ * wrong (words before its JSON, or JSON cut off). */
91
+ const UNREAD_MAX = 2_000;
92
+ /** How much of an answer redactSecrets reads before it gives up on it whole: more than the grader's answer can hold
93
+ * (GRADE_MAX_TOKENS). */
94
+ const UNREAD_SCAN = 256 * 1024;
95
+ /** `text` cut of `values` (redactSecrets), whole, and then in size at whitespace. Cut of secrets first: a key may hold a
96
+ * space, or be written in spaced parts, and a cut before could leave a part of it. */
97
+ const unreadShown = (text, values) => {
98
+ const cut = redactSecrets(text, values, UNREAD_SCAN);
99
+ return cut.length <= UNREAD_MAX ? cut : `${cut.slice(0, 1_500).replace(/\S*$/, "")}\n…\n${cut.slice(-(UNREAD_MAX - 1_503)).replace(/^\S*/, "")}`;
100
+ };
89
101
  /** `verdict` with its reason, and each item's question and why, cut of `values` (learn/secrets.ts redactSecrets). */
90
102
  const cutVerdict = (verdict, values) => ({
91
103
  ...verdict,
@@ -322,10 +334,10 @@ export class LearningRuns {
322
334
  }
323
335
  /** A run's process launched, handed the secrets named `names`: what each held then, as handover read it, kept beside
324
336
  * the run while its learning is under way (a key replaced since stays refused in its notes). */
325
- onLaunch(run, names) {
337
+ onLaunch(run, names, also = []) {
326
338
  if (!run.meta.learning || ended(run.meta.learning))
327
339
  return;
328
- const values = names.flatMap((name) => secret(name, this.options.storedKeys) ?? []);
340
+ const values = [...names.flatMap((name) => secret(name, this.options.storedKeys) ?? []), ...also];
329
341
  if (!values.length)
330
342
  return;
331
343
  const kept = this.handed.get(run.id) ?? new Set();
@@ -766,8 +778,17 @@ export class LearningRuns {
766
778
  // Kept cut of every secret the run's notes were checked against, the keys its launches handed it included, which a
767
779
  // read no longer knows: its reason and its items' words are what the run's words are said from again (wordsOf).
768
780
  kept.verdict = cutVerdict(judged.verdict, this.refused(run));
769
- if (!kept.verdict.merge)
770
- return await end("dropped", "grader", notKept(kept.verdict));
781
+ if (!kept.verdict.merge) {
782
+ // What it proposed is lost whole: its skill and its draft are named, from the proposal (a verdict the host
783
+ // refused has no items), and the line cut of every secret the verdict was.
784
+ const lost = (proposal.files ?? []).flatMap(({ file }) => {
785
+ const place = /^(?:skills\/([^/]+)\/SKILL\.md|workflows\/([^/]+)\/workflow\.json)$/.exec(file);
786
+ return place ? [{ file, name: (place[1] ?? place[2]) }] : [];
787
+ });
788
+ // Two answers it could not read: the last kept, in size and cut of every secret, to diagnose it by.
789
+ const unread = "unread" in judged && judged.unread !== undefined ? { unread: unreadShown(judged.unread, this.refused(run)) } : {};
790
+ return await end("dropped", "grader", redactSecrets(notKept(kept.verdict, lost), this.refused(run)), { ...(lost.length ? { lost } : {}), ...unread });
791
+ }
771
792
  // Kept before the merge, with the blobs it judged superseded: a restart merges on this verdict, never asks the
772
793
  // grader again, and checks the same blobs.
773
794
  kept.graded = main.graded;
@@ -67,10 +67,14 @@ export declare const said: {
67
67
  };
68
68
  /** Why a verdict kept nothing, in a person's words: the grader's word on the first note it did not keep, since its
69
69
  * reason may open on a note it kept; when it dropped none, or gave one no word, its own reason, unless that is
70
- * parseVerdict's own; an answer that held neither is said as such. */
71
- export declare function notKept(verdict: Pick<Verdict, "reason" | "items">): string;
70
+ * parseVerdict's own; an answer that held neither is said as such. Nothing merged, so the skill and the workflow draft
71
+ * the run proposed (`lost`, from its proposal: a verdict the host refused has no items) are lost with it: named before
72
+ * the why, so a long why cut short never cuts them off; the one the why speaks of as its subject ("Not kept, the
73
+ * skill X: …"), any other as lost with it ("Not kept, with the skill X: …"). The caller cuts the line of the host's
74
+ * secrets: a name is the run's to choose. */
75
+ export declare function notKept(verdict: Pick<Verdict, "reason" | "items">, lost?: readonly Pick<LearnedFile, "file">[]): string;
72
76
  /** A run's learning in words as a read says them, whole: what it learned and what waits for the owner's OK, or why the
73
77
  * grader kept nothing, said again from its parts (`learned`, `pending`, `verdict`) each cut by `cut` first (the host's
74
78
  * secrets as they are now); any other detail, the server's own sentence, cut as well. The caller cuts the words short
75
79
  * after. */
76
- export declare function wordsOf(learning: Pick<Learning, "state" | "reason" | "detail" | "learned" | "pending" | "verdict" | "skills" | "workflows" | "problems">, cut: (text: string) => string): string | null;
80
+ export declare function wordsOf(learning: Pick<Learning, "state" | "reason" | "detail" | "learned" | "pending" | "verdict" | "skills" | "workflows" | "problems" | "lost">, cut: (text: string) => string): string | null;
@@ -146,14 +146,28 @@ export const said = {
146
146
  * it refused (an item for a file it was not asked about, a file judged twice, a new note with no item, a merge that
147
147
  * did not keep every note). Found by asking it, so they follow it. */
148
148
  const OWN_REASONS = new Set(["", "[]", '{"merge":true,"reason":"r","items":[{"file":"a.md","keep":false,"why":"w"}]}', '{"merge":false,"reason":"r","items":[]}', '{"merge":false,"reason":"r","items":[{"file":"b.md","keep":false,"why":"w"}]}', '{"merge":false,"reason":"r","items":[{"file":"a.md","keep":false,"why":"w"},{"file":"a.md","keep":false,"why":"w"}]}'].map((answer) => parseVerdict(answer, ["a.md"]).reason));
149
+ /** The skill or the workflow draft at `file` as a person names it ("the skill X", "the workflow Y"), or undefined for a
150
+ * note's file or a draft's README.md. */
151
+ const learnedWords = (file) => {
152
+ const place = /^(skills)\/([^/]+)\/SKILL\.md$|^(workflows)\/([^/]+)\/workflow\.json$/.exec(file);
153
+ return place ? (place[1] ? `the skill ${place[2]}` : `the workflow ${place[4]}`) : undefined;
154
+ };
149
155
  /** Why a verdict kept nothing, in a person's words: the grader's word on the first note it did not keep, since its
150
156
  * reason may open on a note it kept; when it dropped none, or gave one no word, its own reason, unless that is
151
- * parseVerdict's own; an answer that held neither is said as such. */
152
- export function notKept(verdict) {
153
- const why = verdict.items.find((item) => !item.keep)?.why;
154
- if (why)
155
- return said.grader(why);
156
- return OWN_REASONS.has(verdict.reason) ? said.stopped(STOPPED.unread) : said.grader(verdict.reason);
157
+ * parseVerdict's own; an answer that held neither is said as such. Nothing merged, so the skill and the workflow draft
158
+ * the run proposed (`lost`, from its proposal: a verdict the host refused has no items) are lost with it: named before
159
+ * the why, so a long why cut short never cuts them off; the one the why speaks of as its subject ("Not kept, the
160
+ * skill X: …"), any other as lost with it ("Not kept, with the skill X: …"). The caller cuts the line of the host's
161
+ * secrets: a name is the run's to choose. */
162
+ export function notKept(verdict, lost = []) {
163
+ const dropped = verdict.items.find((item) => !item.keep);
164
+ const said_ = dropped?.why ? said.grader(dropped.why) : OWN_REASONS.has(verdict.reason) ? said.stopped(STOPPED.unread) : said.grader(verdict.reason);
165
+ const subject = dropped?.why ? learnedWords(dropped.file) : undefined;
166
+ const others = [...new Set(lost.flatMap(({ file }) => learnedWords(file) ?? []))].filter((words) => words !== subject);
167
+ if (!subject && !others.length)
168
+ return said_;
169
+ const named = [subject, others.length ? `with ${listed(others)}` : ""].filter(Boolean).join(" ");
170
+ return said_.replace(/^Not kept: /, `Not kept, ${named}: `);
157
171
  }
158
172
  /** A run's learning in words as a read says them, whole: what it learned and what waits for the owner's OK, or why the
159
173
  * grader kept nothing, said again from its parts (`learned`, `pending`, `verdict`) each cut by `cut` first (the host's
@@ -168,7 +182,11 @@ export function wordsOf(learning, cut) {
168
182
  if (kept.length || waiting.length || files.length)
169
183
  return said.merged(kept.map((note) => ({ name: cut(note.name), supersedes: note.supersedes })), waiting.map((note) => ({ name: cut(note.name) })), files.map((file) => ({ file: file.file, name: cut(file.name), ...(file.pending ? { pending: true } : {}) })), (verdict?.items ?? []).filter((item) => !item.keep && typeof item.why === "string").map((item) => ({ why: cut(item.why) })), Array.isArray(learning.problems) ? learning.problems : []);
170
184
  }
171
- if (learning.state === "dropped" && learning.reason === "grader" && verdict)
172
- return notKept({ reason: cut(verdict.reason), items: (verdict.items ?? []).map((item) => ({ ...item, why: cut(item.why) })) });
185
+ if (learning.state === "dropped" && learning.reason === "grader" && verdict) {
186
+ // serve.json's `lost` is read as untrusted: an entry out of shape is left out. The whole line is cut again, the names
187
+ // in it included.
188
+ const lost = Array.isArray(learning.lost) ? learning.lost.filter((file) => typeof file?.file === "string") : [];
189
+ return cut(notKept({ reason: cut(verdict.reason), items: (verdict.items ?? []).map((item) => ({ ...item, why: cut(item.why) })) }, lost));
190
+ }
173
191
  return learning.detail === null ? null : cut(learning.detail);
174
192
  }
@@ -89,6 +89,12 @@ export type Learning = {
89
89
  * for a person's OK (`status: pending` in its SKILL.md or README.md), and no run is given it until approved. */
90
90
  skills?: LearnedFile[];
91
91
  workflows?: LearnedFile[];
92
+ /** A grader's drop's skill and workflow draft, from what the run proposed: lost with the rest, and named when its
93
+ * learning is said (learning-words.ts notKept). */
94
+ lost?: LearnedFile[];
95
+ /** A grader's drop on two answers the host could not read: the last, cut of secrets and in size (UNREAD_MAX), kept on the
96
+ * run's file to diagnose it by, and served by no read. */
97
+ unread?: string;
92
98
  };
93
99
  /** A skill or a workflow draft a merge added or changed. */
94
100
  export type LearnedFile = {
@@ -242,7 +248,9 @@ export declare const LEARNED_WORKFLOWS_FILE = "learned-workflows.json";
242
248
  * together: every harness sends the description with each request, so it never grows with what an agent learned. */
243
249
  export declare const LEARNED_WORKFLOWS_BUDGET: number;
244
250
  /** A learned workflow's line in the `learned_workflow` tool's description: its name, and what its README says it does. */
245
- export declare const workflowLine: ({ name, description }: Pick<LearnedWorkflow, "name" | "description">) => string;
251
+ export declare const workflowLine: ({ name, description, workflow }: Pick<LearnedWorkflow, "name" | "description"> & {
252
+ workflow?: string;
253
+ }) => string;
246
254
  /** The most bytes of learned skills one run gets, every file of each together. They get no more than what the
247
255
  * revision's own skills leave of the adapters' cap on a run's skills in all (SKILL_BYTES): over that cap an adapter
248
256
  * refuses the whole set, and every skill, the revision's too, would be inlined in the prompt (skills.ts splitSkills). */
package/dist/learning.js CHANGED
@@ -146,7 +146,62 @@ export const LEARNED_WORKFLOWS_FILE = "learned-workflows.json";
146
146
  * together: every harness sends the description with each request, so it never grows with what an agent learned. */
147
147
  export const LEARNED_WORKFLOWS_BUDGET = 8 * 1024;
148
148
  /** A learned workflow's line in the `learned_workflow` tool's description: its name, and what its README says it does. */
149
- export const workflowLine = ({ name, description }) => `- ${name}: ${description || "(no description)"}`;
149
+ export const workflowLine = ({ name, description, workflow }) => [`- ${name}: ${description || "(no description)"}`, ...inputLine(workflow)].join("\n");
150
+ /** The most of a field's description a workflow's input line carries. */
151
+ const FIELD_DESCRIPTION = 60;
152
+ /** A workflow's input as its line in learned_workflow's description says it: its input schema, compact (inputSchema), on
153
+ * a line of its own, so a call names the fields the workflow takes; none for a workflow whose input names no schema. */
154
+ function inputLine(workflow) {
155
+ let doc;
156
+ try {
157
+ doc = workflow ? JSON.parse(workflow) : undefined;
158
+ }
159
+ catch {
160
+ return [];
161
+ }
162
+ const id = doc?.input?.schemaId;
163
+ const schema = typeof id === "string" ? doc?.schemas?.[id] : undefined;
164
+ if (!schema)
165
+ return [];
166
+ const shown = compactSchema(schema, doc?.schemas ?? {}, 0, definitionsOf(schema));
167
+ return [` input: ${shown}${shown.includes("*") ? " (* required)" : ""}`];
168
+ }
169
+ /** A schema's own inline definitions (`definitions`, `$defs`), which its `#/definitions/` references read first. */
170
+ const definitionsOf = (schema) => {
171
+ const s = schema && typeof schema === "object" ? schema : {};
172
+ return { ...(s.$defs ?? {}), ...(s.definitions ?? {}) };
173
+ };
174
+ /** A JSON Schema in one line: an object's fields as `name type`, a required one marked `*`, each with its description cut
175
+ * short; an array as `array of <items>`; a reference to another of the workflow's schemas followed, two levels deep. */
176
+ function compactSchema(schema, schemas, depth = 0, defs = {}) {
177
+ const s = schema && typeof schema === "object" ? schema : undefined;
178
+ if (!s)
179
+ return "any";
180
+ if (typeof s.$ref === "string") {
181
+ // As the DSL resolves it: `#/definitions/` and `#/$defs/` in the schema's own inline definitions first, then the
182
+ // workflow's schemas by that name.
183
+ const inline = /^#\/(?:definitions|\$defs)\//.test(s.$ref);
184
+ const name = s.$ref.replace(/^#\/(?:schemas|definitions|\$defs)\//, "");
185
+ const target = (inline ? defs[name] : undefined) ?? schemas[name];
186
+ return depth > 2 || !target ? name : compactSchema(target, schemas, depth + 1, defs);
187
+ }
188
+ if (s.properties && typeof s.properties === "object") {
189
+ if (depth > 2)
190
+ return "object";
191
+ const required = new Set(Array.isArray(s.required) ? s.required : []);
192
+ const fields = Object.entries(s.properties).map(([key, value]) => {
193
+ const said = value && typeof value === "object" ? value.description : undefined;
194
+ const words = typeof said === "string" && said.trim() ? ` "${said.trim().length > FIELD_DESCRIPTION ? `${said.trim().slice(0, FIELD_DESCRIPTION - 1)}…` : said.trim()}"` : "";
195
+ return `${key}${required.has(key) ? "*" : ""} ${compactSchema(value, schemas, depth + 1, defs)}${words}`;
196
+ });
197
+ return `{${fields.join(", ")}}`;
198
+ }
199
+ if (s.type === "array")
200
+ return `array of ${compactSchema(s.items, schemas, depth + 1, defs)}`;
201
+ if (Array.isArray(s.enum))
202
+ return s.enum.map((value) => JSON.stringify(value)).join("|");
203
+ return typeof s.type === "string" ? s.type : Array.isArray(s.type) ? s.type.join("|") : "any";
204
+ }
150
205
  /** The most bytes of learned skills one run gets, every file of each together. They get no more than what the
151
206
  * revision's own skills leave of the adapters' cap on a run's skills in all (SKILL_BYTES): over that cap an adapter
152
207
  * refuses the whole set, and every skill, the revision's too, would be inlined in the prompt (skills.ts splitSkills). */
@@ -904,7 +959,7 @@ export async function readPin(runDir) {
904
959
  export const LEARNED_HEADING = "# Learned";
905
960
  /** What every run that learns is told first under it, notes or none: a run not told it learns saves what the person
906
961
  * asks it to remember in a file, or says it cannot, and that is never kept. */
907
- const LEARNS = "You learn from your runs. When this run ends you are asked what to keep for later runs, anything the person asked you to remember included, and only your answer then is kept: a file you write is not. So when the person asks you to remember something, don't put it in a file or say you can't: tell them you will keep it for later runs. A secret (a password, key or token) is never kept, so say so instead.";
962
+ const LEARNS = "You learn from your runs. When this run ends you are asked what to keep for later runs, anything the person asked you to remember included, and only your answer then is kept: a file you write is not. So when the person asks you to remember something, don't put it in a file or say you can't: tell them you will keep it for later runs, in one short sentence at the start of your reply, never after a closing line or sign-off they asked you to end with. A secret (a password, key or token) is never kept, so say so instead.";
908
963
  /** What a run that starts with no note is told in place of what it learned. */
909
964
  const NOTHING_YET = "Nothing learned yet.";
910
965
  /** A run's instructions, with `# Learned` after them when its pin in `runDir` says it learns: that it learns, then what