@parcha/agentrun-serve 0.1.0-beta.51 → 0.1.0-beta.53

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 (322) hide show
  1. package/CHANGELOG.md +160 -1
  2. package/README.md +306 -36
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +14 -4
  5. package/dist/agent-delete.js +30 -58
  6. package/dist/agent-package.d.ts +71 -0
  7. package/dist/agent-package.js +345 -0
  8. package/dist/agents-store.d.ts +28 -18
  9. package/dist/agents-store.js +48 -34
  10. package/dist/api-only.d.ts +30 -8
  11. package/dist/api-only.js +40 -16
  12. package/dist/archil-routes.d.ts +1 -0
  13. package/dist/archil-routes.js +28 -2
  14. package/dist/claude-login.d.ts +1 -0
  15. package/dist/claude-login.js +1 -1
  16. package/dist/cli-learning/cli.d.ts +3 -0
  17. package/dist/cli-learning/cli.js +17 -3
  18. package/dist/cli-learning/connections.js +3 -2
  19. package/dist/cli-learning/schema.js +2 -1
  20. package/dist/cli.js +70 -7
  21. package/dist/composio-preset.d.ts +2 -1
  22. package/dist/composio-preset.js +4 -3
  23. package/dist/composio-triggers.d.ts +4 -0
  24. package/dist/composio-triggers.js +4 -1
  25. package/dist/computer-needs.d.ts +32 -0
  26. package/dist/computer-needs.js +80 -0
  27. package/dist/computer-setting.d.ts +9 -0
  28. package/dist/computer-setting.js +19 -1
  29. package/dist/computers.d.ts +6 -2
  30. package/dist/computers.js +2 -2
  31. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  32. package/dist/console/assets/index-DbilxljH.css +1 -0
  33. package/dist/console/index.html +2 -2
  34. package/dist/console-links.d.ts +1 -0
  35. package/dist/console-links.js +2 -0
  36. package/dist/env-switch.d.ts +14 -0
  37. package/dist/env-switch.js +23 -0
  38. package/dist/errors.d.ts +1 -0
  39. package/dist/errors.js +3 -0
  40. package/dist/eval-previous.js +4 -3
  41. package/dist/fal-price.d.ts +76 -0
  42. package/dist/fal-price.js +365 -0
  43. package/dist/handed-secret.d.ts +4 -0
  44. package/dist/handed-secret.js +10 -0
  45. package/dist/harness-archive.d.ts +15 -5
  46. package/dist/harness-archive.js +71 -34
  47. package/dist/harness-check.d.ts +2 -1
  48. package/dist/harness-check.js +36 -95
  49. package/dist/harness-egress.d.ts +23 -0
  50. package/dist/harness-egress.js +69 -0
  51. package/dist/harness-recipe-entry.d.ts +71 -0
  52. package/dist/harness-recipe-entry.js +184 -0
  53. package/dist/harness-recipe.d.ts +73 -6
  54. package/dist/harness-recipe.js +185 -31
  55. package/dist/harness-sign-in.d.ts +29 -0
  56. package/dist/harness-sign-in.js +122 -0
  57. package/dist/harness-table.d.ts +21 -0
  58. package/dist/harness-table.js +58 -3
  59. package/dist/harness-zip.d.ts +6 -0
  60. package/dist/harness-zip.js +203 -0
  61. package/dist/ids.d.ts +11 -0
  62. package/dist/ids.js +36 -0
  63. package/dist/learn/commit.d.ts +19 -1
  64. package/dist/learn/commit.js +160 -2
  65. package/dist/learn/compile.d.ts +13 -5
  66. package/dist/learn/compile.js +46 -15
  67. package/dist/learn/delete.d.ts +12 -6
  68. package/dist/learn/delete.js +17 -11
  69. package/dist/learn/folder.d.ts +16 -0
  70. package/dist/learn/folder.js +30 -4
  71. package/dist/learn/learning-of.d.ts +8 -0
  72. package/dist/learn/learning-of.js +8 -0
  73. package/dist/learn/learning.sh +29 -4
  74. package/dist/learn/promote.d.ts +51 -7
  75. package/dist/learn/promote.js +51 -8
  76. package/dist/learn/secrets.js +30 -7
  77. package/dist/learning-reset.d.ts +18 -0
  78. package/dist/learning-reset.js +115 -0
  79. package/dist/learning-routes.d.ts +23 -11
  80. package/dist/learning-routes.js +110 -20
  81. package/dist/learning-words.d.ts +5 -0
  82. package/dist/learning-words.js +5 -0
  83. package/dist/learning.d.ts +15 -10
  84. package/dist/learning.js +14 -8
  85. package/dist/llms.txt +1 -0
  86. package/dist/mcp-gateway.d.ts +39 -2
  87. package/dist/mcp-gateway.js +56 -12
  88. package/dist/mcp-pin-first.js +1 -1
  89. package/dist/mcp-probe.d.ts +3 -0
  90. package/dist/mcp-probe.js +7 -2
  91. package/dist/mcp-resources.d.ts +44 -0
  92. package/dist/mcp-resources.js +100 -0
  93. package/dist/mcp-servers-store.d.ts +17 -12
  94. package/dist/mcp-servers-store.js +2 -1
  95. package/dist/media-duration.d.ts +2 -0
  96. package/dist/media-duration.js +136 -0
  97. package/dist/model.d.ts +4 -4
  98. package/dist/model.js +6 -6
  99. package/dist/native/cli.js +9 -2
  100. package/dist/native/connection.d.ts +2 -2
  101. package/dist/native/connection.js +5 -2
  102. package/dist/native/discovery.d.ts +2 -0
  103. package/dist/native/discovery.js +10 -6
  104. package/dist/native/remote-worker-bridge.js +36 -4
  105. package/dist/native/remote.d.ts +18 -1
  106. package/dist/native/remote.js +126 -37
  107. package/dist/native/schema.d.ts +6 -0
  108. package/dist/native/schema.js +31 -6
  109. package/dist/native/source-account.d.ts +13 -0
  110. package/dist/native/source-account.js +114 -0
  111. package/dist/native/source-capture-hooks.d.ts +5 -0
  112. package/dist/native/source-capture-hooks.js +102 -0
  113. package/dist/native/source-mcp-selection.d.ts +13 -0
  114. package/dist/native/source-mcp-selection.js +72 -0
  115. package/dist/native/source-runtime-tools.d.ts +19 -0
  116. package/dist/native/source-runtime-tools.js +103 -0
  117. package/dist/native/source-snapshot-types.d.ts +138 -0
  118. package/dist/native/source-snapshot-types.js +12 -0
  119. package/dist/native/source-snapshot.d.ts +8 -0
  120. package/dist/native/source-snapshot.js +1201 -0
  121. package/dist/observation/learning.js +3 -2
  122. package/dist/openapi.js +211 -47
  123. package/dist/print.js +1 -1
  124. package/dist/provider.d.ts +8 -0
  125. package/dist/provider.js +14 -2
  126. package/dist/purged-workflow.d.ts +12 -0
  127. package/dist/purged-workflow.js +43 -0
  128. package/dist/refusal-words.d.ts +0 -3
  129. package/dist/refusal-words.js +0 -3
  130. package/dist/request-metadata.d.ts +20 -0
  131. package/dist/request-metadata.js +24 -0
  132. package/dist/run-keys.d.ts +46 -0
  133. package/dist/run-keys.js +109 -0
  134. package/dist/run-launch.d.ts +29 -5
  135. package/dist/run-launch.js +44 -4
  136. package/dist/run-learning-served.d.ts +2 -2
  137. package/dist/run-model-key.d.ts +2 -2
  138. package/dist/run-model-key.js +5 -5
  139. package/dist/run-secrets.d.ts +2 -0
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-usage.d.ts +48 -4
  142. package/dist/run-usage.js +156 -39
  143. package/dist/run-view.d.ts +18 -1
  144. package/dist/run-view.js +28 -8
  145. package/dist/runner/adapter-loop.d.ts +14 -4
  146. package/dist/runner/adapter-loop.js +150 -31
  147. package/dist/runner/adapter-run-spec.d.ts +1 -1
  148. package/dist/runner/adapter-run-spec.js +35 -22
  149. package/dist/runner/audit.d.ts +10 -3
  150. package/dist/runner/audit.js +30 -7
  151. package/dist/runner/beside.js +2 -1
  152. package/dist/runner/claim-secrets.d.ts +31 -4
  153. package/dist/runner/claim-secrets.js +43 -7
  154. package/dist/runner/cli-run-spec.d.ts +1 -1
  155. package/dist/runner/cli-run-spec.js +32 -20
  156. package/dist/runner/conformance/harness.js +4 -2
  157. package/dist/runner/dispatch.js +4 -2
  158. package/dist/runner/harness-loops.d.ts +6 -0
  159. package/dist/runner/harness-loops.js +16 -3
  160. package/dist/runner/held.d.ts +4 -0
  161. package/dist/runner/journal-kinds.d.ts +5 -0
  162. package/dist/runner/learned-first.d.ts +2 -0
  163. package/dist/runner/learned-first.js +1 -1
  164. package/dist/runner/learning-end.d.ts +9 -3
  165. package/dist/runner/learning-end.js +66 -29
  166. package/dist/runner/learning-seed.d.ts +9 -3
  167. package/dist/runner/learning-seed.js +2 -2
  168. package/dist/runner/main.d.ts +1 -0
  169. package/dist/runner/main.js +20 -13
  170. package/dist/runner/mcp-claim.js +7 -2
  171. package/dist/runner/mcp-run.d.ts +12 -0
  172. package/dist/runner/mcp-run.js +14 -1
  173. package/dist/runner/model-route.js +7 -4
  174. package/dist/runner/monid-run.js +9 -11
  175. package/dist/runner/project-checkpoint.d.ts +35 -0
  176. package/dist/runner/project-checkpoint.js +116 -0
  177. package/dist/runner/project-drain.d.ts +8 -0
  178. package/dist/runner/project-drain.js +25 -0
  179. package/dist/runner/project-host.d.ts +10 -0
  180. package/dist/runner/project-host.js +52 -0
  181. package/dist/runner/promotion.d.ts +51 -24
  182. package/dist/runner/promotion.js +206 -78
  183. package/dist/runner/redact.d.ts +13 -0
  184. package/dist/runner/redact.js +67 -1
  185. package/dist/runner/run-channel.d.ts +9 -0
  186. package/dist/runner/run-channel.js +15 -2
  187. package/dist/runner/run-child-host.d.ts +8 -4
  188. package/dist/runner/run-child-host.js +174 -42
  189. package/dist/runner/run-errors.js +2 -2
  190. package/dist/runner/runner-check.js +5 -2
  191. package/dist/runner/runner.js +41 -12
  192. package/dist/runner/sdk-loop.d.ts +2 -2
  193. package/dist/runner/sdk-loop.js +3 -3
  194. package/dist/runner/store-port.d.ts +3 -0
  195. package/dist/runner/store-secrets.js +7 -3
  196. package/dist/runner/workflow-first.d.ts +4 -0
  197. package/dist/runner/workflow-first.js +13 -0
  198. package/dist/runner/workflow-loop.d.ts +2 -1
  199. package/dist/runner/workflow-loop.js +2 -1
  200. package/dist/runner/workflow-spec.js +4 -4
  201. package/dist/runs-over-store.d.ts +39 -8
  202. package/dist/runs-over-store.js +147 -32
  203. package/dist/sdk/check.d.ts +6 -5
  204. package/dist/sdk/check.js +17 -16
  205. package/dist/sdk/runs.d.ts +11 -1
  206. package/dist/sdk/runs.js +185 -78
  207. package/dist/sdk/schema.js +12 -2
  208. package/dist/sdk/workflows.d.ts +1 -1
  209. package/dist/server.d.ts +68 -32
  210. package/dist/server.js +678 -124
  211. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  212. package/dist/source-sync/adoption.d.ts +15 -0
  213. package/dist/source-sync/adoption.js +36 -0
  214. package/dist/source-sync/auxiliary.d.ts +23 -0
  215. package/dist/source-sync/auxiliary.js +64 -0
  216. package/dist/source-sync/capture-git.d.ts +5 -0
  217. package/dist/source-sync/capture-git.js +272 -0
  218. package/dist/source-sync/capture-project.d.ts +53 -0
  219. package/dist/source-sync/capture-project.js +206 -0
  220. package/dist/source-sync/capture-refusal.d.ts +7 -0
  221. package/dist/source-sync/capture-refusal.js +16 -0
  222. package/dist/source-sync/capture.d.ts +11 -0
  223. package/dist/source-sync/capture.js +22 -0
  224. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  225. package/dist/source-sync/checkpoint-gate.js +52 -0
  226. package/dist/source-sync/checkpoints.d.ts +66 -0
  227. package/dist/source-sync/checkpoints.js +168 -0
  228. package/dist/source-sync/claim.d.ts +11 -0
  229. package/dist/source-sync/claim.js +48 -0
  230. package/dist/source-sync/destination.d.ts +47 -0
  231. package/dist/source-sync/destination.js +239 -0
  232. package/dist/source-sync/io.d.ts +15 -0
  233. package/dist/source-sync/io.js +52 -0
  234. package/dist/source-sync/local.d.ts +43 -0
  235. package/dist/source-sync/local.js +229 -0
  236. package/dist/source-sync/prepare.d.ts +59 -0
  237. package/dist/source-sync/prepare.js +93 -0
  238. package/dist/source-sync/projects.d.ts +61 -0
  239. package/dist/source-sync/projects.js +130 -0
  240. package/dist/source-sync/registry.d.ts +95 -0
  241. package/dist/source-sync/registry.js +226 -0
  242. package/dist/source-sync/service.d.ts +33 -0
  243. package/dist/source-sync/service.js +118 -0
  244. package/dist/source-sync/skill-edits.d.ts +12 -0
  245. package/dist/source-sync/skill-edits.js +122 -0
  246. package/dist/source-sync/snapshots.d.ts +48 -0
  247. package/dist/source-sync/snapshots.js +448 -0
  248. package/dist/source-sync/types.d.ts +9 -0
  249. package/dist/source-sync/types.js +14 -0
  250. package/dist/source-sync/workspace.d.ts +66 -0
  251. package/dist/source-sync/workspace.js +273 -0
  252. package/dist/store/agent-body.d.ts +8 -0
  253. package/dist/store/agent-body.js +20 -6
  254. package/dist/store/index.d.ts +2 -2
  255. package/dist/store/index.js +1 -1
  256. package/dist/store/journal/storage.d.ts +2 -0
  257. package/dist/store/journal/storage.js +2 -1
  258. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  259. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  260. package/dist/store/schema.d.ts +15 -1
  261. package/dist/store/schema.js +43 -4
  262. package/dist/store/seal.d.ts +5 -1
  263. package/dist/store/seal.js +12 -3
  264. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  265. package/dist/store/sqlite/project-checkpoints.js +70 -0
  266. package/dist/store/sqlite/run-launch.d.ts +14 -0
  267. package/dist/store/sqlite/run-launch.js +58 -7
  268. package/dist/store/sqlite/run-patch.d.ts +2 -1
  269. package/dist/store/sqlite/run-patch.js +4 -3
  270. package/dist/store/sqlite/store.js +319 -153
  271. package/dist/store/store-schema.js +2 -2
  272. package/dist/store/store.d.ts +173 -33
  273. package/dist/store/store.js +14 -1
  274. package/dist/store-reads/learning.d.ts +12 -8
  275. package/dist/store-reads/learning.js +33 -24
  276. package/dist/store-reads/loop.d.ts +4 -3
  277. package/dist/store-reads/loop.js +7 -5
  278. package/dist/store-view.d.ts +3 -1
  279. package/dist/store-view.js +17 -5
  280. package/dist/template-eval.js +4 -4
  281. package/dist/template-import.d.ts +10 -2
  282. package/dist/template-import.js +116 -13
  283. package/dist/templates.d.ts +29 -5
  284. package/dist/templates.js +68 -14
  285. package/dist/timeline/index.d.ts +1 -1
  286. package/dist/timeline/index.js +1 -1
  287. package/dist/timeline/labels.js +1 -1
  288. package/dist/timeline/timeline.d.ts +5 -0
  289. package/dist/timeline/timeline.js +8 -0
  290. package/dist/tool-plane.d.ts +12 -12
  291. package/dist/tools.d.ts +8 -8
  292. package/dist/tools.js +1 -1
  293. package/dist/trigger-launch-hook.d.ts +47 -0
  294. package/dist/trigger-launch-hook.js +90 -0
  295. package/dist/trigger-targets.d.ts +14 -1
  296. package/dist/trigger-targets.js +20 -0
  297. package/dist/triggers.d.ts +54 -5
  298. package/dist/triggers.js +143 -8
  299. package/dist/uploads-archil.js +2 -1
  300. package/dist/uploads.d.ts +0 -3
  301. package/dist/uploads.js +2 -11
  302. package/dist/validate.js +4 -1
  303. package/dist/web-save.d.ts +3 -0
  304. package/dist/web-save.js +17 -2
  305. package/dist/workspace/archil-exec.js +1 -1
  306. package/dist/workspace/archil.js +1 -1
  307. package/dist/workspace/computer-for-claim.d.ts +2 -0
  308. package/dist/workspace/computer-for-claim.js +43 -0
  309. package/dist/workspace/paths.d.ts +6 -0
  310. package/dist/workspace/paths.js +6 -0
  311. package/dist/workspace/resolve-computer.d.ts +1 -0
  312. package/dist/workspace/revision-skills.js +24 -11
  313. package/dist/workspace/run-tools.d.ts +2 -0
  314. package/dist/workspace/run-tools.js +8 -0
  315. package/dist/workspace/synced-folder.d.ts +3 -3
  316. package/dist/workspace/synced-folder.js +7 -6
  317. package/launcher/agentrun-serve +1 -1
  318. package/package.json +10 -10
  319. package/skills/agentrun-serve/SKILL.md +2 -1
  320. package/templates/README.md +5 -2
  321. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  322. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -11,7 +11,9 @@
