@parcha/agentrun-serve 0.0.0-bootstrap.0 → 0.1.0-beta.29

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 (229) hide show
  1. package/CHANGELOG.md +560 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +1724 -0
  5. package/dist/adapters.d.ts +205 -0
  6. package/dist/adapters.js +459 -0
  7. package/dist/agents.d.ts +124 -0
  8. package/dist/agents.js +302 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +324 -0
  11. package/dist/bound-files.d.ts +4 -0
  12. package/dist/bound-files.js +164 -0
  13. package/dist/box/record.d.ts +6 -0
  14. package/dist/box/record.js +41 -0
  15. package/dist/box/sweep.d.ts +53 -0
  16. package/dist/box/sweep.js +193 -0
  17. package/dist/box-image.d.ts +98 -0
  18. package/dist/box-image.js +283 -0
  19. package/dist/box-relay.d.ts +42 -0
  20. package/dist/box-relay.js +222 -0
  21. package/dist/boxes.d.ts +54 -0
  22. package/dist/boxes.js +182 -0
  23. package/dist/cap.d.ts +224 -0
  24. package/dist/cap.js +721 -0
  25. package/dist/catalog.d.ts +20 -0
  26. package/dist/catalog.js +53 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +167 -0
  29. package/dist/coding-tools.d.ts +31 -0
  30. package/dist/coding-tools.js +81 -0
  31. package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
  32. package/dist/console/assets/index-BN7oVcO4.js +445 -0
  33. package/dist/console/assets/index-By-jkqki.css +1 -0
  34. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  35. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  36. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  37. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  38. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  39. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  40. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  41. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  42. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  53. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  54. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  57. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  58. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  59. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  60. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  61. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  62. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  63. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  64. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  65. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  66. package/dist/console/index.html +15 -0
  67. package/dist/daytona-api.d.ts +21 -0
  68. package/dist/daytona-api.js +101 -0
  69. package/dist/decision-rows.d.ts +11 -0
  70. package/dist/decision-rows.js +116 -0
  71. package/dist/decisions.d.ts +94 -0
  72. package/dist/decisions.js +184 -0
  73. package/dist/effort-guidance.d.ts +5 -0
  74. package/dist/effort-guidance.js +14 -0
  75. package/dist/environment.d.ts +5 -0
  76. package/dist/environment.js +11 -0
  77. package/dist/errors.d.ts +72 -0
  78. package/dist/errors.js +66 -0
  79. package/dist/exa-keyless.d.ts +35 -0
  80. package/dist/exa-keyless.js +202 -0
  81. package/dist/fetch-page.d.ts +114 -0
  82. package/dist/fetch-page.js +182 -0
  83. package/dist/files.d.ts +60 -0
  84. package/dist/files.js +153 -0
  85. package/dist/grade.d.ts +96 -0
  86. package/dist/grade.js +348 -0
  87. package/dist/graph-view.d.ts +100 -0
  88. package/dist/graph-view.js +212 -0
  89. package/dist/harness-app.d.ts +38 -0
  90. package/dist/harness-app.js +626 -0
  91. package/dist/harness.d.ts +53 -0
  92. package/dist/harness.js +74 -0
  93. package/dist/home-path.d.ts +27 -0
  94. package/dist/home-path.js +78 -0
  95. package/dist/host-tools.d.ts +20 -0
  96. package/dist/host-tools.js +140 -0
  97. package/dist/host.d.ts +39 -0
  98. package/dist/host.js +81 -0
  99. package/dist/hosted-search.d.ts +27 -0
  100. package/dist/hosted-search.js +129 -0
  101. package/dist/import-sources.d.ts +104 -0
  102. package/dist/import-sources.js +629 -0
  103. package/dist/import-summary.d.ts +25 -0
  104. package/dist/import-summary.js +75 -0
  105. package/dist/import-worker.d.ts +26 -0
  106. package/dist/import-worker.js +41 -0
  107. package/dist/import.d.ts +145 -0
  108. package/dist/import.js +1221 -0
  109. package/dist/index.d.ts +7 -0
  110. package/dist/index.js +6 -0
  111. package/dist/key-check.d.ts +36 -0
  112. package/dist/key-check.js +108 -0
  113. package/dist/key-refusal.d.ts +51 -0
  114. package/dist/key-refusal.js +187 -0
  115. package/dist/learn/check.d.ts +99 -0
  116. package/dist/learn/check.js +259 -0
  117. package/dist/learn/grade.d.ts +79 -0
  118. package/dist/learn/grade.js +433 -0
  119. package/dist/learn/index.d.ts +7 -0
  120. package/dist/learn/index.js +11 -0
  121. package/dist/learn/invisible.d.ts +5 -0
  122. package/dist/learn/invisible.js +42 -0
  123. package/dist/learn/notes.d.ts +59 -0
  124. package/dist/learn/notes.js +146 -0
  125. package/dist/learn/reflect.d.ts +49 -0
  126. package/dist/learn/reflect.js +167 -0
  127. package/dist/learn/secrets.d.ts +18 -0
  128. package/dist/learn/secrets.js +111 -0
  129. package/dist/learn/skills.d.ts +84 -0
  130. package/dist/learn/skills.js +198 -0
  131. package/dist/learning-routes.d.ts +196 -0
  132. package/dist/learning-routes.js +609 -0
  133. package/dist/learning-run.d.ts +304 -0
  134. package/dist/learning-run.js +797 -0
  135. package/dist/learning-words.d.ts +73 -0
  136. package/dist/learning-words.js +171 -0
  137. package/dist/learning.d.ts +377 -0
  138. package/dist/learning.js +801 -0
  139. package/dist/llm.d.ts +40 -0
  140. package/dist/llm.js +37 -0
  141. package/dist/llms.txt +37 -0
  142. package/dist/mcp-servers.d.ts +115 -0
  143. package/dist/mcp-servers.js +445 -0
  144. package/dist/mcp.d.ts +51 -0
  145. package/dist/mcp.js +392 -0
  146. package/dist/model.d.ts +184 -0
  147. package/dist/model.js +484 -0
  148. package/dist/monid.d.ts +74 -0
  149. package/dist/monid.js +277 -0
  150. package/dist/openapi/agentrun-v2.openapi.json +4805 -0
  151. package/dist/openapi.d.ts +10 -0
  152. package/dist/openapi.js +1417 -0
  153. package/dist/owner.d.ts +55 -0
  154. package/dist/owner.js +222 -0
  155. package/dist/packs.d.ts +71 -0
  156. package/dist/packs.js +180 -0
  157. package/dist/page.d.ts +32 -0
  158. package/dist/page.js +133 -0
  159. package/dist/paid-calls.d.ts +46 -0
  160. package/dist/paid-calls.js +110 -0
  161. package/dist/pause.d.ts +68 -0
  162. package/dist/pause.js +97 -0
  163. package/dist/pdf-pages.d.ts +44 -0
  164. package/dist/pdf-pages.js +147 -0
  165. package/dist/place.d.ts +46 -0
  166. package/dist/place.js +105 -0
  167. package/dist/print.d.ts +20 -0
  168. package/dist/print.js +29 -0
  169. package/dist/propose.d.ts +38 -0
  170. package/dist/propose.js +82 -0
  171. package/dist/quiet-sqlite-warning.d.ts +1 -0
  172. package/dist/quiet-sqlite-warning.js +14 -0
  173. package/dist/request-start.d.ts +14 -0
  174. package/dist/request-start.js +226 -0
  175. package/dist/result.d.ts +3 -0
  176. package/dist/result.js +5 -0
  177. package/dist/rows.d.ts +46 -0
  178. package/dist/rows.js +121 -0
  179. package/dist/run-box.d.ts +134 -0
  180. package/dist/run-box.js +440 -0
  181. package/dist/run-manifest.d.ts +27 -0
  182. package/dist/run-manifest.js +60 -0
  183. package/dist/runnable.d.ts +80 -0
  184. package/dist/runnable.js +162 -0
  185. package/dist/runs.d.ts +840 -0
  186. package/dist/runs.js +2279 -0
  187. package/dist/secret-cut.d.ts +27 -0
  188. package/dist/secret-cut.js +109 -0
  189. package/dist/secrets.d.ts +50 -0
  190. package/dist/secrets.js +140 -0
  191. package/dist/server-lock.d.ts +44 -0
  192. package/dist/server-lock.js +140 -0
  193. package/dist/server.d.ts +626 -0
  194. package/dist/server.js +1756 -0
  195. package/dist/sessions.d.ts +4 -0
  196. package/dist/sessions.js +105 -0
  197. package/dist/skills.d.ts +31 -0
  198. package/dist/skills.js +68 -0
  199. package/dist/stats.d.ts +101 -0
  200. package/dist/stats.js +82 -0
  201. package/dist/tool-keys.d.ts +151 -0
  202. package/dist/tool-keys.js +273 -0
  203. package/dist/tool-plane.d.ts +143 -0
  204. package/dist/tool-plane.js +242 -0
  205. package/dist/tools.d.ts +147 -0
  206. package/dist/tools.js +253 -0
  207. package/dist/turn-end.d.ts +23 -0
  208. package/dist/turn-end.js +14 -0
  209. package/dist/turns.d.ts +34 -0
  210. package/dist/turns.js +202 -0
  211. package/dist/uploads.d.ts +104 -0
  212. package/dist/uploads.js +474 -0
  213. package/dist/usage.d.ts +29 -0
  214. package/dist/usage.js +58 -0
  215. package/dist/validate.d.ts +55 -0
  216. package/dist/validate.js +175 -0
  217. package/dist/web-fetch.d.ts +64 -0
  218. package/dist/web-fetch.js +262 -0
  219. package/dist/web-search.d.ts +54 -0
  220. package/dist/web-search.js +136 -0
  221. package/dist/webhooks.d.ts +182 -0
  222. package/dist/webhooks.js +487 -0
  223. package/dist/workspace-paths.d.ts +33 -0
  224. package/dist/workspace-paths.js +104 -0
  225. package/dist/workspace.d.ts +88 -0
  226. package/dist/workspace.js +369 -0
  227. package/launcher/agentrun-serve +109 -0
  228. package/package.json +96 -1
  229. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,801 @@
