@parcha/agentrun-serve 0.1.0-beta.44 → 0.1.0-beta.45

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 (346) hide show
  1. package/CHANGELOG.md +131 -5
  2. package/README.md +371 -300
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +52 -16
  28. package/dist/composio-preset.js +69 -7
  29. package/dist/composio-triggers.d.ts +14 -0
  30. package/dist/composio-triggers.js +79 -15
  31. package/dist/computer-attach.d.ts +40 -5
  32. package/dist/computer-attach.js +130 -15
  33. package/dist/computer-keys.d.ts +3 -0
  34. package/dist/computer-keys.js +7 -1
  35. package/dist/computer-live.js +3 -2
  36. package/dist/computers.d.ts +21 -10
  37. package/dist/computers.js +39 -28
  38. package/dist/console/assets/index-3O2Yl6hZ.js +701 -0
  39. package/dist/console/assets/index-DaFsZuzQ.css +1 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/decisions.d.ts +1 -1
  42. package/dist/dial-relay.d.ts +29 -0
  43. package/dist/dial-relay.js +94 -0
  44. package/dist/email/tools.js +10 -5
  45. package/dist/env-proxy.d.ts +2 -0
  46. package/dist/env-proxy.js +35 -0
  47. package/dist/errors.d.ts +3 -1
  48. package/dist/errors.js +7 -4
  49. package/dist/faux-computers.d.ts +8 -2
  50. package/dist/faux-computers.js +83 -6
  51. package/dist/harness-archive.d.ts +67 -0
  52. package/dist/harness-archive.js +177 -0
  53. package/dist/harness-goose.d.ts +34 -0
  54. package/dist/harness-goose.js +87 -0
  55. package/dist/harness-install.d.ts +21 -0
  56. package/dist/harness-install.js +24 -11
  57. package/dist/harness-opencode/adapter.js +1 -1
  58. package/dist/harness-table.d.ts +9 -1
  59. package/dist/harness-table.js +20 -3
  60. package/dist/harness.d.ts +1 -2
  61. package/dist/harness.js +3 -4
  62. package/dist/host.js +2 -1
  63. package/dist/key-check.js +3 -0
  64. package/dist/learn/audit.d.ts +6 -6
  65. package/dist/learn/audit.js +3 -7
  66. package/dist/learn/check.d.ts +23 -89
  67. package/dist/learn/check.js +57 -335
  68. package/dist/learn/commit.d.ts +63 -90
  69. package/dist/learn/commit.js +124 -316
  70. package/dist/learn/compile.d.ts +53 -50
  71. package/dist/learn/compile.js +87 -102
  72. package/dist/learn/corrections.d.ts +13 -0
  73. package/dist/learn/corrections.js +23 -0
  74. package/dist/learn/delete.d.ts +5 -5
  75. package/dist/learn/delete.js +8 -10
  76. package/dist/learn/folder.d.ts +35 -47
  77. package/dist/learn/folder.js +118 -134
  78. package/dist/learn/index.d.ts +3 -5
  79. package/dist/learn/index.js +6 -9
  80. package/dist/learn/learning.sh +45 -15
  81. package/dist/learn/promote.d.ts +13 -1
  82. package/dist/learn/promote.js +9 -0
  83. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
  84. package/dist/learn/{skills.js → workflow-draft.js} +48 -58
  85. package/dist/learn/workflow-nodes.js +1 -1
  86. package/dist/learned-workflow.js +2 -2
  87. package/dist/learning-cost.d.ts +38 -24
  88. package/dist/learning-cost.js +41 -24
  89. package/dist/learning-routes.d.ts +91 -170
  90. package/dist/learning-routes.js +183 -421
  91. package/dist/learning-run.d.ts +19 -40
  92. package/dist/learning-run.js +23 -93
  93. package/dist/learning-setting.d.ts +4 -4
  94. package/dist/learning-setting.js +6 -6
  95. package/dist/learning-words.d.ts +28 -74
  96. package/dist/learning-words.js +64 -162
  97. package/dist/learning.d.ts +61 -392
  98. package/dist/learning.js +101 -651
  99. package/dist/live-reach.d.ts +25 -2
  100. package/dist/live-reach.js +46 -4
  101. package/dist/llms.txt +1 -1
  102. package/dist/local-models.d.ts +3 -11
  103. package/dist/local-models.js +5 -6
  104. package/dist/mcp-servers-store.d.ts +4 -4
  105. package/dist/model-form.js +6 -5
  106. package/dist/model.d.ts +4 -0
  107. package/dist/model.js +26 -9
  108. package/dist/native/binding.js +1 -1
  109. package/dist/native/connection.js +1 -1
  110. package/dist/native/discovery.js +1 -1
  111. package/dist/native/instructions.d.ts +3 -0
  112. package/dist/native/instructions.js +5 -3
  113. package/dist/native/remote-worker-bridge.js +9 -43
  114. package/dist/native/remote.d.ts +8 -15
  115. package/dist/native/remote.js +3 -3
  116. package/dist/native/schema.js +1 -1
  117. package/dist/native/types.d.ts +2 -2
  118. package/dist/openapi.js +268 -316
  119. package/dist/paid-calls.d.ts +8 -0
  120. package/dist/paid-calls.js +20 -0
  121. package/dist/particle-provider.d.ts +11 -0
  122. package/dist/particle-provider.js +135 -0
  123. package/dist/port-models.d.ts +12 -4
  124. package/dist/port-models.js +28 -11
  125. package/dist/print.d.ts +27 -0
  126. package/dist/print.js +21 -0
  127. package/dist/provider.d.ts +7 -0
  128. package/dist/provider.js +15 -1
  129. package/dist/reflect-range.js +2 -3
  130. package/dist/run-launch.d.ts +14 -28
  131. package/dist/run-launch.js +9 -12
  132. package/dist/run-learning-served.d.ts +15 -89
  133. package/dist/run-listing.d.ts +34 -0
  134. package/dist/run-listing.js +128 -0
  135. package/dist/run-model-key.js +1 -1
  136. package/dist/run-timeline-served.js +5 -3
  137. package/dist/run-trace.d.ts +97 -0
  138. package/dist/run-trace.js +253 -0
  139. package/dist/run-view.d.ts +15 -0
  140. package/dist/run-view.js +9 -0
  141. package/dist/runnable.js +2 -1
  142. package/dist/runner/adapter-loop.d.ts +8 -6
  143. package/dist/runner/adapter-loop.js +16 -12
  144. package/dist/runner/adapter-run-spec.d.ts +16 -4
  145. package/dist/runner/adapter-run-spec.js +64 -58
  146. package/dist/runner/adapters/index.js +22 -0
  147. package/dist/runner/adapters/pi.d.ts +4 -12
  148. package/dist/runner/adapters/pi.js +2 -2
  149. package/dist/runner/audit.d.ts +1 -1
  150. package/dist/runner/audit.js +16 -8
  151. package/dist/runner/beside.d.ts +6 -2
  152. package/dist/runner/beside.js +38 -9
  153. package/dist/runner/claim-secrets.d.ts +18 -2
  154. package/dist/runner/claim-secrets.js +42 -18
  155. package/dist/runner/cli-run-spec.js +55 -51
  156. package/dist/runner/conformance/harness.d.ts +6 -0
  157. package/dist/runner/conformance/harness.js +16 -5
  158. package/dist/runner/dispatch.d.ts +2 -2
  159. package/dist/runner/end-of-run.d.ts +6 -14
  160. package/dist/runner/end-of-run.js +8 -33
  161. package/dist/runner/feedback-round.d.ts +2 -2
  162. package/dist/runner/feedback-round.js +7 -7
  163. package/dist/runner/github-app.js +3 -1
  164. package/dist/runner/harness-loops.d.ts +0 -8
  165. package/dist/runner/harness-loops.js +11 -59
  166. package/dist/runner/held.d.ts +170 -0
  167. package/dist/runner/held.js +57 -0
  168. package/dist/runner/journal-kinds.d.ts +2 -3
  169. package/dist/runner/journal-kinds.js +2 -3
  170. package/dist/runner/learned-first.d.ts +40 -0
  171. package/dist/runner/learned-first.js +32 -0
  172. package/dist/runner/learning-end.d.ts +77 -69
  173. package/dist/runner/learning-end.js +250 -303
  174. package/dist/runner/learning-seed.d.ts +15 -33
  175. package/dist/runner/learning-seed.js +24 -45
  176. package/dist/runner/loop-contract.d.ts +2 -3
  177. package/dist/runner/main.d.ts +17 -9
  178. package/dist/runner/main.js +63 -20
  179. package/dist/runner/mcp-run.d.ts +11 -0
  180. package/dist/runner/mcp-run.js +67 -0
  181. package/dist/runner/memory-claim.d.ts +10 -5
  182. package/dist/runner/memory-claim.js +12 -6
  183. package/dist/runner/model-route.d.ts +7 -4
  184. package/dist/runner/model-route.js +22 -10
  185. package/dist/runner/native-loop.d.ts +0 -7
  186. package/dist/runner/native-loop.js +9 -101
  187. package/dist/runner/promotion.d.ts +8 -6
  188. package/dist/runner/promotion.js +19 -12
  189. package/dist/runner/reflect-hook.d.ts +64 -95
  190. package/dist/runner/reflect-hook.js +112 -225
  191. package/dist/runner/run-channel.d.ts +43 -0
  192. package/dist/runner/run-channel.js +467 -0
  193. package/dist/runner/run-child-host.d.ts +169 -0
  194. package/dist/runner/run-child-host.js +1222 -0
  195. package/dist/runner/run-child.d.ts +1 -0
  196. package/dist/runner/run-child.js +254 -0
  197. package/dist/runner/run-errors.d.ts +2 -0
  198. package/dist/runner/run-errors.js +20 -0
  199. package/dist/runner/runner.js +1 -5
  200. package/dist/runner/sdk-ask.d.ts +78 -0
  201. package/dist/runner/sdk-ask.js +158 -0
  202. package/dist/runner/sdk-loop.d.ts +2 -4
  203. package/dist/runner/sdk-loop.js +29 -49
  204. package/dist/runner/store-secrets.d.ts +5 -3
  205. package/dist/runner/store-secrets.js +5 -1
  206. package/dist/runner/workflow-first.d.ts +5 -0
  207. package/dist/runner/workflow-first.js +4 -0
  208. package/dist/runner/workflow-spec.js +7 -2
  209. package/dist/runs-over-store.d.ts +16 -28
  210. package/dist/runs-over-store.js +31 -38
  211. package/dist/sdk/runs.d.ts +6 -11
  212. package/dist/sdk/runs.js +20 -41
  213. package/dist/sdk/schema.js +3 -4
  214. package/dist/seal-key.d.ts +5 -0
  215. package/dist/seal-key.js +7 -0
  216. package/dist/secrets.d.ts +3 -0
  217. package/dist/secrets.js +16 -3
  218. package/dist/server.d.ts +55 -33
  219. package/dist/server.js +685 -320
  220. package/dist/sign-ins-store.d.ts +8 -0
  221. package/dist/sign-ins-store.js +36 -1
  222. package/dist/skills.js +1 -1
  223. package/dist/store/index.d.ts +2 -2
  224. package/dist/store/index.js +1 -1
  225. package/dist/store/journal/storage.js +3 -0
  226. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  227. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  228. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  229. package/dist/store/schema.d.ts +53 -4
  230. package/dist/store/schema.js +137 -6
  231. package/dist/store/sqlite/connection.d.ts +2 -0
  232. package/dist/store/sqlite/connection.js +3 -1
  233. package/dist/store/sqlite/run-patch.d.ts +0 -17
  234. package/dist/store/sqlite/run-patch.js +4 -33
  235. package/dist/store/sqlite/store.js +246 -63
  236. package/dist/store/sqlite/worker.js +25 -0
  237. package/dist/store/store.d.ts +193 -36
  238. package/dist/store/store.js +25 -3
  239. package/dist/store-reads/learning.d.ts +102 -204
  240. package/dist/store-reads/learning.js +159 -321
  241. package/dist/store-reads/loop.d.ts +0 -1
  242. package/dist/store-reads/loop.js +1 -1
  243. package/dist/store-view.d.ts +29 -1
  244. package/dist/store-view.js +97 -31
  245. package/dist/template-eval.d.ts +3 -6
  246. package/dist/template-eval.js +22 -36
  247. package/dist/templates.d.ts +2 -1
  248. package/dist/templates.js +6 -3
  249. package/dist/timeline/index.d.ts +1 -1
  250. package/dist/timeline/index.js +1 -1
  251. package/dist/timeline/timeline.d.ts +5 -1
  252. package/dist/timeline/timeline.js +16 -0
  253. package/dist/tool-gate.d.ts +0 -7
  254. package/dist/tool-gate.js +1 -15
  255. package/dist/tool-keys-store.d.ts +1 -1
  256. package/dist/tool-keys.d.ts +6 -4
  257. package/dist/tool-keys.js +12 -6
  258. package/dist/tools.d.ts +2 -2
  259. package/dist/tools.js +11 -4
  260. package/dist/triggers.d.ts +60 -5
  261. package/dist/triggers.js +123 -18
  262. package/dist/validate.js +1 -1
  263. package/dist/webhooks.d.ts +4 -1
  264. package/dist/webhooks.js +11 -4
  265. package/dist/workspace/agent-computer.d.ts +2 -0
  266. package/dist/workspace/agent-computer.js +2 -0
  267. package/dist/workspace/archil-claim.d.ts +7 -0
  268. package/dist/workspace/archil-claim.js +29 -0
  269. package/dist/workspace/archil.d.ts +9 -1
  270. package/dist/workspace/archil.js +165 -3
  271. package/dist/workspace/attach.d.ts +3 -1
  272. package/dist/workspace/attach.js +2 -0
  273. package/dist/workspace/attached-computers.d.ts +16 -5
  274. package/dist/workspace/attached-computers.js +25 -9
  275. package/dist/workspace/computer-deps.js +1 -1
  276. package/dist/workspace/computer-for-claim.d.ts +7 -3
  277. package/dist/workspace/computer-for-claim.js +119 -22
  278. package/dist/workspace/computer-hold.js +2 -1
  279. package/dist/workspace/computer-kept.d.ts +11 -1
  280. package/dist/workspace/computer-kept.js +24 -3
  281. package/dist/workspace/resolve-computer.d.ts +33 -19
  282. package/dist/workspace/resolve-computer.js +172 -64
  283. package/dist/workspace/revision-skills.d.ts +1 -2
  284. package/dist/workspace/revision-skills.js +3 -4
  285. package/dist/workspace/run-workspace.d.ts +1 -1
  286. package/dist/workspace/run-workspace.js +5 -0
  287. package/dist/workspace/synced-folder.d.ts +85 -0
  288. package/dist/workspace/synced-folder.js +230 -0
  289. package/dist/workspace/workspace.d.ts +4 -0
  290. package/launcher/agentrun-serve +1 -1
  291. package/package.json +10 -10
  292. package/templates/README.md +7 -7
  293. package/templates/inbound-lead/agent.md +3 -3
  294. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  295. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  296. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  297. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  298. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  299. package/templates/inbound-lead/lead.schema.json +6 -5
  300. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  301. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  302. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  303. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  304. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  305. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  306. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  307. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  308. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  309. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  310. package/dist/console/assets/index-BUktRvS-.css +0 -1
  311. package/dist/console/assets/index-nB9kTfIN.js +0 -711
  312. package/dist/learn/grade.d.ts +0 -138
  313. package/dist/learn/grade.js +0 -682
  314. package/dist/learn/notes.d.ts +0 -81
  315. package/dist/learn/notes.js +0 -178
  316. package/dist/learn/reflect.d.ts +0 -77
  317. package/dist/learn/reflect.js +0 -228
  318. package/dist/learn/relevance.d.ts +0 -24
  319. package/dist/learn/relevance.js +0 -91
  320. package/dist/learn/seed-check.d.ts +0 -74
  321. package/dist/learn/seed-check.js +0 -103
  322. package/dist/learning-batch.d.ts +0 -291
  323. package/dist/learning-batch.js +0 -600
  324. package/dist/learning-evals.d.ts +0 -35
  325. package/dist/learning-evals.js +0 -99
  326. package/dist/native/context.d.ts +0 -6
  327. package/dist/native/context.js +0 -22
  328. package/dist/propose.d.ts +0 -52
  329. package/dist/propose.js +0 -224
  330. package/dist/runner/learning-ask.d.ts +0 -47
  331. package/dist/runner/learning-ask.js +0 -128
  332. package/dist/runner/learning-dispatch.d.ts +0 -45
  333. package/dist/runner/learning-dispatch.js +0 -99
  334. package/dist/runner/learning-factory.d.ts +0 -16
  335. package/dist/runner/learning-factory.js +0 -50
  336. package/dist/runner/learning-loop.d.ts +0 -273
  337. package/dist/runner/learning-loop.js +0 -521
  338. package/dist/usage.d.ts +0 -11
  339. package/dist/usage.js +0 -11
  340. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  341. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  342. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  343. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  344. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  345. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  346. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -1,37 +1,17 @@