11
11
  # `update-ref refs/heads/main <new> <old>`, the compare and swap. A lost race exits 3 and writes nothing. A run's
12
12
  # merge also creates `refs/agentrun/runs/<run>` in the same ref transaction, so a run (and round) merges once: a
13
13
  # second merge of it, however it raced the first, exits 6 and writes nothing but the first one's diff file when a
14
- # stop left it none;
14
+ # stop left it none. The host's scrub of a purged run's merge creates `refs/agentrun/purged/<run>` (its
15
+ # round's key, as its diff file is named) the same way, so it lands once too (a second exits 6 with the first's
16
+ # commit);
15
17
  # 2. for a run's merge, `.agentrun/diffs/<run>.json`: each path's patch, parent against merge, as git diffs it;
16
18
  # 3. the working tree brought in line with the new main (read-tree -u --reset);
17
19
  # 4. `.agentrun/snapshot.json`, written to a temporary name and moved into place, LAST.
@@ -32,10 +34,15 @@
32
34
  # snapshot <json> snapshot.json, one line, where a \001M\001 stands for the new main
33
35
  # path <path> (a merge) a path its diff covers
34
36
  # absent <path> <path> must not be on <old>, any mode, any type (else 4: "absent <path>" on stdout)
35
- # same <commit> <path> <path> must be the same on <commit> as on <old> (else 4: "same <path>" on stdout)
37
+ # same <commit> <path> <path> must be the same on <commit> as on <old> (else 4: "same <path>" on stdout); a
38
+ # <commit> the repository does not hold fails it (the folder was reset since it was read)
39
+ # seed <commit> (a run's merge) the commit the run was seeded from, which the repository held as its end began
40
+ # and must hold still (else 4: "seed <commit>" on stdout): a reset since merges nothing, a
41
+ # correction alone included
42
+ # purged <run> (the host's scrub of a purged run's merge, <run> its round's key) that scrub, which lands once
36
43
  # Exit: 0 done (the new main on stdout), 3 stale (main as it is on stdout), 4 a precondition failed, 5 main moved but