1
+ // Learning: an agent whose definition says `learning: true` keeps a folder of what it learned, and each of its runs
2
+ // starts from it. The folder is its home's `learning/` (files.ts homeOf), in Claude Code's auto-memory format
3
+ // (learn/notes.ts): `MEMORY.md`, the index, one line per active note, and one `<slug>.md` per note. It is plain
4
+ // git with main checked out, so any reader sees its files. This server is its only writer. Every git call runs with the
5
+ // repository's hooks, fsmonitor, replace refs and lazy fetches off and reads no system or global config, and every call
6
+ // on one agent's folder waits its turn in that agent's queue in this process.
7
+ //
8
+ // When a run of such an agent is made the server makes the folder if it is absent (one host commit on main, holding an
9
+ // empty `MEMORY.md`), resolves main's commit and reads it with plumbing, never the working tree. It copies that commit's
10
+ // index and active notes into the run's `work/.learning/` and pins the commit in the run's directory (`learning.json`),
11
+ // with what the run reads under `# Learned` (learnedOf): each active note whole while they fit the server's learning
12
+ // budget, else the index and the notes changed last, whole, while they fit; every text cut of the server's secrets, the
13
+ // copy's too. The run's process reads that pin (withLearned, for app.ts) and never runs git, so it may run anywhere its
14
+ // directory is. When the run ends the server asks it one more turn, which answers with the notes
15
+ // it would keep (learning-run.ts). As the run settles, before anything can open it again, that answer is kept in the
16
+ // run's directory (`learning-turn.json`); its notes are checked from there (propose.ts), graded and merged into main
17
+ // (grade.ts). The copy in the run's work is only for reading: nothing the run writes there is ever kept.
18
+ //
19
+ // The skills the agent wrote are in the folder too, one folder each under `skills/` (SKILLS_DIR). A run
20
+ // gets those of its commit beside its revision's own, in `work/.agents/skills/`, read with plumbing as its notes are: a
21
+ // skill named like one of the revision's is the revision's, and the learned ones fit their own budget
22
+ // (LEARNED_SKILLS_BUDGET) within what the revision's leave of the adapters' cap on a run's skills, so they never push the
23
+ // revision's out of a harness's own loading (skills.ts splitSkills). One that does not fit is left out, and the pin
24
+ // names it. A link at `skills/` or anywhere under it is never followed: the run starts with nothing learned.
25
+ //
26
+ // The host never follows a symbolic link into the folder (agentFolder): a link at the agent's home, at its `learning/`
27
+ // or at `learning/.git`, or a `MEMORY.md` that is one when the host writes it, is refused, and the run starts with
28
+ // nothing learned. The end-of-run turn's seed, its proposal's check, its grade and its merge reach the folder the same
29
+ // way, and a link there drops what the run learned. A person's reads and writes (learning-routes.ts) check it the same
30
+ // way (readFolder, agentFolder), and a link there is an error.
31
+ import { spawn } from "node:child_process";
32
+ import { constants, existsSync } from "node:fs";
33
+ import { lstat, mkdir, readFile, rm, writeFile } from "node:fs/promises";
34
+ import { dirname, join, posix, relative } from "node:path";
35
+ import { SKILL_BYTES } from "@parcha/agentrun-kernel";
36
+ import { INDEX_FILE, loadedIndex, NOTE_FILE, parseNoteFile, redactSecrets, secretShapes, servedSkill, SKILLS_DIR, valueMatcher } from "./learn/index.js";
37
+ import { homeOf, serialBy, writeDurable } from "./files.js";
38
+ import { DETAIL_MAX, LIST_DETAIL, short, wordsOf } from "./learning-words.js";
39
+ import { isObject } from "./validate.js";
40
+ import { readWorkText } from "./workspace.js";
41
+ /** The server's learning switch (`--learning`, AGENTRUN_SERVE_LEARNING; capabilities.features.learning). `on`, the
42
+ * default: a run learns when its agent's definition says `learning: true`. `off`: no run this server starts does. */
43
+ export const LEARNING_MODES = ["on", "off"];
44
+ export const LEARNING_ENV = "AGENTRUN_SERVE_LEARNING";
45
+ /** The switch: `given`, else AGENTRUN_SERVE_LEARNING, else on. Any other value is an error, and the server does not start. */
46
+ export function learningOf(env, given) {
47
+ const value = given ?? (env[LEARNING_ENV] || "on");
48
+ if (!LEARNING_MODES.includes(value))
49
+ throw new Error(`learning is on or off (--learning, ${LEARNING_ENV}), not ${value}`);
50
+ return value;
51
+ }
52
+ /** How much of what a run learned its instructions hold under `# Learned` by default, in UTF-8 bytes (learnedOf): its
53
+ * notes whole while they fit, else the index and the notes changed last, whole, while they fit. */
54
+ export const LEARNING_BUDGET = 8000;
55
+ export const LEARNING_BUDGET_ENV = "AGENTRUN_SERVE_LEARNING_BUDGET";
56
+ /** The learning budget: `given` (`--learning-budget`), else AGENTRUN_SERVE_LEARNING_BUDGET, else LEARNING_BUDGET. Any
57
+ * value that is not a whole number of bytes, 0 or more, is an error, and the server does not start. */
58
+ export function learningBudgetOf(env, given) {
59
+ const named = env[LEARNING_BUDGET_ENV];
60
+ const value = given ?? (named ? (/^\d+$/.test(named) ? Number(named) : Number.NaN) : LEARNING_BUDGET);
61
+ if (!Number.isSafeInteger(value) || value < 0)
62
+ throw new Error(`the learning budget is a whole number of bytes, 0 or more (--learning-budget, ${LEARNING_BUDGET_ENV}), not ${given ?? named}`);
63
+ return value;
64
+ }
65
+ /** Where a run's learning stands (its `learning`, runs.ts): `seeded` once it starts from what its agent learned,
66
+ * `reflecting` while its end-of-run turn runs and until what it answered is checked, `proposed` once that passed the
67
+ * checks and is kept in the run's directory (propose.ts), `merged` once it is on main (grade.ts), or `dropped` with a
68
+ * reason from the closed list. A learning fault never refuses a run: it starts with nothing learned, `seed_failed`. */
69
+ export const LEARNING_STATES = ["seeded", "reflecting", "proposed", "merged", "dropped"];
70
+ export const LEARNING_REASONS = ["seed_failed", "no_budget", "unknown_cost", "no_write_tool", "tool_denied", "cancelled", "crashed", "reflect_timeout", "reflect_failed", "empty", "unparsed", "propose_failed", "checker", "screen", "screen_down", "grader", "grade_failed"];
71
+ /** The reasons only an older server gave (an agent with no write tool, or a tool gate denying it, from before the
72
+ * end-of-run turn answered with its notes): still read, from a run's serve.json and the ledger, and counted; never
73
+ * given now. */
74
+ export const LEGACY_LEARNING_REASONS = ["no_write_tool", "tool_denied"];
75
+ export const NO_TOKENS = { input: 0, cache_read: 0, cache_write: 0, output: 0 };
76
+ /** The variable that names the grader's model, as `--grade-model` does. */
77
+ export const GRADE_MODEL_ENV = "AGENTRUN_SERVE_GRADE_MODEL";
78
+ /** The model this server grades on, by name: `given` (`--grade-model`), else GRADE_MODEL_ENV, else its strong tier
79
+ * (AGENT_MODEL_STRONG); undefined when it names none, and each run is graded on its agent's own model (grade.ts). A
80
+ * name is a model as the strong tier takes one: sent as it is to a gateway, a provider/model-id otherwise. */
81
+ export const gradeModelOf = (env, given) => given || env[GRADE_MODEL_ENV] || env.AGENT_MODEL_STRONG || undefined;
82
+ /** What a run's learning keeps whatever its learning does after: what it read, how many notes it started from, and its
83
+ * answer's time and its costs (learning-run.ts setLearning). */
84
+ export const KEPT_LEARNING = ["used", "seed_notes", "answered_at", "job_cost_usd", "look_back_usd"];
85
+ /** What a name holding a secret reads: learn/secrets.ts redactSecrets' mark, the name's whole, never a part of it. */
86
+ const REDACTED = "[redacted]";
87
+ /** The host's secrets as a reader cuts them: a text holding a value or a shape is cut of it (whole when long:
88
+ * learn/secrets.ts redactSecrets), and a file's name holding one reads REDACTED whole, not a name of the folder's (its
89
+ * route still answers the real name, to a caller who knows it); any other text or name is shown as it is. */
90
+ export function secretsShown(values) {
91
+ const matches = valueMatcher(values);
92
+ const holds = (text) => matches(text) || secretShapes(text).length > 0;
93
+ return { holds, text: (text) => (holds(text) ? redactSecrets(text, values) : text), name: (name) => (holds(name) ? REDACTED : name) };
94
+ }
95
+ const isText = (value) => typeof value === "string";
96
+ /** The notes a run read and learned, as a view or a list shows them, each name cut of the host's secrets (`shown`):
97
+ * `used` once the run settled, `learned` and `pending` (what waits for the owner's OK) once it merged, and the skill
98
+ * and the workflow draft it merged (`skills`, `workflows`, each `pending` while it waits), each only when it holds one.
99
+ * serve.json's are read as untrusted: an entry out of shape is left out. */
100
+ export function notesView({ state, used, learned, pending, skills, workflows }, shown, settled) {
101
+ const read = settled && Array.isArray(used) ? used.filter((note) => isText(note?.file) && isText(note.name)).map(({ file, name }) => ({ file: shown.name(file), name: shown.text(name) })) : [];
102
+ const added = state === "merged" && Array.isArray(learned) ? learned.filter((note) => isText(note?.file) && isText(note.name) && Array.isArray(note.supersedes) && note.supersedes.every(isText)).map(({ file, name, supersedes }) => ({ file: shown.name(file), name: shown.text(name), supersedes: supersedes.map(shown.name) })) : [];
103
+ const waiting = state === "merged" && Array.isArray(pending) ? pending.filter((note) => isText(note?.file) && isText(note.name)).map(({ file, name }) => ({ file: shown.name(file), name: shown.text(name) })) : [];
104
+ const files = (list) => (state === "merged" && Array.isArray(list) ? list.filter((item) => isText(item?.file) && isText(item.name)).map(({ file, name, pending: waits }) => ({ file: shown.name(file), name: shown.name(name), ...(waits === true ? { pending: true } : {}) })) : []);
105
+ const [kept, drafts] = [files(skills), files(workflows)];
106
+ return { ...(read.length ? { used: read } : {}), ...(added.length ? { learned: added } : {}), ...(waiting.length ? { pending: waiting } : {}), ...(kept.length ? { skills: kept } : {}), ...(drafts.length ? { workflows: drafts } : {}) };
107
+ }
108
+ /** A run's learning in a person's words as a read shows them (learning-words.ts wordsOf): each part cut of the host's
109
+ * secrets as they are now (`shown`) first, then the words cut short to `max`, so a secret is never shown in part. */
110
+ export const detailShown = (learning, shown, max = DETAIL_MAX) => {
111
+ const words = wordsOf(learning, shown.text);
112
+ return words === null ? null : short(words, max);
113
+ };
114
+ /** A run's learning as its view shows it: the state, why in a person's words (detailShown), and when, and the notes it
115
+ * read, learned and holds for the owner's OK (notesView). */
116
+ export const learningView = (learning, shown, settled) => {
117
+ const { state, reason, at } = learning;
118
+ return { state, reason, detail: detailShown(learning, shown), at, ...notesView(learning, shown, settled) };
119
+ };
120
+ /** A run's learning as a list shows it: its state and reason, its detail cut of the host's secrets and then short (at
121
+ * most LIST_DETAIL characters, so a secret is never cut in half and shown), and the notes it read and learned
122
+ * (notesView); never its time. */
123
+ export const shortLearning = (learning, shown, settled) => (learning ? shortOf(learningView(learning, shown, settled)) : null);
124
+ /** A run's learning as its view shows it, in short for a list: all of it but its time, its detail cut short. */
125
+ export function shortOf({ state, reason, detail, at: _, ...notes }) {
126
+ return { state, reason, detail: detail === null ? null : short(detail, LIST_DETAIL), ...notes };
127
+ }
128
+ /** The label of the end-of-run turn's timeline rows, and the kind and label of a run's learning row. */
129
+ export const LEARNING_LABEL = "learning";
130
+ /** A run's proposal, in its directory (propose.ts): the seed it was checked against, each new note's file and text, its
131
+ * skill's and workflow draft's files by path and text (`files`: a SKILL.md, a workflow.json and its README.md; absent
132
+ * when it gives none), and what the user said in the run as the grader reads it (each message cut of the host's
133
+ * secrets, then shortened to GRADE_CAPS.askedMessage; absent in a proposal kept before the grader read them). */
134
+ export const PROPOSAL = "learning-proposal.json";
135
+ /** A run's pin, in its directory: written once, when the run is made, and never changed by a resume. */
136
+ export const LEARNING_PIN = "learning.json";
137
+ /** Where a run finds its agent's notes: in its work, a copy the run may read and nothing reads back. */
138
+ export const LEARNED_DIR = ".learning";
139
+ /** What the run's end-of-run turn answered, and what the user said in the run, kept in the run's directory as the run
140
+ * settles (learning-run.ts beforeSettle), where the host alone reads it: what propose.ts checks. */
141
+ export const LEARNING_TURN = "learning-turn.json";
142
+ /** The most bytes of learned skills one run gets, every file of each together. They get no more than what the
143
+ * revision's own skills leave of the adapters' cap on a run's skills in all (SKILL_BYTES): over that cap an adapter
144
+ * refuses the whole set, and every skill, the revision's too, would be inlined in the prompt (skills.ts splitSkills). */
145
+ export const LEARNED_SKILLS_BUDGET = 256 * 1024;
146
+ /** Where a run's harness finds its skills in its work: the revision's, and the learned ones laid beside them. */
147
+ const RUN_SKILLS = [".agents", "skills"];
148
+ /** A learned skill's folder: the shared skills convention's name (lowercase letters, digits and single dashes). */
149
+ const SKILL_NAME = /^(?=.{1,64}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;
150
+ /** A file's path inside a learned skill, as every adapter takes one (agentrun-kernel skillProblems). */
151
+ const SKILL_FILE_PATH = /^(?:[A-Za-z0-9_][A-Za-z0-9._-]{0,99}\/){0,4}[A-Za-z0-9_][A-Za-z0-9._-]{0,99}$/;
152
+ /** The `status` a SKILL.md's front matter sets, quotes dropped, or undefined when it sets none. The host alone sets one
153
+ * (`status: pending` on a skill held for its owner's OK); the checker refuses a run's skill that does. */
154
+ const statusOf = (text) => {
155
+ const lf = (text ?? "").replace(/\r\n/g, "\n");
156
+ const end = lf.startsWith("---\n") ? lf.indexOf("\n---\n", 3) : -1;
157
+ const line = end < 0 ? undefined : lf.slice(4, end).split("\n").find((entry) => entry.startsWith("status:"));
158
+ return line?.slice("status:".length).trim().replace(/^(["'])(.*)\1$/, "$2");
159
+ };
160
+ /** A file main holds over this is not read: a note is short, and the index is read only so far (loadedIndex). */
161
+ const FILE_CAP = 1 << 20;
162
+ const IDENTITY = { name: "agentrun-serve", email: "serve@agentrun.invalid" };
163
+ /** The floor of git this server's learning needs: the one the repository's other learning packages test on. Its own
164
+ * calls need 2.32 (GIT_CONFIG_GLOBAL). */
165
+ const MIN_GIT = [2, 40];
166
+ /** How long one git call may take before it is killed: a hung call would hold its agent's queue. */
167
+ const GIT_TIMEOUT_MS = 60_000;
168
+ /** The agent's learning folder: its home's `learning/` entry, which only the host writes. The home is files.ts homeOf,
169
+ * the one definition the home's routes use too, so two ids that differ only in case never share a folder. */
170
+ export const learningRepo = (data, agentId) => join(homeOf(data, agentId), "learning");
171
+ /** Makes `dir` where it is absent: a plain `mkdir`, never recursive (which would follow a link on the way). One that is
172
+ * there, whatever it is, is left for the check after. */
173
+ async function makeDir(dir) {
174
+ try {
175
+ await mkdir(dir, { mode: 0o700 });
176
+ }
177
+ catch (error) {
178
+ if (error.code === "EEXIST")
179
+ return;
180
+ throw error;
181
+ }
182
+ await learningTestHooks.afterMkdir?.(dir);
183
+ }
184
+ /** Throws when `path` is a symbolic link or not a directory, by `lstat`, which never follows one. A missing one passes
185
+ * when `absent` says it may be. What it throws names `path` in the data directory, never where a link points. */
186
+ async function refuseLink(data, path, absent = false) {
187
+ let stats;
188
+ try {
189
+ stats = await lstat(path);
190
+ }
191
+ catch (error) {
192
+ if (absent && error.code === "ENOENT")
193
+ return;
194
+ throw error;
195
+ }
196
+ if (stats.isSymbolicLink())
197
+ throw new Error(`${relative(data, path)} is a symbolic link, and the host never follows one into a learning folder`);
198
+ if (!stats.isDirectory())
199
+ throw new Error(`${relative(data, path)} is not a directory`);
200
+ }
201
+ /** The agent's learning folder, each level checked by `lstat`: its home, its `learning/` and, once there, `.git`. None
202
+ * may be a symbolic link or anything but a directory, or the host's git would read from, and write to, where the link
203
+ * points. `make`: the home and the folder are made where absent first, one level at a time, each checked after it is
204
+ * made (agentFolder); without it nothing is made and a missing level passes (readFolder). The one link rule. */
205
+ async function checkedFolder(data, agentId, make) {
206
+ const home = homeOf(data, agentId);
207
+ const repo = learningRepo(data, agentId);
208
+ if (make)
209
+ await makeDir(dirname(home));
210
+ for (const dir of [home, repo]) {
211
+ if (make)
212
+ await makeDir(dir);
213
+ await refuseLink(data, dir, !make);
214
+ }
215
+ await refuseLink(data, join(repo, ".git"), true);
216
+ return repo;
217
+ }
218
+ /** The agent's learning folder, its home and the folder made where absent (checkedFolder). A link swapped in for a part
219
+ * just made is caught by the check after. `<data>/homes` is the operator's, as the data directory is. Every write into
220
+ * the folder goes through it, in the agent's queue: before anything reads or makes the repository, and again once
221
+ * `git init` has made `.git`; before a run's end-of-run turn reads its seed again (seedAt), before its proposal is
222
+ * checked against it (propose.ts), before its grade reads main and its merge writes it (grade.ts), and before a
223
+ * person's edit, create or retire (learning-routes.ts). A refusal throws: a run about to start starts with nothing
224
+ * learned (seed_failed), a run that ended drops what it learned (reflect_failed, propose_failed or grade_failed), and
225
+ * a person's write is an error. */
226
+ export const agentFolder = (data, agentId) => checkedFolder(data, agentId, true);
227
+ /** The agent's learning folder for a person's read, outside the queue: the same check as agentFolder's, and nothing
228
+ * made. A link or a non-directory throws as it does there; a missing level passes, so a folder never made reads as
229
+ * empty (mainOf finds no main). */
230
+ export const readFolder = (data, agentId) => checkedFolder(data, agentId, false);
231
+ /** Before every command: a `-c` flag wins over the repository's own config. No hook or fsmonitor runs, no replace ref
232
+ * is read, a commit is never signed (which would run a program), and no transport runs, so nothing is fetched lazily.
233
+ * No optional lock is taken (GIT_OPTIONAL_LOCKS), so a read never writes. */
234
+ const SAFE = ["--no-replace-objects", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "commit.gpgSign=false", "-c", "protocol.allow=never"];
235
+ /** Every call's environment, built from nothing: no system or global config (so no template or hooks folder named
236
+ * there), no HOME, no prompt, the host's identity, and the repository named outright, never looked for. */
237
+ const gitEnv = (gitDir) => ({
238
+ PATH: process.env.PATH ?? "/usr/bin:/bin",
239
+ GIT_CONFIG_NOSYSTEM: "1",
240
+ GIT_CONFIG_GLOBAL: "/dev/null",
241
+ GIT_ATTR_NOSYSTEM: "1",
242
+ GIT_NO_REPLACE_OBJECTS: "1",
243
+ GIT_NO_LAZY_FETCH: "1",
244
+ GIT_OPTIONAL_LOCKS: "0",
245
+ GIT_TERMINAL_PROMPT: "0",
246
+ LC_ALL: "C",
247
+ GIT_AUTHOR_NAME: IDENTITY.name,
248
+ GIT_AUTHOR_EMAIL: IDENTITY.email,
249
+ GIT_COMMITTER_NAME: IDENTITY.name,
250
+ GIT_COMMITTER_EMAIL: IDENTITY.email,
251
+ ...(gitDir ? { GIT_DIR: gitDir } : {}),
252
+ });
253
+ /** One git call on `repo` (none for `init`), from `cwd`: its stdout, or a rejection naming the command and its stderr.
254
+ * `env` adds to the call's environment (a temporary index, a work tree named outright). */
255
+ export function git(cwd, repo, args, input = "", env = {}) {
256
+ learningTestHooks.git?.(args);
257
+ return new Promise((resolve, reject) => {
258
+ const child = spawn("git", [...SAFE, ...args], { cwd, env: { ...gitEnv(repo && join(repo, ".git")), ...env }, stdio: ["pipe", "pipe", "pipe"], timeout: GIT_TIMEOUT_MS });
259
+ const out = [];
260
+ const err = [];
261
+ child.stdout.on("data", (chunk) => out.push(chunk));
262
+ child.stderr.on("data", (chunk) => err.push(chunk));
263
+ child.stdin.on("error", () => undefined);
264
+ child.once("error", reject);
265
+ child.once("close", (code, signal) => {
266
+ if (code === 0)
267
+ return resolve(Buffer.concat(out));
268
+ reject(new Error(`git ${args[0]} failed (${signal ?? code}): ${Buffer.concat(err).toString("utf8").trim().slice(0, 500)}`));
269
+ });
270
+ child.stdin.end(input);
271
+ });
272
+ }
273
+ export const line = (out) => out.toString("utf8").trim();
274
+ const gitChecks = new Map();
275
+ /** Why this host keeps no learning folder, or undefined when it can: git MIN_GIT or later on `env`'s PATH. */
276
+ export function learningBlocker(env = process.env) {
277
+ const key = env.PATH ?? "";
278
+ let check = gitChecks.get(key);
279
+ if (!check) {
280
+ const floor = MIN_GIT.join(".");
281
+ check = new Promise((resolve) => {
282
+ const child = spawn("git", ["--version"], { env: { PATH: key }, stdio: ["ignore", "pipe", "ignore"], timeout: GIT_TIMEOUT_MS });
283
+ let out = "";
284
+ child.stdout.on("data", (chunk) => (out += chunk.toString("utf8")));
285
+ child.once("error", () => resolve(`learning needs git ${floor} or later on PATH, and this host has none`));
286
+ child.once("close", (code) => {
287
+ const [major = 0, minor = 0] = (/(\d+)\.(\d+)/.exec(out) ?? []).slice(1).map(Number);
288
+ if (code !== 0)
289
+ resolve(`learning needs git ${floor} or later on PATH, and this host has none`);
290
+ else
291
+ resolve(major > MIN_GIT[0] || (major === MIN_GIT[0] && minor >= MIN_GIT[1]) ? undefined : `learning needs git ${floor} or later, and this host has ${out.trim()}`);
292
+ });
293
+ });
294
+ gitChecks.set(key, check);
295
+ }
296
+ return check;
297
+ }
298
+ const queues = new Map();
299
+ /** Runs `work` once every call queued before it on the agent's folder has finished: one at a time per agent, in this
300
+ * process. Everything that touches an agent's folder goes through it, so two runs made at once never both make it. */
301
+ export const withAgentRepo = (data, agentId, work) => queued(learningRepo(data, agentId), work);
302
+ /** Runs `work` after every grade of the agent's runs queued before it (grade.ts): one grade at a time per agent, each
303
+ * against main as the one before left it. Its own queue, so a grade's model call never holds a run's seed. */
304
+ export const withAgentGrade = (data, agentId, work) => queued(`${learningRepo(data, agentId)}\0grade`, work);
305
+ function queued(key, work) {
306
+ return serialBy(queues, key, work);
307
+ }
308
+ /** Main's commit, or undefined when there is no main yet: no repository, one whose `init` never finished, or one whose
309
+ * making stopped before main. A main that is there, by its ref, and names no commit git can read is an error: the
310
+ * repository is never made again over it. */
311
+ export async function mainOf(cwd, repo) {
312
+ if (!existsSync(join(repo, ".git")) || !(await git(cwd, repo, ["rev-parse", "--git-dir"]).then(() => true, () => false)))
313
+ return undefined;
314
+ if (!line(await git(cwd, repo, ["for-each-ref", "--format=%(objectname)", "refs/heads/main"])))
315
+ return undefined;
316
+ return line(await git(cwd, repo, ["rev-parse", "--verify", "--quiet", "refs/heads/main^{commit}"]));
317
+ }
318
+ /** Makes the agent's folder, or finishes one whose making stopped before main: `init` with no template, then the host's
319
+ * one commit on main, holding an empty `MEMORY.md` alone, made with plumbing. The working tree and the index show that
320
+ * commit's tree first (written here, never checked out; a `MEMORY.md` that is a link is refused, never written
321
+ * through), and main is created last, only where it is not there yet: a making that stops anywhere before leaves no
322
+ * main, and the next one does it all again. Called in the queue, on the folder agentFolder made and checked; `check`
323
+ * checks it again once `.git` is made. */
324
+ export async function openAgentRepo(cwd, repo, check) {
325
+ const known = await mainOf(cwd, repo);
326
+ if (known)
327
+ return known;
328
+ await git(cwd, undefined, ["init", "-q", "--template=", "--initial-branch=main", repo]);
329
+ await check();
330
+ const blob = line(await git(cwd, repo, ["hash-object", "-w", "--no-filters", "--stdin"], ""));
331
+ const tree = line(await git(cwd, repo, ["mktree"], `100644 blob ${blob}\t${INDEX_FILE}\n`));
332
+ await writeFile(join(repo, INDEX_FILE), "", { flag: constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW }).catch((error) => {
333
+ throw error.code === "ELOOP" ? new Error(`the learning folder's ${INDEX_FILE} is a symbolic link, and the host never writes through one`) : error;
334
+ });
335
+ await git(cwd, repo, ["read-tree", tree]);
336
+ const commit = line(await git(cwd, repo, ["commit-tree", tree, "-m", "host: the agent's learning folder"]));
337
+ await git(cwd, repo, ["update-ref", "-m", "host: the agent's learning folder", "refs/heads/main", commit, ""]);
338
+ return commit;
339
+ }
340
+ /** Brings the folder's checked-out files in line with commit `sha` of main: host-only files, so no hook or filter runs,
341
+ * with the work tree named outright, the folder itself. Why it could not, when it could not. In the queue, on the
342
+ * folder agentFolder checked. */
343
+ export const checkOut = (repo, sha) => git(repo, repo, ["read-tree", "-u", "--reset", sha], "", { GIT_WORK_TREE: repo }).then(() => undefined, (error) => error);
344
+ /** The blobs `oids` hold, in order, read in one `cat-file --batch`. One git cannot read throws. */
345
+ export async function readBlobs(cwd, repo, oids) {
346
+ if (!oids.length)
347
+ return [];
348
+ const out = await git(cwd, repo, ["cat-file", "--batch"], oids.map((oid) => `${oid}\n`).join(""));
349
+ const blobs = [];
350
+ let at = 0;
351
+ for (const oid of oids) {
352
+ const end = out.indexOf(10, at);
353
+ const [named, type, size] = out.subarray(at, end < 0 ? at : end).toString("utf8").split(" ");
354
+ if (end < 0 || named !== oid || type !== "blob")
355
+ throw new Error(`git cat-file could not read ${oid}`);
356
+ blobs.push(out.subarray(end + 1, end + 1 + Number(size)));
357
+ at = end + 2 + Number(size);
358
+ }
359
+ return blobs;
360
+ }
361
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
362
+ /** What commit `sha` holds for a run, read with plumbing: its index and its active notes, the `.md` files at its top.
363
+ * Only a regular file (mode 100644) under FILE_CAP, in UTF-8, is read, and only a note in shape (learn/notes.ts
364
+ * parseNoteFile); anything else is named in `skipped`. Only an active note is a run's: a pending, superseded or retired
365
+ * one is not, and nothing serves it (learnedOf, layLearned). A read git fails (an
366
+ * object missing, a timeout) throws. */
367
+ export async function readSeed(cwd, repo, sha) {
368
+ const seed = { sha, notes: {}, files: [], skipped: [] };
369
+ const listed = (await git(cwd, repo, ["ls-tree", "-l", "-z", sha])).toString("utf8").split("\0").filter(Boolean);
370
+ const wanted = [];
371
+ for (const entry of listed) {
372
+ const tab = entry.indexOf("\t");
373
+ const [mode, type, oid, size] = entry.slice(0, tab).split(/\s+/);
374
+ const path = entry.slice(tab + 1);
375
+ seed.files.push(path);
376
+ if (!path.endsWith(".md"))
377
+ continue;
378
+ if (path !== INDEX_FILE && !NOTE_FILE.test(path))
379
+ seed.skipped.push(`${path} (not a note's file name)`);
380
+ else if (mode !== "100644" || type !== "blob" || !oid)
381
+ seed.skipped.push(`${path} (mode ${mode})`);
382
+ else if (Number(size) > FILE_CAP)
383
+ seed.skipped.push(`${path} (over ${FILE_CAP} bytes)`);
384
+ else
385
+ wanted.push({ path, oid });
386
+ }
387
+ const blobs = await readBlobs(cwd, repo, wanted.map(({ oid }) => oid));
388
+ wanted.forEach(({ path }, i) => {
389
+ let text;
390
+ try {
391
+ text = utf8.decode(blobs[i]);
392
+ }
393
+ catch {
394
+ return void seed.skipped.push(`${path} (not UTF-8)`);
395
+ }
396
+ if (path === INDEX_FILE)
397
+ return void (seed.index = text);
398
+ const note = parseNoteFile(path, text);
399
+ if (Array.isArray(note))
400
+ seed.skipped.push(`${path} (${note.join("; ")})`);
401
+ else if (note.status === "active")
402
+ seed.notes[path] = text;
403
+ });
404
+ return seed;
405
+ }
406
+ /** The skills commit `sha` holds under SKILLS_DIR, read with plumbing, by name. A skill is read when its folder's
407
+ * name and each of its files' paths are in shape, it holds a SKILL.md, and each file is a regular one (mode 100644) in
408
+ * UTF-8; else it is named in `skipped`. Only an active skill is a run's, one whose SKILL.md sets no status (or
409
+ * `active`): one held for its owner's OK (`status: pending`), or with any other status, is left out as a note that is
410
+ * not active is (readSeed). One over LEARNED_SKILLS_BUDGET, which no run could get, is held with its bytes and none of
411
+ * its files. A symbolic link or a submodule at SKILLS_DIR or anywhere under it throws, as a read
412
+ * git fails does: the run starts with nothing learned, and no link is ever laid in its work or followed. */
413
+ export async function readSkills(cwd, repo, sha) {
414
+ const listed = (await git(cwd, repo, ["ls-tree", "-r", "-t", "-l", "-z", "--full-tree", sha, "--", SKILLS_DIR])).toString("utf8").split("\0").filter(Boolean);
415
+ const found = new Map();
416
+ const refused = new Set();
417
+ const skipped = [];
418
+ for (const entry of listed) {
419
+ const tab = entry.indexOf("\t");
420
+ const [mode, type, oid, size] = entry.slice(0, tab).split(/\s+/);
421
+ const path = entry.slice(tab + 1);
422
+ if (path !== SKILLS_DIR && !path.startsWith(`${SKILLS_DIR}/`))
423
+ continue;
424
+ if (mode === "120000" || mode === "160000")
425
+ throw new Error(`the learning folder's ${path} is a ${mode === "120000" ? "symbolic link" : "submodule"}, and the host never lays one in a run`);
426
+ if (type === "tree")
427
+ continue;
428
+ if (path === SKILLS_DIR) {
429
+ skipped.push(`${path} (not a folder)`);
430
+ continue;
431
+ }
432
+ const [name = "", ...rest] = path.slice(SKILLS_DIR.length + 1).split("/");
433
+ const file = rest.join("/");
434
+ const why = !SKILL_NAME.test(name) || !file ? "not in a skill's folder named in lowercase letters, digits and dashes" : !SKILL_FILE_PATH.test(file) ? "not a plain path inside a skill" : mode !== "100644" || type !== "blob" || !oid ? `mode ${mode}` : undefined;
435
+ if (why) {
436
+ refused.add(name);
437
+ skipped.push(`${path} (${why})`);
438
+ }
439
+ else
440
+ (found.get(name) ?? found.set(name, []).get(name)).push({ path: file, oid, size: Number(size) });
441
+ }
442
+ const skills = [];
443
+ for (const [name, files] of [...found].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
444
+ if (refused.has(name))
445
+ continue;
446
+ if (!files.some(({ path }) => path === "SKILL.md")) {
447
+ skipped.push(`${SKILLS_DIR}/${name} (no SKILL.md)`);
448
+ continue;
449
+ }
450
+ const bytes = files.reduce((sum, { size }) => sum + size, 0);
451
+ if (bytes > LEARNED_SKILLS_BUDGET) {
452
+ skills.push({ name, bytes });
453
+ continue;
454
+ }
455
+ const blobs = await readBlobs(cwd, repo, files.map(({ oid }) => oid));
456
+ let texts;
457
+ try {
458
+ texts = Object.fromEntries(files.map(({ path }, i) => [path, utf8.decode(blobs[i])]));
459
+ }
460
+ catch {
461
+ skipped.push(`${SKILLS_DIR}/${name} (not UTF-8)`);
462
+ continue;
463
+ }
464
+ const status = statusOf(texts["SKILL.md"]);
465
+ if (status === undefined || status === "active")
466
+ skills.push({ name, bytes, files: texts });
467
+ }
468
+ return { skills, skipped };
469
+ }
470
+ /** Each file's place in main's first-parent log from `sha`, by the newest commit that changed it: 0 for those the newest
471
+ * commit changed, and so on, so two changes in one second keep their order. A run's notes (seedOf) and a person's view
472
+ * of them (learning-routes.ts) are in this order, the one changed last first. */
473
+ export async function changedOrder(cwd, repo, sha) {
474
+ const walked = (await git(cwd, repo, ["log", "--first-parent", "-z", "--name-only", "--format=%x1e", sha])).toString("utf8");
475
+ const order = new Map();
476
+ walked.split("\x1e").slice(1).forEach((record, i) => {
477
+ const end = record.indexOf("\0");
478
+ if (end < 0)
479
+ return;
480
+ for (const file of record.slice(end + 1).split("\0").map((name) => name.replace(/^\n/, "")).filter(Boolean))
481
+ if (!order.has(file))
482
+ order.set(file, i);
483
+ });
484
+ return order;
485
+ }
486
+ /** The seed of a run of agent `agentId` about to be made: main's commit, the folder made first when it is absent, and
487
+ * what that commit holds, its active notes in the order they changed on main, the one changed last first (then by
488
+ * name). In the agent's queue. */
489
+ export function seedOf(data, agentId) {
490
+ return withAgentRepo(data, agentId, async () => {
491
+ const check = () => agentFolder(data, agentId);
492
+ const repo = await check();
493
+ const home = homeOf(data, agentId);
494
+ const sha = await openAgentRepo(home, repo, check);
495
+ const seed = await readSeed(home, repo, sha);
496
+ const order = await changedOrder(home, repo, sha);
497
+ const place = (file) => order.get(file) ?? Number.POSITIVE_INFINITY;
498
+ seed.recent = Object.keys(seed.notes).sort((a, b) => place(a) - place(b) || (a < b ? -1 : a > b ? 1 : 0));
499
+ const { skills, skipped } = await readSkills(home, repo, sha);
500
+ // A skill's place is its file changed last's; by name (readSkills' order) among skills changed in one commit.
501
+ const skillPlace = new Map();
502
+ for (const [file, at] of order) {
503
+ const name = file.startsWith(`${SKILLS_DIR}/`) ? file.slice(SKILLS_DIR.length + 1).split("/")[0] : undefined;
504
+ if (name !== undefined && at < (skillPlace.get(name) ?? Number.POSITIVE_INFINITY))
505
+ skillPlace.set(name, at);
506
+ }
507
+ const placeOf = (skill) => skillPlace.get(skill.name) ?? Number.POSITIVE_INFINITY;
508
+ seed.skills = [...skills].sort((a, b) => placeOf(a) - placeOf(b) || 0);
509
+ seed.skipped.push(...skipped);
510
+ return seed;
511
+ });
512
+ }
513
+ /** The skills the agent wrote at commit `sha` (readSkills): what a run's pin names, laid again. In the agent's queue,
514
+ * through agentFolder. */
515
+ export const skillsAt = (data, agentId, sha) => withAgentRepo(data, agentId, async () => (await readSkills(homeOf(data, agentId), await agentFolder(data, agentId), sha)).skills);
516
+ /** What commit `sha` of the agent's folder holds for a run, as seedOf reads main: a run's seed, read again. In the
517
+ * agent's queue, through agentFolder. */
518
+ export const seedAt = (data, agentId, sha) => withAgentRepo(data, agentId, async () => readSeed(homeOf(data, agentId), await agentFolder(data, agentId), sha));
519
+ /** The active notes of a seed, parsed. */
520
+ export const activeOf = (seed) => Object.entries(seed.notes).flatMap(([file, text]) => {
521
+ const note = parseNoteFile(file, text);
522
+ return Array.isArray(note) ? [] : [note];
523
+ });
524
+ /** Test seams, tests only: once a part of an agent's learning folder is made (before its check), before a run's
525
+ * learned files are written, once its pin is in place, before what its end-of-run turn wrote is checked, as a run that
526
+ * learns opens again for a follow-up, and as each git call starts (its arguments). */
527
+ export const learningTestHooks = {};
528
+ /** As the run in `runDir` settles after its end-of-run turn ended, before it reads ended and before a follow-up can
529
+ * open it again: what the turn answered and what the user said, kept whole in `<run dir>/learning-turn.json`, so
530
+ * nothing the run does after its end reaches what is checked. One already there stays (a server that went after it
531
+ * was written). Throws when the write fails. */
532
+ export async function keepTurn(runDir, turn) {
533
+ const file = join(runDir, LEARNING_TURN);
534
+ if (await lstat(file).then(() => true, (error) => (error.code === "ENOENT" ? false : Promise.reject(error))))
535
+ return;
536
+ await writeDurable(file, `${JSON.stringify(turn)}\n`);
537
+ }
538
+ /** The turn a run's directory keeps (keepTurn). One that is not there, or out of shape, throws. */
539
+ export async function readTurn(runDir) {
540
+ const turn = JSON.parse(await readFile(join(runDir, LEARNING_TURN), "utf8"));
541
+ if (!isObject(turn) || typeof turn.answer !== "string" || !Array.isArray(turn.asked) || !turn.asked.every((message) => typeof message === "string"))
542
+ throw new Error(`the run's ${LEARNING_TURN} is not a turn`);
543
+ return turn;
544
+ }
545
+ /** `text` cut of the host's secrets (`shown`) a line at a time: the index, which may be longer than a whole text is
546
+ * read (learn/secrets.ts PRINT_MAX). */
547
+ const linesShown = (text, shown) => text.split("\n").map(shown.text).join("\n");
548
+ /** Every link's target on an index line: `<…>` or up to a space or `)`. */
549
+ const LINKS = /\]\(\s*(?:<([^>\n]*)>|([^)\s]+))/g;
550
+ /** The files an index line links to, each as the folder's path to it: its #fragment dropped, percent-decoded, and
551
+ * normalized at the folder's top, so `./x.md`, `/x.md` and `a/../x.md` are all x.md. */
552
+ const linkedFiles = (entry) => [...entry.matchAll(LINKS)].map((link) => {
553
+ const target = (link[1] ?? link[2]).split("#")[0];
554
+ let decoded = target;
555
+ try {
556
+ decoded = decodeURIComponent(target);
557
+ }
558
+ catch {
559
+ // Not percent-encoded right: taken as written.
560
+ }
561
+ return posix.normalize(decoded).replace(/^(?:\.?\/)+/, "");
562
+ });
563
+ /** `seed`'s index as a run is given it: each line with a link, any of them in any spelling (linkedFiles), to a file main
564
+ * holds that is no active note (a pending, superseded or retired one, or one not read) left out, so it is never served
565
+ * or counted. The host's index names none; a hand edit might. A line naming only files main does not hold stays. */
566
+ function servedIndex(seed) {
567
+ if (seed.index === undefined)
568
+ return undefined;
569
+ const held = new Set(seed.files);
570
+ return seed.index.split("\n").filter((entry) => !linkedFiles(entry).some((file) => held.has(file) && !Object.hasOwn(seed.notes, file))).join("\n");
571
+ }
572
+ /** Lays `seed`'s index and active notes in `dir`, made fresh: whatever was there goes. The index names the active notes
573
+ * alone (servedIndex), and each file is cut of the host's secrets (`shown`), the index a line at a time. */
574
+ export async function layLearned(dir, seed, shown) {
575
+ await rm(dir, { recursive: true, force: true });
576
+ await mkdir(dir, { mode: 0o700 });
577
+ const files = Object.entries(seed.notes).map(([file, text]) => [file, shown.text(text)]);
578
+ const index = servedIndex(seed);
579
+ if (index !== undefined)
580
+ files.unshift([INDEX_FILE, linesShown(index, shown)]);
581
+ for (const [file, text] of files)
582
+ await writeFile(join(dir, file), text, { flag: "wx" });
583
+ }
584
+ /** The lines before what a run learned, under `# Learned` after LEARNS, and the one that names `.learning/` to an agent
585
+ * that can read it. */
586
+ const KEPT = "Follow a note when it applies to what you are doing.";
587
+ const WHOLE_INTRO = `What you learned in earlier runs: each note whole, newest first. ${KEPT}`;
588
+ const SOME_INTRO = `What you learned in earlier runs: the index, one line per note, then the newest notes whole. ${KEPT}`;
589
+ const INDEX_INTRO = `What you learned in earlier runs, one line per note. ${KEPT}`;
590
+ const READ_LINE = `The notes not given whole here are files in \`${LEARNED_DIR}/\` in your working directory: open one with the read tool when it applies.`;
591
+ /** How a pin an earlier server wrote, the index alone, was read: its intro then. */
592
+ const EARLIER_INTRO = `What you learned in earlier runs, one line per note. Each note is a file in \`${LEARNED_DIR}/\` in your working directory: open one when it applies to what you are doing.`;
593
+ const oneLine = (text) => text.replace(/\s+/g, " ").trim();
594
+ /** A note as a run reads it whole: its name and file, its description, then its body, each cut of the host's secrets. */
595
+ const wholeNote = (note, shown) => [`## ${shown.text(oneLine(note.name))} (${shown.name(note.file)})`, shown.text(oneLine(note.description)), shown.text(note.body.trim())].filter(Boolean).join("\n\n");
596
+ /** What a run of `seed` reads under `# Learned`, the same for every harness, or undefined when it learned nothing. Only
597
+ * active notes are served: a pending, superseded or retired one is never there, whole or in the index, nor counted
598
+ * toward the budget (readSeed reads active notes alone, and servedIndex drops their lines). Its active notes, newest
599
+ * first (`seed.recent`, else by name): each whole while all fit `budget`, the UTF-8 bytes of
600
+ * what follows the first paragraph. Past it, or when the index names a note main does not hold whole: the index as a
601
+ * run loads it (learn/notes.ts loadedIndex, the first 200 lines and no more than 25 KB, past the budget when it is
602
+ * larger), then the newest notes that fit what is left, each whole, and the rest named only in the index; an agent
603
+ * with the read tool is told they are in `.learning/`, one without is not. Every text is cut of the host's secrets. */
604
+ export function learnedOf(seed, options) {
605
+ const { budget, read, shown } = options;
606
+ const active = new Map(activeOf(seed).map((note) => [note.file, note]));
607
+ const notes = (seed.recent ?? [...active.keys()].sort()).flatMap((file) => active.get(file) ?? []);
608
+ const index = servedIndex(seed);
609
+ const lines = index === undefined ? [] : loadedIndex(index).split("\n").filter((entry) => entry.trim() !== "");
610
+ if (!notes.length && !lines.length)
611
+ return undefined;
612
+ const blocks = notes.map((note) => wholeNote(note, shown));
613
+ // Each part's bytes, and the blank line before it.
614
+ const size = (text) => Buffer.byteLength(text) + 2;
615
+ // Each line's first link, in any spelling (`./x.md` is x.md: linkedFiles, as servedIndex reads it), names an active note.
616
+ const named = lines.every((entry) => active.has(linkedFiles(entry)[0] ?? ""));
617
+ if (named && blocks.reduce((sum, block) => sum + size(block), 0) <= budget)
618
+ return [WHOLE_INTRO, ...blocks].join("\n\n");
619
+ const shownIndex = lines.map(shown.text).join("\n");
620
+ let left = budget - (shownIndex ? size(shownIndex) : 0);
621
+ const whole = blocks.filter((block) => size(block) <= left && ((left -= size(block)), true));
622
+ return [whole.length ? SOME_INTRO : INDEX_INTRO, shownIndex, ...(read && whole.length < notes.length ? [READ_LINE] : []), ...whole].filter(Boolean).join("\n\n");
623
+ }
624
+ /** `rel`, a folder of the run's `work`, made where absent by a plain `mkdir` (which follows no link), then checked by
625
+ * `lstat`: a symbolic link there, or anything but a folder, throws, and nothing is written through it. */
626
+ async function workFolder(work, rel) {
627
+ const path = join(work, rel);
628
+ await mkdir(path).catch((error) => {
629
+ if (error.code !== "EEXIST")
630
+ throw error;
631
+ });
632
+ const stats = await lstat(path);
633
+ if (stats.isSymbolicLink() || !stats.isDirectory())
634
+ throw new Error(`the run's ${rel} is not a folder, and the host never writes through a link`);
635
+ }
636
+ /** Lays each of `skills` in the run's `work/.agents/skills/<name>/`, a folder made new for it (one already there
637
+ * throws), every folder on the way checked (workFolder). Each name goes in `made` once its folder is, so a caller that
638
+ * fails takes back what was laid. */
639
+ async function laySkills(work, skills, made) {
640
+ if (!skills.length)
641
+ return;
642
+ for (let depth = 1; depth <= RUN_SKILLS.length; depth++)
643
+ await workFolder(work, RUN_SKILLS.slice(0, depth).join("/"));
644
+ for (const { name, files = {} } of skills) {
645
+ await mkdir(join(work, ...RUN_SKILLS, name));
646
+ made.push(name);
647
+ for (const [path, text] of Object.entries(files)) {
648
+ const parts = path.split("/");
649
+ for (let depth = 1; depth < parts.length; depth++)
650
+ await workFolder(work, [...RUN_SKILLS, name, ...parts.slice(0, depth)].join("/"));
651
+ // A SKILL.md as a harness is given it: its name and description alone in its front matter (servedSkill).
652
+ await writeFile(join(work, ...RUN_SKILLS, name, ...parts), path === "SKILL.md" ? servedSkill(text) : text, { flag: "wx" });
653
+ }
654
+ }
655
+ }
656
+ /** Takes the learned skills `names` back out of the run's work: each `work/.agents/skills/<name>/`, unless a folder on
657
+ * the way is a link (or no folder), when nothing is touched. */
658
+ async function takeSkills(work, names) {
659
+ for (let depth = 1; depth <= RUN_SKILLS.length; depth++) {
660
+ const stats = await lstat(join(work, ...RUN_SKILLS.slice(0, depth))).catch(() => undefined);
661
+ if (!stats?.isDirectory())
662
+ return;
663
+ }
664
+ for (const name of names)
665
+ await rm(join(work, ...RUN_SKILLS, name), { recursive: true, force: true });
666
+ }
667
+ /** The learned skills' names a pin's `skills` hold, each once. */
668
+ const namesIn = (files) => [...new Set((files ?? []).map((path) => path.split("/")[0]))];
669
+ /** Which of `seed`'s learned skills a run gets, in `work`, in the seed's order: each whole while they fit their budget,
670
+ * LEARNED_SKILLS_BUDGET and never more than the revision's `own` skill files (by their bytes in `work`) leave of
671
+ * SKILL_BYTES. One named like a folder of the revision's skills, or like anything already in `work/.agents/skills/`, is
672
+ * the revision's, and not the run's; one that does not fit, or holds a host secret (`shown`), is left out. */
673
+ async function chooseSkills(work, seed, own, shown) {
674
+ if (!seed.skills?.length)
675
+ return { taken: [], left: [] };
676
+ let ownBytes = 0;
677
+ for (const path of own)
678
+ ownBytes += (await lstat(join(work, ...RUN_SKILLS, ...path.split("/")))).size;
679
+ let room = Math.max(0, Math.min(LEARNED_SKILLS_BUDGET, SKILL_BYTES - ownBytes));
680
+ const owned = new Set(namesIn(own));
681
+ const taken = [];
682
+ const left = [];
683
+ for (const skill of seed.skills) {
684
+ if (owned.has(skill.name) || (await lstat(join(work, ...RUN_SKILLS, skill.name)).then(() => true, () => false)))
685
+ continue;
686
+ const secret = shown.holds(skill.name) || Object.entries(skill.files ?? {}).some(([path, text]) => shown.holds(path) || shown.holds(text));
687
+ if (!skill.files || secret || skill.bytes > room) {
688
+ left.push(shown.name(skill.name));
689
+ continue;
690
+ }
691
+ room -= skill.bytes;
692
+ taken.push(skill);
693
+ }
694
+ return { taken, left };
695
+ }
696
+ /** Writes `seed` into the run just made in `runDir`: the index and each active note into `work/.learning/`, made fresh
697
+ * (whatever was there goes), then the pin, with what the run reads under `# Learned` (learnedOf) and the learned
698
+ * skills it gets beside the revision's `own` skill files (chooseSkills), then those skills, last, into
699
+ * `work/.agents/skills/`. A write that fails leaves no `.learning/`, no learned skill and no pin, and throws. */
700
+ export async function pinSeed(runDir, work, seed, options) {
701
+ const dir = join(work, LEARNED_DIR);
702
+ const pinFile = join(runDir, LEARNING_PIN);
703
+ const made = [];
704
+ try {
705
+ await learningTestHooks.beforePin?.(runDir);
706
+ await layLearned(dir, seed, options.shown);
707
+ const section = learnedOf(seed, options);
708
+ const { taken, left } = await chooseSkills(work, seed, options.own ?? [], options.shown);
709
+ const skills = taken.flatMap(({ name, files = {} }) => Object.keys(files).sort().map((path) => `${name}/${path}`));
710
+ const pin = { seed: seed.sha, ...(section ? { section } : {}), ...(skills.length ? { skills } : {}), ...(left.length ? { skills_left_out: left } : {}) };
711
+ // The pin names the skills before they are laid: a server that goes down while they are takes them back (dropSeed).
712
+ await writeDurable(pinFile, `${JSON.stringify(pin)}\n`);
713
+ await laySkills(work, taken, made);
714
+ await learningTestHooks.afterPin?.(runDir);
715
+ return pin;
716
+ }
717
+ catch (error) {
718
+ // writeDurable renames the pin into place before it syncs the run's directory, so a failure there leaves the pin
719
+ // behind: it goes too, or the run's instructions would still say what it learned, of notes it has no copy of.
720
+ await rm(pinFile, { force: true }).catch(() => undefined);
721
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
722
+ await takeSkills(work, made).catch(() => undefined);
723
+ throw error;
724
+ }
725
+ }
726
+ /** Lays the learned skills a reopened run's pin names (`pin.skills`) again, fresh, from `read` (the skills of its seed's
727
+ * commit: skillsAt): what the run wrote over them, or took away, is not what it learned. Each only with the files the
728
+ * pin names. Throws when it cannot, a link on the way among the reasons. */
729
+ export async function layPinnedSkills(work, pin, read) {
730
+ const names = namesIn(pin.skills);
731
+ if (!names.length)
732
+ return;
733
+ const files = new Set(pin.skills);
734
+ const skills = (await read()).filter(({ name }) => names.includes(name)).map(({ name, bytes, files: all = {} }) => ({ name, bytes, files: Object.fromEntries(Object.entries(all).filter(([path]) => files.has(`${name}/${path}`))) }));
735
+ await takeSkills(work, names);
736
+ await laySkills(work, skills, []);
737
+ }
738
+ /** Takes back a seed whose copy a server went down during (runs.ts load): the learned skills its pin names, the pin,
739
+ * then its `work/.learning/`. True when the pin or the copy was there. */
740
+ export async function dropSeed(runDir, work) {
741
+ const pinFile = join(runDir, LEARNING_PIN);
742
+ const dir = join(work, LEARNED_DIR);
743
+ const there = Boolean((await lstat(pinFile).catch(() => null)) ?? (await lstat(dir).catch(() => null)));
744
+ if (!there)
745
+ return false;
746
+ await takeSkills(work, namesIn((await readPin(runDir).catch(() => undefined))?.skills));
747
+ await rm(pinFile, { force: true });
748
+ await rm(dir, { recursive: true, force: true });
749
+ return there;
750
+ }
751
+ /** The run's pin, as its process reads it: undefined when the run has none (its agent does not learn, its seed failed, a
752
+ * workflow's run). A pin out of shape is an error, never read as none. */
753
+ export async function readPin(runDir) {
754
+ let text;
755
+ try {
756
+ text = await readFile(join(runDir, LEARNING_PIN), "utf8");
757
+ }
758
+ catch (error) {
759
+ if (error.code === "ENOENT")
760
+ return undefined;
761
+ throw error;
762
+ }
763
+ const pin = JSON.parse(text);
764
+ const names = (value, shape) => value === undefined || (Array.isArray(value) && value.every((entry) => typeof entry === "string" && shape(entry)));
765
+ const skillFile = (entry) => SKILL_NAME.test(entry.split("/")[0]) && SKILL_FILE_PATH.test(entry.slice(entry.indexOf("/") + 1)) && entry.includes("/");
766
+ if (!isObject(pin) || typeof pin.seed !== "string" || (pin.section !== undefined && typeof pin.section !== "string") || (pin.learned !== undefined && typeof pin.learned !== "string") || !names(pin.skills, skillFile) || !names(pin.skills_left_out, () => true))
767
+ throw new Error(`the run's ${LEARNING_PIN} is not a learning pin`);
768
+ return pin;
769
+ }
770
+ /** The heading of what a run learned, in its instructions. */
771
+ export const LEARNED_HEADING = "# Learned";
772
+ /** What every run that learns is told first under it, notes or none: a run not told it learns saves what the person
773
+ * asks it to remember in a file, or says it cannot, and that is never kept. */
774
+ 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.";
775
+ /** What a run that starts with no note is told in place of what it learned. */
776
+ const NOTHING_YET = "Nothing learned yet.";
777
+ /** A run's instructions, with `# Learned` after them when its pin in `runDir` says it learns: that it learns, then what
778
+ * the pin says it learned, or that it has learned nothing yet. A run with no pin (its agent does not learn, its seed
779
+ * failed, a workflow's run) is never asked what to keep, so it is told nothing. And its skill files: the revision's
780
+ * `own`, then the learned ones its pin names, by their paths under `.agents/skills/` in `work`, but for a skill named
781
+ * like one of the revision's, which is the revision's. A learned skill the work no longer holds whole, as a harness reads
782
+ * it (no link on the way: workspace.ts), is left out: a learning fault never fails a run. The one path for every harness
783
+ * (app.ts): pi's system prompt, claude-agent's and codex's instructions, and the skills each gets. */
784
+ export async function withLearned(runDir, work, instructions, own = []) {
785
+ const pin = await readPin(runDir);
786
+ const section = pin?.section ?? (pin?.learned?.trim() ? `${EARLIER_INTRO}\n\n${pin.learned.trim()}` : undefined);
787
+ const owned = new Set(namesIn(own));
788
+ const learned = (pin?.skills ?? []).filter((path) => !owned.has(path.split("/")[0]));
789
+ const whole = new Set();
790
+ for (const name of namesIn(learned)) {
791
+ const files = learned.filter((path) => path.startsWith(`${name}/`));
792
+ if (await Promise.all(files.map((path) => readWorkText(work, [...RUN_SKILLS, path].join("/")))).then(() => true, () => false))
793
+ whole.add(name);
794
+ else
795
+ process.stderr.write(`agentrun-serve: the skill ${name} its agent learned is no longer whole in the run's work, so the run goes on without it\n`);
796
+ }
797
+ return {
798
+ instructions: pin ? `${instructions.trim()}\n\n${LEARNED_HEADING}\n\n${LEARNS}\n\n${section ?? NOTHING_YET}` : instructions,
799
+ skills: [...own, ...learned.filter((path) => whole.has(path.split("/")[0]))],
800
+ };
801
+ }