1
- // What a person sees and controls of an agent's learning: this server's own routes under /v2 (learning/1).
2
- // - Per agent: main's index, its notes and its log of changes, each a page, its skills and workflow drafts, and how its
3
- // runs' learning fared; one note, a skill's SKILL.md or a draft's file as text with its ETag, its blob id on main.
4
- // - A person's approval of a note, a skill or a draft that waits for the owner's OK, and their edit, create or retire of
5
- // one note (a skill or a draft is a run's to change): a precondition on the note's version (If-Match, or If-None-Match: * to
6
- // create; neither is 428), the structural checks a run's notes pass (learn/check.ts checkNote; a retire, the note's
7
- // format alone, so a leaking note can always be revoked) and no grader, then one commit on main by the learning
8
- // script (learn/folder.ts writeLearning: one exec, compare and swap), with MEMORY.md rebuilt and a `Changed-By: user`
9
- // trailer, the checked-out files brought in line and the snapshot written. MEMORY.md itself is never written here.
10
- // - Per run: its learning whole, and its diff: what it proposed against its seed, or once merged, its merge commit against
11
- // its parent, as its merge's script wrote it (`.agentrun/diffs/<run>.json`).
12
- // Every read is the folder's snapshot (`.agentrun/snapshot.json`), the working-tree bodies it names, each checked against
13
- // its blob id, and the diff files, through the folder's Workspace file API: no git and no exec (learn/folder.ts
14
- // readLearning). A body that is not the snapshot's, twice, is a write in flight: 503. A page's cursor names the main it
15
- // was read at; a later page is read at that main while this server still holds its snapshot, else as the first page of
16
- // main now. A text that leaves holding one of the host's secrets as they are now (a value made secret after it was
17
- // written) is cut of it, a file's name holding one reads "[redacted]" whole, and a diff's file holding one is withheld.
18
- import { noteBytes } from "./learn/check.js";
19
1
  import { createHash } from "node:crypto";