37
- # the files could not be brought in line (the new main on stdout; no snapshot written), 6 the run merged already (its
38
- # merge on stdout), else git's error on stderr.
44
+ # the files could not be brought in line (the new main on stdout; no snapshot written), 6 the run merged already, or
45
+ # the purged run's scrub landed already (that commit on stdout), else git's error on stderr.
39
46
  set -u
40
47
  set -f
41
48
 
@@ -187,10 +194,19 @@ preconditions() {
187
194
  done < "$tmp/absent"
188
195
  sed -n 's/^same //p' "$tmp/head" > "$tmp/same"
189
196
  while read -r c p; do
197
+ # A commit this repository does not hold (the agent's learning reset after the run read it) is no ground to merge on.
198
+ if ! g cat-file -e "$c^{commit}" 2>/dev/null; then
199
+ printf 'same %s\n' "$p" >> "$tmp/failed"
200
+ continue
201
+ fi
190
202
  a=$(g rev-parse -q --verify "$c:$p" 2>/dev/null || true)
191
203
  b=$(g rev-parse -q --verify "$old:$p" 2>/dev/null || true)
192
204
  [ "$a" = "$b" ] || printf 'same %s\n' "$p" >> "$tmp/failed"
193
205
  done < "$tmp/same"
206
+ sed -n 's/^seed //p' "$tmp/head" > "$tmp/seed"
207
+ while read -r c; do
208
+ g cat-file -e "$c^{commit}" 2>/dev/null || printf 'seed %s\n' "$c" >> "$tmp/failed"
209
+ done < "$tmp/seed"
194
210
  if [ -s "$tmp/failed" ]; then
195
211
  cat "$tmp/failed"
196
212
  exit 4
@@ -252,6 +268,10 @@ commit() {
252
268
  case $ref in
253
269
  *[!0-9a-z/-]*) die "the import ref is not one this script takes" ;;
254
270
  esac
271
+ purged=$(sed -n 's/^purged //p' "$tmp/head")
272
+ case $purged in
273
+ *[!A-Za-z0-9._-]*) die "a purged run's key is letters, digits, dots, dashes and underscores" ;;
274
+ esac
255
275
  cur=$(main_now)
256
276
  if [ "$cur" != "$old" ]; then
257
277
  printf '%s\n' "$cur"
