@parcha/agentrun-serve 0.1.0-beta.36 → 0.1.0-beta.37

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 (325) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +158 -52
  3. package/dist/attach-conformance-cli.d.ts +1 -0
  4. package/dist/attach-conformance-cli.js +18 -0
  5. package/dist/attach-conformance.d.ts +25 -0
  6. package/dist/attach-conformance.js +343 -0
  7. package/dist/browser-cost.d.ts +1 -1
  8. package/dist/browser-live.d.ts +20 -8
  9. package/dist/browser-live.js +50 -27
  10. package/dist/cap.d.ts +0 -17
  11. package/dist/cap.js +0 -91
  12. package/dist/catalog.d.ts +1 -12
  13. package/dist/catalog.js +3 -33
  14. package/dist/cli.js +13 -4
  15. package/dist/composio-preset.d.ts +36 -0
  16. package/dist/composio-preset.js +179 -0
  17. package/dist/computer-attach.d.ts +125 -0
  18. package/dist/computer-attach.js +330 -0
  19. package/dist/computer-calls.d.ts +48 -0
  20. package/dist/computer-calls.js +126 -0
  21. package/dist/computer-channel.d.ts +57 -0
  22. package/dist/computer-channel.js +115 -0
  23. package/dist/computer-commands.d.ts +1 -1
  24. package/dist/computer-held-routes.d.ts +35 -0
  25. package/dist/computer-held-routes.js +106 -0
  26. package/dist/computer-held.d.ts +48 -0
  27. package/dist/computer-held.js +87 -0
  28. package/dist/computer-keys.d.ts +21 -1
  29. package/dist/computer-keys.js +53 -11
  30. package/dist/computer-live.d.ts +160 -0
  31. package/dist/computer-live.js +643 -0
  32. package/dist/computer-view.d.ts +13 -0
  33. package/dist/computer-view.js +50 -3
  34. package/dist/computer-viewer.d.ts +6 -0
  35. package/dist/computer-viewer.js +297 -0
  36. package/dist/computers.d.ts +33 -7
  37. package/dist/computers.js +50 -8
  38. package/dist/console/assets/index-Cn6JX1uH.js +563 -0
  39. package/dist/console/assets/index-DRN62V5v.css +1 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/faux-computers.d.ts +9 -20
  42. package/dist/faux-computers.js +53 -25
  43. package/dist/github-connection.d.ts +10 -2
  44. package/dist/github-connection.js +65 -2
  45. package/dist/github-faux.js +1 -1
  46. package/dist/graph-view.d.ts +1 -1
  47. package/dist/harness.d.ts +1 -0
  48. package/dist/harness.js +35 -1
  49. package/dist/host-tools.d.ts +1 -1
  50. package/dist/hosted-search.d.ts +5 -4
  51. package/dist/hosted-search.js +2 -7
  52. package/dist/import-sources.d.ts +10 -0
  53. package/dist/import-sources.js +44 -2
  54. package/dist/import.d.ts +3 -3
  55. package/dist/import.js +37 -6
  56. package/dist/learn/check.d.ts +4 -1
  57. package/dist/learn/check.js +1 -1
  58. package/dist/learn/commit.d.ts +4 -2
  59. package/dist/learn/commit.js +5 -5
  60. package/dist/learn/folder.d.ts +6 -0
  61. package/dist/learn/folder.js +4 -1
  62. package/dist/learn/general.d.ts +66 -0
  63. package/dist/learn/general.js +73 -0
  64. package/dist/learn/grade.d.ts +4 -0
  65. package/dist/learn/grade.js +22 -1
  66. package/dist/learn/reflect.d.ts +10 -1
  67. package/dist/learn/reflect.js +14 -4
  68. package/dist/learn/skills.d.ts +33 -5
  69. package/dist/learn/skills.js +53 -7
  70. package/dist/learned-workflow.d.ts +24 -0
  71. package/dist/learned-workflow.js +66 -3
  72. package/dist/learning-batch.d.ts +283 -0
  73. package/dist/learning-batch.js +574 -0
  74. package/dist/learning-evals.d.ts +33 -0
  75. package/dist/learning-evals.js +98 -0
  76. package/dist/learning-routes.d.ts +25 -2
  77. package/dist/learning-routes.js +39 -6
  78. package/dist/learning-words.d.ts +6 -0
  79. package/dist/learning-words.js +6 -0
  80. package/dist/learning.d.ts +28 -15
  81. package/dist/learning.js +84 -44
  82. package/dist/live/stream.js +6 -3
  83. package/dist/live/translate.d.ts +4 -3
  84. package/dist/live/translate.js +8 -4
  85. package/dist/live-reach.d.ts +37 -0
  86. package/dist/live-reach.js +62 -0
  87. package/dist/mcp-gateway.d.ts +9 -0
  88. package/dist/mcp-gateway.js +60 -11
  89. package/dist/mcp-oauth.d.ts +57 -7
  90. package/dist/mcp-oauth.js +133 -18
  91. package/dist/mcp-private-hosts.d.ts +4 -4
  92. package/dist/mcp-private-hosts.js +20 -12
  93. package/dist/mcp-probe.d.ts +19 -2
  94. package/dist/mcp-probe.js +44 -9
  95. package/dist/mcp-secret-writes.js +4 -0
  96. package/dist/mcp-servers-store.d.ts +38 -15
  97. package/dist/mcp-servers-store.js +112 -20
  98. package/dist/mcp-store.d.ts +10 -4
  99. package/dist/mcp-store.js +17 -6
  100. package/dist/model-form.d.ts +26 -0
  101. package/dist/model-form.js +80 -0
  102. package/dist/model.js +23 -10
  103. package/dist/openapi.js +386 -21
  104. package/dist/page.d.ts +18 -0
  105. package/dist/page.js +48 -20
  106. package/dist/paid-calls.d.ts +1 -1
  107. package/dist/place-offers.d.ts +2 -3
  108. package/dist/place-offers.js +3 -7
  109. package/dist/place.js +1 -2
  110. package/dist/print.d.ts +15 -1
  111. package/dist/print.js +14 -3
  112. package/dist/propose.d.ts +3 -0
  113. package/dist/propose.js +13 -5
  114. package/dist/provider.js +3 -2
  115. package/dist/reflect-range.d.ts +8 -1
  116. package/dist/reflect-range.js +1 -1
  117. package/dist/run-launch.d.ts +14 -2
  118. package/dist/run-launch.js +9 -4
  119. package/dist/run-learning-served.d.ts +2 -2
  120. package/dist/run-reads-over-store.d.ts +1 -1
  121. package/dist/run-repo.d.ts +20 -0
  122. package/dist/run-repo.js +63 -0
  123. package/dist/run-timeline-served.d.ts +1 -1
  124. package/dist/run-view.d.ts +3 -3
  125. package/dist/run-view.js +14 -7
  126. package/dist/runner/adapter-loop.d.ts +23 -7
  127. package/dist/runner/adapter-loop.js +648 -62
  128. package/dist/runner/adapter-run-spec.d.ts +11 -3
  129. package/dist/runner/adapter-run-spec.js +77 -22
  130. package/dist/runner/adapters/pi-computer.d.ts +7 -0
  131. package/dist/runner/adapters/pi-computer.js +43 -0
  132. package/dist/runner/adapters/pi.d.ts +9 -4
  133. package/dist/runner/adapters/pi.js +76 -14
  134. package/dist/runner/beside.d.ts +7 -3
  135. package/dist/runner/beside.js +21 -11
  136. package/dist/runner/claim-secrets.d.ts +4 -0
  137. package/dist/runner/claim-secrets.js +6 -1
  138. package/dist/runner/cli-run-spec.d.ts +20 -3
  139. package/dist/runner/cli-run-spec.js +113 -43
  140. package/dist/runner/commands.d.ts +3 -1
  141. package/dist/runner/commands.js +28 -3
  142. package/dist/runner/computer-channel.d.ts +34 -0
  143. package/dist/runner/computer-channel.js +61 -0
  144. package/dist/runner/conformance/harness.js +80 -14
  145. package/dist/runner/conformance/subject.d.ts +1 -1
  146. package/dist/runner/dispatch.js +3 -0
  147. package/dist/runner/end-of-run.d.ts +22 -12
  148. package/dist/runner/end-of-run.js +38 -16
  149. package/dist/runner/github-app.d.ts +2 -1
  150. package/dist/runner/github-app.js +4 -2
  151. package/dist/runner/harness-loops.js +15 -1
  152. package/dist/runner/held-run.d.ts +65 -0
  153. package/dist/runner/held-run.js +158 -0
  154. package/dist/runner/journal-kinds.d.ts +20 -1
  155. package/dist/runner/journal-kinds.js +14 -0
  156. package/dist/runner/journal-reader.d.ts +5 -4
  157. package/dist/runner/journal-reader.js +12 -10
  158. package/dist/runner/learning-ask.d.ts +7 -1
  159. package/dist/runner/learning-ask.js +21 -6
  160. package/dist/runner/learning-dispatch.d.ts +22 -0
  161. package/dist/runner/learning-dispatch.js +77 -10
  162. package/dist/runner/learning-end.d.ts +22 -1
  163. package/dist/runner/learning-end.js +92 -12
  164. package/dist/runner/learning-factory.d.ts +1 -1
  165. package/dist/runner/learning-factory.js +11 -5
  166. package/dist/runner/learning-loop.d.ts +67 -7
  167. package/dist/runner/learning-loop.js +173 -21
  168. package/dist/runner/learning-seed.d.ts +7 -0
  169. package/dist/runner/learning-seed.js +13 -0
  170. package/dist/runner/live-ticker.js +1 -0
  171. package/dist/runner/loop-contract.d.ts +8 -1
  172. package/dist/runner/loop.d.ts +5 -1
  173. package/dist/runner/loop.js +2 -1
  174. package/dist/runner/main.d.ts +13 -1
  175. package/dist/runner/main.js +27 -5
  176. package/dist/runner/mcp-claim.d.ts +10 -7
  177. package/dist/runner/mcp-claim.js +113 -24
  178. package/dist/runner/mcp-github.js +1 -1
  179. package/dist/runner/mcp-run.d.ts +5 -5
  180. package/dist/runner/mcp-run.js +15 -3
  181. package/dist/runner/metrics.d.ts +11 -2
  182. package/dist/runner/metrics.js +12 -2
  183. package/dist/runner/pr-checkout.d.ts +1 -0
  184. package/dist/runner/pr-checkout.js +1 -1
  185. package/dist/runner/reflect-hook.d.ts +18 -0
  186. package/dist/runner/reflect-hook.js +20 -8
  187. package/dist/runner/runner.d.ts +26 -0
  188. package/dist/runner/runner.js +184 -15
  189. package/dist/runner/scratch-sweep.d.ts +13 -0
  190. package/dist/runner/scratch-sweep.js +62 -0
  191. package/dist/runner/sessions.d.ts +1 -1
  192. package/dist/runner/store-port.d.ts +4 -2
  193. package/dist/runner/store-secrets.js +4 -3
  194. package/dist/runner/subagent.js +3 -1
  195. package/dist/runner/workflow-host.d.ts +6 -1
  196. package/dist/runner/workflow-host.js +1 -1
  197. package/dist/runner/workflow-loop.d.ts +1 -1
  198. package/dist/runner/workflow-spec.d.ts +14 -2
  199. package/dist/runner/workflow-spec.js +56 -20
  200. package/dist/runs-over-store.d.ts +6 -1
  201. package/dist/runs-over-store.js +38 -9
  202. package/dist/seal-key.js +3 -3
  203. package/dist/sealed-settings-store.d.ts +5 -2
  204. package/dist/sealed-settings-store.js +10 -4
  205. package/dist/secret-writes.d.ts +5 -4
  206. package/dist/secret-writes.js +5 -4
  207. package/dist/server-secrets-store.d.ts +4 -3
  208. package/dist/server-secrets-store.js +15 -9
  209. package/dist/server-secrets.js +3 -2
  210. package/dist/server.d.ts +43 -14
  211. package/dist/server.js +472 -126
  212. package/dist/settings-wake.d.ts +21 -0
  213. package/dist/settings-wake.js +59 -0
  214. package/dist/standard-webhooks.d.ts +4 -1
  215. package/dist/standard-webhooks.js +8 -4
  216. package/dist/store/command-wake.d.ts +12 -0
  217. package/dist/store/command-wake.js +37 -0
  218. package/dist/store/dialect.d.ts +6 -0
  219. package/dist/store/dialect.js +5 -0
  220. package/dist/store/index.d.ts +1 -1
  221. package/dist/store/journal/storage.d.ts +3 -2
  222. package/dist/store/journal/storage.js +13 -5
  223. package/dist/store/postgres/dialect.js +4 -0
  224. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  225. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  226. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  227. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  228. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  229. package/dist/store/schema.d.ts +1 -1
  230. package/dist/store/schema.js +77 -8
  231. package/dist/store/sqlite/run-patch.d.ts +7 -5
  232. package/dist/store/sqlite/run-patch.js +28 -13
  233. package/dist/store/sqlite/store.js +272 -54
  234. package/dist/store/store.d.ts +268 -9
  235. package/dist/store/store.js +12 -1
  236. package/dist/store-reads/cap.d.ts +1 -1
  237. package/dist/store-reads/cap.js +8 -1
  238. package/dist/store-reads/decisions.d.ts +2 -2
  239. package/dist/store-reads/decisions.js +1 -1
  240. package/dist/store-reads/import-summary.d.ts +1 -1
  241. package/dist/store-reads/journal.d.ts +5 -4
  242. package/dist/store-reads/journal.js +73 -15
  243. package/dist/store-reads/learning.d.ts +20 -4
  244. package/dist/store-reads/learning.js +74 -18
  245. package/dist/store-reads/runs.d.ts +1 -1
  246. package/dist/store-reads/workflow.d.ts +1 -1
  247. package/dist/store-view.d.ts +5 -0
  248. package/dist/store-view.js +26 -11
  249. package/dist/template-eval.js +6 -4
  250. package/dist/template-github-permissions.d.ts +22 -8
  251. package/dist/template-github-permissions.js +35 -15
  252. package/dist/timeline/timeline.d.ts +27 -0
  253. package/dist/timeline/timeline.js +10 -9
  254. package/dist/timeline/util.d.ts +4 -0
  255. package/dist/timeline/util.js +14 -0
  256. package/dist/tool-budget.d.ts +19 -7
  257. package/dist/tool-budget.js +14 -8
  258. package/dist/tool-gate.d.ts +16 -9
  259. package/dist/tool-gate.js +53 -42
  260. package/dist/tool-plane.d.ts +16 -12
  261. package/dist/tool-plane.js +9 -4
  262. package/dist/tools.d.ts +13 -4
  263. package/dist/tools.js +13 -4
  264. package/dist/trigger-adapter.d.ts +4 -0
  265. package/dist/trigger-secrets-shown.d.ts +2 -2
  266. package/dist/trigger-secrets-shown.js +1 -1
  267. package/dist/trigger-signatures.d.ts +25 -6
  268. package/dist/trigger-signatures.js +41 -7
  269. package/dist/trigger-targets.d.ts +2 -0
  270. package/dist/trigger-targets.js +1 -0
  271. package/dist/trigger-webhook.js +5 -2
  272. package/dist/triggers.d.ts +7 -3
  273. package/dist/triggers.js +35 -5
  274. package/dist/turns.js +16 -1
  275. package/dist/validate.js +11 -1
  276. package/dist/web-fetch.d.ts +1 -1
  277. package/dist/web-search.d.ts +10 -5
  278. package/dist/web-search.js +7 -6
  279. package/dist/webhooks.d.ts +145 -102
  280. package/dist/webhooks.js +559 -322
  281. package/dist/workflow/decisions.d.ts +1 -1
  282. package/dist/workflow/node-runner.d.ts +2 -1
  283. package/dist/workflow/node.d.ts +2 -1
  284. package/dist/workflow/node.js +3 -1
  285. package/dist/workflow/pi-versions.d.ts +23 -0
  286. package/dist/workflow/pi-versions.js +57 -0
  287. package/dist/workflow/record-tool.d.ts +2 -1
  288. package/dist/workflow/store.d.ts +1 -1
  289. package/dist/workflow/task.js +3 -2
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/attached-computers.d.ts +41 -0
  292. package/dist/workspace/attached-computers.js +114 -0
  293. package/dist/workspace/computer-deps.d.ts +16 -9
  294. package/dist/workspace/computer-deps.js +19 -7
  295. package/dist/workspace/computer-for-claim.d.ts +17 -8
  296. package/dist/workspace/computer-for-claim.js +62 -21
  297. package/dist/workspace/computer-hold.d.ts +11 -27
  298. package/dist/workspace/computer-hold.js +36 -56
  299. package/dist/workspace/computer-ledger.d.ts +3 -1
  300. package/dist/workspace/computer-ledger.js +4 -0
  301. package/dist/workspace/computer-mcp.d.ts +25 -0
  302. package/dist/workspace/computer-mcp.js +41 -0
  303. package/dist/workspace/computer-ports.d.ts +4 -13
  304. package/dist/workspace/computer-ports.js +4 -107
  305. package/dist/workspace/computer-script.d.ts +37 -0
  306. package/dist/workspace/computer-script.js +138 -0
  307. package/dist/workspace/executors.d.ts +1 -1
  308. package/dist/workspace/index.d.ts +4 -2
  309. package/dist/workspace/index.js +3 -1
  310. package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
  311. package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
  312. package/dist/workspace/resolve-computer.d.ts +3 -0
  313. package/dist/workspace/resolve-computer.js +8 -2
  314. package/dist/workspace/run-tools.d.ts +32 -15
  315. package/dist/workspace/run-tools.js +23 -30
  316. package/package.json +19 -16
  317. package/templates/market-monitor/agent.md +1 -1
  318. package/dist/console/assets/index-BI4Byidu.js +0 -550
  319. package/dist/console/assets/index-C19gUF2n.css +0 -1
  320. package/dist/run-db.d.ts +0 -53
  321. package/dist/run-db.js +0 -116
  322. package/dist/workflow/readers.d.ts +0 -36
  323. package/dist/workflow/readers.js +0 -145
  324. package/dist/workflow/wal.d.ts +0 -11
  325. package/dist/workflow/wal.js +0 -106