20
- import { approve, buildIndex, CAPS, checkNote, draftProblems, frontKeys, INDEX_FILE, INDEX_LINES, isHeld, LEARNED_KEYS, learnedName, learnedPlace, learnedStatus, NOTE_FILE, NOTE_STATUSES, parseNoteFile, printable, released, retire, retiredLearned, skillProblems, SKILLS_DIR, supersede, UNCLEAR_FRONT, unstorable, WORKFLOWS_DIR, unclearFront, restorable, restore, restoredLearned } from "./learn/index.js";
21
- import { blobOid, FolderBusy, FolderRefused, FolderTooLarge, FolderUnreadable, heldOnMain, isBodyMismatch, readLearning, PATCH_CAP, readRunDiff, readSnapshot, runDiffKey, snapshotNotes, textsAt, writeLearning } from "./learn/folder.js";
2
+ import { CORRECTIONS_CAP, draftProblems, frontKeys, isHeld, LEARNED_KEYS, learnedPlace, learnedStatus, printable, released, restorable, restoredLearned, retiredLearned, UNCLEAR_FRONT, unclearFront, unstorable, WORKFLOW_NAME, WORKFLOWS_DIR } from "./learn/index.js";
3
+ import { readmeProblems } from "./learn/workflow-draft.js";
4
+ import { putCorrections, readCorrections } from "./learn/commit.js";
5
+ import { blobOid, FolderBusy, FolderRefused, FolderTooLarge, FolderUnreadable, readLearning, PATCH_CAP, readRunDiff, readSnapshot, runDiffKey, textsAt, writeLearning } from "./learn/folder.js";
22
6
  import { ApiError, invalid } from "./errors.js";
23
- import { detailShown, learningFolderOf, notesView, reasonShown, secretsShown, withAgentRepo } from "./learning.js";
7
+ import { detailShown, filesView, learningFolderOf, reasonShown, withAgentRepo } from "./learning.js";
24
8
  import { isObject } from "./validate.js";
25
9
  import { launchOf } from "./handed-values.js";
26
10
  import { learningStartOf } from "./run-launch.js";
27
11
  import { runLearningEnd } from "./store-reads/learning.js";
28
- /** The agent view's first pages, and the most a page holds. */
29
- const NOTES_PAGE = 50;
12
+ /** The agent view's first page of its log, and the most a page holds. */
30
13
  const LOG_PAGE = 20;
31
14
  const PAGE_MAX = 200;
32
- /** What a retire adds to a note, on top of the note cap a retired note may fill (learn/notes.ts retire). */
33
- /** What a retire adds to a note: its status line and the status it took it from (the longer of the two). */
34
- const RETIRED_LINE = Buffer.byteLength("status: retired\nretired_from: pending\n");
35
15
  export { secretsShown } from "./learning.js";
36
16
  /** The few values last kept, by key, oldest dropped first: at most `entries` of them. */
37
17
  class Recent {
@@ -88,24 +68,16 @@ async function reading(data, agentId, read, none) {
88
68
  await end();
89
69
  }
90
70
  }
91
- /** A retired item's `retired`: its newest retire by a person; else, one a person made retired another way (an edit to
92
- * status: retired, or created so), their newest change; else (retired by none of theirs) its newest change's time. */
93
- /** `from`: the status its restore gives back (its retire recorded it, retired_from; none recorded reads pending, as its
94
- * restore gives it: only an approval makes an item active). `unread`: the host could not read its file. */
71
+ /** A retired draft's `retired`: its newest retire by a person; else, one a person made retired another way, their
72
+ * newest change; else its newest change's time. `from`: the status its restore gives back (its retire recorded it,
73
+ * retired_from; none recorded reads pending). `unread`: the host could not read its README.md. */
95
74
  const retiredOf = (history, from, unread = false) => (unread ? { at: history.at, by: "host", why: "unreadable" } : { ...(history.retire ? { at: history.retire.at, by: "person" } : history.person ? { at: history.person.at, by: "person" } : { at: history.at, by: "run" }), from: from ?? "pending" });