@@ -271,12 +291,17 @@ commit() {
271
291
  # there), both or neither.
272
292
  printf 'update refs/heads/main %s %s\n' "$new" "${old:-$ZERO}" > "$tmp/refs"
273
293
  [ -n "$run" ] && printf 'create refs/agentrun/runs/%s %s\n' "$run" "$new" >> "$tmp/refs"
294
+ [ -n "$purged" ] && printf 'create refs/agentrun/purged/%s %s\n' "$purged" "$new" >> "$tmp/refs"
274
295
  if ! g update-ref -m learning --stdin < "$tmp/refs" 2> "$tmp/cas"; then
275
296
  if [ -n "$run" ] && merged=$(g rev-parse -q --verify "refs/agentrun/runs/$run^{commit}" 2> /dev/null); then
276
297
  diff_of_ref "$run" "$merged"
277
298
  printf '%s\n' "$merged"
278
299
  exit 6
279
300
  fi
301
+ if [ -n "$purged" ] && scrubbed=$(g rev-parse -q --verify "refs/agentrun/purged/$purged^{commit}" 2> /dev/null); then
302
+ printf '%s\n' "$scrubbed"
303
+ exit 6
304
+ fi
280
305
  cur=$(main_now)
281
306
  if [ "$cur" != "$old" ]; then
282
307
  printf '%s\n' "$cur"
@@ -80,9 +80,10 @@ export interface PromotionRecord {
80
80
  /** The learning commit whose workflows/<workflow>/workflow.json is this digest's text: the seed of the claim that
81
81
  * recorded it. What the digest serves from as the champion (championOf) once a newer revision is on the folder's main. */
82
82
  readonly commit?: string;
83
- /** `sdk`: a connected (SDK) agent's check (runner/promotion.ts reserveSdkCheck), on its reservation and the record that
84
- * decides it. Its one run (`runs`) is the agent's own native turn, not a replay run; a replaying one with no `runs`
85
- * waits for the next native turn the draft takes. Absent: a server replay's. */
83
+ /** `sdk`: a connected (SDK) agent's check (runner/promotion.ts reserveSdkCheck), on each reservation and the record that
84
+ * decides it. Its one run (`runs`) is the agent's native turn reserved now, not a replay run; a replaying one with no
85
+ * `runs` waits for the next native turn the draft takes. It collects its checked turns (`check.turns`) and decides once
86
+ * it holds compile_after of them, as a managed check decides once on its inputs. Absent: a server replay's. */
86
87
  readonly via?: "sdk";
87
88
  }
88
89
  /** One audit row a hold was decided on that disagreed: the served run (`served`) and its input, the run whose answer is
@@ -146,17 +147,34 @@ export type CheckRecord = CheckBar & {
146
147
  readonly skipped_tools?: readonly SkippedTool[];
147
148
  readonly disagreements?: readonly CheckDisagreement[];
148
149
  readonly stopped?: true;
149
- /** A connected agent's check: how many of its reserved native turns gave no answer to check the draft against (a
150
- * cancelled or refused turn, a subagent, redacted evidence, no shadow report) and were given back to wait for the
151
- * next one (runner/promotion.ts SDK_CHECK_RELEASES stops it). Absent: none. */
150
+ /** A connected agent's check: how many of its reserved native turns in a row gave no answer to check the draft against
151
+ * and were given back to wait for the next one (see runner/promotion.ts SDK_CHECK_RELEASES for the causes, and the
152
+ * hold it ends in). Absent: none. */
152
153
  readonly released?: number;
153
154
  /** A connected agent's check: how many fresh read-only calls its shadow made where the native turn's recording had
154
155
  * no result (the client's opt-in shadowReadFallback). Absent: none, every call was answered from the recording. */
155
156
  readonly fresh_reads?: number;
157
+ /** A connected agent's check still collecting native turns (runner/promotion.ts sdkCheckTurn): the turns checked so
158
+ * far, until it holds compile_after of them and decides once on them all. Absent once decided on them, and on a
159
+ * managed check; a check stopped or set aside before it held them keeps the turns it had. */
160
+ readonly turns?: CheckTurns;
156
161
  /** How it compared with no agree_on: the fast model that read the answers (its name), when it was asked on any input.
157
162
  * With agree_on, the paths compared (CheckBar.agree_on); with neither, the whole answer. */
158
163
  readonly grader?: string;
159
164
  };
165
+ /** A connected agent's checked native turns before its check decides, counted as a decided check counts its inputs:
166
+ * `n` turns, `agreed` and `alone` of them, the agent's runs (`of`, newest first), one outcome per turn (a turn past its
167
+ * deadline failed), each turn it did not agree on, and the shadows' fresh reads. Each is compared on its own turn, its
168
+ * texts cut as a decided check's are. */
169
+ export interface CheckTurns {
170
+ readonly n: number;
171
+ readonly agreed: number;
172
+ readonly alone: number;
173
+ readonly of: readonly string[];
174
+ readonly outcomes: ReplayOutcomes;
175
+ readonly disagreements?: readonly CheckDisagreement[];
176
+ readonly fresh_reads?: number;
177
+ }
160
178
  /** The most characters of an input or an answer a check's disagreement keeps. */
161
179
  export declare const CHECK_TEXT_MAX = 1200;
162
180
  /** A check's two shares: `agreement`, of the inputs the draft answered alone those that say what the agent said (0 when
@@ -196,6 +214,30 @@ export declare function skippedToolsOf(rows: readonly {
196
214
  }[]): SkippedTool[];
197
215
  export declare const gradesKey: (agentId: string) => string;
198
216
  export declare const promotionsKey: (agentId: string) => string;
217
+ /** A learned workflow revision an agent's learning reset deleted (DELETE /agents/{id}/learning, learning-reset.ts): its
218
+ * workflow, its digest and its K (its check's compile_after; null when its records named none), nothing else of its
219
+ * records. What the runs it served carry of its compile and check (store-reads/learning.ts revisionLedgerOf) is read
220
+ * from it after the reset, so a kept run's cost reads as before. The runs keep the same names and digests. */
221
+ export interface ResetRevision {
222
+ readonly workflow: string;
223
+ readonly digest: string;
224
+ readonly k: number | null;
225
+ }
226
+ export declare const resetLedgerKey: (agentId: string) => string;
227
+ /** The revisions the agent's resets deleted, first reset first. */
228
+ export declare const resetLedgerOf: (settings: Pick<Settings, "get">, agentId: string) => Promise<ResetRevision[]>;
229
+ /** Each revision `records` name (one per workflow and digest, its newest record's K) added to the agent's reset ledger,
230
+ * before a reset deletes the records. A revision it holds already keeps its place and takes the records' K: while they
231
+ * stood, the ledger read their K (revisionLedgerOf), so the runs' shares read the same after this reset too. */
232
+ export declare function keepResetLedger(settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, agentId: string, records: readonly PromotionRecord[]): Promise<void>;
233
+ /** The agent's reset watermark: when its newest reset began (epoch ms). Learning reads only the runs after it
234
+ * (learn/compile.ts sinceReset): a run that started, or read its learning seed, at or before it learns nothing and is
235
+ * read by no compile, check, audit or money rule. Kept with the reset ledger, and removed with it by the agent's delete (learn/delete.ts). */
236
+ export declare const resetAtKey: (agentId: string) => string;
237
+ /** The agent's reset watermark (resetAtKey), or undefined when its learning was never reset. */
238
+ export declare const resetAtOf: (settings: Pick<Settings, "get">, agentId: string) => Promise<number | undefined>;
239
+ /** Agent `agentId`'s reset watermark set to `at`, in place of an earlier reset's. */
240
+ export declare const keepResetAt: (settings: Pick<Settings, "put">, agentId: string, at: number) => Promise<void>;
199
241
  /** The agent's grades, oldest first. */