@@ -3,34 +3,41 @@
3
3
  // its own database file ("SELECT record FROM entries ORDER BY id") and fed the same pure renderer; these read the one store instead.
4
4
  // The renderer and the hearing keep their words; only where the entries come from changes.
5
5
  import { createHash } from "node:crypto";
6
- import { CAPS, costLabel, timelineOf, TOOL_COST } from "../timeline/index.js";
6
+ import { CALL_REFUSED, CAPS, costLabel, timelineOf, TOOL_COST } from "../timeline/index.js";
7
7
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
8
8
  import { wireName } from "../catalog.js";
9
9
  import { TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
10
10
  import { Hearing } from "../heard.js";
11
11
  import { redactedAnswer } from "../key-refusal.js";
12
12
  import { LEARNED_NODES, LEARNED_NODES_MAX } from "../learned-nodes.js";
13
- import { labelled } from "../reflect-range.js";
14
- import { reflectFrom } from "../runner/end-of-run.js";
15
- import { journalEntries, journalRecords } from "../runner/journal-reader.js";
13
+ import { computerCallsOf } from "../computer-calls.js";
14
+ import { labelled, reflects } from "../reflect-range.js";
15
+ import { reflectRanges } from "../runner/end-of-run.js";
16
+ import { journalEntries, journalRecords, recordOf } from "../runner/journal-reader.js";
16
17
  import { endedAnswer, KINDS } from "../runner/journal-kinds.js";
17
18
  import { bookedSpend, cliModelWorked, costIsBooked } from "../runner/metrics.js";
18
19
  import { waitingText } from "../tool-gate.js";
20
+ import { Turns } from "../turns.js";
19
21
  /** A run's entries from the one store, in log order (by id across every conversation), as the old "SELECT record FROM
20
22
  * entries ORDER BY id" read them for a settled run. A run with no journal reads as none. */
21
23
  export async function runEntries(store, runId, context) {
22
24
  const entries = (await journalEntries(store.readJournal(runId), context));
23
25
  return entries.slice().sort((a, b) => Number(a.id ?? 0) - Number(b.id ?? 0));
24
26
  }
25
- /** Where a run's end-of-run turn is in its journal, as the server's Reflect names it for labelled(): `after`, the entry
26
- * before its input; `until`, the run's end entry once written. Undefined for a run that asked none. */
27
+ /** Where a run's end-of-run turn is in its journal, as the server's Reflect names it for labelled(): its newest round's
28
+ * `after`, the entry before its input, and `until`, the run's end entry once written; `earlier`, each earlier round's (a
29
+ * follow-up opened the run again after it). Undefined for a run that asked none. */
27
30
  export async function runReflect(store, runId, context) {
28
- const records = await journalRecords(store.readJournal(runId), context);
29
- const from = reflectFrom(records.submissions ?? [], records.entries);
30
- if (from === undefined)
31
+ return reflectOf(await journalRecords(store.readJournal(runId), context));
32
+ }
33
+ /** runReflect over records already read. */
34
+ function reflectOf(records) {
35
+ const ranges = reflectRanges(records.submissions ?? [], records.entries);
36
+ const newest = ranges.at(-1);
37
+ if (newest === undefined)
31
38
  return undefined;
32
- const end = records.entries.find((entry) => entry.kind === KINDS.end && Number(entry.id) >= from);
33
- return { after: from - 1, ...(end ? { until: Number(end.id) } : {}) };
39
+ const earlier = ranges.slice(0, -1).flatMap(({ from, until }) => (until === undefined ? [] : [{ after: from - 1, until }]));
40
+ return { after: newest.from - 1, ...(newest.until !== undefined ? { until: newest.until } : {}), ...(earlier.length ? { earlier } : {}) };
34
41
  }
35
42
  /** The CLI record (a harness whose own records are resume log only, record "loop": adapter-loop.ts openCliRecord) as the
36
43
  * pi-shaped entries the timeline renderer reads: a model message is an assistant turn, a person message a user turn, and a
@@ -97,7 +104,10 @@ function piShaped(entries) {
97
104
  // text), as pi's own interrupted result does, never an empty failure.
98
105
  const failed = data.status !== undefined && data.status !== "done";
99
106
  const content = data.output === undefined && data.status === "interrupted" ? endedAnswer("", { status: "interrupted" }).text : (data.output ?? "");
100
- return { ...entry, kind: "pi.tool-result", model: [{ role: "tool", toolCallId: String(data.callId ?? ""), content, ...(failed ? { isError: true } : {}), ...timestamp }] };
107
+ // One refused before it ran (its gate's deny, a person's, an approval the run ended without) carries pi's refusal
108
+ // mark, so its rows read refused, as pi's do, never as a call that ran and failed.
109
+ const refused = data.status === "refused" ? { details: { [CALL_REFUSED]: true } } : {};
110
+ return { ...entry, kind: "pi.tool-result", model: [{ role: "tool", toolCallId: String(data.callId ?? ""), content, ...(failed ? { isError: true } : {}), ...refused, ...timestamp }] };
101
111
  }
102
112
  return entry;
103
113
  });
@@ -189,12 +199,39 @@ const inWorkspace = (cwd) => (path) => {
189
199
  export async function runTimeline(store, runId, context, options = {}) {
190
200
  const entries = await runEntries(store, runId, context);
191
201
  const cli = isCliRecord(entries);
202
+ const records = await journalRecords(store.readJournal(runId), context);
203
+ const reflect = reflectOf(records);
192
204
  // A CLI names a file by its absolute path under its working directory (CallStartData.cwd): the rows name it by its
193
205
  // name in the workspace, never a path on the runner's machine. Its arguments, as the harness sent them, stay.
194
206
  const cwd = cli && !options.path ? entries.find((entry) => entry.kind === KINDS.callStart && typeof entry.data?.cwd === "string")?.data : undefined;
195
- const rendered = timelineOf(withPaidCosts(cli ? piShaped(entries) : entries), cwd ? { ...options, path: inWorkspace(cwd.cwd) } : options);
196
- const rows = costIsBooked(entries, cli) ? bookedUsage(rendered, entries, options) : rendered;
197
- return labelled((await runReflect(store, runId, context)), withLearnedNodes(await datedRows(store, runId, rows), entries, options.redact));
207
+ // A run whose newest turn a stop or a cancel cut reads it over (run-view.ts statusOf: input_required) from the moment pi
208
+ // settles that turn's message aborted, before the runner books what the abort cut (its request's end mark comes once the
209
+ // session's proxy sees its upstream end). Its cost reads that turn the same way, the request it cut a charge with no
210
+ // price, never one in flight: never the known sum as its cost while the run reads stopped.
211
+ const read = { ...options, ...(cwd ? { path: inWorkspace(cwd.cwd) } : {}), ...(!options.settled && turnCutOf(records, reflect) ? { turnCut: true } : {}) };
212
+ const rendered = timelineOf(withPaidCosts(cli ? piShaped(entries) : entries), read);
213
+ const rows = costIsBooked(entries, cli) ? bookedUsage(rendered, entries, options) : withSideUsage(rendered, entries);
214
+ return labelled(reflect, withComputerCalls(withLearnedNodes(await datedRows(store, runId, rows), entries, options.redact), entries));
215
+ }
216
+ /** Whether the run's newest turn is over, cut (turns.ts: no message of the run's open, the newest one's end interrupted),
217
+ * its end-of-run turn's entries apart, as the run's view reads its status. */
218
+ function turnCutOf(records, reflect) {
219
+ const turns = new Turns();
220
+ turns.note(recordOf(records.entries), records.submissions ?? [], reflect ? (id) => reflects(reflect, id) : undefined);
221
+ return turns.end()?.status === "interrupted";
222
+ }
223
+ /** `rows` with each tool call's result row carrying the computer protocol calls it made (`computer_calls`, and
224
+ * `computer_calls_dropped` past the record's bound), from the COMPUTER_CALLS entry the adapter loop kept beside the call
225
+ * (computer-calls.ts), joined by the call's id. A record holds no param's value and no answer's bytes, so it needs no cut.
226
+ * Rows of a run whose tools made none are as they were. */
227
+ function withComputerCalls(rows, entries) {
228
+ const made = computerCallsOf(entries);
229
+ if (!made.size)
230
+ return rows;
231
+ return rows.map((row) => {
232
+ const kept = row.kind === "tool_result" && row.tool_use_id ? made.get(row.tool_use_id) : undefined;
233
+ return kept ? { ...row, computer_calls: kept.calls, ...(kept.dropped > 0 ? { computer_calls_dropped: kept.dropped } : {}) } : row;
234
+ });
198
235
  }
199
236
  /** `rows` with each learned_workflow call's result row carrying the nodes its workflow ran (`learned_nodes`), from the
200
237
  * LEARNED_NODES entry the call kept beside itself (learned-workflow.ts), joined by the call's id: each label through
@@ -221,6 +258,27 @@ function withLearnedNodes(rows, entries, redact) {
221
258
  return rows;
222
259
  return rows.map((row) => (row.kind === "tool_result" && row.tool_use_id && traces.has(row.tool_use_id) ? { ...row, learned_nodes: traces.get(row.tool_use_id) } : row));
223
260
  }
261
+ /** A pi run's `rows` with its side calls in its usage row: the requests its session booked that no answer of pi's carries
262
+ * (a learned workflow's nodes, a request on another model: runner/metrics.ts bookedSpend "side"), at what they were
263
+ * booked at, unknown when one's price is, beside the answers the renderer counted. Their requests join its count; its
264
+ * words are the renderer's, figures changed. A run with none is as rendered. */
265
+ function withSideUsage(rows, entries) {
266
+ const side = bookedSpend(entries, "side");
267
+ const at = rows.findLastIndex((row) => row.kind === "usage");
268
+ if (!side.requests || at < 0)
269
+ return [...rows];
270
+ const row = rows[at];
271
+ const own = row.usage ?? { usd: 0, requests: 0 };
272
+ const known = (own.usd ?? own.so_far_usd ?? 0) + side.known;
273
+ const unpriced = (own.usd === null ? (own.unpriced ?? 0) : 0) + side.unpriced;
274
+ const usd = unpriced ? null : Math.round(known * 1e6) / 1e6;
275
+ const requests = own.requests + side.requests;
276
+ const dollars = (value) => (value === 0 ? "$0" : `$${value.toFixed(4)}`);
277
+ const spent = usd !== null ? dollars(usd) : `${dollars(Math.round(known * 1e6) / 1e6)} known, ${unpriced} not priced,`;
278
+ const summary = (row.summary ?? "").replace(/^([^:]+): .+? over \d+ model requests?/, `$1: ${spent} over ${requests} model request${requests === 1 ? "" : "s"}`);
279
+ const usage = { usd, requests, ...(usd === null ? { so_far_usd: Math.round(known * 1e6) / 1e6, unpriced } : {}), ...(own.not_metered ? { not_metered: own.not_metered } : {}) };
280
+ return rows.map((each, i) => (i === at ? { ...row, summary, usage } : each));
281
+ }
224
282
  /** A CLI or workflow run's `rows` with its usage row in its booking's words (runner/metrics.ts bookedSpend over every
225
283
  * session of the run but its decisions'): its model requests and its paid tool calls, their sum (unknown while one's cost is, with what is known so far,
226
284
  * costsofar/1), in the renderer's words (`Cost` once ended, else `Cost so far`). The renderer's own row is replaced in
@@ -9,8 +9,8 @@ import type { AnalyticsFilter } from "./analytics.js";
9
9
  import type { Store } from "../store/store.js";
10
10
  /** A run's learning end: the Learning fields its end sets. */
11
11
  export type RunLearningEnd = Pick<Learning, "state" | "reason" | "detail" | "at" | "problems" | "verdict" | "graded" | "merged" | "cost_usd" | "tokens" | "learned" | "pending" | "skills" | "workflows" | "lost" | "answered_at" | "job_cost_usd" | "look_back_usd">;
12
- /** Run `runId`'s learning end; null when the run kept no learning. Proposed while its learning run has not ended. */
13
- export declare function runLearningEnd(store: Store, runId: string): Promise<RunLearningEnd | null>;
12
+ /** Run `runId`'s learning end (its newest round's, or round `round`'s); null when the run kept no learning. Proposed while its learning run has not ended. */
13
+ export declare function runLearningEnd(store: Store, runId: string, round?: number): Promise<RunLearningEnd | null>;
14
14
  /** How the runs that tried to learn fared (GET /stats's `learning`): `runs` with a learning end, `merged`, `dropped` by
15
15
  * reason, and `in_progress` (proposed, its learning run not ended). The shape today's counts give (learning-run.ts
16
16
  * learningStats). */
@@ -65,6 +65,9 @@ export declare function agentCostOverStore(store: Store, agentId: string, limit?
65
65
  total_runs: number;
66
66
  unknown_cost_runs: number;
67
67
  }>;
68
+ /** One run of the cost series, as number `n` of it: its figures and its path (agentCostOverStore's loop body, and a learning
69
+ * batch's row once the run's learning has settled). */
70
+ export declare function costRunOf(store: Store, run: NonNullable<Awaited<ReturnType<Store["runs"]["get"]>>>, n: number): Promise<CostRun>;
68
71
  /** What a run's claim laid of its learning seed: the learned skills and workflows it was given, by name. */
69
72
  type Laid = {
70
73
  readonly skills: readonly string[];
@@ -74,6 +77,16 @@ type Laid = {
74
77
  * claim's skill folders there already and lays none of them again, though the run still has them. None laid when it has
75
78
  * no entry. */
76
79
  export declare function laidOf(entries: readonly EntryLike[]): Laid;
80
+ /** What every round of a run that a follow-up opened again spent (undefined for a run with one round): when its first
81
+ * round's job answered and what the job cost to then, the look-backs of every round added up, and every round's grade. A
82
+ * figure that is unknown in any round is unknown (null). */
83
+ type RoundsSpend = {
84
+ answered_at: string;
85
+ job_cost_usd: number | null;
86
+ look_back_usd: number | null;
87
+ grade_usd: number | null;
88
+ };
89
+ export declare function roundsSpendOf(store: Store, runId: string): Promise<RoundsSpend | undefined>;
77
90
  /** A run's learning end with the notes its start gave it (`given`, when it started from a seed) and those its job read
78
91
  * (`read`, only when it read one): what a run view and GET /runs/{id}/learning show beside the end. */
79
92
  export type RunLearning = RunLearningEnd & {
@@ -121,6 +134,9 @@ export declare function learnedUseOf(started: RunLaunch["learning"], reflect: Pi
121
134
  }>, laid?: Pick<Laid, "skills">, loads?: readonly string[]): LearnedUse;
122
135
  /** `end` with its run's given notes (from its launch's learning start) and the notes its job read. */
123
136
  export declare function withNotes(end: RunLearningEnd, started: RunLaunch["learning"], read: readonly NoteUsed[]): RunLearning;
137
+ /** The learning of a run that only uses what its agent learned (`learning: "use"`): seeded while it runs, as a run that
138
+ * learns is; dropped `use` once it ended, since it is never asked what to keep. */
139
+ export declare function usedOnly(started: NonNullable<RunLaunch["learning"]>, terminal: boolean, at: string): RunLearningEnd;
124
140
  /** GET /runs/{id}/learning from the one store, in the shape the route gives (learning-routes.ts runLearningBody): the
125
141
  * run's learning end (runLearningEnd), the notes it was given and the seed it started from as its launch records them,
126
142
  * what it held for its owner's OK as it stands on its agent's folder's main (`statuses`, learning-routes.ts statusesOf,
@@ -173,8 +189,8 @@ export declare function runLearningOverStore(store: Store, runId: string, shown:
173
189
  skills?: import("../learning.js").LearnedFile[];
174
190
  workflows?: import("../learning.js").LearnedFile[];
175
191
  run: string;
176
- state: "proposed" | "merged" | "seeded" | "reflecting" | "dropped";
177
- reason: "cancelled" | "empty" | "unparsed" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_timeout" | "reflect_failed" | "propose_failed" | "checker" | "grader" | "grade_failed" | null;
192
+ state: "dropped" | "proposed" | "merged" | "seeded" | "reflecting";
193
+ reason: "cancelled" | "use" | "empty" | "unparsed" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_timeout" | "reflect_failed" | "propose_failed" | "checker" | "grader" | "grade_failed" | null;
178
194
  detail: string | null;
179
195
  at: string;
180
196
  } | null>;
@@ -9,7 +9,8 @@ import { posix } from "node:path";
9
9
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
10
10
  import { currentLearning, holdsForOk, LEARNING_REASONS } from "../learning.js";
11
11
  import { runLearningBody } from "../learning-routes.js";
12
- import { learningStartOf, readLaunchBody } from "../run-launch.js";
12
+ import { learningStartOf, readLaunchBody, seedFailed } from "../run-launch.js";
13
+ import { said, STOPPED } from "../learning-words.js";
13
14
  import { learningImpact, noteRuns, notesRead } from "../learning-run.js";
14
15
  import { costSummary, runCostOf } from "../learning-cost.js";
15
16
  import { runPathOf, workflowNameOf } from "../runner/learning-end.js";
@@ -20,6 +21,7 @@ import { FINAL_STATES } from "../store/store.js";
20
21
  import { journalEntries } from "../runner/journal-reader.js";
21
22
  import { KINDS } from "../runner/journal-kinds.js";
22
23
  import { keptOf, learnedOf, lostOf } from "../runner/learning-loop.js";
24
+ import { GENERAL_NO_BUDGET, GENERAL_NO_ROOM, GENERAL_UNCHECKED } from "../learn/general.js";
23
25
  const timeOf = (ms) => new Date(ms).toISOString();
24
26
  const usdOrNull = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
25
27
  /** What a kept row says of a run that looked back (learning-run.ts closeLearning's fields): none for one that did not. */
@@ -28,9 +30,9 @@ function answeredOf(row) {
28
30
  return {};
29
31
  return { answered_at: row.answered_at, job_cost_usd: usdOrNull(row.job_cost_usd), look_back_usd: usdOrNull(row.look_back_usd) };
30
32
  }
31
- /** Run `runId`'s learning end; null when the run kept no learning. Proposed while its learning run has not ended. */
32
- export async function runLearningEnd(store, runId) {
33
- const kept = await store.learning.proposal(runId);
33
+ /** Run `runId`'s learning end (its newest round's, or round `round`'s); null when the run kept no learning. Proposed while its learning run has not ended. */
34
+ export async function runLearningEnd(store, runId, round) {
35
+ const kept = await store.learning.proposal(runId, round);
34
36
  if (!kept)
35
37
  return null;
36
38
  const row = (kept.proposal ?? {});
@@ -60,20 +62,26 @@ async function endOfKept(store, kept, row) {
60
62
  // What the grade spent: the graded entry's, or what a grade that failed spent before it did.
61
63
  const spent = graded ?? (dropped && "usd" in dropped ? { usd: dropped.usd ?? null, tokens: dropped.tokens ?? null } : undefined);
62
64
  const cost = spent ? { cost_usd: { grade: spent.usd }, tokens: { grade: spent.tokens ?? null } } : {};
65
+ // A generality check that could not run (learning-loop.ts `unchecked`) is said after the end's words: the grader read
66
+ // every note. Its provider's error stays in the journal.
67
+ // One skipped for no room under the cap (GENERAL_NO_BUDGET) says so.
68
+ const unchecked = graded?.unchecked ?? dropped?.unchecked;
69
+ const skip = unchecked === undefined ? undefined : unchecked === GENERAL_NO_BUDGET ? GENERAL_NO_ROOM : GENERAL_UNCHECKED;
70
+ const withSkip = (detail) => (skip ? [detail, skip].filter(Boolean).join(" ") : detail);
63
71
  if (merged && graded) {
64
72
  // Each item as the merge settled it: its record's verdict (a note it left out is no longer kept, and says why). A merge
65
73
  // recorded with none (before the record kept it) reads no item decisions.
66
74
  const verdict = merged.verdict;
67
75
  const what = verdict ? learnedOf(keptOf(row.proposal, verdict), verdict) : { learned: [], pending: [], skills: [], workflows: [] };
68
76
  return {
69
- state: "merged", reason: null, detail: merged.detail, at: endedAt, ...left, ...(verdict ? { verdict } : {}), graded: { ...graded.graded }, ...cost, merged: merged.commit,
77
+ state: "merged", reason: null, detail: withSkip(merged.detail), at: endedAt, ...left, ...(verdict ? { verdict } : {}), graded: { ...graded.graded }, ...cost, merged: merged.commit,
70
78
  learned: what.learned, ...(what.pending.length ? { pending: what.pending } : {}), ...(what.skills.length ? { skills: what.skills } : {}), ...(what.workflows.length ? { workflows: what.workflows } : {}),
71
79
  };
72
80
  }
73
81
  const reason = (dropped?.reason ?? null);
74
82
  const lost = reason === "grader" ? lostOf(row.proposal) : [];
75
83
  return {
76
- state: "dropped", reason, detail: dropped?.detail ?? null, at: endedAt,
84
+ state: "dropped", reason, detail: withSkip(dropped?.detail ?? null), at: endedAt,
77
85
  ...(dropped?.problems?.length ? { problems: [...dropped.problems] } : left),
78
86
  // The verdict, when one was given; the blobs it read only go with a merge (the server kept them for its merge alone).
79
87
  ...(graded ? { verdict: graded.verdict } : {}), ...cost, ...(lost.length ? { lost } : {}),
@@ -149,7 +157,8 @@ export async function agentLearningOverStore(store, agentId) {
149
157
  kinds.set(run.revisionId, (await store.agents.revision(run.revisionId))?.kind);
150
158
  const final = FINAL_STATES.includes(run.state);
151
159
  const started = await learningStartOfRun(store, run.id);
152
- const end = await runLearningEnd(store, run.id);
160
+ // A run that only uses what its agent learned keeps no proposal: its end is its start's (usedOnly), as its run reads give it.
161
+ const end = (await runLearningEnd(store, run.id)) ?? (started?.use ? usedOnly(started, final, timeOf(run.endedAt ?? run.startedAt)) : null);
153
162
  const { read, laid } = await journalReadsOf(store, run, started);
154
163
  if (started || end)
155
164
  files.push(notesOf({ given: started?.given ?? [], read }));
@@ -161,7 +170,7 @@ export async function agentLearningOverStore(store, agentId) {
161
170
  });
162
171
  // What its claims laid of the skills and workflows it was offered (every learningLaid entry, laidOf): the run started
163
172
  // from those alone.
164
- learnings.set(run.id, end ? impactLearningOf(end, started, laid) : null);
173
+ learnings.set(run.id, end ? impactLearningOf(end, started, laid, await roundsSpendOf(store, run.id)) : null);
165
174
  }
166
175
  return { counts, impact: learningImpact(rows, (row) => learnings.get(row.id) ?? null), notes: noteRuns(files) };
167
176
  }
@@ -181,10 +190,7 @@ export async function agentCostOverStore(store, agentId, limit = Infinity) {
181
190
  kinds.set(run.revisionId, (await store.agents.revision(run.revisionId))?.kind);
182
191
  if (kinds.get(run.revisionId) === "workflow")
183
192
  continue;
184
- const started = await learningStartOfRun(store, run.id);
185
- const { looked, grade } = await learningSpendOf(store, run.id);
186
- const { path, workflow } = await journalReadsOf(store, run, started);
187
- runs.push({ n: runs.length + 1, run_id: run.id, started_at: new Date(run.startedAt).toISOString(), path, workflow, learned_revision: started?.seed ?? null, ...runCostOf(run.costUsd, looked, grade) });
193
+ runs.push(await costRunOf(store, run, runs.length + 1));
188
194
  }
189
195
  return { runs: runs.slice(Math.max(0, runs.length - limit)), summary: costSummary(runs), total_runs: runs.length, unknown_cost_runs: runs.filter((run) => run.total_usd === null).length };
190
196
  }
@@ -200,6 +206,17 @@ async function learningSpendOf(store, runId) {
200
206
  const learningRun = kept.learningRunId ? await store.runs.get(kept.learningRunId) : undefined;
201
207
  return { looked, grade: learningRun && FINAL_STATES.includes(learningRun.state) ? (learningRun.costUsd ?? null) : 0 };
202
208
  }
209
+ /** One run of the cost series, as number `n` of it: its figures and its path (agentCostOverStore's loop body, and a learning
210
+ * batch's row once the run's learning has settled). */
211
+ export async function costRunOf(store, run, n) {
212
+ const started = await learningStartOfRun(store, run.id);
213
+ // A run a follow-up opened again (a review's, a person's) learned in rounds: every round's look-back and grade are its
214
+ // learning (roundsSpendOf), never the newest round's alone.
215
+ const rounds = await roundsSpendOf(store, run.id);
216
+ const { looked, grade } = rounds ? { looked: rounds, grade: rounds.grade_usd } : await learningSpendOf(store, run.id);
217
+ const { path, workflow } = await journalReadsOf(store, run, started);
218
+ return { n, run_id: run.id, started_at: new Date(run.startedAt).toISOString(), path, workflow, learned_revision: started?.seed ?? null, ...runCostOf(run.costUsd, looked, grade) };
219
+ }
203
220
  /** What a run's journal tells the agent's learning view and its cost per run: the notes its job opened (`read`, once
204
221
  * final), what its claims laid of the skills and workflows it was offered (`laid`), and, for a run offered a learned
205
222
  * workflow, the path it took and the workflow it called last (`path`, `workflow`: runner/learning-end.ts
@@ -262,16 +279,42 @@ export function laidOf(entries) {
262
279
  }
263
280
  return { skills: [...skills], workflows: [...workflows] };
264
281
  }
282
+ export async function roundsSpendOf(store, runId) {
283
+ const newest = await store.learning.proposal(runId);
284
+ if (!newest || newest.round < 2)
285
+ return undefined;
286
+ let first;
287
+ let look = 0;
288
+ let grade = 0;
289
+ for (let round = 1; round <= newest.round; round++) {
290
+ const kept = round === newest.round ? newest : await store.learning.proposal(runId, round);
291
+ if (!kept)
292
+ continue;
293
+ const answered = answeredOf((kept.proposal ?? {}));
294
+ if (!first && answered.answered_at !== undefined)
295
+ first = answered;
296
+ // A round that never looked back (no figures kept) added none.
297
+ look = look === null || answered.look_back_usd === null ? null : look + (answered.look_back_usd ?? 0);
298
+ const learningRun = kept.learningRunId ? await store.runs.get(kept.learningRunId) : undefined;
299
+ const spent = learningRun && FINAL_STATES.includes(learningRun.state) ? (learningRun.costUsd ?? null) : 0;
300
+ grade = grade === null || spent === null ? null : grade + spent;
301
+ }
302
+ if (!first || typeof first.answered_at !== "string")
303
+ return undefined;
304
+ return { answered_at: first.answered_at, job_cost_usd: first.job_cost_usd ?? null, look_back_usd: look, grade_usd: grade };
305
+ }
265
306
  /** What a run's learning end tells its impact, as ofAgent's learningOf read a held run: how it ended and when, the notes
266
307
  * it started from; when its job answered and its costs once it looked back (a look-back of 0 for an ended one that did
267
308
  * not); its grade's cost once it ended (0 when nothing was graded). */
268
- function impactLearningOf(end, started, laid) {
309
+ function impactLearningOf(end, started, laid, rounds) {
269
310
  const over = end.state === "merged" || end.state === "dropped";
270
- const looked = end.answered_at !== undefined ? { answered_at: end.answered_at, job_cost_usd: end.job_cost_usd ?? null, look_back_usd: end.look_back_usd ?? null } : over ? { look_back_usd: 0 } : {};
311
+ // A run a follow-up opened again: its job answered at its first round's end, and every round's look-back and grade are
312
+ // its learning (the newest round's `job_cost_usd` also holds the earlier rounds' look-backs, never the job's own).
313
+ const looked = rounds ? { answered_at: rounds.answered_at, job_cost_usd: rounds.job_cost_usd, look_back_usd: rounds.look_back_usd } : end.answered_at !== undefined ? { answered_at: end.answered_at, job_cost_usd: end.job_cost_usd ?? null, look_back_usd: end.look_back_usd ?? null } : over ? { look_back_usd: 0 } : {};
271
314
  return {
272
315
  state: end.state, reason: end.reason, at: end.at, ...(started?.seedNotes !== undefined ? { seed_notes: started.seedNotes } : {}),
273
316
  ...(laid?.skills.length ? { seed_skills: laid.skills.length } : {}), ...(laid?.workflows.length ? { seed_workflows: laid.workflows.length } : {}), ...looked,
274
- ...(over ? { grade_usd: end.cost_usd ? end.cost_usd.grade : 0 } : {}),
317
+ ...(over ? { grade_usd: rounds ? rounds.grade_usd : end.cost_usd ? end.cost_usd.grade : 0 } : {}),
275
318
  };
276
319
  }
277
320
  /** The notes a run's job read (learning-run.ts noteRead's rule, over the runner's journal rows): its own successful
@@ -412,18 +455,31 @@ async function learningStartOfRun(store, runId) {
412
455
  const launch = row ? readLaunchBody(row.body) : undefined;
413
456
  return launch ? learningStartOf(launch) : undefined;
414
457
  }
458
+ /** The learning of a run that only uses what its agent learned (`learning: "use"`): seeded while it runs, as a run that
459
+ * learns is; dropped `use` once it ended, since it is never asked what to keep. */
460
+ export function usedOnly(started, terminal, at) {
461
+ // A start that could not be made (a folder unreadable or not copied) handed the run nothing: said so from its start, as
462
+ // the end hook says it for a run that learns, never "seeded" and then `use`. No proposal is written for it.
463
+ if (seedFailed(started)) {
464
+ const why = started.seedFailed === "unreadable" ? STOPPED.unreadable : started.seedFailed === "not_copied" ? STOPPED.notCopied : STOPPED.noSeed;
465
+ return { state: "dropped", reason: "seed_failed", detail: said.stopped(why), at };
466
+ }
467
+ return terminal ? { state: "dropped", reason: "use", detail: said.use, at } : { state: "seeded", reason: null, detail: said.seeded(started.seedNotes ?? 0), at };
468
+ }
415
469
  /** GET /runs/{id}/learning from the one store, in the shape the route gives (learning-routes.ts runLearningBody): the
416
470
  * run's learning end (runLearningEnd), the notes it was given and the seed it started from as its launch records them,
417
471
  * what it held for its owner's OK as it stands on its agent's folder's main (`statuses`, learning-routes.ts statusesOf,
418
472
  * read only when it held something; none: as the merge wrote it), settled once the run is final. Null when the run kept
419
473
  * no learning. */
420
474
  export async function runLearningOverStore(store, runId, shown, secrets, statuses) {
421
- const end = await runLearningEnd(store, runId);
422
- if (!end)
423
- return null;
424
475
  const started = await learningStartOfRun(store, runId);
425
476
  const row = await store.runs.get(runId);
426
477
  const settled = row !== undefined && FINAL_STATES.includes(row.state);
478
+ // A run that only uses what its agent learned keeps no proposal: its learning is its start (seeded, then dropped `use`
479
+ // once it ended), the same words its run view gives.
480
+ const end = (await runLearningEnd(store, runId)) ?? (started?.use && row ? usedOnly(started, settled, timeOf(row.endedAt ?? row.startedAt)) : null);
481
+ if (!end)
482
+ return null;
427
483
  const used = started?.given.length || started?.skills?.length || started?.workflows?.length;
428
484
  const [reflect, rows, entries] = used ? await Promise.all([runReflect(store, runId, BACKGROUND_CONTEXT), runTimeline(store, runId, BACKGROUND_CONTEXT, { settled }), runEntries(store, runId, BACKGROUND_CONTEXT)]) : [undefined, [], []];
429
485
  const read = started?.given.length ? notesReadOf(started.given, reflect, rows) : [];
@@ -1,4 +1,4 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type ImportedFrom, type RunRow, type Store } from "../store/store.js";
3
3
  /** A revision's kind, as the row names it. */
4
4
  export type RevisionKind = "agentic" | "workflow";
@@ -1,4 +1,4 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type WorkflowRunView } from "../workflow-run.js";
3
3
  import type { Store } from "../store/store.js";
4
4
  /** The workflow run `runId`'s view from A: its graph's node status, and, once it ended, its outcome, the node it escalated
@@ -20,6 +20,11 @@ export interface ViewDeps {
20
20
  * for its owner's OK reads as it stands there. None: as the merge wrote it. */
21
21
  readonly statuses?: (agentId: string) => Promise<ReadonlyMap<string, ItemStatus> | undefined>;
22
22
  }
23
+ /** A run's whole answer as answerOfRun read it from the rows: its newest final-answer row, never the learning turn's, and
24
+ * never an earlier turn's: a final answer row before the person's last message belongs to the turn that message
25
+ * followed, so a follow-up whose own stop said nothing (no text block: a thinking-only stop) has no answer, null, not
26
+ * the answer before it. */
27
+ export declare const answerOf: (rows: readonly TimelineEvent[]) => string | null;
23
28
  /** GET /runs/{id}'s answer from the store, byte-identical to runs.ts's view for the same run. Undefined for an unknown run. */
24
29
  export declare function viewOverStore(store: Store, runId: string, deps: ViewDeps): Promise<Record<string, unknown> | undefined>;
25
30
  /** The run list's answer from the store, byte-identical to runs.ts's summary: the view's subset a list shows. */
@@ -4,7 +4,7 @@
4
4
  // model sees do not change. runs.ts still answers the API from files; this is the store-backed path the server cut switches
5
5
  // onto. viewOverStore answers the run read, summaryOverStore the run list, momentOverStore the one acceptance each act reads.
6
6
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
7
- import { CAPS } from "./timeline/index.js";
7
+ import { CAPS, isMessageRow } from "./timeline/index.js";
8
8
  import { runLink } from "./console-links.js";
9
9
  import { redacted, redactedAnswer, redactedOutput, withoutLoopback } from "./key-refusal.js";
10
10
  import { structuredAnswer } from "./answer-json.js";
@@ -19,7 +19,7 @@ import { overCapMessage, SPEND_CAP_REACHED } from "@parcha/agentrun-kernel/kerne
19
19
  import { bookedSpend } from "./runner/metrics.js";
20
20
  import { journalRecords, recordOf } from "./runner/journal-reader.js";
21
21
  import { capNowOf, KINDS } from "./runner/journal-kinds.js";
22
- import { notesReadOf, runLearningEnd, withNotes } from "./store-reads/learning.js";
22
+ import { notesReadOf, runLearningEnd, usedOnly, withNotes } from "./store-reads/learning.js";
23
23
  import { runReflect, runTimeline, wholeAnswerFor, wholeAnswers } from "./store-reads/journal.js";
24
24
  import { readRun } from "./store-reads/runs.js";
25
25
  import { runCutValues, runErrorWordsOf, underCut } from "./run-cut.js";
@@ -60,8 +60,15 @@ function servedOnce(store, runId, input, values) {
60
60
  }
61
61
  return out;
62
62
  }
63
- /** A run's whole answer as answerOfRun read it from the rows: its newest final-answer row, never the learning turn's. */
64
- const answerOf = (rows) => rows.findLast((r) => r.kind === "final_answer" && r.agent_label !== LEARNING_LABEL)?.text ?? null;
63
+ /** A run's whole answer as answerOfRun read it from the rows: its newest final-answer row, never the learning turn's, and
64
+ * never an earlier turn's: a final answer row before the person's last message belongs to the turn that message
65
+ * followed, so a follow-up whose own stop said nothing (no text block: a thinking-only stop) has no answer, null, not
66
+ * the answer before it. */
67
+ export const answerOf = (rows) => {
68
+ const asked = rows.findLastIndex((r) => isMessageRow(r) && r.agent_label === null && r.text !== null);
69
+ const row = rows.findLast((r) => r.kind === "final_answer" && r.agent_label !== LEARNING_LABEL);
70
+ return row && rows.lastIndexOf(row) > asked ? row.text ?? null : null;
71
+ };
65
72
  /** A failed run's error from its row (its own words are the summary; the store keeps no code or detail apart). A run
66
73
  * its cap ended once its cost passed it (the kernel's overCapEnd) is code spend_cap_reached, its message the words after
67
74
  * the code, as main served it; a provider's content-filter stop is `moderated`, in words a person can act on
@@ -169,7 +176,7 @@ async function storeRunIn(store, runId, deps, cut) {
169
176
  // run that learns is seeded, then looking back once its end-of-run turn starts (main's seeded and reflecting).
170
177
  const started = launch ? learningStartOf(launch) : undefined;
171
178
  const read = started?.given.length ? notesReadOf(started.given, reflectRange, await runTimeline(store, runId, context, { settled: terminal })) : [];
172
- const under = !ended && started && !seedFailed(started) ? underWay(started, reflectRange, iso(runRow.startedAt)) : null;
179
+ const under = !ended && started && started.use ? usedOnly(started, terminal, iso(runRow.endedAt ?? runRow.startedAt)) : !ended && started && !seedFailed(started) ? underWay(started, reflectRange, iso(runRow.startedAt)) : null;
173
180
  const sofar = ended ?? under;
174
181
  const shownEnd = sofar && withNotes(sofar, started, read);
175
182
  const turns = new Turns();
@@ -228,6 +235,9 @@ async function storeRunIn(store, runId, deps, cut) {
228
235
  ((command.kind === "steer" && command.body?.answers !== false) || (command.kind === "raise" && budget?.kind === "budget"));
229
236
  const submitted = terminal || row.kind !== "agentic" || working ? 0 : (await commandsNow()).filter(pending).length;
230
237
  const outcome = terminal ? STATUS_OF[row.state] : undefined;
238
+ // A cancel the person asked for reads cancelled from the 202 on, while the runner is still cutting the turn: its command
239
+ // row (not refused) is the request, so a poll never reads working or completed between the request and the end.
240
+ const cancelling = !terminal && (await commandsNow()).some((command) => command.kind === "cancel" && command.refused === null);
231
241
  const view = {
232
242
  id: row.id,
233
243
  agentId: row.agent,
@@ -235,8 +245,9 @@ async function storeRunIn(store, runId, deps, cut) {
235
245
  ...(row.importedFrom ? { imported: { source: row.importedFrom.source, session: row.importedFrom.session } } : {}),
236
246
  kind: row.kind,
237
247
  ...(outcome ? { outcome } : {}),
248
+ ...(cancelling ? { finishing: "cancelled" } : {}),
238
249
  // A cancel is the run's outcome 'cancelled', never its state alone: a person's stop is stopped too, and is no cancel.
239
- cancel: runRow.outcome === "cancelled",
250
+ cancel: runRow.outcome === "cancelled" || cancelling,
240
251
  working,
241
252
  submitted,
242
253
  updatedAt: iso(updatedAtMs),
@@ -298,7 +309,11 @@ export async function viewOverStore(store, runId, deps) {
298
309
  const { row, runRow, launch, view, unshown, values, output, review: kept, structured } = run;
299
310
  const { status, state } = statusOf(view, factsOf(run));
300
311
  const terminal = TERMINAL.has(status);
301
- const endedAtMs = terminal ? (runRow.endedAt ?? runRow.startedAt) : null;
312
+ // A cancel reads cancelled from its 202 (status terminal) while the runner is still cutting the turn: the run is settled
313
+ // only once the store holds its end (its row no longer running), so its end time, poll hint, timeline `final` and learning
314
+ // come from that end, never from the optimistic status. Later tool results, withdrawals and charges still stream in.
315
+ const ended = row.state !== "running";
316
+ const endedAtMs = terminal && ended ? (runRow.endedAt ?? runRow.startedAt) : null;
302
317
  const shownWords = (text) => withoutLoopback(redacted(text, values));
303
318
  // The answer row's text is the answer as served (whole, through redactedAnswer, once per held value set, when the row
304
319
  // was cut; else the rows' redactor over what was never cut): served again through redactedAnswer once per that set.
@@ -339,7 +354,7 @@ export async function viewOverStore(store, runId, deps) {
339
354
  // card), else its agent waiting on a person in its browser (browserPending), else the question its turn ended on (pendingOf).
340
355
  const redactor = redactorOf(values);
341
356
  const pending = !unshown && status === "input_required" && state === "waiting" ? (approvalOf(view, redactor) ?? run.budget ?? browserPending(run.browserAsk, redactor) ?? computerPending(run.computerAsk, redactor) ?? pendingOf(run.rows)) : null;
342
- const settled = terminal;
357
+ const settled = terminal && ended;
343
358
  return {
344
359
  run_id: row.id,
345
360
  agent_id: row.agent,
@@ -375,8 +390,8 @@ export async function viewOverStore(store, runId, deps) {
375
390
  imported_from: runRow.importedFrom ? { source: runRow.importedFrom.source, session: runRow.importedFrom.session } : null,
376
391
  trigger: launch?.trigger ?? null,
377
392
  // Cut by the run's one cut (the pointers it was handed among them), and none for a withheld run, as its words.
378
- learning: unshown ? null : learningViewOf(run.learningEnd, secretsShown(values), terminal && settled),
379
- poll_after_ms: terminal && settled ? 0 : 1000,
393
+ learning: unshown ? null : learningViewOf(run.learningEnd, secretsShown(values), settled),
394
+ poll_after_ms: settled ? 0 : 1000,
380
395
  last_progress_at: run.lastProgressAt,
381
396
  };
382
397
  }
@@ -401,7 +416,7 @@ export async function factsOverStore(store, runId, deps) {
401
416
  if (!run)
402
417
  return undefined;
403
418
  const { status } = statusOf(run.view, factsOf(run));
404
- const endedAtMs = TERMINAL.has(status) ? (run.runRow.endedAt ?? run.runRow.startedAt) : null;
419
+ const endedAtMs = TERMINAL.has(status) && run.row.state !== "running" ? (run.runRow.endedAt ?? run.runRow.startedAt) : null;
405
420
  return { kind: run.row.kind, revision: run.row.revision, agentId: run.row.agent, status, createdAt: iso(run.runRow.startedAt), endedAt: endedAtMs === null ? null : iso(endedAtMs), unshown: run.unshown };
406
421
  }
407
422
  /** A run's live moment from the store (momentOf), for the one acceptance each act a run takes reads. A run no runner holds
@@ -17,7 +17,7 @@ import { parseDocument } from "yaml";
17
17
  import { answerJson, lastJsonBlock, schemaCheck } from "./answer-json.js";
18
18
  import { checkNote } from "./learn/index.js";
19
19
  import { NOTE_FILE } from "./learn/notes.js";
20
- import { MCP_SERVER_NAME } from "./mcp-probe.js";
20
+ import { MCP_SERVER_NAME, shownUrl } from "./mcp-probe.js";
21
21
  import { settingsKeyOf, shellToolOf } from "./tool-gate.js";
22
22
  import { ASK_TOOL, BOUND_TOOLS } from "./tools.js";
23
23
  import { applyBodyOf, compiled, filledPins, packageView, readPackage } from "./templates.js";
@@ -708,7 +708,8 @@ export async function evalTemplate(options) {
708
708
  // directory of its own, gone when the eval is.
709
709
  cpSync(options.dir, join(scratch, "templates", pkg.name), { recursive: true });
710
710
  const { startServe } = await import("./server.js");
711
- const serve = await startServe({ data: join(scratch, "data"), port: 0, token: randomBytes(24).toString("base64url"), templates: join(scratch, "templates"), drainTimeout: "5s", ...(options.serve ?? {}) }).catch((error) => {
711
+ // A local install by construction: its own scratch server, reached on loopback, its fake MCP servers there too.
712
+ const serve = await startServe({ mcpLoopback: true, data: join(scratch, "data"), port: 0, token: randomBytes(24).toString("base64url"), templates: join(scratch, "templates"), drainTimeout: "5s", ...(options.serve ?? {}) }).catch((error) => {
712
713
  removeTree(scratch);
713
714
  throw error;
714
715
  });
@@ -719,7 +720,8 @@ export async function evalTemplate(options) {
719
720
  const { fauxEnvOf } = await import("./server.js");
720
721
  const { withoutFaux } = await import("./model.js");
721
722
  const serveOptions = options.serve ?? {};
722
- const beside = await runnerBeside(join(scratch, "data"), serveOptions.faux ? { env: { ...withoutFaux(process.env), ...fauxEnvOf({ data: join(scratch, "data"), ...serveOptions }) } } : {}).catch(async (error) => {
723
+ // Its run lines go to stderr: stdout is the eval's report.
724
+ const beside = await runnerBeside(join(scratch, "data"), { mcpLoopback: serve.localInstall, onLine: (line) => console.error(line), ...(serveOptions.faux ? { env: { ...withoutFaux(process.env), ...fauxEnvOf({ data: join(scratch, "data"), ...serveOptions }) } } : {}) }).catch(async (error) => {
723
725
  await serve.close();
724
726
  removeTree(scratch);
725
727
  throw error;
@@ -831,7 +833,7 @@ async function runCase(ctx, one) {
831
833
  }
832
834
  }
833
835
  /** Whether the server's MCP server `name` is still this eval's fake at `url`. */
834
- const ownsFake = (api, name, url) => api("GET", `/settings/mcp-servers/${name}`).then((read) => read.status === 200 && isObject(read.body) && read.body.url === url, () => false);
836
+ const ownsFake = (api, name, url) => api("GET", `/settings/mcp-servers/${name}`).then((read) => read.status === 200 && isObject(read.body) && read.body.url === shownUrl(url), () => false);
835
837
  const caseCost = (runs) => Math.round(runs.reduce((sum, r) => sum + (r.cost_usd ?? 0) + r.graders.reduce((g, x) => g + (x.cost_usd ?? 0), 0), 0) * 1e6) / 1e6;
836
838
  /** One run of a case: a fresh agent (so one run's learning never reaches the next), its notes, the run, its grades. */
837
839
  async function runOnce(ctx, one, n, fakes) {
@@ -1,18 +1,32 @@
1
1
  import type { InputIssue } from "./errors.js";
2
- import { APP_PERMISSIONS } from "./github-connection.js";
3
2
  import type { McpNeed } from "./templates.js";
4
- type Level = "read" | "write";
3
+ export type Level = "read" | "write";
4
+ /** What the App's installations hold, as GitHub says now: each one's account and permissions map; or why it could not be
5
+ * read (in words that end a sentence's clause, with no full stop). */
6
+ export type Held = {
7
+ readonly installations: readonly {
8
+ readonly account: string;
9
+ readonly permissions: Readonly<Record<string, Level>>;
10
+ }[];
11
+ readonly unread?: readonly {
12
+ readonly account: string;
13
+ readonly why: string;
14
+ }[];
15
+ } | {
16
+ readonly unreadable: string;
17
+ };
5
18
  /** Each GitHub MCP tool a template may grant that needs more than reading what the App's metadata gives: the permission
6
- * and level it needs, the thing it acts on, and what the template does instead when it can't. */
19
+ * and level GitHub's permission table for its request names, and what the template does instead when it can't. */
7
20
  export declare const TOOL_PERMISSIONS: Record<string, {
8
- permission: keyof typeof APP_PERMISSIONS;
21
+ permission: string;
9
22
  level: Level;
10
23
  instead: string;
11
24
  }>;
12
- /** The warnings applying `pkg` adds: one for each GitHub MCP tool it grants that needs a permission `permissions` (the
13
- * App's manifest) does not hold, on an MCP server `onApp` says runs on the App's tokens. */
25
+ /** The warnings applying `pkg` adds: one for each GitHub MCP tool it grants that needs a permission an installation of the
26
+ * App does not hold (naming each installation's account and what it holds), on an MCP server `onApp` says runs on the App's
27
+ * tokens; or, where `held` could not be read, one saying it could not check. `held` is asked once, and only when a tool
28
+ * with a need is granted on such a server. */
14
29
  export declare function appPermissionWarnings(pkg: {
15
30
  name: string;
16
31
  mcp: readonly McpNeed[];
17
- }, onApp: (server: string) => boolean, permissions?: Readonly<Record<string, Level>>): InputIssue[];
18
- export {};
32
+ }, onApp: (server: string) => boolean, held: () => Promise<Held>): Promise<InputIssue[]>;