@parcha/agentrun-serve 0.0.0-stage → 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 +1723 -2
  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 +94 -4
  229. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,797 @@
1
+ // A run's learning, a step the kernel calls. runs.ts owns a run's process, its door, its rows and its serve.json; it
2
+ // builds one LearningRuns and calls it where a run's life meets learning:
3
+ // onStart the run about to be made: its seed read first, then pinned in it once it is (learning.ts)
4
+ // onSaved its serve.json written: the learning ledger's line, once its learning ended (usage.ts)
5
+ // onLoad a run read at a start, before the kernel holds it: a seed copy a server went down during taken back
6
+ // beforeFinish its job ended: the end-of-run turn asked first, and the run let go once the turn ends
7
+ // onAdopt a running run read at a start: one a server left in its end-of-run turn finishes, its turn asked again
8
+ // onLaunch its process launched: the saved keys it was handed, kept for the check of what its turn writes
9
+ // beforeSettle its end being written: the turn's rows closed, and what the turn answered kept aside
10
+ // afterSettle its end written: the notes the turn answered with checked (propose.ts), graded and merged (grade.ts)
11
+ // onReopen, afterReopen a follow-up: its copy laid again where it is gone, and a turn its process went in aborted
12
+ // recover the server's start: what a server left between steps, picked up once
13
+ // close, idle the server closing: grades stopped, then every check and grade in flight waited for
14
+ // It holds the runs' learning in flight; a run's learning itself is in its serve.json (`learning`, `reflect`), which
15
+ // the kernel writes.
16
+ import { lstat, readFile } from "node:fs/promises";
17
+ import { join, posix } from "node:path";
18
+ import { ANSWER_MAX, INDEX_FILE, parseNoteFile, redactSecrets } from "./learn/index.js";
19
+ import { CAP_REFUSAL_PREFIX, SPEND_CAP_REACHED } from "./cap.js";
20
+ import { readJson, RUN_META, runDoorToken } from "./files.js";
21
+ import { activeOf, detailShown, dropSeed, gradeModelOf, keepTurn, KEPT_LEARNING, layLearned, layPinnedSkills, LEARNED_DIR, LEARNING_BUDGET, LEARNING_LABEL, learningBlocker, learningTestHooks, learningView, pinSeed, PROPOSAL, readPin, readTurn, secretsShown, seedAt, seedOf, shortLearning, skillsAt, withAgentGrade } from "./learning.js";
22
+ import { withoutFaux } from "./model.js";
23
+ import { hostSecrets, secret, SECRET_NAMES, withSecrets } from "./secrets.js";
24
+ import { notKept, said, STOPPED } from "./learning-words.js";
25
+ import { ended, outcomeOf, outcomes, record } from "./usage.js";
26
+ import { isObject } from "./validate.js";
27
+ import { REFLECT_REQUEST } from "./turns.js";
28
+ /** Who sent the end-of-run turn: the server, never a person, and no request field sets it. The one value it is sent
29
+ * with, at its one call (reflectTurn); the per-tool gate, once this server has one, takes it there. */
30
+ const REFLECT_ORIGIN = "reflect";
31
+ /** The run asked its end-of-run turn and has not ended since. */
32
+ export const reflecting = (run) => run.meta.reflect !== undefined && run.meta.reflect.until === undefined;
33
+ /** The run ended after its end-of-run turn did, and what the turn wrote is neither checked nor dropped yet. */
34
+ const awaitsPropose = (meta) => meta?.learning?.state === "reflecting" && meta.reflect?.ended === true && meta.reflect.until !== undefined;
35
+ /** The end-of-run turn's request id: the door and pi take one id once, so a turn asked again after a restart is not
36
+ * asked twice. */
37
+ const reflectId = (runId) => `${REFLECT_REQUEST}${runId}`;
38
+ /** How long a run's end-of-run turn may take before it is aborted and the run finishes without it. */
39
+ const REFLECT_TIMEOUT_MS = 5 * 60_000;
40
+ /** How often the run's door is asked whether its end-of-run turn has ended. */
41
+ const REFLECT_POLL_MS = 250;
42
+ /** A row's store entry, from its id (`<conversation>:<entry>[:...]`); NaN for a row no entry made (a live one, usage). */
43
+ const entryOf = (id) => Number(id.split(":")[1]);
44
+ /** Whether entry `id` (a number), or the row `id`, is the end-of-run turn's. Before the run has ended every later entry
45
+ * is, and so is a live row. */
46
+ export function reflects(reflect, id) {
47
+ if (!reflect)
48
+ return false;
49
+ const entry = typeof id === "number" ? id : entryOf(id);
50
+ if (Number.isInteger(entry))
51
+ return entry > reflect.after && (reflect.until === undefined || entry <= reflect.until);
52
+ return reflect.until === undefined && typeof id === "string" && id.includes(":live:");
53
+ }
54
+ /** `rows` with the end-of-run turn's labelled: never the run's answer (meaningful skips the label), its answer shown as
55
+ * a text row, and its message as the host's, in a person's words (learning-words.ts): what the model is asked stays in
56
+ * the run's store, and no row shows it. */
57
+ export function labelled(reflect, rows) {
58
+ if (!reflect)
59
+ return rows;
60
+ return rows.map((row) => (!reflects(reflect, row.id) ? row : {
61
+ ...row, agent_label: LEARNING_LABEL,
62
+ ...(row.kind === "final_answer" ? { kind: "text_block" } : {}),
63
+ ...(row.kind === "user_message" ? { summary: said.asked, text: said.asked } : {}),
64
+ }));
65
+ }
66
+ /** A path that names a file at the top of a run's copy of the folder: `.learning/<file>` relative to its work, as a
67
+ * harness's file tools take it, or the same at the end of an absolute path (claude-agent's CLI joins its working
68
+ * directory; a box names its own). */
69
+ const IN_COPY = new RegExp(`(?:^|/)${LEARNED_DIR.replace(".", "\\.")}/([^/]+)$`);
70
+ /** The files of the run's copy of the folder its job read, in the order it first read them, each once: every `read`
71
+ * call whose result came back a success, matched to its call by id (claude-agent's rows can hold the result above the
72
+ * call), on any harness: pi's, claude-agent's (the host's `read`, served to its CLI as `mcp__hands__read`) and codex's
73
+ * (the same tool, as an app-server dynamic tool) rows all name it `read`, with the path as the model gave it. The
74
+ * end-of-run turn's reads are its own, not the job's, and are left out; so is a read that failed or never ended, and
75
+ * MEMORY.md, which is no note. Which of these files are notes the run started from is for its seed to say (noteUsed). */
76
+ export function notesRead(reflect, rows) {
77
+ const done = new Set(rows.flatMap((row) => (row.kind === "tool_result" && row.tool_status === "success" && row.tool_use_id ? [row.tool_use_id] : [])));
78
+ const read = new Set();
79
+ for (const row of rows) {
80
+ if (row.kind !== "tool_use" || row.tool_name !== "read" || !row.tool_use_id || !done.has(row.tool_use_id) || reflects(reflect, row.id))
81
+ continue;
82
+ const file = IN_COPY.exec(posix.normalize(row.tool_input_preview ?? ""))?.[1];
83
+ if (file && file !== INDEX_FILE)
84
+ read.add(file);
85
+ }
86
+ return [...read];
87
+ }
88
+ /** `verdict` with its reason, and each item's question and why, cut of `values` (learn/secrets.ts redactSecrets). */
89
+ const cutVerdict = (verdict, values) => ({
90
+ ...verdict,
91
+ reason: redactSecrets(verdict.reason, values),
92
+ items: verdict.items.map((item) => ({ ...item, ...(item.question === undefined ? {} : { question: redactSecrets(item.question, values) }), why: redactSecrets(item.why, values) })),
93
+ });
94
+ /** The notes a run's learning added, from its proposal: each note's file, name and the notes it supersedes. */
95
+ const learnedOf = (proposal) => proposal.notes.flatMap(({ file, text }) => {
96
+ const note = parseNoteFile(file, text);
97
+ return Array.isArray(note) ? [] : [{ file, name: note.name, supersedes: note.supersedes }];
98
+ });
99
+ /** The run's learning row, once its learning was proposed, merged or dropped (`seed_failed` included): its state, reason
100
+ * and detail, its summary the detail itself as the run's view says it (learning.ts detailShown: cut of the host's
101
+ * secrets now, `shown`, then cut short). One row, which says where the learning ended. */
102
+ export function withLearning(rows, learning, shown) {
103
+ if (!learning || learning.state === "seeded" || learning.state === "reflecting")
104
+ return [...rows];
105
+ const detail = detailShown(learning, shown);
106
+ const row = {
107
+ id: LEARNING_LABEL, timestamp: learning.at, created_at: learning.at, kind: "learning", summary: detail ?? `Learning ${learning.state}`, agent_label: LEARNING_LABEL,
108
+ tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null, text: detail,
109
+ learning: { state: learning.state, reason: learning.reason, detail },
110
+ };
111
+ return [...rows, row];
112
+ }
113
+ /** How the runs that tried to learn fared, over the runs the analytics' `from`, `to` and `agent` pick (by when they
114
+ * started, unarchived): `runs` with a learning block, `merged`, `dropped` by reason, and `in_progress` (seeded,
115
+ * reflecting or proposed: a run this server holds). A run with learning off, a workflow's or an imported one, has
116
+ * none, and is not counted. */
117
+ export function learningStats(rows, filter, learningOf) {
118
+ const from = filter.from === undefined ? -Infinity : Date.parse(filter.from);
119
+ const to = filter.to === undefined ? Infinity : Date.parse(filter.to);
120
+ const out = { runs: 0, merged: 0, dropped: {}, in_progress: 0 };
121
+ for (const row of rows) {
122
+ const at = Date.parse(row.startedAt);
123
+ if (row.kind !== "agentic" || row.importedFrom || row.archivedAt || !(at >= from && at < to) || (filter.agent !== undefined && row.agent !== filter.agent))
124
+ continue;
125
+ const learning = learningOf(row);
126
+ if (!learning)
127
+ continue;
128
+ out.runs += 1;
129
+ if (learning.state === "merged")
130
+ out.merged += 1;
131
+ else if (learning.state === "dropped")
132
+ out.dropped[learning.reason ?? "unknown"] = (out.dropped[learning.reason ?? "unknown"] ?? 0) + 1;
133
+ else
134
+ out.in_progress += 1;
135
+ }
136
+ return out;
137
+ }
138
+ /** A note's name, from its front matter; its file when it has none. */
139
+ const nameOf = (file, text) => {
140
+ const note = parseNoteFile(file, text);
141
+ return Array.isArray(note) ? file : note.name;
142
+ };
143
+ /** What run `run`'s end-of-run turn answered, and what the user said in the run, as beforeSettle keeps them: the whole
144
+ * text of each of the turn's assistant messages, in order (its notes may come in more than one), cut once past
145
+ * ANSWER_MAX, which the parser refuses; and each message the run was sent before the turn. */
146
+ function turnOf(run) {
147
+ const answer = [...(run.turnText ?? new Map())].sort(([a], [b]) => a - b).map(([, text]) => text).filter(Boolean).join("\n\n");
148
+ const asked = run.rows.filter((row) => row.kind === "user_message" && row.agent_label !== LEARNING_LABEL && !reflects(run.meta.reflect, row.id)).map((row) => row.text ?? "");
149
+ return { answer: answer.length > ANSWER_MAX ? answer.slice(0, ANSWER_MAX + 1) : answer, asked };
150
+ }
151
+ /** The middle of `values` (the mean of the two middle ones when there is an even count); undefined for none. */
152
+ const median = (values) => {
153
+ if (!values.length)
154
+ return undefined;
155
+ const sorted = [...values].sort((a, b) => a - b);
156
+ const mid = sorted.length >> 1;
157
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
158
+ };
159
+ const usd = (value) => (value === undefined ? null : Math.round(value * 1e6) / 1e6);
160
+ const sideOf = (runs) => {
161
+ const costs = runs.flatMap((run) => (run.cost === null ? [] : [run.cost]));
162
+ return {
163
+ runs: runs.length,
164
+ median_duration_s: Math.round(median(runs.map((run) => run.seconds)) * 10) / 10,
165
+ median_cost_usd: usd(median(costs)),
166
+ cost_runs: costs.length,
167
+ median_learning_usd: usd(median(runs.flatMap((run) => (typeof run.learning === "number" ? [run.learning] : [])))),
168
+ };
169
+ };
170
+ /** Completed run `row` as its impact counts it, `learning` what its learning says. One that looked back answered when
171
+ * its job ended, and its job's cost is what it had cost by then; any other's are its row's end and cost, which no look
172
+ * back follows. Undefined for one whose learning a server before these figures kept (it says neither how many notes
173
+ * it started from nor when it answered): its row's end and cost hold its look-back too. */
174
+ function figuresOf(row, learning) {
175
+ if (learning && learning.seed_notes === undefined && learning.reason !== "seed_failed")
176
+ return undefined;
177
+ const looked = learning?.answered_at !== undefined;
178
+ const answered = looked ? Date.parse(learning.answered_at) : Date.parse(row.endedAt);
179
+ const cost = looked ? (learning.job_cost_usd ?? null) : (row.costUsd ?? null);
180
+ if (!learning)
181
+ return { seconds: (answered - Date.parse(row.startedAt)) / 1000, cost };
182
+ const { look_back_usd: back, grade_usd: grade } = learning;
183
+ return { seconds: (answered - Date.parse(row.startedAt)) / 1000, cost, learning: typeof back === "number" && typeof grade === "number" ? back + grade : null };
184
+ }
185
+ /** What learning changed for an agent, from its run rows (`rows`) and what its runs' learning says (`learningOf`),
186
+ * never a run's files. `after`: its completed agentic runs that started from at least one active note. `before`: its
187
+ * completed agentic runs that started before its first note, the earlier of its first merge's end and the start of its
188
+ * first run that started from a note (a person's note comes first that way); none of them could have. Each side's
189
+ * figures (sideOf, figuresOf): its time to the answer in seconds to a tenth, its job's own cost, what learning cost.
190
+ * An imported or archived run is on neither side, nor is a later one with learning off or seeded with no note (every
191
+ * note retired), nor one whose learning predates these figures. Null unless both sides hold 2 runs or more. */
192
+ export function learningImpact(rows, learningOf) {
193
+ const done = rows.filter((row) => row.kind === "agentic" && !row.importedFrom && !row.archivedAt && row.state === "completed" && row.endedAt);
194
+ const after = done.filter((row) => (learningOf(row)?.seed_notes ?? 0) > 0);
195
+ const merges = rows.flatMap((row) => {
196
+ const learning = learningOf(row);
197
+ return learning?.state === "merged" ? [Date.parse(learning.at)] : [];
198
+ });
199
+ const first = Math.min(...merges, ...after.map((row) => Date.parse(row.startedAt)));
200
+ const counted = (side) => side.flatMap((row) => figuresOf(row, learningOf(row)) ?? []);
201
+ const [before, later] = [counted(done.filter((row) => Date.parse(row.startedAt) < first)), counted(after)];
202
+ return before.length >= 2 && later.length >= 2 ? { before: sideOf(before), after: sideOf(later) } : null;
203
+ }
204
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
205
+ const warn = (runId, text) => void process.stderr.write(`agentrun-serve: run ${runId}: ${text}\n`);
206
+ /** A row of the run's that a person sees. Its rows never hold the reducer's quiet ones (runs.ts take). */
207
+ const shows = (row) => row.kind !== "usage" && row.kind !== "phase";
208
+ /** `work` for `key`, one at a time: the one in flight, else a new one, forgotten once it settles. */
209
+ function once(running, key, work) {
210
+ let current = running.get(key);
211
+ if (!current)
212
+ running.set(key, (current = work().finally(() => running.delete(key))));
213
+ return current;
214
+ }
215
+ /** The learning of every run the kernel holds, from the end-of-run turn to the merge. */
216
+ export class LearningRuns {
217
+ options;
218
+ kernel;
219
+ /** Why this host keeps no learning folder, said once. */
220
+ learningOff;
221
+ /** The secrets each launch of a run that learns handed its process (runs.ts launch()), by run id, so a key a person
222
+ * replaced or deleted while the run lived is still refused in what its end-of-run turn wrote. In memory only, never on
223
+ * disk: a server that restarts loses them, and the run's next launch hands it the keys as they are then, which the
224
+ * check reads too. Dropped once the run's learning ends, and when the server closes. */
225
+ handed = new Map();
226
+ /** Aborted as the server closes: a grade's screen and grader stop, and leave the run's learning `proposed`. */
227
+ stopping = new AbortController();
228
+ /** The runs whose learning's end is in the learning ledger (usage.ts): read at the start, and each one written since. */
229
+ recorded = new Set();
230
+ /** By run: what its end-of-run turn wrote, being checked (proposeOnce), and its proposal, being graded (gradeOnce). */
231
+ proposing = new Map();
232
+ grading = new Map();
233
+ /** The host's secrets as shown() last cut them, by their values, and the saved keys it read. */
234
+ cut;
235
+ saved;
236
+ constructor(options, kernel) {
237
+ this.options = options;
238
+ this.kernel = kernel;
239
+ }
240
+ get closing() {
241
+ return this.stopping.signal.aborted;
242
+ }
243
+ // ---- the kernel's calls ---------------------------------------------------------------------------------------------
244
+ /** A run of `revision` about to be made for agent `agentId`. It learns when the server's switch (`--learning`) is on and
245
+ * its agent's definition says `learning: true`; then its seed is read now, before the run is made, so the folder is
246
+ * read once whatever the run's setup does, and what comes back pins it in the run once it is made and its input
247
+ * saved (a server that goes down during the copy leaves no learning saved: onLoad), at `at`: its
248
+ * learning, `seeded`, or `dropped` as `seed_failed` (a learning fault never refuses a run). Undefined when it does
249
+ * not learn. What the run reads under `# Learned` is its notes within the server's learning budget, told of
250
+ * `.learning/` only when its agent has the read tool, and cut of the host's secrets as they are then. */
251
+ async onStart(agentId, revision) {
252
+ const learns = this.options.learning !== "off" && revision.kind === "agentic" && revision.body.learning === true;
253
+ if (!learns)
254
+ return undefined;
255
+ const read = revision.kind === "agentic" && revision.body.tools.includes("read");
256
+ const seeded = await this.seedFor(agentId);
257
+ return async (started, at) => {
258
+ let failed = "failed" in seeded ? seeded.failed : undefined;
259
+ if ("seed" in seeded) {
260
+ try {
261
+ const own = revision.kind === "agentic" ? Object.keys(revision.body.skills) : [];
262
+ const pin = await pinSeed(started.dir, started.workspace, seeded.seed, { budget: this.options.learningBudget ?? LEARNING_BUDGET, read, shown: this.shown(), own });
263
+ for (const path of seeded.seed.skipped)
264
+ warn(started.runId, `its learning folder's ${path} was not read`);
265
+ for (const name of pin.skills_left_out ?? [])
266
+ warn(started.runId, `starts without the skill ${name} its agent learned: it is over what is left of the learned skills' budget, or holds a secret`);
267
+ }
268
+ catch (error) {
269
+ warn(started.runId, `starts with nothing learned: ${error.message}`);
270
+ failed = said.stopped(STOPPED.notCopied);
271
+ }
272
+ }
273
+ const notes = "seed" in seeded ? Object.keys(seeded.seed.notes).length : 0;
274
+ return failed === undefined ? { state: "seeded", reason: null, detail: said.seeded(notes), at, seed_notes: notes } : { state: "dropped", reason: "seed_failed", detail: failed, at };
275
+ };
276
+ }
277
+ /** The run's serve.json holds `learning` now: the learning ledger's line for the run (usage.ts), once, when that
278
+ * learning has ended. Never rejects: a line not written is written by the next save, or by the next start's pass. */
279
+ onSaved(run, learning) {
280
+ if (ended(learning))
281
+ this.handed.delete(run.id);
282
+ if (!ended(learning) || this.recorded.has(run.id))
283
+ return Promise.resolve();
284
+ this.recorded.add(run.id);
285
+ return record(this.options.agents.dir, outcomeOf(run.id, run.agentId, learning)).catch((error) => {
286
+ this.recorded.delete(run.id);
287
+ warn(run.id, `its learning's end is not in the ledger yet: ${error.message}`);
288
+ });
289
+ }
290
+ /** The run's job ended with `end`. True when its end-of-run turn is asked first: the run is finishing with that
291
+ * outcome, and is let go once the turn ends. False when it is let go now, its learning dropped when it skips the turn. */
292
+ beforeFinish(run, end) {
293
+ const skip = this.reflectSkip(run, end);
294
+ if (skip === undefined) {
295
+ this.reflect(run, end.outcome);
296
+ return true;
297
+ }
298
+ if (skip)
299
+ this.dropLearning(run, ...skip);
300
+ return false;
301
+ }
302
+ /** A run read at a start, before the kernel holds it, `save` writing its serve.json: one a server went down while it
303
+ * copied the run's seed (running, its input saved and no learning, and a pin or a `work/.learning/` there) has both
304
+ * taken back, so it starts again with nothing learned, and its learning dropped as `seed_failed`, saved before the
305
+ * ledger's line (onSaved). Called before anything reads the run: its relaunch, a settle, a follow-up. A seed_failed
306
+ * run asks no end-of-run turn (reflectSkip). A copy that never began leaves nothing, and the learning stays null. */
307
+ async onLoad(row, dir, meta, save) {
308
+ if (row.state !== "running" || meta.learning || !(await dropSeed(dir, join(dir, "work"))))
309
+ return;
310
+ meta.learning = { state: "dropped", reason: "seed_failed", detail: said.stopped(STOPPED.serverStopped), at: new Date().toISOString() };
311
+ await save();
312
+ warn(row.id, "its server stopped while it copied what its agent learned; it starts again with nothing learned");
313
+ await this.onSaved({ id: row.id, agentId: row.agent }, meta.learning);
314
+ }
315
+ /** A run's process launched, handed the secrets named `names`: what each held then, as handover read it, kept beside
316
+ * the run while its learning is under way (a key replaced since stays refused in its notes). */
317
+ onLaunch(run, names) {
318
+ if (!run.meta.learning || ended(run.meta.learning))
319
+ return;
320
+ const values = names.flatMap((name) => secret(name, this.options.storedKeys) ?? []);
321
+ if (!values.length)
322
+ return;
323
+ const kept = this.handed.get(run.id) ?? new Set();
324
+ for (const value of values)
325
+ kept.add(value);
326
+ this.handed.set(run.id, kept);
327
+ }
328
+ /** A running run read at a start, `live` when its process serves it still. One a server left while its end-of-run turn
329
+ * ran is finishing with its job's outcome, and nothing opens it again; when its process lives, the turn is asked again
330
+ * under the same request id, which it takes once, and waited for. */
331
+ onAdopt(run, live) {
332
+ if (!reflecting(run))
333
+ return;
334
+ run.finishing = run.meta.reflect.outcome;
335
+ if (run.meta.error)
336
+ run.error = { ...run.meta.error, retryable: false };
337
+ if (live)
338
+ void this.reflectTurn(run);
339
+ }
340
+ /** The run's end being written: its end-of-run turn's rows closed, and its learning settled from how the turn went;
341
+ * then what the turn answered, and what the user said in the run, kept in its directory before the run reads ended,
342
+ * so a follow-up that opens it again never changes what is checked. */
343
+ async beforeSettle(run, outcome) {
344
+ this.closeLearning(run, outcome);
345
+ if (awaitsPropose(run.meta)) {
346
+ await keepTurn(run.dir, turnOf(run)).catch((error) => {
347
+ warn(run.id, `what its end-of-run turn answered could not be kept: ${error.message}`);
348
+ this.setLearning(run, "dropped", "propose_failed", said.stopped(STOPPED.notSetAside));
349
+ });
350
+ }
351
+ await this.noteUsed(run);
352
+ }
353
+ /** The run's end written, as it would be without learning: what its end-of-run turn wrote checked, then graded and
354
+ * merged. Called only then, so a slow or failing check never holds the job. A run already `proposed` is graded: one
355
+ * a follow-up opened again mid-grade, whose server went while it ran, which the next start passed over as running.
356
+ * gradeOnce does nothing for any other state, nor while a grade of the run is in flight here. */
357
+ afterSettle(run) {
358
+ const proposing = this.proposeOnce(run);
359
+ void this.gradeOnce(run);
360
+ return proposing;
361
+ }
362
+ /** A run that learns, opened again for a follow-up, before its process starts: `work/.learning/` laid again from its
363
+ * seed where the run took it away, so the follow-up finds the notes its instructions name where they say, and the
364
+ * learned skills its pin names laid again, fresh, so its process reads each where it was. A fault leaves it without. */
365
+ async onReopen(run) {
366
+ await learningTestHooks.beforeReopen?.(run.dir);
367
+ const dir = join(run.dir, "work", LEARNED_DIR);
368
+ if (!run.meta.reflect)
369
+ return;
370
+ try {
371
+ const pin = await readPin(run.dir);
372
+ if (pin && !(await lstat(dir).then(() => true, () => false)))
373
+ await layLearned(dir, await seedAt(this.options.agents.dir, run.agentId, pin.seed), this.shown());
374
+ if (pin)
375
+ await layPinnedSkills(join(run.dir, "work"), pin, () => skillsAt(this.options.agents.dir, run.agentId, pin.seed));
376
+ }
377
+ catch (error) {
378
+ warn(run.id, `opens again without its copy of what its agent learned: ${error.message}`);
379
+ }
380
+ }
381
+ /** Its process launched again for the follow-up: an end-of-run turn its process went in would resume with the run, so
382
+ * it is aborted before the follow-up is sent. One that cannot be aborted runs out ahead of it, and its rows are never
383
+ * the follow-up's answer, which comes after them. */
384
+ async afterReopen(run) {
385
+ if (run.meta.reflect && run.meta.learning?.reason === "crashed")
386
+ await this.kernel.toDoor(run, "/abort", {}).catch(() => undefined);
387
+ }
388
+ /** The server's start: the learning ledger read from now, beside the running runs' pass, never before it (a line
389
+ * written twice meanwhile is read once). What comes back takes every run once that pass is done: each ended run whose
390
+ * learning a server left between steps, what its end-of-run turn wrote not checked yet, or its proposal not graded or
391
+ * merged, is checked or graded now, once; a learning end saved and not in the ledger (a server that went between the
392
+ * two) is written there. */
393
+ recover() {
394
+ const inLedger = outcomes(this.options.agents.dir).catch(() => new Map());
395
+ return async (rows) => {
396
+ for (const run of (await inLedger).keys())
397
+ this.recorded.add(run);
398
+ for (const row of rows) {
399
+ if (this.closing)
400
+ return;
401
+ if (row.state === "running" || row.importedFrom || row.kind !== "agentic")
402
+ continue;
403
+ const meta = (await readJson(join(this.options.agents.dir, "runs", row.id, RUN_META)));
404
+ const learning = isObject(meta?.learning) ? meta.learning : undefined;
405
+ await this.onSaved({ id: row.id, agentId: row.agent }, learning);
406
+ if (!awaitsPropose(meta) && learning?.state !== "proposed")
407
+ continue;
408
+ const run = await this.kernel.get(row.id).catch((error) => (warn(row.id, `not read: ${error.message}; the next start tries again`), null));
409
+ if (run && awaitsPropose(run.meta))
410
+ await this.proposeOnce(run);
411
+ else if (run)
412
+ void this.gradeOnce(run);
413
+ }
414
+ };
415
+ }
416
+ /** The server closing: a grade's screen and grader stop, and leave the run's learning `proposed`; nothing new starts. */
417
+ close() {
418
+ this.stopping.abort();
419
+ this.handed.clear();
420
+ }
421
+ /** Once every run has settled: each check in flight, then each grade, ended. */
422
+ async idle() {
423
+ await Promise.all(this.proposing.values());
424
+ await Promise.all(this.grading.values());
425
+ }
426
+ /** A held run's learning, in short, from memory (null when it does not learn); undefined for a run the kernel does not
427
+ * hold. For a count, which reads the rest from the learning ledger and never a run's files. */
428
+ heldLearning(runId) {
429
+ const held = this.kernel.held(runId);
430
+ if (!held)
431
+ return undefined;
432
+ const learning = held.meta.learning;
433
+ return learning ? { state: learning.state, reason: learning.reason } : null;
434
+ }
435
+ /** The host's secrets as they are now, as a reader cuts them (secretsShown): the ones this server holds, the keys
436
+ * saved on it, and its tokens, as the learning routes cut them. Built again only once they change. Every run's view
437
+ * and every row of a list asks it, so the saved keys, which are read from their file and opened one by one, are read
438
+ * once and kept until a person saves or deletes one (keysChanged). */
439
+ shown() {
440
+ const saved = (this.saved ??= new Map(SECRET_NAMES.map((name) => [name, this.options.storedKeys?.(name)])));
441
+ const values = [...hostSecrets(process.env, (name) => saved.get(name)), this.options.token, this.options.doorToken];
442
+ const key = values.join("\0");
443
+ if (this.cut?.key !== key)
444
+ this.cut = { key, shown: secretsShown(values) };
445
+ return this.cut.shown;
446
+ }
447
+ /** A key was saved on this server or deleted from it: the next view reads them again. */
448
+ keysChanged() {
449
+ this.saved = undefined;
450
+ }
451
+ /** A run's learning as its view shows it (learning.ts learningView), cut of the host's secrets now; `settled`, once
452
+ * the run has ended and settled, shows the notes it read. */
453
+ view(learning, settled) {
454
+ return learning ? learningView(learning, this.shown(), settled) : null;
455
+ }
456
+ /** A run's learning as a list shows it (learning.ts shortLearning): from serve.json for a run the kernel does not hold. */
457
+ short(learning, settled) {
458
+ return shortLearning(learning, this.shown(), settled);
459
+ }
460
+ /** How the runs `rows` holds that tried to learn fared, over `filter` (learningStats): a held run's learning from
461
+ * memory, any other's end from the learning ledger, never a run's files. */
462
+ async counts(rows, filter) {
463
+ const ledger = await outcomes(this.options.agents.dir);
464
+ return learningStats(rows, filter, (row) => this.heldLearning(row.id) ?? ledger.get(row.id) ?? null);
465
+ }
466
+ /** Agent `agentId`'s runs (`rows`, its own) as its learning view counts them, the ledger read once: how they fared
467
+ * (counts, less `runs`), and what learning changed (learningImpact), each run's learning from memory when the kernel
468
+ * holds it, else its end from its ledger line; never a run's files. */
469
+ async ofAgent(rows, agentId) {
470
+ const ledger = await outcomes(this.options.agents.dir);
471
+ const learningOf = (row) => {
472
+ const held = this.kernel.held(row.id);
473
+ if (!held) {
474
+ const line = ledger.get(row.id);
475
+ return line ? { ...line, grade_usd: line.cost } : null;
476
+ }
477
+ const learning = held.meta.learning;
478
+ if (!learning)
479
+ return null;
480
+ // As its ledger line will say it (usage.ts outcomeOf): its grade's cost and its look-back's once it ended.
481
+ const over = ended(learning);
482
+ const { look_back_usd, ...rest } = learning;
483
+ return { ...rest, ...(over ? { grade_usd: learning.cost_usd ? learning.cost_usd.grade : 0 } : {}), ...(learning.answered_at !== undefined ? { look_back_usd } : over ? { look_back_usd: 0 } : {}) };
484
+ };
485
+ const { runs: _, ...counts } = learningStats(rows, { agent: agentId }, learningOf);
486
+ return { counts, impact: learningImpact(rows, learningOf) };
487
+ }
488
+ // ---- the run's learning ---------------------------------------------------------------------------------------------
489
+ /** What a run of `agentId` starts from: its learning folder's main (learning.ts), the folder made first when it is
490
+ * absent; else why it starts with nothing learned. A learning fault never refuses a run: a host without the git
491
+ * learning needs is said once, and a folder that cannot be made or read once per run. */
492
+ async seedFor(agentId) {
493
+ const blocked = await learningBlocker(process.env);
494
+ if (blocked) {
495
+ if (this.learningOff !== blocked)
496
+ process.stderr.write(`agentrun-serve: runs start with nothing learned: ${blocked}\n`);
497
+ this.learningOff = blocked;
498
+ return { failed: said.stopped(STOPPED.noGit) };
499
+ }
500
+ return seedOf(this.options.agents.dir, agentId).then((seed) => ({ seed }), (error) => {
501
+ process.stderr.write(`agentrun-serve: the agent ${agentId}'s learning folder could not be read, so its run starts with nothing learned: ${error.message}\n`);
502
+ return { failed: said.stopped(STOPPED.unreadable) };
503
+ });
504
+ }
505
+ /** Moves the run's learning on, and shows its row. What it keeps whatever it does after (learning.ts KEPT_LEARNING:
506
+ * the notes the run read, how many it started from, its answer's time and costs) stays with it. Saved by the caller,
507
+ * or with the run's end. */
508
+ setLearning(run, state, reason = null, detail = null, more = {}) {
509
+ const before = run.meta.learning;
510
+ const kept = Object.fromEntries(KEPT_LEARNING.flatMap((key) => (before?.[key] === undefined ? [] : [[key, before[key]]])));
511
+ run.meta.learning = { state, reason, detail, at: new Date().toISOString(), ...kept, ...more };
512
+ run.updatedAt = run.meta.learning.at;
513
+ this.kernel.show(run);
514
+ }
515
+ /** As the run settles, before its end is written: the notes its job read from its copy of the folder (notesRead), by
516
+ * their names in its seed, kept with its learning (`used`), so a view or a list reads them from serve.json and never
517
+ * from its rows again. Only a note the run started from counts: MEMORY.md, a file the run wrote there, and a note
518
+ * not in its seed are not notes it used. Read again at each settle, a follow-up's reads with the rest. A seed that
519
+ * cannot be read leaves what was there, and says why. */
520
+ async noteUsed(run) {
521
+ if (!run.meta.learning)
522
+ return;
523
+ const files = notesRead(run.meta.reflect, run.rows);
524
+ let used = [];
525
+ if (files.length) {
526
+ try {
527
+ const pin = await readPin(run.dir);
528
+ const names = new Map(pin ? activeOf(await seedAt(this.options.agents.dir, run.agentId, pin.seed)).map((note) => [note.file, note.name]) : []);
529
+ used = files.flatMap((file) => (names.has(file) ? [{ file, name: names.get(file) }] : []));
530
+ }
531
+ catch (error) {
532
+ return warn(run.id, `which notes it read is not known: ${error.message}`);
533
+ }
534
+ }
535
+ // As the learning is now: nothing else changed it meanwhile, but its object may be a new one.
536
+ const learning = run.meta.learning;
537
+ if (!learning)
538
+ return;
539
+ const { used: _, ...rest } = learning;
540
+ run.meta.learning = used.length ? { ...rest, used } : rest;
541
+ }
542
+ dropLearning(run, reason, detail) {
543
+ this.setLearning(run, "dropped", reason, detail);
544
+ void this.kernel.save(run).catch((error) => warn(run.id, `its learning's drop is not saved: ${error.message}`));
545
+ }
546
+ /** Why a run that just ended asks no end-of-run turn: a drop's reason and detail; null when it does not learn, or asked
547
+ * one already (one per run, ever); undefined when it asks one. The cap keeps no reserve: a run its cap stopped has no
548
+ * room left, and one whose spend is unknown cannot be kept within its cap. */
549
+ reflectSkip(run, end) {
550
+ if (run.meta.learning?.state !== "seeded" || run.meta.reflect)
551
+ return null;
552
+ if (run.cancel)
553
+ return ["cancelled", said.stopped(STOPPED.cancelled)];
554
+ if (end.abort || end.error?.code === SPEND_CAP_REACHED)
555
+ return ["no_budget", said.noBudget];
556
+ if (run.meta.max_cost_usd !== undefined && this.kernel.costOf(run.rows) === null)
557
+ return ["unknown_cost", said.unknownCost];
558
+ return undefined;
559
+ }
560
+ /** The run answered or failed: it is finishing with that outcome, and its harness is asked one end-of-run turn first.
561
+ * The turn is saved before it is asked, so a restart asks it again under the same id, never twice. */
562
+ reflect(run, outcome) {
563
+ run.finishing = outcome;
564
+ run.endedAt = new Date().toISOString();
565
+ const after = run.lastEntry ?? Math.max(0, ...run.rows.map((row) => entryOf(row.id)).filter(Number.isInteger));
566
+ run.meta.reflect = { outcome, after, deadline: new Date(Date.now() + (this.options.reflectTimeoutMs ?? REFLECT_TIMEOUT_MS)).toISOString() };
567
+ // The job's error, kept for a restart: the turn's is never the run's.
568
+ if (run.error)
569
+ run.meta.error = { code: run.error.code, message: run.error.message, ...(run.error.details ? { details: run.error.details } : {}) };
570
+ // Its answer is final now: when, and what its job cost, before the end-of-run turn spends any more.
571
+ this.setLearning(run, "reflecting", null, said.reflecting, { answered_at: run.endedAt, job_cost_usd: this.kernel.costOf(run.rows) });
572
+ this.kernel.mark(run);
573
+ void this.reflectTurn(run);
574
+ }
575
+ /** Asks the end-of-run turn through the run's door and waits for its end, its deadline (the turn is aborted) or the
576
+ * process to go; then lets the run go. The turn answers with its notes: it writes nothing, so nothing the run left in
577
+ * its copy of the folder counts. */
578
+ async reflectTurn(run) {
579
+ const reflect = run.meta.reflect;
580
+ let end = "gone";
581
+ try {
582
+ const pin = await readPin(run.dir);
583
+ if (!pin)
584
+ throw new Error("the run has no learning pin");
585
+ const seed = await seedAt(this.options.agents.dir, run.agentId, pin.seed);
586
+ await this.kernel.save(run);
587
+ const { reflectPrompt } = await import("./learn/index.js");
588
+ const tools = await this.draftTools(run);
589
+ // The one call that sends the end-of-run turn, with its origin.
590
+ await this.kernel.toLiveDoor(run, "/submit", { requestId: reflectId(run.id), content: reflectPrompt({ dir: LEARNED_DIR, active: Object.keys(seed.notes).length, tools }), whenBusy: "followUp" }, REFLECT_ORIGIN);
591
+ end = await this.reflectEnd(run, Date.parse(reflect.deadline));
592
+ }
593
+ catch (error) {
594
+ if (!this.kernel.live(run) || run.cancel)
595
+ return;
596
+ warn(run.id, `its end-of-run turn was not asked: ${error.message}`);
597
+ this.dropLearning(run, "reflect_failed", said.stopped(STOPPED.notAsked));
598
+ return this.kernel.terminate(run);
599
+ }
600
+ if (end === "gone")
601
+ return;
602
+ if (end === "ended")
603
+ reflect.ended = true;
604
+ else {
605
+ reflect.timedOut = true;
606
+ await this.kernel.abortTurn(run);
607
+ }
608
+ await this.kernel.save(run).catch((error) => warn(run.id, `its end-of-run turn's end is not saved: ${error.message}`));
609
+ this.kernel.terminate(run);
610
+ }
611
+ /** How the end-of-run turn ends: `ended` once the run's door says it is idle (the turn was taken before the submit was
612
+ * answered, so idle is after it), `timeout` at `deadline`, `gone` when the process went or the run was cancelled. */
613
+ async reflectEnd(run, deadline) {
614
+ for (;;) {
615
+ const status = await this.kernel.toLiveDoor(run, "/status").catch(() => null);
616
+ if (!this.kernel.live(run) || run.cancel)
617
+ return "gone";
618
+ if (isObject(status?.busy) && status.busy.kind === "idle")
619
+ return "ended";
620
+ if (Date.now() >= deadline)
621
+ return "timeout";
622
+ await sleep(REFLECT_POLL_MS);
623
+ }
624
+ }
625
+ /** At the run's end: the end-of-run turn's rows closed, and its learning settled from how the turn went. A run that
626
+ * never left `seeded` went before it could reflect. */
627
+ closeLearning(run, outcome) {
628
+ const { learning, reflect } = run.meta;
629
+ if (learning?.state === "seeded")
630
+ return this.setLearning(run, "dropped", ...(run.cancel || outcome === "cancelled" ? ["cancelled", said.stopped(STOPPED.cancelled)] : ["crashed", said.stopped(STOPPED.crashed)]));
631
+ if (!reflect || reflect.until !== undefined)
632
+ return;
633
+ reflect.until = run.lastEntry ?? reflect.after;
634
+ // The run ends now, when its end-of-run turn closed: `answered_at` keeps when its job answered, and the end the run's
635
+ // settle writes once (runs.ts carryBack) is this one, not the answer's.
636
+ run.endedAt = new Date().toISOString();
637
+ // What the turn cost: the run's cost now, its job's set apart; unknown when either is.
638
+ if (learning) {
639
+ const total = this.kernel.costOf(run.rows);
640
+ const job = learning.job_cost_usd;
641
+ run.meta.learning = { ...learning, look_back_usd: total === null || job === null || job === undefined ? null : Math.max(0, Math.round((total - job) * 1e9) / 1e9) };
642
+ }
643
+ if (learning?.state !== "reflecting")
644
+ return;
645
+ const last = run.rows.findLast((row) => row.agent_label === LEARNING_LABEL && shows(row));
646
+ if (run.cancel)
647
+ this.setLearning(run, "dropped", "cancelled", said.stopped(STOPPED.cancelledLooking));
648
+ else if (reflect.timedOut)
649
+ this.setLearning(run, "dropped", "reflect_timeout", said.stopped(STOPPED.timedOut));
650
+ else if (last?.kind === "error" && CAP_REFUSAL_PREFIX.test(last.text ?? ""))
651
+ this.setLearning(run, "dropped", "no_budget", said.noBudget);
652
+ else if (last?.kind === "error")
653
+ this.setLearning(run, "dropped", "reflect_failed", said.stopped(STOPPED.failed));
654
+ else if (!reflect.ended)
655
+ this.setLearning(run, "dropped", "crashed", said.stopped(STOPPED.crashedLooking));
656
+ else
657
+ this.setLearning(run, "reflecting", null, said.reflecting);
658
+ }
659
+ /** What the run's end-of-run turn wrote, checked and kept as its proposal or dropped (propose.ts), once at a time, after
660
+ * the run has ended. Never rejects: `proposed` or `dropped`, `propose_failed` for a fault. A server that goes
661
+ * meanwhile leaves it `reflecting` in serve.json, and the next start checks it again. */
662
+ proposeOnce(run) {
663
+ if (!awaitsPropose(run.meta))
664
+ return Promise.resolve();
665
+ return once(this.proposing, run.id, () => this.propose(run));
666
+ }
667
+ /** The tools a run's workflow draft may name: its revision's granted tools a workflow node runs here (tools.ts
668
+ * learnedWorkflowTools); none for a revision not found, so a draft that names one is refused. */
669
+ async draftTools(run) {
670
+ const known = await this.options.agents.revision(run.agentId, run.revision);
671
+ if (known?.revision.kind !== "agentic")
672
+ return [];
673
+ const { learnedWorkflowTools } = await import("./tools.js");
674
+ return learnedWorkflowTools(known.revision.body.tools);
675
+ }
676
+ async propose(run) {
677
+ try {
678
+ await learningTestHooks.beforePropose?.(run.dir);
679
+ const pin = await readPin(run.dir);
680
+ if (!pin)
681
+ throw new Error("the run has no learning pin");
682
+ const { proposeRun } = await import("./propose.js");
683
+ // The secrets this server holds, wherever its launcher put them, the keys saved on it, what each launch handed the
684
+ // run, and its own tokens. How the job ended, before its end-of-run turn: only a completed run keeps a skill.
685
+ const proposed = await proposeRun({ data: this.options.agents.dir, agentId: run.agentId, runDir: run.dir, seed: pin.seed, turn: await readTurn(run.dir), refuse: this.refused(run), ...(run.meta.reflect ? { outcome: run.meta.reflect.outcome } : {}), tools: await this.draftTools(run) });
686
+ if (proposed.state === "proposed")
687
+ this.setLearning(run, "proposed", null, said.proposed(proposed.notes, proposed.skills, proposed.workflows));
688
+ else if (proposed.reason === "empty")
689
+ this.setLearning(run, "dropped", "empty", said.empty);
690
+ else if (proposed.reason === "unparsed") {
691
+ warn(run.id, `its end-of-run turn's answer was not read: ${proposed.detail}`);
692
+ this.setLearning(run, "dropped", "unparsed", said.unparsed);
693
+ }
694
+ else
695
+ this.setLearning(run, "dropped", "checker", said.checker(proposed.problems), { problems: proposed.problems });
696
+ }
697
+ catch (error) {
698
+ warn(run.id, `what its end-of-run turn answered could not be checked: ${error.message}`);
699
+ this.setLearning(run, "dropped", "propose_failed", said.stopped(STOPPED.notChecked));
700
+ }
701
+ await this.kernel.save(run).catch((error) => warn(run.id, `its learning is not saved: ${error.message}`));
702
+ void this.gradeOnce(run);
703
+ }
704
+ /** The run's proposal merged into main or dropped (grade.ts), one grade at a time per agent, after the checks and
705
+ * never in a run's way. The verdict and what the grade spent are kept in serve.json before the merge, so a restart
706
+ * never asks the grader again; what it spent is in the ledger with the run's end. A server that closes mid-grade leaves the
707
+ * learning `proposed`, and its next start grades it. */
708
+ gradeOnce(run) {
709
+ if (run.meta.learning?.state !== "proposed")
710
+ return Promise.resolve();
711
+ return once(this.grading, run.id, () => withAgentGrade(this.options.agents.dir, run.agentId, () => this.grade(run)));
712
+ }
713
+ async grade(run) {
714
+ const before = run.meta.learning;
715
+ if (before?.state !== "proposed" || this.closing)
716
+ return;
717
+ const data = this.options.agents.dir;
718
+ let kept = before.verdict ? { verdict: before.verdict, graded: before.graded, cost_usd: before.cost_usd, tokens: before.tokens } : {};
719
+ // Its end saved, and with it its line in the ledger, which carries what the grade spent (onSaved).
720
+ const end = (state, reason, detail, more = {}) => {
721
+ this.setLearning(run, state, reason, detail, { ...kept, ...more });
722
+ return this.kernel.save(run).catch((error) => warn(run.id, `its learning is not saved: ${error.message}`));
723
+ };
724
+ try {
725
+ const proposal = JSON.parse(await readFile(join(run.dir, PROPOSAL), "utf8"));
726
+ const known = await this.options.agents.revision(run.agentId, run.revision);
727
+ if (known?.revision.kind !== "agentic")
728
+ throw new Error("the run's revision is not agentic");
729
+ const { judgeProposal, mergeProposal, readForGrade } = await import("./grade.js");
730
+ const main = kept.verdict ? undefined : await readForGrade(data, run.agentId, run.id, proposal);
731
+ // Main took a note of the same name, or superseded one it supersedes, since the run started: refused before the
732
+ // grader is asked.
733
+ if (main && "problems" in main)
734
+ return await end("dropped", "checker", said.stale(main.problems), { problems: main.problems });
735
+ if (main && !("merged" in main)) {
736
+ const { instructions, harness, model, thinking } = known.revision.body;
737
+ const env = this.hostEnv();
738
+ const gradeModel = gradeModelOf(env, this.options.gradeModel);
739
+ const judged = await judgeProposal({ runId: run.id, agent: { instructions, harness, model, thinking }, main, proposed: proposal.notes, ...(proposal.files ? { files: proposal.files } : {}), ...(proposal.asked ? { asked: proposal.asked } : {}), ...(gradeModel ? { gradeModel } : {}), env, signal: this.stopping.signal, ...(this.options.gradeTimeoutMs ? { gradeTimeoutMs: this.options.gradeTimeoutMs } : {}) });
740
+ kept = { cost_usd: { grade: judged.cost.usd }, tokens: { grade: judged.cost.tokens } };
741
+ if ("file" in judged)
742
+ return await end("dropped", judged.reason, judged.reason === "screen" ? said.screen : said.stopped(STOPPED.screenDown));
743
+ if ("error" in judged) {
744
+ warn(run.id, `its grader gave no verdict: ${judged.error.message}`);
745
+ return await end("dropped", "grade_failed", said.stopped(STOPPED.noReview));
746
+ }
747
+ // Kept cut of every secret the run's notes were checked against, the keys its launches handed it included, which a
748
+ // read no longer knows: its reason and its items' words are what the run's words are said from again (wordsOf).
749
+ kept.verdict = cutVerdict(judged.verdict, this.refused(run));
750
+ if (!kept.verdict.merge)
751
+ return await end("dropped", "grader", notKept(kept.verdict));
752
+ // Kept before the merge, with the blobs it judged superseded: a restart merges on this verdict, never asks the
753
+ // grader again, and checks the same blobs.
754
+ kept.graded = main.graded;
755
+ this.setLearning(run, "proposed", null, before.detail, kept);
756
+ await this.kernel.save(run);
757
+ }
758
+ // A verdict kept with no `graded`: a note the proposal supersedes is refused, never marked on a text nobody knows
759
+ // was read.
760
+ const merge = await mergeProposal(data, run.agentId, run.id, proposal, kept.verdict?.reason || "The grader kept every new note.", kept.graded ?? {}, kept.verdict);
761
+ if ("problems" in merge)
762
+ return await end("dropped", "checker", said.stale(merge.problems), { problems: merge.problems });
763
+ if (merge.checkout)
764
+ warn(run.id, `its merge is on main, but the folder's files were not brought in line: ${merge.checkout.message}`);
765
+ // A note the user asked for whose rule is risky waits on main for their OK: named here, and no run reads it yet.
766
+ const waiting = new Set((kept.verdict?.items ?? []).filter((item) => item.pending).map((item) => item.file));
767
+ const pending = proposal.notes.filter(({ file }) => waiting.has(file)).map(({ file, text }) => ({ file, name: nameOf(file, text) }));
768
+ // What it learned: the notes it added that runs read, a note that waits for its OK not among them; and its skill
769
+ // and workflow draft, each pending when it waits.
770
+ const learned = learnedOf(proposal).filter(({ file }) => !waiting.has(file));
771
+ const made = (suffix) => (proposal.files ?? []).filter(({ file }) => file.endsWith(suffix)).map(({ file }) => ({ file, name: file.split("/")[1], ...(waiting.has(file) ? { pending: true } : {}) }));
772
+ const skills = made("/SKILL.md");
773
+ const workflows = made("/workflow.json");
774
+ await end("merged", null, redactSecrets(said.merged(learned, pending, [...skills, ...workflows]), this.refused(run)), { merged: merge.merged, learned, ...(pending.length ? { pending } : {}), ...(skills.length ? { skills } : {}), ...(workflows.length ? { workflows } : {}) });
775
+ }
776
+ catch (error) {
777
+ // A server closing: nothing was decided, and the next start grades the run.
778
+ if (this.closing)
779
+ return;
780
+ warn(run.id, `what it proposed could not be graded: ${error.message}`);
781
+ await end("dropped", "grade_failed", said.stopped(STOPPED.notReviewed));
782
+ }
783
+ }
784
+ /** What a run's learning refuses, and cuts from what it says: the secrets this server holds, wherever its launcher put
785
+ * them, the keys saved on it, what each launch handed the run, and its own tokens. */
786
+ refused(run) {
787
+ // The run's own door token too: its process holds it, so its notes may.
788
+ const own = run.doorToken ?? runDoorToken(run.dir);
789
+ return [...hostSecrets(process.env, this.options.storedKeys), ...(this.handed.get(run.id) ?? []), this.options.token, this.options.doorToken, ...(own ? [own] : [])];
790
+ }
791
+ /** This server's environment for a call of its own (a grade's screen and grader): its secrets readable, never a
792
+ * child's, the keys saved on it with them (a Jev key saved through the settings API screens as one in the environment
793
+ * does), and the test hooks a run's process gets. */
794
+ hostEnv() {
795
+ return withSecrets({ ...withoutFaux(process.env), ...this.kernel.fauxEnv() }, "all", this.options.storedKeys);
796
+ }
797
+ }