200
242
  export declare const gradesOf: (settings: Pick<Settings, "get">, agentId: string) => Promise<Grade[]>;
201
243
  /** Keeps `grade`, in place of any earlier grade of the same run, the newest GRADES_KEPT kept, at the next `seq`. */
@@ -276,7 +318,9 @@ export type Recorded = {
276
318
  };
277
319
  /** Keeps `record` as the newest of its workflow at its digest, when `still` holds of the one there now (none: undefined)
278
320
  * and of every record kept (`items`: a check across revisions, one at a time, in the same guarded write): so of two
279
- * claims deciding at once only the first decision is kept, and only its claim acts on it (Recorded.won). */
321
+ * claims deciding at once only the first decision is kept, and only its claim acts on it (Recorded.won). What the one
322
+ * there now has blanked is blanked in `record` too (forgetRunIn): a record built on a copy read before a run's purge
323
+ * (a connected agent's next turn, release or decision carries its turns on) never writes that run's text back. */
280
324
  export declare function recordPromotion(settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, agentId: string, record: PromotionRecord, still: (now: PromotionRecord | undefined, items: readonly PromotionRecord[]) => boolean): Promise<Recorded>;
281
325
  /** The newest records, at most PROMOTIONS_KEPT, in order, with each workflow's champion (championOf) the same after as
282
326
  * before, whatever was dropped: championOf reads the digest promoted last and its newest record, so the trim keeps both
@@ -7,6 +7,7 @@
7
7
  // its workflows' promotion records), over the settings table; the orchestration is runner/promotion.ts. Grades are what
8
8
  // a person or an eval said of a run (PUT /runs/{id}/grade).
9
9
  import { createHash } from "node:crypto";
10
+ import { isDeepStrictEqual } from "node:util";
10
11
  import { answerJson } from "../answer-json.js";
11
12
  import { pathSegments } from "../learning-setting.js";
12
13
  import { isObject } from "../validate.js";
@@ -61,6 +62,35 @@ async function updateKept(settings, key, update) {
61
62
  }
62
63
  throw new Error(`${key} kept changing under this write; try again`);
63
64
  }
65
+ export const resetLedgerKey = (agentId) => `learning.reset-ledger.${agentId}`;
66
+ /** The revisions the agent's resets deleted, first reset first. */
67
+ export const resetLedgerOf = async (settings, agentId) => itemsOf(await settings.get(resetLedgerKey(agentId)));
68
+ /** Each revision `records` name (one per workflow and digest, its newest record's K) added to the agent's reset ledger,
69
+ * before a reset deletes the records. A revision it holds already keeps its place and takes the records' K: while they
70
+ * stood, the ledger read their K (revisionLedgerOf), so the runs' shares read the same after this reset too. */
71
+ export async function keepResetLedger(settings, agentId, records) {
72
+ const newest = new Map();
73
+ for (const record of records)
74
+ newest.set(`${record.workflow}\0${record.digest}`, { workflow: record.workflow, digest: record.digest, k: record.check?.compile_after ?? null });
75
+ if (!newest.size)
76
+ return;
77
+ await updateKept(settings, resetLedgerKey(agentId), (items) => {
78
+ const held = new Set(items.map((one) => `${one.workflow}\0${one.digest}`));
79
+ return [...items.map((one) => newest.get(`${one.workflow}\0${one.digest}`) ?? one), ...[...newest].filter(([key]) => !held.has(key)).map(([, one]) => one)];
80
+ });
81
+ }
82
+ /** The agent's reset watermark: when its newest reset began (epoch ms). Learning reads only the runs after it
83
+ * (learn/compile.ts sinceReset): a run that started, or read its learning seed, at or before it learns nothing and is
84
+ * read by no compile, check, audit or money rule. Kept with the reset ledger, and removed with it by the agent's delete (learn/delete.ts). */
85
+ export const resetAtKey = (agentId) => `learning.reset-at.${agentId}`;
86
+ /** The agent's reset watermark (resetAtKey), or undefined when its learning was never reset. */
87
+ export const resetAtOf = async (settings, agentId) => {
88
+ const read = await settings.get(resetAtKey(agentId));
89
+ const at = typeof read === "object" && read !== null ? read.at : undefined;
90
+ return typeof at === "number" && Number.isFinite(at) ? at : undefined;
91
+ };
92
+ /** Agent `agentId`'s reset watermark set to `at`, in place of an earlier reset's. */
93
+ export const keepResetAt = (settings, agentId, at) => settings.put(resetAtKey(agentId), { at });
64
94
  /** The agent's grades, oldest first. */
65
95
  export const gradesOf = async (settings, agentId) => itemsOf(await settings.get(gradesKey(agentId)));
66
96
  /** Keeps `grade`, in place of any earlier grade of the same run, the newest GRADES_KEPT kept, at the next `seq`. */
@@ -88,24 +118,31 @@ const blankCheck = (one) => ({
88
118
  });
89
119
  /** An audit's disagreement blanked the same way: its run ids and whether a grade wrote it kept. */
90
120
  const blankAudit = (one) => ({ run: one.run, served: one.served, input: "", agent: null, draft: null, ...(one.graded ? { graded: true } : {}) });
91
- /** `record` with what it copied from run `runId` blanked: each disagreement naming it (a check's agent run; an audit's
92
- * served run or shadow run), and the grader's words its reason quotes from one (differentDecisionWords' example). Its
93
- * decision, numbers and run ids stay. The record itself when it names no such disagreement. */
121
+ /** `record` with what it copied from run `runId` blanked: each disagreement naming it (a check's agent run, a connected
122
+ * agent's collected turn too; an audit's served run or shadow run), and the grader's words its reason quotes from one
123
+ * (differentDecisionWords' example). Its decision, numbers and run ids stay. The record itself when it names no such
124
+ * disagreement. */
94
125
  function forgetRunIn(record, runId) {
95
126
  if (!record || typeof record !== "object")
96
127
  return record;
97
128
  const check = record.check?.disagreements?.some((one) => one.run === runId);
129
+ const turns = record.check?.turns?.disagreements?.some((one) => one.run === runId);
98
130
  const audit = record.audit?.disagreements.some((one) => one.run === runId || one.served === runId);
99
- if (!check && !audit)
131
+ if (!check && !turns && !audit)
100
132
  return record;
101
133
  let reason = record.reason;
102
134
  for (const one of record.check?.disagreements ?? [])
103
135
  if (one.run === runId && one.differs_on !== undefined)
104
136
  reason = reason.replace(` (for example: ${one.differs_on})`, "");
137
+ const blanked = (list) => list.map((one) => (one.run === runId ? blankCheck(one) : one));
105
138
  return {
106
139
  ...record,
107
140
  reason,
108
- ...(check && record.check ? { check: { ...record.check, disagreements: record.check.disagreements.map((one) => (one.run === runId ? blankCheck(one) : one)) } } : {}),
141
+ ...((check || turns) && record.check ? { check: {
142
+ ...record.check,
143
+ ...(check ? { disagreements: blanked(record.check.disagreements) } : {}),
144
+ ...(turns ? { turns: { ...record.check.turns, disagreements: blanked(record.check.turns.disagreements) } } : {}),
145
+ } } : {}),
109
146
  ...(audit && record.audit ? { audit: { ...record.audit, disagreements: record.audit.disagreements.map((one) => (one.run === runId || one.served === runId ? blankAudit(one) : one)) } } : {}),
110
147
  };
111
148
  }
@@ -214,9 +251,14 @@ export function shownDeep(value, shown, key) {
214
251
  : value !== null && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([field, one]) => [field, shownDeep(one, shown, field)]))