96
- /** A note as the view shows it, cut of the host's secrets: its name and the one that superseded it whole; with its
97
- * ETag, the one its file's GET answers, so an edit or a retire from the card names the version it shows; its last
98
- * change, and when and by whom it was retired on a retired one. */
99
- const noteView = (note, text, shown, runs) => ({
100
- file: shown.name(note.file), name: shown.text(note.name), description: shown.text(note.description), type: note.type, status: note.status, origin: note.origin, superseded_by: note.superseded_by === null ? null : shown.name(note.superseded_by), text: shown.text(text), etag: etagOf(note.oid), runs: { ...(runs.get(note.file) ?? { given: 0, read: 0 }) },
101
- ...(note.history.last ? { last_change: note.history.last } : {}),
102
- ...(note.status === "retired" ? { retired: retiredOf(note.history, note.retired_from) } : {}),
103
- });
104
- function learnedView(item, kind, shown, unread = false) {
105
- const file = kind === "skill" ? item.file : `${WORKFLOWS_DIR}/${item.name}/workflow.json`;
75
+ function workflowView(item, shown, stateOf, unread = false) {
76
+ const file = `${WORKFLOWS_DIR}/${item.name}/workflow.json`;
106
77
  const bytes = item.files.find(({ path }) => path === file)?.bytes ?? item.bytes;
78
+ const status = item.status === "active" ? stateOf(item.name) : item.status;
107
79
  return {
108
- name: shown.name(item.name), file: shown.name(file), ...(kind === "workflow" ? { readme: shown.name(item.file) } : {}), description: shown.text(item.description), status: item.status, run: item.run, bytes, etag: etagOf(item.oid),
80
+ name: shown.name(item.name), file: shown.name(file), readme: shown.name(item.file), description: shown.text(item.description), status, run: item.run, bytes, etag: etagOf(item.oid),
109
81
  ...(item.history.last ? { last_change: item.history.last } : {}),
110
82
  ...(item.status === "retired" ? { retired: retiredOf(item.history, item.retired_from, unread) } : {}),
111
83
  };
@@ -127,32 +99,25 @@ function pageRequest(query, fallback) {
127
99
  throw new ApiError("bad_request", "cursor is not one this server gave");
128
100
  return { limit, at: { sha: named[1], offset: Number(named[2]) } };
129
101
  }
130
- /** The snapshot a page reads, and from where: main now's, or the one its cursor names while this server holds it
131
- * (`older`), else main now's from its first item. */
102
+ /** The snapshot a page reads: main now's, or the one its cursor names while this server holds it, else main now's from
103
+ * its first item. */
132
104
  function pageAt(agentId, snapshot, at) {
133
105
  if (!at)
134
- return { snapshot, offset: 0, older: false };
106
+ return { snapshot, offset: 0 };
135
107
  if (at.sha === snapshot.main)
136
- return { snapshot, offset: at.offset, older: false };
108
+ return { snapshot, offset: at.offset };
137
109
  const kept = seen.get(seenKey(agentId, at.sha));
138
- return kept ? { snapshot: kept, offset: at.offset, older: true } : { snapshot, offset: 0, older: false };
139
- }
140
- /** A page of `notes`, from `offset`, at most `limit`, each with its text (only the page's are read and cut of
141
- * secrets). */
142
- async function notesPage(notes, main, offset, limit, body, shown, runs) {
143
- const items = await Promise.all(notes.slice(offset, offset + limit).map(async (note) => noteView(note, await body(note.file, note.oid), shown, runs)));
144
- return { items, total: notes.length, next_cursor: offset + limit < notes.length ? cursorOf(main, offset + limit) : null };
110
+ return kept ? { snapshot: kept, offset: at.offset } : { snapshot, offset: 0 };
145
111
  }
146
112
  /** A page of the changes on main, newest first, cut of the host's secrets. */
147
113
  const logPage = (snapshot, offset, limit, shown) => ({ items: snapshot.log.slice(offset, offset + limit).map((change) => changeView(change, shown)), total: snapshot.log.length, next_cursor: offset + limit < snapshot.log.length ? cursorOf(snapshot.main, offset + limit) : null });
148
114
  /** For tests: how many times a folder's statuses were read (once per commit of its main). */
149
115
  export const pendingTestHooks = { reads: 0 };
150
- /** By agent: its folder's main commit and each learned item's status there. */
116
+ /** By agent: its folder's main commit and each draft's status there. */
151
117
  const statusBy = new Map();
152
- /** Each learned item's status on agent `agentId`'s folder's main, by file (a note's; a skill's SKILL.md; a workflow
153
- * draft's workflow.json, as its README.md says it), from its snapshot: `active`, `pending`, `superseded` or `retired`,
154
- * with what a note supersedes. Built once per main (a list asks for many runs). A folder never made, or with no main,
155
- * holds none; one whose snapshot cannot be read is undefined. */
118
+ /** Each workflow draft's status on agent `agentId`'s folder's main, by its workflow.json (as its README.md says it):
119
+ * `active`, `pending` or `retired`. Built once per main (a list asks for many runs). A folder never made, or with no
120
+ * main, holds none; one whose snapshot cannot be read is undefined. */
156
121
  export async function statusesOf(data, agentId) {
157
122
  const folder = learningFolderOf(data, agentId);
158
123
  try {
@@ -164,11 +129,7 @@ export async function statusesOf(data, agentId) {
164
129
  return known.status;
165
130
  // Built at once, with no wait between the miss and the keep: requests that miss together build it once.
166
131
  pendingTestHooks.reads += 1;
167
- const status = new Map([
168
- ...snapshot.notes.map((note) => [note.file, { status: note.status, supersedes: note.supersedes }]),
169
- ...snapshot.skills.map((item) => [item.file, { status: item.status }]),
170
- ...snapshot.workflows.map((item) => [`${WORKFLOWS_DIR}/${item.name}/workflow.json`, { status: item.status }]),
171
- ]);
132
+ const status = new Map(snapshot.workflows.map((item) => [`${WORKFLOWS_DIR}/${item.name}/workflow.json`, { status: item.status }]));
172
133
  statusBy.set(agentId, { sha: snapshot.main, status });
173
134
  return status;
174
135
  }
@@ -179,46 +140,20 @@ export async function statusesOf(data, agentId) {
179
140
  await folder.end();
180
141
  }
181
142
  }
182
- /** How many of agent `agentId`'s learned items wait for its owner's OK on its folder's main (statusesOf): notes, skills
183
- * and workflow drafts held with `status: pending`. A folder never made has none waiting; one that cannot be read is
184
- * undefined (the caller shows no count). */
143
+ /** How many of agent `agentId`'s workflow drafts wait for its owner's OK on its folder's main (statusesOf). A folder
144
+ * never made has none waiting; one that cannot be read is undefined (the caller shows no count). */
185
145
  export async function pendingCount(data, agentId) {
186
146
  const status = await statusesOf(data, agentId);
187
147
  return status === undefined ? undefined : [...status.values()].filter((value) => value.status === "pending").length;
188
148
  }
189
- export async function agentLearning(data, agentId, shown, counts, impact, runs = new Map()) {
149
+ export async function agentLearning(data, agentId, shown, counts, impact, stateOf) {
190
150
  return reading(data, agentId, async ({ snapshot, body }) => {
191
- const index = snapshot.index.bytes ? await body(INDEX_FILE, snapshot.index.oid) : "";
192
- const notes = await notesPage(snapshot.notes, snapshot.main, 0, NOTES_PAGE, body, shown, runs);
193
- // A retired skill or draft whose key file can't be read is said so (unclearFront), read from its file now, as the
194
- // snapshot's status was: a few retired items, one read each.
151
+ const corrections = (await readCorrections(snapshot, body)).text;
152
+ // A retired draft whose README.md can't be read is said so (unclearFront), read from its file now, as the snapshot's
153
+ // status was: a few retired items, one read each.
195
154
  const unread = async (item) => item.status === "retired" && unclearFront(await body(item.file, item.oid));
196
- return { agent: agentId, main: snapshot.main, index: shown.text(index), notes, skills: await Promise.all(snapshot.skills.map(async (item) => learnedView(item, "skill", shown, await unread(item)))), workflows: await Promise.all(snapshot.workflows.map(async (item) => learnedView(item, "workflow", shown, await unread(item)))), log: logPage(snapshot, 0, LOG_PAGE, shown), counts, impact };
197
- }, () => ({ agent: agentId, main: null, index: "", notes: EMPTY, skills: [], workflows: [], log: EMPTY, counts, impact }));
198
- }
199
- /** GET /agents/{id}/learning/notes?cursor=&limit=&status=: a page of the notes, ordered as the view's. A page at an
200
- * older main whose notes this server cannot read as they were any more is the first page of main now. */
201
- export async function learningNotes(data, agentId, query, shown, runs = new Map()) {
202
- const status = query.get("status");
203
- if (status !== null && !NOTE_STATUSES.includes(status))
204
- throw new ApiError("bad_request", `status is one of ${NOTE_STATUSES.join(", ")}`);
205
- const { limit, at } = pageRequest(query, NOTES_PAGE);
206
- return reading(data, agentId, async ({ snapshot: now, body }) => {
207
- const listed = (snapshot) => (status === null ? snapshot.notes : snapshot.notes.filter((note) => note.status === status));
208
- const page = pageAt(agentId, now, at);
209
- if (page.older) {
210
- try {
211
- return await notesPage(listed(page.snapshot), page.snapshot.main, page.offset, limit, body, shown, runs);
212
- }
213
- catch (error) {
214
- // A note of that main is not on the folder as it was: the first page of main now.
215
- if (!isBodyMismatch(error))
216
- throw error;
217
- }
218
- return notesPage(listed(now), now.main, 0, limit, body, shown, runs);
219
- }
220
- return notesPage(listed(page.snapshot), page.snapshot.main, page.offset, limit, body, shown, runs);
221
- }, () => EMPTY);
155
+ return { agent: agentId, main: snapshot.main, corrections: shown.text(corrections), workflows: await Promise.all(snapshot.workflows.map(async (item) => workflowView(item, shown, stateOf, await unread(item)))), log: logPage(snapshot, 0, LOG_PAGE, shown), counts, impact };
156
+ }, () => ({ agent: agentId, main: null, corrections: "", workflows: [], log: EMPTY, counts, impact }));
222
157
  }
223
158
  /** GET /agents/{id}/learning/log?cursor=&limit=: a page of the changes on main, newest first. */
224
159
  export async function learningLog(data, agentId, query, shown) {
@@ -228,6 +163,42 @@ export async function learningLog(data, agentId, query, shown) {
228
163
  return logPage(page.snapshot, page.offset, limit, shown);
229
164
  }, () => EMPTY);
230
165
  }
166
+ /** GET /agents/{id}/learning/corrections: corrections.md on main as text (empty when main holds none), its ETag (its blob
167
+ * id; an empty file's when there is none) and the cap a PUT keeps to, cut of the host's secrets as every read is. */
168
+ export async function correctionsView(data, agentId, shown) {
169
+ const read = await reading(data, agentId, ({ snapshot, body }) => readCorrections(snapshot, body), () => ({ text: "", oid: blobOid("") }));
170
+ return { text: shown.text(read.text), etag: etagOf(read.oid), cap_bytes: CORRECTIONS_CAP };
171
+ }
172
+ /** PUT /agents/{id}/learning/corrections: corrections.md replaced whole by a person (`text`), only over the version they
173
+ * read (`ifMatch`: its ETag; none, or `*`, is 428; another version is 412). Refused whole, nothing written, when it holds
174
+ * what must never be stored (a host secret, text shaped like one, a hidden character) or passes the cap (422 with the
175
+ * problems, printable). A text read cut of a secret and sent back replaces the secret with the cut: a person's write never
176
+ * puts a secret back. In the agent's queue, one commit on main. */
177
+ export async function correctionsWrite(data, agentId, input) {
178
+ const match = input.ifMatch?.trim();
179
+ if (!match || match === "*")
180
+ throw new ApiError("precondition_required", "A write names the version it read: If-Match with corrections.md's ETag, as GET answered it.");
181
+ return withAgentRepo(data, agentId, async () => {
182
+ const { workspace: ws, end } = learningFolderOf(data, agentId);
183
+ try {
184
+ const done = await putCorrections(ws, { text: input.text, ifMatch: match, refuseValues: input.refuse });
185
+ if (done.ok)
186
+ return { text: done.text, etag: etagOf(done.oid), cap_bytes: CORRECTIONS_CAP };
187
+ if (done.reason === "conflict")
188
+ throw new ApiError("precondition_failed", "corrections.md changed since it was read (a run's correction, or another edit): read it again.");
189
+ const problems = done.problems.map((problem) => printable(problem, input.refuse));
190
+ throw invalid(problems.map((problem) => ({ field: "text", reason: problem.rule, message: problem.detail })));
191
+ }
192
+ catch (error) {
193
+ if (error instanceof FolderTooLarge)
194
+ throw invalid([{ field: "text", reason: "too_large", message: error.message }]);
195
+ throw routeFailure(error);
196
+ }
197
+ finally {
198
+ await end();
199
+ }
200
+ });
201
+ }
231
202
  /** The most revisions a workflow's history answers, and its default. */
232
203
  const REVISIONS_MAX = 50;
233
204
  const REVISIONS_DEFAULT = 20;
@@ -237,7 +208,7 @@ const REVISIONS_DEFAULT = 20;
237
208
  * of them. `total` counts every such commit the log holds, `truncated` says the log itself is cut (it keeps the latest
238
209
  * LOG_KEEP changes). A workflow no commit of the log changed is not_found. */
239
210
  export async function workflowRevisions(data, agentId, name, query, shown) {
240
- if (!learnedName("workflow", name))
211
+ if (!WORKFLOW_NAME.test(name))
241
212
  throw new ApiError("bad_request", "A workflow's folder is named with lowercase letters, digits, dashes and underscores.");
242
213
  const given = query.get("limit");
243
214
  const limit = given === null ? REVISIONS_DEFAULT : Number(given);
@@ -268,7 +239,7 @@ export async function workflowRevisions(data, agentId, name, query, shown) {
268
239
  * first commit whose workflow.json is that digest's text, with the commit it was read at. Undefined when none is (no
269
240
  * main yet, or no commit read holds it). One read-only exec per commit tried (textsAt). */
270
241
  export async function workflowAtDigest(data, agentId, name, digest, commits) {
271
- if (!learnedName("workflow", name))
242
+ if (!WORKFLOW_NAME.test(name))
272
243
  return undefined;
273
244
  const path = `${WORKFLOWS_DIR}/${name}/workflow.json`;
274
245
  return reading(data, agentId, async ({ ws, snapshot }) => {
@@ -280,22 +251,16 @@ export async function workflowAtDigest(data, agentId, name, digest, commits) {
280
251
  return undefined;
281
252
  }, () => undefined);
282
253
  }
283
- /** The blob of `file` on the snapshot's main, as a route names it: the index, a note, a skill's SKILL.md, a draft's
284
- * README.md or workflow.json; undefined when main holds no such file the snapshot names. */
254
+ /** The blob of a draft's `file` on the snapshot's main; undefined when main holds no such file the snapshot names. */
285
255
  function blobIn(snapshot, file) {
286
- if (!snapshot)
287
- return undefined;
288
- if (file === INDEX_FILE)
289
- return snapshot.index.oid;
290
256
  const place = learnedPlace(file);
291
- if (!place)
292
- return snapshot.notes.find((note) => note.file === file)?.oid;
293
- const items = place.kind === "skill" ? snapshot.skills : snapshot.workflows;
294
- return items.find((item) => item.name === place.name)?.files.find(({ path }) => path === file)?.oid;
257
+ if (!snapshot || !place)
258
+ return undefined;
259
+ return snapshot.workflows.find((item) => item.name === place.name)?.files.find(({ path }) => path === file)?.oid;
295
260
  }
296
- /** The file a route names, decoded, for its `use`: a note's name; for a read MEMORY.md too, and a skill's SKILL.md or a
297
- * draft's workflow.json or README.md (`skills/<name>/SKILL.md`, percent-encoded); for an approval a skill's SKILL.md or
298
- * a draft's README.md, the file that says it waits. Anything else is 400. The name is never echoed. */
261
+ /** The file a route names, decoded: a draft's workflow.json or README.md (`workflows/<name>/README.md`,
262
+ * percent-encoded); for an approve, a retire or a restore, its README.md, the file that says whether it waits. Anything
263
+ * else is 400. The name is never echoed. */
299
264
  function fileOf(raw, use) {
300
265
  let file;
301
266
  try {
@@ -305,28 +270,17 @@ function fileOf(raw, use) {
305
270
  throw new ApiError("bad_request", "the file name is not percent-encoded right");
306
271
  }
307
272
  const place = learnedPlace(file);
308
- if (place) {
309
- if (!learnedName(place.kind, place.name))
310
- throw new ApiError("bad_request", "A skill's folder is named with lowercase letters, digits and single dashes, a workflow's with lowercase letters, digits, dashes and underscores.");
311
- if (use === "write")
312
- throw new ApiError("bad_request", "A skill or a workflow is changed by a run's learning, approved by its owner, or retired: a person edits and creates notes.");
313
- if (use === "approve" && place.kind === "workflow")
314
- throw new ApiError("bad_request", "A workflow is approved by its README.md, the file that says it waits.");
315
- if (use === "retire" && place.kind === "workflow")
316
- throw new ApiError("bad_request", "A workflow is retired by its README.md, the file that says whether it is in use.");
317
- if (use === "restore" && place.kind === "workflow")
318
- throw new ApiError("bad_request", "A workflow is restored by its README.md, the file that says whether it is in use.");
319
- return file;
320
- }
321
- if (file === INDEX_FILE && use !== "read")
322
- throw new ApiError("bad_request", "MEMORY.md is built by the server from the active notes, one line each, and is never written: edit, create or retire a note instead.");
323
- if (file !== INDEX_FILE && !NOTE_FILE.test(file))
324
- throw new ApiError("bad_request", "A learning file is a note's name at the folder's top: letters, digits, dots, dashes and underscores, starting with a letter or digit, ending .md.");
273
+ if (!place)
274
+ throw new ApiError("bad_request", "A learning file is a workflow draft's workflow.json or README.md (workflows/<name>/...); corrections.md has its own route.");
275
+ if (!WORKFLOW_NAME.test(place.name))
276
+ throw new ApiError("bad_request", "A workflow's folder is named with lowercase letters, digits, dashes and underscores.");
277
+ if (use !== "read" && place.kind !== "readme")
278
+ throw new ApiError("bad_request", "A workflow is approved, retired and restored by its README.md, the file that says whether it is in use.");
325
279
  return file;
326
280
  }
327
- /** GET /agents/{id}/learning/files/{file}: the file on main as text, its ETag, and its type (a draft's workflow.json is
281
+ /** GET /agents/{id}/learning/files/{file}: a draft's file on main as text, its ETag, and its type (workflow.json is
328
282
  * JSON). */
329
- export async function readNote(data, agentId, raw, shown) {
283
+ export async function readLearnedFile(data, agentId, raw, shown) {
330
284
  const file = fileOf(raw, "read");
331
285
  const found = await reading(data, agentId, async ({ snapshot, body }) => {
332
286
  const oid = blobIn(snapshot, file);
@@ -336,21 +290,21 @@ export async function readNote(data, agentId, raw, shown) {
336
290
  throw new ApiError("not_found", "the agent's learning folder has no such file on main");
337
291
  return { text: shown.text(found.text), etag: etagOf(found.oid), ...(file.endsWith(".json") ? { type: "application/json; charset=utf-8" } : {}) };
338
292
  }
339
- /** A note (or a skill's or draft's file) as a text answer: its ETag, an explicit type (markdown unless it names one),
340
- * nosniff, and a sandbox on whatever opens it. */
341
- export function sendNote(res, status, note, headers = {}) {
342
- res.writeHead(status, { "content-type": note.type ?? "text/markdown; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff", "content-security-policy": "sandbox", etag: note.etag, ...headers });
343
- res.end(note.text);
293
+ /** A learning file as a text answer: its ETag, an explicit type (markdown unless it names one), nosniff, and a sandbox on
294
+ * whatever opens it. */
295
+ export function sendText(res, status, file, headers = {}) {
296
+ res.writeHead(status, { "content-type": file.type ?? "text/markdown; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff", "content-security-policy": "sandbox", etag: file.etag, ...headers });
297
+ res.end(file.text);
344
298
  }
345
- /** A PUT's body, read to its end (over `max` bytes is 413): the note's whole text, as `text/markdown` or `text/plain`, or
346
- * as `application/json` `{text}`, the one form the console's page may send under its session (page.ts: a write from
347
- * the page is JSON from its own origin). A JSON body that is not an object is 400; one whose `text` is missing or not
348
- * text, or with another field, is 422 by field, as every JSON body here. */
349
- export async function noteBody(req, max) {
299
+ /** A PUT's body, read to its end (over `max` bytes is 413): the file's whole text, as `text/markdown` or `text/plain`, or
300
+ * as `application/json` `{text}`, the one form the console's page may send under its session (page.ts: a write from the
301
+ * page is JSON from its own origin). A JSON body that is not an object is 400; one whose `text` is missing or not text,
302
+ * or with another field, is 422 by field, as every JSON body here. A body that is not UTF-8 is 422. */
303
+ export async function textBody(req, max) {
350
304
  const type = String(req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
351
305
  const json = type === "application/json";
352
306
  if (!json && type !== "text/markdown" && type !== "text/plain")
353
- throw new ApiError("unsupported_media_type", "the body is the note's whole text, front matter included: text/markdown or text/plain, or application/json {text}");
307
+ throw new ApiError("unsupported_media_type", "the body is the file's whole text: text/markdown or text/plain, or application/json {text}");
354
308
  const chunks = [];
355
309
  let size = 0;
356
310
  for await (const chunk of req) {
@@ -360,11 +314,16 @@ export async function noteBody(req, max) {
360
314
  }
361
315
  if (size > max)
362
316
  throw new ApiError("payload_too_large", `the body is over ${max} bytes`, { details: { limit: "max_body_bytes" } });
363
- if (!json)
364
- return Buffer.concat(chunks);
317
+ const raw = Buffer.concat(chunks);
318
+ if (!json) {
319
+ const text = raw.toString("utf8");
320
+ if (!Buffer.from(text, "utf8").equals(raw))
321
+ throw invalid([{ field: "text", reason: "wrong_type", message: "the body is not UTF-8 text" }]);
322
+ return text;
323
+ }
365
324
  let value;
366
325
  try {
367
- value = JSON.parse(Buffer.concat(chunks).toString("utf8") || "null");
326
+ value = JSON.parse(raw.toString("utf8") || "null");
368
327
  }
369
328
  catch {
370
329
  throw new ApiError("bad_request", "the body is not JSON");
@@ -372,215 +331,94 @@ export async function noteBody(req, max) {
372
331
  if (!isObject(value))
373
332
  throw new ApiError("bad_request", "the body is not a JSON object");
374
333
  const issues = Object.keys(value).filter((key) => key !== "text").map((key) => ({ field: key, reason: "not_allowed", message: `The body keeps no field ${key}.` }));
375
- // A lone surrogate is no text: UTF-8 would carry it as U+FFFD, a note other than the one sent.
334
+ // A lone surrogate is no text: UTF-8 would carry it as U+FFFD, a text other than the one sent.
376
335
  if (typeof value.text !== "string" || /\p{Cs}/u.test(value.text))
377
- issues.push({ field: "text", reason: value.text === undefined ? "missing" : "wrong_type", message: "text is the note's whole text, front matter included" });
336
+ issues.push({ field: "text", reason: value.text === undefined ? "missing" : "wrong_type", message: "text is the file's whole text" });
378
337
  if (issues.length)
379
338
  throw invalid(issues);
380
- return Buffer.from(value.text, "utf8");
339
+ return value.text;
381
340
  }
382
- const refused = (problems) => new ApiError("bad_request", `The note does not pass the checks: ${[...new Set(problems.map((problem) => problem.rule))].join(", ")}.`, { problems });
383
- /** What a write's headers ask (RFC 9110 13.1): If-Match, the ETags of the note as GET answered it, or for a PUT
384
- * If-None-Match: *, only if the name is not taken. Neither, or If-Match: *, which names no version read, is 428. */
385
- function conditionOf(ifMatch, ifNoneMatch, put) {
386
- const match = ifMatch?.split(",").map((tag) => tag.trim()).filter(Boolean);
387
- const absent = put && ifNoneMatch?.trim() === "*";
341
+ const refused = (problems) => new ApiError("bad_request", `The workflow does not pass the checks: ${[...new Set(problems.map((problem) => problem.rule))].join(", ")}.`, { problems });
342
+ /** POST /agents/{id}/learning/files/{file}/approve, .../retire or .../restore, as a person, on a draft's README.md
343
+ * (`file`): If-Match on the version read (none, or `*`, is 428; another is 412), then one commit on main by the learning
344
+ * script (learn/folder.ts writeLearning), in the agent's queue, its message `learning: <approved|retired|restored> by a
345
+ * person: <file>` with a `Changed-By: user` trailer (and `Approved-Via: console` on an approval). An approval releases a
346
+ * held draft (status: pending) to every later run; a retire takes it out of every later run unchecked, so a leaking one
347
+ * can always be revoked; a restore brings it back to the status its retire recorded, checked again as a new draft is
348
+ * (secrets' shapes, the host's values, hidden characters, its README's format, its workflow.json against the agent's
349
+ * tools and gate). A retire of a retired draft commits nothing. `refuse`: the host's secrets. */
350
+ export async function changeWorkflow(data, agentId, raw, input) {
351
+ const file = fileOf(raw, input.action);
352
+ const place = learnedPlace(file);
353
+ const match = input.ifMatch?.split(",").map((tag) => tag.trim()).filter(Boolean);
388
354
  if (match?.includes("*"))
389
- throw new ApiError("precondition_required", "If-Match: * names no version: send the note's ETag, as GET answered it.");
390
- if (!match?.length && !absent)
391
- throw new ApiError("precondition_required", put ? "A write names the version it read: If-Match with the note's ETag to edit it, or If-None-Match: * to create it." : "A retire names the version it read: If-Match with the note's ETag.");
392
- return { ...(match?.length ? { match } : {}), absent };
393
- }
394
- /** A file main holds by this name that is no note (another mode, over the read cap, not UTF-8, out of shape) is never
395
- * written over: a create of the name is refused, and an edit or a retire gives no hint to create it. */
396
- const NOT_NOTE = "The folder's file by this name on main is no note (not a regular UTF-8 file of at most 1 MiB in a note's format), and a person's write never replaces it.";
397
- /** PUT /agents/{id}/learning/files/{file} (`body`, the note's whole text), or POST .../retire or .../approve (`approve`;
398
- * no body), as a person: the precondition, then the checks (a retire's and an approve's, the note's format alone: never
399
- * its secrets), then one commit on main by the learning script (learn/folder.ts writeLearning), in the agent's queue,
400
- * on the agent's learning folder: the note, and MEMORY.md rebuilt from main's notes with it, its message
401
- * `learning: <edited|created|retired|approved> by a person: <file>` and a `Changed-By: user` trailer (and
402
- * `Approved-Via: console` on an approval), main moved only from the main it read (computed again on a main that moved
403
- * meanwhile), then the checked-out files and the snapshot. A note the checks refuse is never written to git. A retire
404
- * of a note that is not active, and an edit that changes nothing, commit nothing. `refuse`: the host's secrets. */
405
- export async function writeNote(data, agentId, raw, input) {
406
- const file = fileOf(raw, input.approve ? "approve" : input.restore ? "restore" : input.body === undefined ? "retire" : "write");
407
- // A skill's SKILL.md or a draft's README.md: only ever approved or retired here.
408
- const learned = learnedPlace(file);
409
- const condition = conditionOf(input.ifMatch, input.ifNoneMatch, input.body !== undefined);
410
- let given;
411
- if (input.body !== undefined) {
412
- const { problems, note } = checkNote(file, input.body, input.refuse);
413
- if (!note)
414
- throw refused(problems);
415
- given = note.text;
416
- }
355
+ throw new ApiError("precondition_required", "If-Match: * names no version: send the README's ETag, as GET answered it.");
356
+ if (!match?.length)
357
+ throw new ApiError("precondition_required", "A change names the version it read: If-Match with the README's ETag.");
417
358
  return withAgentRepo(data, agentId, async () => {
418
359
  // The folder as a run's merge reaches it: a link in it is refused (an error naming it, nothing written), never
419
360
  // followed.
420
361
  const { workspace: ws, end } = learningFolderOf(data, agentId);
421
362
  try {
422
363
  const { result } = await writeLearning(ws, async ({ snapshot, body, bytes }) => {
423
- const main = snapshot?.main;
424
364
  const oid = blobIn(snapshot, file);
425
- const current = oid === undefined || file === INDEX_FILE ? undefined : { oid, text: await body(file, oid) };
426
- if (condition.match && !(current && condition.match.includes(etagOf(current.oid)))) {
427
- const held = !current && main !== undefined && (await heldOnMain(ws, main, file));
428
- throw new ApiError("precondition_failed", current ? "The note changed since it was read (a run's merge, or another edit): read it again." : held ? NOT_NOTE : "There is no such note on main: create it with If-None-Match: *.");
429
- }
430
- if (condition.absent && current)
431
- throw new ApiError("precondition_failed", "The folder has a note by this name: read it, then edit it with If-Match.");
432
- // A note whose text holds one of the host's secrets as they are now (a value made secret after it was written) is
433
- // read cut of it, under its own ETag: an edit of what was shown would write the cut over the hidden text. Only a
434
- // retire reaches it. So is one holding a loopback address, read as "a local address" (secretsShown).
435
- if (given !== undefined && current && secretsShown(input.refuse).holds(current.text)) {
436
- throw refused([{ rule: "secret_value", path: file, detail: "This note holds a value the server now keeps secret, so its text was shown with that value hidden, and saving would replace the hidden text. Retire it and write a new note instead." }]);
437
- }
438
- if (given !== undefined && current && secretsShown(input.refuse).text(current.text) !== current.text) {
439
- throw refused([{ rule: "note", path: file, detail: "This note holds a local address, so its text was shown with it hidden, and saving would replace it. Retire it and write a new note instead." }]);
440
- }
441
- let text = given;
442
- // A note that waits for its owner's OK is made active by an approval alone: an edit keeps it waiting, so one that
443
- // drops or changes its status is refused, whoever sends it. A retired note comes back by its restore alone, to the
444
- // status its retire recorded: an edit keeps it retired and keeps that record (retired_from) as it is.
445
- if (given !== undefined && current) {
446
- const was = parseNoteFile(file, current.text);
447
- const now = parseNoteFile(file, given);
448
- if (!Array.isArray(was) && was.status === "pending" && !Array.isArray(now) && now.status !== "pending")
449
- throw refused([printable({ rule: "status", path: file, detail: "it waits for its owner's OK: an edit keeps status: pending, only an approval makes it active, and a retire takes it out" }, input.refuse)]);
450
- if (!Array.isArray(was) && was.status === "retired" && !Array.isArray(now)) {
451
- const kept = was.retired_from ?? "pending";
452
- if (now.status !== "retired" || (now.keys.includes("retired_from") && now.retired_from !== kept))
453
- throw refused([printable({ rule: "status", path: file, detail: `it is retired: an edit keeps status: retired and retired_from: ${kept}, and only its restore brings it back, as it was before its retire` }, input.refuse)]);
454
- // What its retire recorded is the host's: the edit carries it, written or not.
455
- text = retire(given, kept);
365
+ const current = oid === undefined ? undefined : { oid, text: await body(file, oid) };
366
+ if (!current)
367
+ throw new ApiError("not_found", "the agent's learning folder has no such workflow on main");
368
+ if (!match.includes(etagOf(current.oid)))
369
+ throw new ApiError("precondition_failed", "The workflow changed since it was read (a run's merge, or another change): read it again.");
370
+ let text;
371
+ if (input.action === "restore") {
372
+ const status = learnedStatus(current.text);
373
+ if (status !== "retired")
374
+ throw new ApiError("bad_request", `The workflow is not retired: it is ${status}.`);
375
+ // Read as retired since its front matter reads no way, or its status (or the retired_from its retire recorded) is
376
+ // set on more than one line, which no writer edits: refused until it is written so.
377
+ if (!restorable(current.text))
378
+ throw refused([printable({ rule: "workflow", path: file, detail: UNCLEAR_FRONT }, input.refuse)]);
379
+ // Back to the status its retire recorded, never active unless it was active: a held draft waits for its owner's OK again.
380
+ text = restoredLearned(current.text);
381
+ const problems = readmeProblems(text, place.name).map((detail) => printable({ rule: "workflow", path: file, detail }, input.refuse));
382
+ const extra = (frontKeys(text) ?? []).filter((key) => !LEARNED_KEYS.includes(key) && key !== "status");
383
+ if (extra.length)
384
+ problems.push(printable({ rule: "workflow", path: file, detail: `its front matter sets ${extra.join(", ")}: a learned workflow's README sets name and description alone` }, input.refuse));
385
+ const others = snapshot.workflows.find((item) => item.name === place.name)?.files.filter(({ path }) => path !== file) ?? [];
386
+ const changes = [{ path: file, status: "modified", bytes: Buffer.from(text, "utf8") }, ...(await Promise.all(others.map(async ({ path, oid: blob }) => ({ path, status: "modified", bytes: await bytes(path, blob) }))))];
387
+ problems.push(...unstorable(changes, input.refuse));
388
+ // Its workflow.json passes the checks a run's draft passes (its tools and the gate's settings), so a restore never
389
+ // brings back a draft no run could run.
390
+ const draft = changes.find(({ path }) => path === `${WORKFLOWS_DIR}/${place.name}/workflow.json`);
391
+ if (draft && input.draftTools) {
392
+ const { tools, gated, deniedBy, decisions } = await input.draftTools();
393
+ const dsl = await import("@parcha/agentrun-dsl");
394
+ for (const { rule, detail } of draftProblems(dsl, draft.bytes.toString("utf8"), tools, gated, deniedBy ?? {}, decisions))
395
+ problems.push(printable({ rule, path: draft.path, detail }, input.refuse));
456
396
  }
397
+ if (problems.length)
398
+ throw refused(problems);
457
399
  }
458
- // Beside the note itself: what an approve marks of the notes the approved one supersedes.
459
- const also = new Map();
460
- const notes = new Map(snapshotNotes(snapshot).map((note) => [note.file, note]));
461
- const noteOid = (name) => snapshot.notes.find((note) => note.file === name).oid;
462
- const mark = async (superseded) => {
463
- for (const old of superseded)
464
- if (notes.get(old)?.status === "active")
465
- also.set(old, supersede(await body(old, noteOid(old)), file));
466
- };
467
- if (input.restore) {
468
- // Restored, a retired note, skill or draft goes back to the status its retire recorded (retired_from): active, so
469
- // given to every later run, or waiting for its owner's OK again, so a retire and a restore never skip that OK
470
- // (a retire that recorded none restores it waiting). It is checked again as a new one is (secrets' shapes, the
471
- // host's values, hidden characters, its format, every file of a skill's or a draft's folder): a retire takes a
472
- // leaking one out of every run unchecked, and a restore never brings it back. A restore is never an approval.
473
- if (learned) {
474
- const status = learnedStatus(current.text);
475
- const kind = learned.kind === "skill" ? "skill" : "workflow";
476
- if (status !== "retired")
477
- throw new ApiError("bad_request", `The ${kind} is not retired: it is ${status}.`);
478
- // Read as retired since its front matter reads no way, or its status (or the retired_from its retire recorded) is
479
- // set on more than one line, which no writer edits (learnedStatus, restorable): refused until it is written so.
480
- if (!restorable(current.text))
481
- throw refused([printable({ rule: kind, path: file, detail: UNCLEAR_FRONT }, input.refuse)]);
482
- // Back to the status its retire recorded (restoredLearned: retired_from, read by the one reader), never active
483
- // unless it was active: a held skill or draft waits for its owner's OK again.
484
- text = restoredLearned(current.text);
485
- const problems = skillProblems(text, learned.name).map((detail) => printable({ rule: kind, path: file, detail }, input.refuse));
486
- const extra = (frontKeys(text) ?? []).filter((key) => !LEARNED_KEYS.includes(key) && key !== "status");
487
- if (extra.length)
488
- problems.push(printable({ rule: "skill_front_matter", path: file, detail: `its front matter sets ${extra.join(", ")}: a learned ${kind} sets name and description alone` }, input.refuse));
489
- const folder = `${learned.kind === "skill" ? SKILLS_DIR : WORKFLOWS_DIR}/${learned.name}/`;
490
- const others = (learned.kind === "skill" ? snapshot.skills : snapshot.workflows).find((item) => item.name === learned.name)?.files.filter(({ path }) => path !== file) ?? [];
491
- const changes = [{ path: file, status: "modified", bytes: Buffer.from(text, "utf8") }, ...(await Promise.all(others.map(async ({ path, oid: blob }) => ({ path, status: "modified", bytes: await bytes(path, blob) }))))];
492
- problems.push(...unstorable(changes, input.refuse));
493
- // A draft's workflow.json passes the learning checker as a run's would (its tools and the gate's settings), so
494
- // a restore never brings back a draft no run could run.
495
- const draft = changes.find(({ path }) => path === `${folder}workflow.json`);
496
- if (learned.kind !== "skill" && draft && input.draftTools) {
497
- const { tools, gated, deniedBy, decisions } = await input.draftTools();
498
- const dsl = await import("@parcha/agentrun-dsl");
499
- for (const { rule, detail } of draftProblems(dsl, draft.bytes.toString("utf8"), tools, gated, deniedBy ?? {}, decisions))
500
- problems.push(printable({ rule, path: draft.path, detail }, input.refuse));
501
- }
502
- if (problems.length)
503
- throw refused(problems);
504
- }
505
- else {
506
- const note = parseNoteFile(file, current.text);
507
- if (Array.isArray(note))
508
- throw refused(note.map((detail) => printable({ rule: "note", path: file, detail }, input.refuse)));
509
- if (note.status !== "retired")
510
- throw new ApiError("bad_request", `The note is not retired: it is ${note.status}.`);
511
- text = restore(current.text, note);
512
- const { problems } = checkNote(file, Buffer.from(text, "utf8"), input.refuse);
513
- if (problems.length)
514
- throw refused(problems);
515
- // Back active, what it supersedes, and is active still, is superseded now, as an approval marks it; back
516
- // waiting, it supersedes nothing until it is approved.
517
- if (note.retired_from === "active")
518
- await mark(note.supersedes);
519
- }
520
- }
521
- else if (text === undefined && learned && !input.approve) {
522
- // Retired, as a note is: no later run is given it. One already retired is answered as it is; nothing else in
523
- // the folder changes.
400
+ else if (input.action === "retire") {
401
+ // One already retired is answered as it is; nothing else in the folder changes.
524
402
  if (learnedStatus(current.text) === "retired")
525
403
  return { result: { status: 200, file, text: current.text, etag: etagOf(current.oid) } };
526
404
  text = retiredLearned(current.text);
527
405
  }
528
- else if (text === undefined && learned) {
406
+ else {
529
407
  // Approved, it is no longer held: given to every later run. Nothing else in the folder changes.
530
408
  if (!isHeld(current.text))
531
- throw new ApiError("bad_request", `The ${learned.kind === "skill" ? "skill" : "workflow"} is not waiting for an OK: it is ${learnedStatus(current.text)}.`);
409
+ throw new ApiError("bad_request", `The workflow is not waiting for an OK: it is ${learnedStatus(current.text)}.`);
532
410
  text = released(current.text);
533
411
  }
534
- else if (text === undefined && input.approve) {
535
- const note = parseNoteFile(file, current.text);
536
- if (Array.isArray(note))
537
- throw refused(note.map((detail) => printable({ rule: "note", path: file, detail }, input.refuse)));
538
- if (note.status !== "pending")
539
- throw new ApiError("bad_request", `The note is not waiting for an OK: it is ${note.status}.`);
540
- // Approved, it is active: in the index, and every later run reads it. What it supersedes, and is active still, is
541
- // superseded now, as a run's merge marks it.
542
- text = approve(current.text);
543
- await mark(note.supersedes);
544
- }
545
- else if (text === undefined) {
546
- const note = parseNoteFile(file, current.text);
547
- if (Array.isArray(note))
548
- throw refused(note.map((detail) => printable({ rule: "note", path: file, detail }, input.refuse)));
549
- // A pending note is retired too: a person who will never approve it takes it out of the folder's waiting list.
550
- if (note.status !== "active" && note.status !== "pending")
551
- return { result: { status: 200, file, text: current.text, etag: etagOf(current.oid) } };
552
- // A retire is how a person takes a note out of every later run's prompt, a leaking one above all, so it always
553
- // can: only the note's format is checked as retired (its front matter parses, and it fits the note cap with the
554
- // status line added), never a secret in its name or text. Every answer cuts those as any read does.
555
- text = retire(current.text, note.status === "pending" ? "pending" : "active");
556
- const retired = parseNoteFile(file, text);
557
- if (Array.isArray(retired))
558
- throw refused(retired.map((detail) => printable({ rule: "note", path: file, detail }, input.refuse)));
559
- const size = noteBytes(text);
560
- if (size > CAPS.note + RETIRED_LINE)
561
- throw refused([printable({ rule: "too_large", path: file, detail: `${size} bytes as retired; the cap is ${CAPS.note}, and the status lines a retire adds (a compiled_into line on top)` }, input.refuse)]);
562
- }
563
- if (current && text === current.text)
564
- return { result: { status: 200, file, text, etag: etagOf(current.oid) } };
565
- const after = learned ? [...notes.values()] : [...[...notes.values()].filter((note) => note.file !== file && !also.has(note.file)), parseNoteFile(file, text), ...[...also].map(([old, marked]) => parseNoteFile(old, marked))];
566
- const lines = after.filter((note) => note.status === "active").length;
567
- if (lines > INDEX_LINES)
568
- throw refused([{ rule: "index_full", detail: `the index would hold ${lines} lines; it holds at most ${INDEX_LINES}, so retire a note first` }]);
569
- const kind = input.approve ? "approved" : input.restore ? "restored" : given === undefined ? "retired" : current ? "edited" : "created";
570
- const change = {
571
- // Who approved, and how, in the trailers; the commit's own date is when. Never the note's text.
572
- by: { person: kind, file, approved: Boolean(input.approve) },
573
- writes: [{ path: file, text: text }, { path: INDEX_FILE, text: buildIndex(after) }, ...[...also].map(([path, marked]) => ({ path, text: marked }))],
574
- // A create takes a name main holds nothing by, as git holds it: a file the notes leave out included.
575
- ...(current ? {} : { absent: [file] }),
576
- };
577
- return { result: { status: current ? 200 : 201, file, text: text, etag: etagOf(blobOid(text)) }, change };
412
+ const kind = input.action === "approve" ? "approved" : input.action === "restore" ? "restored" : "retired";
413
+ // Who approved, and how, in the trailers; the commit's own date is when. Never the file's text.
414
+ const change = { by: { person: kind, file, approved: input.action === "approve" }, writes: [{ path: file, text }] };
415
+ return { result: { status: 200, file, text, etag: etagOf(blobOid(text)) }, change };
578
416
  });
579
417
  return result;
580
418
  }
581
419
  catch (error) {
582
420
  if (error instanceof FolderRefused)
583
- throw new ApiError("precondition_failed", NOT_NOTE);
421
+ throw new ApiError("precondition_failed", "The folder's file by this name on main is no regular UTF-8 file, and a person's change never replaces it.");
584
422
  if (error instanceof FolderTooLarge)
585
423
  throw refused([{ rule: "too_large", path: file, detail: error.message }]);
586
424
  throw routeFailure(error);
@@ -590,113 +428,43 @@ export async function writeNote(data, agentId, raw, input) {
590
428
  }
591
429
  });
592
430
  }
593
- /** POST /agents/{id}/learning/workflows/{name}/promote's read of the learned workflow `raw` (percent-encoded) on agent
594
- * `agentId`'s main: an active one alone, as every later run is given it. One that waits for its owner's OK, or that a
595
- * person retired, is 409 learned_not_active: a promotion never runs what the owner has not let every run use. Each of
596
- * its files is checked again as a restore checks it (unstorable: a secret's shape, the host's values as they are now,
597
- * a hidden character), and its workflow.json as the learning checker checks a run's draft against the agent's tools and
598
- * its gate (draftProblems: the DSL's validation with no code run, no code node, no shell or executor call, no call node
599
- * on a tool the agent does not have or the gate holds to ask or deny). Any of those is 400 with `problems`, printable.
600
- * Reads only: the folder is never written. */
601
- export async function promotable(data, agentId, raw, input) {
602
- let name;
603
- try {
604
- name = decodeURIComponent(raw);
605
- }
606
- catch {
607
- throw new ApiError("bad_request", "the workflow's name is not percent-encoded right");
608
- }
609
- if (!learnedName("workflow", name))
610
- throw new ApiError("bad_request", "A learned workflow's folder is named with lowercase letters, digits, dashes and underscores.");
611
- const found = await reading(data, agentId, async ({ snapshot, body }) => {
612
- const item = snapshot.workflows.find((one) => one.name === name);
613
- if (!item)
614
- return undefined;
615
- if (item.status !== "active")
616
- return { item, files: [] };
617
- return { item, files: await Promise.all(item.files.map(async ({ path, oid }) => ({ path, text: await body(path, oid) }))) };
618
- }, () => undefined);
619
- if (!found)
620
- throw new ApiError("not_found", "the agent's learning folder has no such workflow on main");
621
- const { item, files } = found;
622
- if (item.status === "pending")
623
- throw new ApiError("learned_not_active", "This workflow waits for your OK: approve it first. Making it an agent never skips your OK.");
624
- if (item.status !== "active")
625
- throw new ApiError("learned_not_active", "This workflow is retired: restore it first to make it an agent.");
626
- const file = `${WORKFLOWS_DIR}/${name}/workflow.json`;
627
- const json = files.find(({ path }) => path === file);
628
- const problems = unstorable(files.map(({ path, text }) => ({ path, status: "modified", bytes: Buffer.from(text, "utf8") })), input.refuse);
629
- if (!json)
630
- problems.push(printable({ rule: "workflow", path: file, detail: "the workflow's folder holds no workflow.json" }, input.refuse));
631
- const dsl = await import("@parcha/agentrun-dsl");
632
- if (json && !problems.length) {
633
- // A learned workflow's decision nodes (LS-07) are checked on this server's decision providers, as a restore checks them.
634
- const { tools, gated, deniedBy, decisions } = await input.draftTools();
635
- for (const { rule, detail } of draftProblems(dsl, json.text, tools, gated, deniedBy ?? {}, decisions))
636
- problems.push(printable({ rule, path: file, detail }, input.refuse));
637
- }
638
- if (problems.length)
639
- throw new ApiError("bad_request", `The workflow does not pass the checks: ${[...new Set(problems.map((problem) => problem.rule))].join(", ")}.`, { problems });
640
- const workflow = JSON.parse(json.text);
641
- return { name, description: item.description, workflow, calls: dsl.inspectWorkflow(workflow).requires.tools };
642
- }
643
431
  /** GET /runs/{id}/learning's body, from the run's learning as it reads now, the seed it started from and whether it
644
- * settled: the one shape, read from the one store (store-reads/learning.ts
645
- * runLearningOverStore). */
432
+ * settled: the one shape, read from the one store (store-reads/learning.ts runLearningOverStore). */
646
433
  export function runLearningBody(input, shown, secrets) {
647
434
  const { learning } = input;
648
- const { state, reason, at, verdict, problems, merged, cost_usd, tokens, pending } = learning;
435
+ const { state, reason, at, problems, merged } = learning;
649
436
  return {
650
437
  run: input.id, state, reason: reasonShown(reason, shown), detail: detailShown(learning, shown), at,
651
- // Once it settled (a run that runs again for a follow-up is still reading).
652
- ...notesView(learning, shown, input.settled),
438
+ // The draft it merged, `pending` while it waits for its owner's OK.
439
+ workflows: filesView(learning, shown).workflows ?? [],
440
+ // How many lines of its owner's words its merge added to corrections.md.
441
+ corrections: learning.corrections ?? 0,
653
442
  seed: input.seed,
654
443
  merged: merged ?? null,
655
- // The merge's notes that wait for a person's OK: on main as `status: pending`, read by no run until approved.
656
- pending: (pending ?? []).map(({ file, name }) => ({ file: shown.name(file), name: shown.text(name) })),
657
- // The grader's, with its item for each new note: a name holding one of the host's secrets reads [redacted], and
658
- // each text is cut of them, its origin too (a kept row read back is untrusted).
659
- verdict: verdict ? { merge: verdict.merge, reason: shown.text(verdict.reason), items: (verdict.items ?? []).map(({ file, keep, pending: waits, origin, question, why }) => ({ file: shown.name(file), keep, ...(waits ? { pending: true } : {}), ...(origin ? { origin: shown.text(origin) } : {}), ...(question ? { question: shown.text(question) } : {}), why: shown.text(why) })) } : null,
660
444
  // Each cut of the host's secrets (printable), then as every served text is (`shown`: no loopback address).
661
445
  problems: (problems ?? []).map((problem) => printable(problem, secrets)).map(({ rule, path, detail }) => ({ rule: shown.text(rule), ...(path === undefined ? {} : { path: shown.text(path) }), detail: shown.text(detail) })),
662
- // The compile turn's record (learn/compile.ts): the workflow it wrote, the notes it absorbed and each attempt with
663
- // what the checks refused, its kept draft's digest and whether that serves (its promotion: true, held false, null
664
- // while undecided); null when the run compiled nothing. A draft that never passed is never silent: its
665
- // errors are `draft_errors`. Each text cut of the host's secrets.
666
- compiled: learning.compiled ? { workflow: shown.name(learning.compiled.workflow), from_notes: learning.compiled.from_notes.map(shown.name), attempts: learning.compiled.attempts.map(({ ok, errors }) => ({ ok, errors: errors.map((error) => shown.text(printable({ rule: "workflow", detail: error }, secrets).detail)) })), digest: learning.compiled.digest ?? null, promoted: learning.compiled.promoted ?? null } : null,
446
+ // The compile turn's record (learn/compile.ts): the workflow it wrote and each attempt with what the checks refused,
447
+ // its kept draft's digest and whether that serves (its promotion: true, held false, null while undecided); null when
448
+ // the run compiled nothing. A draft that never passed is never silent: its errors are `draft_errors`. Each text cut of
449
+ // the host's secrets.
450
+ compiled: learning.compiled ? { workflow: shown.name(learning.compiled.workflow), attempts: learning.compiled.attempts.map(({ ok, errors }) => ({ ok, errors: errors.map((error) => shown.text(printable({ rule: "workflow", detail: error }, secrets).detail)) })), digest: learning.compiled.digest ?? null, promoted: learning.compiled.promoted ?? null } : null,
667
451
  draft_errors: (learning.draft_errors ?? []).map((error) => shown.text(printable({ rule: "workflow", detail: error }, secrets).detail)),
668
- // The grade's alone: the end-of-run turn's cost is in the run's own totals.
669
- cost_usd: { grade: cost_usd?.grade ?? null },
670
- tokens: { grade: tokens?.grade ?? null },
671
- // What the job did with the learned skills and workflows it was offered (store-reads/learning.ts learnedUseOf), apart
672
- // from the skills and workflows it learned (notesView's), each name cut of the host's secrets as a note's is.
673
- used: {
674
- skills: (input.used?.skills ?? []).map(({ name, read }) => ({ name: shown.name(name), read })),
675
- workflows: (input.used?.workflows ?? []).map(({ name, calls, failed }) => ({ name: shown.name(name), calls, failed })),
676
- },
452
+ // What the job did with the learned workflows it was offered (store-reads/learning.ts learnedUseOf), each name cut of
453
+ // the host's secrets.
454
+ used: { workflows: (input.used?.workflows ?? []).map(({ name, calls, failed }) => ({ name: shown.name(name), calls, failed })) },
677
455
  };
678
456
  }
679
- /** `text`, an added file, as git's unified diff writes it, hunks only. */
680
- function addedPatch(text) {
681
- if (!text)
682
- return "";
683
- const lines = text.split("\n");
684
- const last = lines.pop();
685
- const added = [...lines.map((one) => `+${one}\n`), ...(last ? [`+${last}\n\\n`] : [])];
686
- return `@@ -0,0 +1${added.length === 1 ? "" : `,${added.length}`} @@\n${added.join("")}`;
687
- }
688
457
  /** GET /runs/{id}/learning/diff over the one store: once merged (its learning end, store-reads/learning.ts
689
458
  * runLearningEnd), its merge commit against its parent, as its merge's script wrote it (`.agentrun/diffs/<run>.json` in
690
- * its agent's learning folder); before, its kept proposal (new notes only, from its learning_proposals row) against its
691
- * seed; a run that proposed nothing, no file, against the seed its launch's learning start names. A run that does not
692
- * learn (no learning start and no learning end) is not_found. A file's patch is withheld when too large (as the script
693
- * wrote it), or when it holds one of the host's secrets now (`shown`); any other is served as every learning text is
694
- * (`shown.text`: a loopback address reads "a local address"). */
459
+ * its agent's learning folder); a run that merged nothing, no file, against the seed its launch's learning start names. A
460
+ * run that does not learn (no learning start and no learning end) is not_found. A file's patch is withheld when too large
461
+ * (as the script wrote it), or when it holds one of the host's secrets now (`shown`); any other is served as every
462
+ * learning text is (`shown.text`: a loopback address reads "a local address"). */
695
463
  export async function runDiffOverStore(data, store, runId, shown) {
696
464
  const [end, kept, launch, row] = await Promise.all([runLearningEnd(store, runId), store.learning.proposal(runId), launchOf(store, runId), store.runs.get(runId)]);
697
465
  const start = launch ? learningStartOf(launch) : undefined;
698
466
  if (!row || (!end && !start))
699
- throw new ApiError("not_found", "the run does not learn, so it proposed nothing");
467
+ throw new ApiError("not_found", "the run does not learn, so it merged nothing");
700
468
  const file = (name, status, patch) => {
701
469
  const path = shown.name(name);
702
470
  if (Buffer.byteLength(patch) > PATCH_CAP)
@@ -713,11 +481,5 @@ export async function runDiffOverStore(data, store, runId, shown) {
713
481
  throw new ApiError("not_found", "the run's merge is not in its agent's learning folder");
714
482
  return { base: diff.parent, head: diff.merge, files: diff.files.map((entry) => ("patch" in entry ? file(entry.path, entry.status, entry.patch) : { path: shown.name(entry.path), status: entry.status, withheld: entry.withheld })) };
715
483
  }
716
- const kept_ = isObject(kept?.proposal) ? kept.proposal.proposal : undefined;
717
- const proposal = isObject(kept_) && typeof kept_.seed === "string" && Array.isArray(kept_.notes) ? { seed: kept_.seed, notes: kept_.notes } : undefined;
718
- if (proposal) {
719
- const notes = proposal.notes.filter((note) => isObject(note) && typeof note.file === "string" && NOTE_FILE.test(note.file) && typeof note.text === "string");
720
- return { base: proposal.seed, head: null, files: notes.map((note) => file(note.file, "added", addedPatch(note.text))) };
721
- }
722
484
  return { base: start?.seed ?? null, head: null, files: [] };
723
485
  }