215
252
  : value;
216
253
  }
254
+ /** The runs whose copies `record`'s check has blanked (forgetRunIn): each disagreement, decided or of a turn collected,
255
+ * left as blankCheck leaves it. */
256
+ const blankedRuns = (record) => [...(record?.check?.disagreements ?? []), ...(record?.check?.turns?.disagreements ?? [])].filter((one) => isDeepStrictEqual(one, blankCheck(one))).map((one) => one.run);
217
257
  /** Keeps `record` as the newest of its workflow at its digest, when `still` holds of the one there now (none: undefined)
218
258
  * and of every record kept (`items`: a check across revisions, one at a time, in the same guarded write): so of two
219
- * claims deciding at once only the first decision is kept, and only its claim acts on it (Recorded.won). */
259
+ * claims deciding at once only the first decision is kept, and only its claim acts on it (Recorded.won). What the one
260
+ * there now has blanked is blanked in `record` too (forgetRunIn): a record built on a copy read before a run's purge
261
+ * (a connected agent's next turn, release or decision carries its turns on) never writes that run's text back. */
220
262
  export async function recordPromotion(settings, agentId, record, still) {
221
263
  let out = { record, won: true };
222
264
  await updateKept(settings, promotionsKey(agentId), (saved) => {
@@ -226,8 +268,9 @@ export async function recordPromotion(settings, agentId, record, still) {
226
268
  out = { record: now, won: false };
227
269
  return items;
228
270
  }
229
- out = { record, won: true };
230
- return trimPromotions([...items, record]);
271
+ const kept = blankedRuns(now).reduce(forgetRunIn, record);
272
+ out = { record: kept, won: true };
273
+ return trimPromotions([...items, kept]);
231
274
  });
232
275
  return out;
233
276
  }
@@ -142,21 +142,44 @@ export function redactLearned(text, values, max = PRINT_MAX) {
142
142
  function redactWith(text, values, max, shapes, shapesOf) {
143
143
  if (Buffer.byteLength(text) > max)
144
144
  return "[redacted]";
145
- const given = withPathSpellings(values.filter((v) => v.length > 0));
146
- const forms = new Set(given.flatMap((v) => [v, asJson(v), ...(longEnough(v) ? [...needlesOf(v).plain, ...percentForms(v)] : [])]).filter((form) => form.length > 0));
145
+ const { forms, hexes, folds: foldPatterns, matchUnfolded, match } = derivedOf(values);
147
146
  const found = [
148
- ...[...forms].flatMap((form) => places(text, form)),
149
- ...given.filter(longEnough).flatMap((v) => spans(text, new RegExp(needlesOf(v).hex, "i"))),
147
+ ...forms.flatMap((form) => places(text, form)),
148
+ ...hexes.flatMap((hex) => spans(text, hex)),
150
149
  ...shapes.flatMap(([, pattern]) => spans(text, pattern)),
151
150
  ];
152
151
  const unfolded = cutAt(text, found);
153
- if (spelledMatcher(given, false)(unfolded) || shapesOf(unfolded).length > 0)
152
+ if (matchUnfolded(unfolded) || shapesOf(unfolded).length > 0)
154
153
  return "[redacted]";
155
154
  // Then the folded finds cut in place, and the fold-aware check over what is left, always: a folded value split by
156
155
  // whitespace or percent-encoded has no span here, but the matcher's squeezed and decoded views still see it.
157
- const folds = given.filter(longEnough).flatMap((v) => needlesOf(v).folded.flatMap((needle) => spans(text, foldedPattern(needle))));
156
+ const folds = foldPatterns.flatMap((pattern) => spans(text, pattern));
158
157
  const out = folds.length ? cutAt(text, [...found, ...folds]) : unfolded;
159
- return spelledMatcher(given)(out) || shapesOf(out).length > 0 ? "[redacted]" : out;
158
+ return match(out) || shapesOf(out).length > 0 ? "[redacted]" : out;
159
+ }
160
+ /** Each value set's Derived, by the array a caller passes, with a copy of the values it was derived of. A run's view
161
+ * redacts every row of its timeline with one array, and deriving it again for each row (path spellings, base64 at three
162
+ * alignments, percent forms, folded patterns, for every value, a private key's PEM among them) took seconds per view.
163
+ * An array whose values changed since is derived again, never served a stale set: what a caller adds is always cut. */
164
+ const DERIVED = new WeakMap();
165
+ function derivedOf(values) {
166
+ const kept = DERIVED.get(values);
167
+ if (kept && kept.values.length === values.length && kept.values.every((value, at) => value === values[at]))
168
+ return kept.derived;
169
+ const given = withPathSpellings(values.filter((v) => v.length > 0));
170
+ const needles = new Map(given.filter(longEnough).map((v) => [v, needlesOf(v)]));
171
+ const derived = {
172
+ forms: [...new Set(given.flatMap((v) => {
173
+ const of = needles.get(v);
174
+ return [v, asJson(v), ...(of ? [...of.plain, ...percentForms(v)] : [])];
175
+ }).filter((form) => form.length > 0))],
176
+ hexes: [...needles.values()].map((of) => new RegExp(of.hex, "i")),
177
+ folds: [...needles.values()].flatMap((of) => of.folded.map(foldedPattern)),
178
+ matchUnfolded: spelledMatcher(given, false),
179
+ match: spelledMatcher(given),
180
+ };
181
+ DERIVED.set(values, { values: [...values], derived });
182
+ return derived;
160
183
  }
161
184
  /** `text` with each of `found` replaced by "[redacted]", overlapping ones as one. */
162
185
  function cutAt(text, found) {
@@ -0,0 +1,18 @@
1
+ import type { DeleteLearning } from "./agent-delete.js";
2
+ import { type Store } from "./store/index.js";
3
+ /** What a reset does outside the learning module, as the server does it. */
4
+ export interface LearningResetHost {
5
+ readonly store: Store;
6
+ readonly deleteLearning: DeleteLearning;
7
+ /** The cancel path, for one run that is not final: true once a cancel stands for it, false when this server cannot
8
+ * end it (agent-delete.ts AgentDeleteHost.cancel). */
9
+ cancel(runId: string): Promise<boolean>;
10
+ /** `work` in agent `agentId`'s learning queue (learning.ts withAgentRepo). */
11
+ inQueue<T>(agentId: string, work: () => Promise<T>): Promise<T>;
12
+ /** How long step 1 waits for the agent's learning runs to be final, and how often it reads them meanwhile. */
13
+ readonly waitMs: number;
14
+ readonly pollMs: number;
15
+ }
16
+ /** Agent `agentId`'s learning reset in the two steps above. Throws ApiError learning_busy, nothing of its learning
17
+ * deleted, while a run of the agent's own is going or its learning runs cannot be stopped in time. */
18
+ export declare function resetLearning(host: LearningResetHost, agentId: string): Promise<void>;
@@ -0,0 +1,115 @@
1
+ // DELETE /v2/agents/{agent_id}/learning: an agent's learning reset, the agent kept. What it learned goes (the learning
2
+ // module's deleteLearning: its learning folder's files, its git history and audit ledger among them, on this server and
3
+ // on every Archil disk its runs used, learn/learning-of.ts namedDisksOf, then its promotions and grades); the agent, its
4
+ // definition, its runs and everything kept of them (their files, journals, costs, the learning each one kept) stay, so
5
+ // the run list, the stats and the usage read the same before and after. A served run's cost carries its share of its
6
+ // revision's compile and check, read from the promotion records the reset deletes: each revision they name is kept
7
+ // first in the agent's reset ledger (learn/promote.ts keepResetLedger: workflow, digest and K alone), so the share reads
8
+ // the same after.
9
+ //
10
+ // What goes with the folder: each run's learning diff (GET /runs/{id}/learning/diff, the text it merged) is the folder's,
11
+ // so it is 404 after; what the run's own record keeps of its learning end stays with the run.
12
+ //
13
+ // In order, in the agent's delete turn (server.ts agentWrite: one learning write of an agent at a time, and none once
14
+ // its DELETE began):
15
+ // 1. The agent's learning work in flight is stopped. A run that exists only for its learning (a check's or an owner's
16
+ // replay, an audit's shadow, a built-in learning run) is cancelled through the cancel path and waited for until it
17
+ // is final. A run of the agent's own still going is not: its learning lives in it (the seed it was started from,
18
+ // a workflow it may be served, its compile turn and look-back at its end), and the owner's job is never cancelled
19
+ // to reset learning. Any such run, or a learning run this server cannot end (an SDK run, an imported one) or one
20
+ // not final by the wait's end, is 409 learning_busy, naming them, and the agent's learning is left as it was.
21
+ // 2. In the agent's learning queue (learning.ts withAgentRepo, where a run's start reads its seed and a person's edit
22
+ // commits), the agent's runs are read again: one still going (a run started meanwhile) is 409 learning_busy, nothing
23
+ // deleted. Then deleteLearning, which reads them once more itself.
24
+ // Idempotent: an agent that never learned, or one reset already, has nothing to delete, and is answered as done.
25
+ //
26
+ // Step 2 sets the agent's reset watermark (learn/promote.ts resetAtKey) before it deletes: from then on learning reads
27
+ // only runs after it (learn/compile.ts sinceReset: compile_after's count, a compile's traces, a check's inputs, an
28
+ // audit's draws, the money rule). A run whose start read the learning folder before step 2
29
+ // and whose row the store wrote after it keeps what it was started with (its corrections are in its launch), but
30
+ // learns nothing: its seed was read before the watermark, so its learning end drops it whole at its entry
31
+ // (runner/learning-end.ts, reason `reset`), and the learning script refuses a merge on a seed the folder no longer holds
32
+ // (learning.sh `seed`). No workflow is laid for it either: they are read at its seed's commit, which is gone.
33
+ import { ApiError } from "./errors.js";
34
+ import { LearningInFlight } from "./learn/delete.js";
35
+ import { isShadowRun } from "./learn/audit.js";
36
+ import { keepResetAt, keepResetLedger, promotionsOf, resetAtKey, resetAtOf } from "./learn/promote.js";
37
+ import { readLaunchBody } from "./run-launch.js";
38
+ import { FINAL_STATES, StoreLaunchMissing } from "./store/index.js";
39
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
40
+ const isFinal = (state) => FINAL_STATES.includes(state);
41
+ /** Whether run `runId` exists only for its agent's learning: an audit's shadow, a replay (a check's or an owner's), or a
42
+ * built-in learning run, by its launch. A run with no launch read here is the agent's own. */
43
+ async function learningOnly(store, runId) {
44
+ if (isShadowRun(runId))
45
+ return true;
46
+ const launch = await store.runs.launch(runId).then((row) => readLaunchBody(row.body), (error) => (error instanceof StoreLaunchMissing ? undefined : Promise.reject(error)));
47
+ return launch !== undefined && (launch.replay !== undefined || launch.audit !== undefined || launch.harness === "learning");
48
+ }
49
+ /** The agent's runs not final, its built-in learning runs included, each with whether it exists only for learning. */
50
+ async function goingOf(store, agentId) {
51
+ const going = (await store.runs.every(agentId)).filter((run) => !isFinal(run.state));
52
+ return Promise.all(going.map(async (run) => ({ id: run.id, learning: await learningOnly(store, run.id) })));
53
+ }
54
+ const busy = (agentId, runs, why, retryMs = 5_000) => new ApiError("learning_busy", `The agent ${agentId}'s learning was not reset: ${why} (${runs.slice(0, 5).join(", ")}${runs.length > 5 ? ` and ${runs.length - 5} more` : ""}). Nothing of its learning was deleted: send the DELETE again once ${runs.length === 1 ? "it has" : "they have"} ended.`, { details: { runs: [...runs] }, retry_after_ms: retryMs });
55
+ const OWN = (n) => (n === 1 ? "a run of its own is still going, and its learning lives in it" : `${n} runs of its own are still going, and their learning lives in them`);
56
+ /** Agent `agentId`'s learning reset in the two steps above. Throws ApiError learning_busy, nothing of its learning
57
+ * deleted, while a run of the agent's own is going or its learning runs cannot be stopped in time. */
58
+ export async function resetLearning(host, agentId) {
59
+ // 1. Its own runs refuse the reset before anything is cancelled; its learning runs are cancelled and waited for.
60
+ const going = await goingOf(host.store, agentId);
61
+ const own = going.filter((run) => !run.learning).map((run) => run.id);
62
+ if (own.length)
63
+ throw busy(agentId, own, OWN(own.length));
64
+ await stopLearningRuns(host, agentId, going.map((run) => run.id));
65
+ // 2. In the agent's learning queue: nothing going (a run started meanwhile refuses it), then its learning deleted.
66
+ await host.inQueue(agentId, async () => {
67
+ const still = await goingOf(host.store, agentId);
68
+ if (still.length)
69
+ throw busy(agentId, still.map((run) => run.id), still.some((run) => !run.learning) ? OWN(still.filter((run) => !run.learning).length) : "its learning work started again");
70
+ // What the agent's kept runs carry of their revisions' compile and check, kept before the records it is read from go.
71
+ await keepResetLedger(host.store.settings, agentId, await promotionsOf(host.store.settings, agentId));
72
+ // The watermark, before anything goes: learning reads no run that started, or read its seed, at or before it (each
73
+ // seed is read in this queue, so one read before this moment never holds a later time). A seed read after the reset
74
+ // in the same millisecond counts as before it: its run learns nothing (reason reset) and an SDK start is refused, to
75
+ // start again, never a run given what the reset deleted. Set first, so no moment has the folder gone and the old runs
76
+ // still read. A delete refused before it removed anything (LearningInFlight) puts the earlier one back, its learning
77
+ // left as it was; one that failed on the way (a disk, a file, a record) may have removed some of it, so the watermark
78
+ // stays and the next call finishes the reset: the old runs never feed a compile into a folder emptied part way.
79
+ const earlier = await resetAtOf(host.store.settings, agentId);
80
+ const at = Date.now();
81
+ await keepResetAt(host.store.settings, agentId, at);
82
+ try {
83
+ await host.deleteLearning(host.store, agentId, { keepResetLedger: true, agentDisk: true });
84
+ }
85
+ catch (error) {
86
+ if (!(error instanceof LearningInFlight))
87
+ throw error;
88
+ await (earlier === undefined ? host.store.settings.remove(resetAtKey(agentId)) : keepResetAt(host.store.settings, agentId, earlier));
89
+ throw busy(agentId, error.runs, "its learning work is in flight");
90
+ }
91
+ });
92
+ }
93
+ /** Step 1's second half: each learning run cancelled once, then read again until each is final. One this server cannot
94
+ * end, or one still going at the wait's end, is learning_busy. */
95
+ async function stopLearningRuns(host, agentId, runs) {
96
+ if (!runs.length)
97
+ return;
98
+ const unended = [];
99
+ for (const runId of runs)
100
+ if (!(await host.cancel(runId)))
101
+ unended.push(runId);
102
+ if (unended.length)
103
+ throw busy(agentId, unended, `its learning work is in ${unended.length === 1 ? "a run" : "runs"} this server cannot end`);
104
+ const deadline = Date.now() + host.waitMs;
105
+ for (;;) {
106
+ const states = new Map((await host.store.runs.every(agentId)).map((run) => [run.id, run.state]));
107
+ // A run no longer there is ended.
108
+ const live = runs.filter((runId) => !isFinal(states.get(runId) ?? "ended"));
109
+ if (!live.length)
110
+ return;
111
+ if (Date.now() >= deadline)
112
+ throw busy(agentId, live, `its learning work was cancelled and ${live.length === 1 ? "one run has" : `${live.length} runs have`} not ended yet`, 2_000);
113
+ await sleep(host.pollMs);
114
+ }
115
+ }
@@ -40,6 +40,11 @@ export type Counts = {
40
40
  };
41
41
  export { secretsShown, type Shown } from "./learning.js";
42
42
  export declare const etagOf: (oid: string) => string;
43
+ /** Which of `runIds` are purged, by the store's purge mark (its row's purge time). */
44
+ export type PurgedOf = (runIds: readonly string[]) => Promise<ReadonlySet<string>>;
45
+ /** Run `runId`'s text taken off agent `agentId`'s learning folder's current files at its purge (learn/commit.ts
46
+ * forgetRunText), in the agent's queue, as every write of the folder is. */
47
+ export declare function forgetRunLearning(data: string, agentId: string, runId: string): Promise<void>;
43
48
  /** A workflow draft as the view lists it: its folder's name, its workflow.json with its `readme`, its description, its
44
49
  * status, the run whose merge last changed it, its size in bytes, and the ETag of its README.md (the file that says
45
50
  * whether it waits, which an approval names); cut of the host's secrets (a name or a file holding one reads [redacted]).
@@ -71,7 +76,8 @@ export declare function pendingCount(data: string, agentId: string): Promise<num
71
76
  /** GET /agents/{id}/learning: main, its corrections.md, its workflow drafts and the first page of its log, and how the
72
77
  * agent's runs fared and what learning changed for them (`counts`, `impact`); an agent with no folder (its learning
73
78
  * never on) has an empty one. `stateOf`: where each workflow neither pending nor retired stands, by its folder name (the
74
- * promotions read's own word: learn/promote.ts servingStateOf over the agent's records). */
79
+ * promotions read's own word: learn/promote.ts servingStateOf over the agent's records). Its log serves no purged run's
80
+ * merge (`purgedOf`). */
75
81
  type AgentView = {
76
82
  agent: string;
77
83
  main: string | null;
@@ -81,9 +87,10 @@ type AgentView = {
81
87
  counts: Counts;
82
88
  impact: Impact;
83
89
  };
84
- export declare function agentLearning(data: string, agentId: string, shown: Shown, counts: Counts, impact: Impact, stateOf: (workflow: string) => ServingState): Promise<AgentView>;
85
- /** GET /agents/{id}/learning/log?cursor=&limit=: a page of the changes on main, newest first. */
86
- export declare function learningLog(data: string, agentId: string, query: URLSearchParams, shown: Shown): Promise<Page<Change>>;
90
+ export declare function agentLearning(data: string, agentId: string, shown: Shown, counts: Counts, impact: Impact, stateOf: (workflow: string) => ServingState, purgedOf: PurgedOf): Promise<AgentView>;
91
+ /** GET /agents/{id}/learning/log?cursor=&limit=: a page of the changes on main, newest first, a purged run's left out
92
+ * (`purgedOf`). */
93
+ export declare function learningLog(data: string, agentId: string, query: URLSearchParams, shown: Shown, purgedOf: PurgedOf): Promise<Page<Change>>;
87
94
  /** GET /agents/{id}/learning/corrections: corrections.md on main as text (empty when main holds none), its ETag (its blob
88
95
  * 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. */
89
96
  export declare function correctionsView(data: string, agentId: string, shown: Shown): Promise<{
@@ -119,8 +126,9 @@ type WorkflowRevision = {
119
126
  * commits on main's log that changed `workflows/<name>/workflow.json`), oldest first, each with the workflow's text at
120
127
  * that commit, so a person can step through how it changed. One read-only exec per revision (textsAt), at most `limit`
121
128
  * of them. `total` counts every such commit the log holds, `truncated` says the log itself is cut (it keeps the latest
122
- * LOG_KEEP changes). A workflow no commit of the log changed is not_found. */
123
- export declare function workflowRevisions(data: string, agentId: string, name: string, query: URLSearchParams, shown: Shown): Promise<{
129
+ * LOG_KEEP changes). A purged run's merge is no revision (`purgedOf`). A workflow no commit of the log changed is
130
+ * not_found. */
131
+ export declare function workflowRevisions(data: string, agentId: string, name: string, query: URLSearchParams, shown: Shown, purgedOf: PurgedOf): Promise<{
124
132
  name: string;
125
133
  revisions: WorkflowRevision[];
126
134
  total: number;
@@ -129,14 +137,18 @@ export declare function workflowRevisions(data: string, agentId: string, name: s
129
137
  /** Learned workflow `name`'s text at `digest` (a champion's, as its promotion records name it), read by that digest and
130
138
  * never by paging the workflow's history: at `commits` (the records' learning commits, newest first), then at main, the
131
139
  * first commit whose workflow.json is that digest's text, with the commit it was read at. Undefined when none is (no
132
- * main yet, or no commit read holds it). One read-only exec per commit tried (textsAt). */
133
- export declare function workflowAtDigest(data: string, agentId: string, name: string, digest: string, commits: readonly string[]): Promise<{
140
+ * main yet, or no commit read holds it). A commit whose text a purged run wrote is never read (purged-workflow.ts),
141
+ * however old. One read-only exec per commit tried (textsAt), and one more for the commit that holds the digest, unless
142
+ * it is main (snapshotAt). */
143
+ export declare function workflowAtDigest(data: string, agentId: string, name: string, digest: string, commits: readonly string[], store: Pick<Store, "runs">): Promise<{
134
144
  text: string;
135
145
  commit: string;
136
146
  } | undefined>;
137
147
  /** GET /agents/{id}/learning/files/{file}: a draft's file on main as text, its ETag, and its type (workflow.json is
138
- * JSON). */
139
- export declare function readLearnedFile(data: string, agentId: string, raw: string, shown: Shown): Promise<{
148
+ * JSON). A purged run's workflow left main with its purge (learn/commit.ts forgetRunText), so its files are the 404
149
+ * any missing file is. A workflow.json still on main whose writer is purged (a run purged before purges took its
150
+ * workflows off, until its DELETE is sent again) is 410 purged, as every route of that run is (purged-workflow.ts). */
151
+ export declare function readLearnedFile(data: string, agentId: string, raw: string, shown: Shown, store: Pick<Store, "runs">): Promise<{
140
152
  text: string;
141
153
  etag: string;
142
154
  type?: string;
@@ -190,7 +202,7 @@ export declare function runLearningBody(input: {
190
202
  }, shown: Shown, secrets: readonly string[]): {
191
203
  run: string;
192
204
  state: "dropped" | "merged" | "seeded" | "reflecting";
193
- reason: "cancelled" | "use" | "empty" | "crashed" | "reflect_failed" | "no_budget" | "checker" | "unknown_cost" | "seed_failed" | null;
205
+ reason: "cancelled" | "reset" | "use" | "empty" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "checker" | null;
194
206
  detail: string | null;
195
207
  at: string;
196
208
  workflows: import("./learning.js").LearnedFile[];