@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
@@ -1,3 +1,4 @@
1
+ import type { ProjectCheckpoint } from "../source-sync/checkpoints.js";
1
2
  import { type ConversationId, type ConversationRetryPolicy, type ConversationStreamOptions, Harness, type Tx } from "@earendil-works/pi-durable";
2
3
  import { type AdapterFacts, type AgentAdapter, type Refusal, type SessionRecord, type SessionSpec } from "@parcha/agentrun-kernel";
3
4
  import type { KernelHooks, ToolCall } from "./conformance/subject.js";
@@ -5,6 +6,7 @@ import { type BudgetData, type EndData, type ToolCalls } from "./journal-kinds.j
5
6
  import { type MessageOrigin } from "../timeline/index.js";
6
7
  type EndCost = Required<Pick<EndData, "costUsd" | "costUpperBound">>;
7
8
  import { type Claim, type EndOfRunTurn, type LoopFactory } from "./loop-contract.js";
9
+ import { type HeldRedact } from "./redact.js";
8
10
  import { Parked } from "./loop.js";
9
11
  import type { PiRun } from "./adapters/pi.js";
10
12
  import { type HeldSpec } from "./held-run.js";
@@ -56,11 +58,13 @@ export type RaiseCheck = {
56
58
  retry?: undefined;
57
59
  };
58
60
  /** The gate's answer for a call: run it, ask a person (`ask` with fields its card shows before the call's input: a
59
- * learned workflow's MCP actions), or refuse it (with the words the model reads, or generic ones). */
61
+ * learned workflow's MCP actions; `because`, why a call its setting allows asks anyway, its ask's own field and never
62
+ * one of the call's arguments), or refuse it (with the words the model reads, or generic ones). */
60
63
  export type GateAnswer = "allow" | "ask" | "deny" | {
61
64
  readonly deny: string;
62
65
  } | {
63
66
  readonly ask: Readonly<Record<string, unknown>>;
67
+ readonly because?: string;
64
68
  };
65
69
  /** The gate before a call's intent; `askedAs`, when it has one, names a call as a person is asked about it (its settings
66
70
  * key, as main's pending approval names it), else the call is asked about by its own name. `replayed`: asked again for a
@@ -174,6 +178,12 @@ export interface AdapterRunSpec {
174
178
  readonly endCost?: () => Promise<EndCost>;
175
179
  /** The most the end's patch may take before the end is written without it. Default END_PATCH_MS. */
176
180
  readonly endPatchMs?: number;
181
+ /** Optional moved-project capture, only after actual dispatch has drained. Failure remains an explicit terminal receipt. */
182
+ readonly projectCheckpoint?: {
183
+ capture(signal: AbortSignal): Promise<ProjectCheckpoint>;
184
+ uncertain(): ProjectCheckpoint;
185
+ readonly timeoutMs?: number;
186
+ };
177
187
  /** The most a booking whose write has begun is waited for before an answer's cost, a park or the end goes on without
178
188
  * it. Default BOOKING_WRITE_MS. */
179
189
  readonly bookingWriteMs?: number;
@@ -283,9 +293,9 @@ export type AdapterRun = PiRun & {
283
293
  * learned workflow's model nodes). Read from the spec's runCap once the spec is known. */
284
294
  readonly ledger: RunLedger;
285
295
  /** The runner's one redactor (LoopDeps.redact; runner.ts), the same instance: the spec gives it to every place a secret
286
- * could reach text (the session's model proxy, the model route's translation, its log lines). Absent where no runner
287
- * gave one (a spec built alone). */
288
- readonly redact?: (text: string) => string;
296
+ * could reach text (the session's model proxy, the model route's translation, its log lines), and its claim carries the
297
+ * run's own tool keys into (claim-secrets.ts). Absent where no runner gave one (a spec built alone). */
298
+ readonly redact?: HeldRedact;
289
299
  /** The claim's signal (LoopDeps.signal): aborted on a lost claim or the runner's shutdown, never on a person's stop. A
290
300
  * spec's per-claim resources let go of what they hold at once on it (the run's Archil mount credential). Absent where
291
301
  * no loop gave one (a spec built alone). */
@@ -1,10 +1,24 @@
1
+ // The kernel's loop for any harness on the adapter contract (AgentAdapter: claude-agent, codex, opencode, and pi through
2
+ // runner/adapters/pi.ts): one claimed run, one Harness on the claim's journal (behind the loop's Gate), one session.
3
+ // What the loop owns, the same for every harness:
4
+ // - the claim and its journal: every commit the loop stages is matched to the commit that carries it (Gate);
5
+ // - the run's end: an `agentrun.end` entry with the run row's patch (ended, stopped with why, failed with why) and a
6
+ // stop's take; a park (an ask with the run parked); an interrupt on a lost claim or a shutdown (nothing more written;
7
+ // the session ended with the adapter's interrupt() and then close(), the path a CLI adapter's kill rides);
8
+ // - a restart of the Session on the kernel's own fault between a call and its result, under a finite restart limit;
9
+ // - the gate before a call's intent (io.gate: the kernel's beforeIntent point, then allow, deny or ask), and the rule
10
+ // before a side effect around every host tool (side-effects.ts: a flush unless the tool is replay-safe, the call, the
11
+ // beforeResult point), on the host-tool path every adapter's calls take;
12
+ // - the paid model requests: the runner's booking (modelPortFor), the one ledger, every request through it;
13
+ // - the held state (pi.live) reported through deps.live; the commands (steer, approve, deny).
14
+ import { ProjectDrain } from "./project-drain.js";
1
15
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
2
16
  import { createModels } from "@earendil-works/pi-ai/models";
3
17
  import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID, ToolTask } from "@earendil-works/pi-durable";
4
18
  import { modelPortFor, RUNNER_RECORDS, sessionSpendOf, turnCostOf } from "@parcha/agentrun-kernel";
5
19
  import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, toolCalls, withdrawnAnswers } from "./journal-kinds.js";
6
20
  import { turnEndedOnAsk } from "../store-reads/journal.js";
7
- import { CAP_WRAPUP, COMPUTER_NOTE, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
21
+ import { CAP_REFUSED, CAP_WRAPUP, COMPUTER_NOTE, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
8
22
  import { raiseFollowUpId } from "../run-view.js";
9
23
  import { durableWait } from "../workflow/pi-versions.js";
10
24
  /** The root entries a claim writes before its turn, whatever the run's turns are (its session's key, a phase row, a
@@ -27,7 +41,8 @@ const outputRetried = (entries) => {
27
41
  return at >= 0 && entries.slice(at + 1).some((entry) => entry.kind === "pi.assistant" || (entry.kind === KINDS.message && entry.data?.role === "model"));
28
42
  };
29
43
  import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
30
- import { ASKED_BECAUSE, deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
44
+ import { heldRedactor } from "./redact.js";
45
+ import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
31
46
  import { ADAPTER_API } from "../turn-end.js";
32
47
  import { answerText, REFLECT_PREFIX, reflectRequestId } from "./end-of-run.js";
33
48
  import { agentEntriesOf, approvalOf, BOOKING_WRITE_MS, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, PARK_SIBLINGS_MS, readAgain, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
@@ -41,9 +56,9 @@ import { COMPUTER_CALLS, recordingCalls } from "../computer-calls.js";
41
56
  import { channelCallOf, runChannelCall } from "./computer-channel.js";
42
57
  import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
43
58
  import { journalSessions } from "./sessions.js";
44
- import { DECISION_SESSION, FIT_TOLERANCE, freeModel, freeRequestsIn, freeWrapUpDue, freeWrapUpWords, noteFor, overCapOf, paidRefusal, requestFigures, runCap, SERVER_NOTE_LABEL, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
59
+ import { DECISION_SESSION, FIT_TOLERANCE, freeModel, freeRequestsIn, freeWrapUpDue, freeWrapUpWords, noteFor, overCapEnd, overCapOf, paidRefusal, requestFigures, runCap, SERVER_NOTE_LABEL, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
45
60
  import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
46
- import { bookedIn } from "../paid-calls.js";
61
+ import { bookedIn, stopRunWith } from "../paid-calls.js";
47
62
  import { sideEffect } from "./side-effects.js";
48
63
  import { McpClaimRefused } from "./mcp-claim.js";
49
64
  import { CODEMODE, defersCatalog, isCatalogWire, TOOLS_CALL, TOOLS_SEARCH } from "@parcha/agentrun-kernel";
@@ -55,6 +70,20 @@ import { LEARNED_CARD_FIELDS, LEARNED_CLIP, LEARNED_WORKFLOW_TOOL, learnedApprov
55
70
  import { warnHoldShort } from "../print.js";
56
71
  import { feedbackAsk, feedbackOf, jobEndOpen, pendingFeedbackOf } from "./feedback-round.js";
57
72
  import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
73
+ /** What a session's requests were charged (sessionSpendOf's figures of those answered, a crash's cut one at its hold among
74
+ * them), never one still in flight at its hold. Null: one charged has no figure. */
75
+ function chargedOf(records) {
76
+ const read = sessionSpendOf(records);
77
+ let usd = 0;
78
+ for (const figure of read.figures) {
79
+ if (!read.answered.has(figure.turn))
80
+ continue;
81
+ if (figure.usd === null)
82
+ return null;
83
+ usd += figure.usd;
84
+ }
85
+ return usd;
86
+ }
58
87
  /** The end of a harness's own call (Claude Code's WebSearch) the gate held and then let run: the host ran nothing of it,
59
88
  * and the harness's next call runs it. */
60
89
  export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool runs it on its next call.";
@@ -62,12 +91,11 @@ export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool
62
91
  export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
63
92
  /** An asked call's card: the gate's own fields (`shown`) first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES)
64
93
  * still names them whatever the input's size, then the call's input, which the model wrote, without any field of
65
- * theirs; a learned_workflow call's card fields (LEARNED_CARD_FIELDS) are only ever the gate's, and so is the reason a
66
- * call its setting allows asks anyway (ASKED_BECAUSE). */
94
+ * theirs; a learned_workflow call's card fields (LEARNED_CARD_FIELDS) are only ever the gate's. */
67
95
  function cardOf(tool, shown, args) {
68
- if (!shown && tool !== LEARNED_WORKFLOW_TOOL && !(args && Object.hasOwn(args, ASKED_BECAUSE)))
96
+ if (!shown && tool !== LEARNED_WORKFLOW_TOOL)
69
97
  return args;
70
- return { ...shown, ...Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => !(shown && Object.hasOwn(shown, key)) && key !== ASKED_BECAUSE && !(tool === LEARNED_WORKFLOW_TOOL && LEARNED_CARD_FIELDS.has(key)))) };
98
+ return { ...shown, ...Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => !(shown && Object.hasOwn(shown, key)) && !(tool === LEARNED_WORKFLOW_TOOL && LEARNED_CARD_FIELDS.has(key)))) };
71
99
  }
72
100
  /** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
73
101
  const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
@@ -376,6 +404,13 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
376
404
  void flushText().catch(() => undefined);
377
405
  else if (event.type === "turn_end")
378
406
  void flushText(event).catch(() => undefined);
407
+ else if (event.type === "notice") {
408
+ // The adapter's own words (the ACP mirror past its budget): a phase row after what the model said before it.
409
+ void flushText().catch(() => undefined);
410
+ void inTurn(async () => {
411
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: HOST_PHASE, data: { summary: event.text, at: now() } }), context);
412
+ }).catch(() => undefined);
413
+ }
379
414
  },
380
415
  flushText,
381
416
  flushSaid: () => (answer === undefined && text.trim() !== "" ? flushText(undefined, true) : Promise.resolve()),
@@ -641,6 +676,8 @@ function adapterLoop(specOf, options, deps) {
641
676
  };
642
677
  /** The current pass's spec's release, until it is called (closeSession). */
643
678
  let releaseNow;
679
+ const projectWork = new ProjectDrain();
680
+ const projectCall = (call, strict = !!specNow?.projectCheckpoint) => strict ? projectWork.run(call) : call();
644
681
  /** The current pass ended in a park that keeps its computer (keepAtPark), for this cause, until its release reads it. */
645
682
  let parkedNow;
646
683
  /** From the end-of-run step's start (or a claim that found its turn open: lookingBackOpen, from its session's open)
@@ -952,7 +989,7 @@ function adapterLoop(specOf, options, deps) {
952
989
  const channelCommand = async (command) => {
953
990
  await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
954
991
  const [theGate, pass, theHeld] = [gate, channelNow, heldNow];
955
- if (!theGate || theGate.sealed)
992
+ if (!theGate || theGate.sealed || projectWork.closed)
956
993
  return { refused: "The run's computer is not up now: the run is starting, parking or ending." };
957
994
  if (!pass)
958
995
  return { refused: specNow?.computer ? "The run's computer is not up now: the run is starting, parking or ending." : "This run has no computer that takes protocol calls: none, or a browser." };
@@ -967,7 +1004,7 @@ function adapterLoop(specOf, options, deps) {
967
1004
  theHeld?.callStarted();
968
1005
  let done;
969
1006
  try {
970
- done = await runChannelCall(pass.computer, call, AbortSignal.any([deps.signal, AbortSignal.timeout(CALL_MS)]), now);
1007
+ done = await projectCall(() => runChannelCall(pass.computer, call, AbortSignal.any([deps.signal, AbortSignal.timeout(CALL_MS)]), now));
971
1008
  }
972
1009
  finally {
973
1010
  theHeld?.callEnded(now());
@@ -1461,7 +1498,7 @@ function adapterLoop(specOf, options, deps) {
1461
1498
  return;
1462
1499
  passGate.expect(writesEntry(kind, test), { run: { summary } }).catch(() => undefined);
1463
1500
  };
1464
- const runOf = { harness, registry, setModels: (given) => (models = given), ledger, ...(deps.redact ? { redact: deps.redact } : {}), signal: deps.signal, stopped: AbortSignal.any([deps.signal, stopAbort.signal]), phase, rowSummaryOn };
1501
+ const runOf = { harness, registry, setModels: (given) => (models = given), ledger, ...(deps.redact ? { redact: heldRedactor(deps.redact) } : {}), signal: deps.signal, stopped: AbortSignal.any([deps.signal, stopAbort.signal]), phase, rowSummaryOn };
1465
1502
  // The spec, its MCP claim step among it (mcpForClaim, before the session opens). A refusal there ends the run in its
1466
1503
  // words with nothing sent; a claim lost during its refresh ends the loop with nothing more written. A claim the spec
1467
1504
  // refuses (ClaimRefused: a handed sign-in that won't read back) ends the run in its words too.
@@ -1532,7 +1569,33 @@ function adapterLoop(specOf, options, deps) {
1532
1569
  // A host tool call's paid requests name the session the call runs in (RunTools.admit `under`): a request of it still
1533
1570
  // in flight may be the one that asked for the call (Claude Code books its cost after its calls; Codex starts a call
1534
1571
  // with its response open), so the call is judged beside it and never waits on it. pi's request has answered by then.
1535
- const paidUnder = { admit: (request) => paid.admit({ ...request, under: spec.session.key }), settle: (id, usd, options) => paid.settle(id, usd, options) };
1572
+ // A call settled above its hold (a fal job whose output states more than its input asked, a monid call charged above
1573
+ // its maxCost) can take what the run was
1574
+ // charged past its cap. From then on, a settle that leaves the run's charges over its cap stops the run at once in
1575
+ // the cap's words (overCap, settled charges only), as a stop for good (paid-calls.ts stopRun): no tool runs after it,
1576
+ // a script's own calls included. A charge is never given back, so that stop holds; a call still in flight counts
1577
+ // only toward admissions (the cap's rule), where it refuses a new call, never stops the run. Its hold, kept from its
1578
+ // admission, tells an overrun.
1579
+ const holds = new Map();
1580
+ let overran = false;
1581
+ const paidUnder = {
1582
+ admit: async (request) => {
1583
+ const admitted = await paid.admit({ ...request, under: spec.session.key });
1584
+ holds.set(request.id, request.holdUsd);
1585
+ return admitted;
1586
+ },
1587
+ settle: async (id, usd, options) => {
1588
+ const held = holds.get(id);
1589
+ holds.delete(id);
1590
+ const settled = await paid.settle(id, usd, options);
1591
+ if (typeof usd === "number" && held !== undefined && Math.round(usd * 1e6) > Math.round(held * 1e6))
1592
+ overran = true;
1593
+ const over = overran ? await overCap({ settled: true }) : undefined;
1594
+ if (over)
1595
+ await stopRunWith(ledger.pause)(over);
1596
+ return settled;
1597
+ },
1598
+ };
1536
1599
  let refused;
1537
1600
  /** The pause a refusal for room journaled before pi heard of it (pauseAtCap), the run parked with it. */
1538
1601
  let pausedAtRefusal = false;
@@ -1541,8 +1604,8 @@ function adapterLoop(specOf, options, deps) {
1541
1604
  /** How the run ends once its booked spend passed its cap (the kernel's overCapEnd, main's run end): every session's
1542
1605
  * booked spend summed, as the cap reads it; the bound, its model session's requests' since the cost last fit, so a
1543
1606
  * cache miss within that bound pauses the run at its next request instead. Undefined while it fits, with no cap, or
1544
- * with a spend unknown. */
1545
- const overCap = async () => {
1607
+ * with a spend unknown. `settled`: what its sessions were charged only, never a request still in flight at its hold. */
1608
+ const overCap = async ({ settled = false } = {}) => {
1546
1609
  // A run whose spec gives no cap (no runCap, or no cap's rule) has none to pass.
1547
1610
  if (!spec.cap || !spec.runCap)
1548
1611
  return undefined;
@@ -1557,11 +1620,15 @@ function adapterLoop(specOf, options, deps) {
1557
1620
  for (const key of await sessions.keys()) {
1558
1621
  if (key === spec.session.key)
1559
1622
  continue;
1560
- const spent = sessionSpendOf(await sessions.read(key)).spentUsd;
1623
+ const spent = settled ? chargedOf(await sessions.read(key)) : sessionSpendOf(await sessions.read(key)).spentUsd;
1561
1624
  if (spent === null)
1562
1625
  return undefined;
1563
1626
  others += spent;
1564
1627
  }
1628
+ if (settled) {
1629
+ const own = chargedOf(await sessions.read(spec.session.key));
1630
+ return own === null ? undefined : overCapEnd(others + own, cap);
1631
+ }
1565
1632
  // Its model session read as the cap reads it (the kernel's overCapOf: a request cut by a crash at its hold plus its
1566
1633
  // bound, and that bound kept, so a possible cache miss pauses the run, never fails it).
1567
1634
  return overCapOf(await sessions.read(spec.session.key), others, cap);
@@ -1618,8 +1685,12 @@ function adapterLoop(specOf, options, deps) {
1618
1685
  // A paid call's refusal is the call's result first: its pause is journaled at the model's next request (beforeRequest,
1619
1686
  // pendingPause), once the harness has stored that result, so the run never reads waiting on a raise before its
1620
1687
  // Timeline says why. The refusal is kept on the root at once (KINDS.pausePending, no run patch, nothing a person
1621
- // reads), so a claim lost in between restores it (pendingPauseOf) and the next claim's request parks the run.
1688
+ // reads), so a claim lost in between restores it (pendingPauseOf) and the next claim's request parks the run. A stop
1689
+ // for good (paid-calls.ts stopRun) stays: a refusal after it (a call admitted after the stop, refused for room) never
1690
+ // replaces it, so no tool runs after the stop.
1622
1691
  pauseFor = async (refusal) => {
1692
+ if (pendingPause?.forGood)
1693
+ return;
1623
1694
  pendingPause = refusal;
1624
1695
  await keepPending(refusal);
1625
1696
  };
@@ -1932,8 +2003,10 @@ function adapterLoop(specOf, options, deps) {
1932
2003
  // spend and each request or paid step still out at its hold and bound, read from the run's records at each call. A
1933
2004
  // hold-only step still open (a browser session's reserve) is no spend in its records, but the cap holds it in
1934
2005
  // flight: it counts at its hold too. One a lost claim left open was given back at this claim's open (bookCut).
1935
- // Its answer is the words a call reads once the run wraps up (wrap-up.ts wrapUpText), undefined while it does not.
1936
- const wrapUp = async () => {
2006
+ // Its answer is the words a call reads once the run wraps up (wrap-up.ts wrapUpText), with the cap it was judged
2007
+ // under (read once, before the spend reads it awaits: a raise landing meanwhile is the next call's), undefined while
2008
+ // it does not.
2009
+ const wrapUpAt = async () => {
1937
2010
  // A run whose spec gives no cap (no runCap) has none to wrap up at, as overCap reads it.
1938
2011
  if (!spec.runCap)
1939
2012
  return undefined;
@@ -1952,9 +2025,32 @@ function adapterLoop(specOf, options, deps) {
1952
2025
  if (!wrappingUp(capUsd, taken, reserveOf(capNote.lastFigures)))
1953
2026
  return undefined;
1954
2027
  // A cap below what the model needs for one more step and an answer is named in the words, by the same rule.
1955
- return wrapUpText(capUsd, capNote.lastModel, stepAndAnswerFor(capNote.lastFigures, (step0Usd) => typicalCost(capNote.costs, step0Usd)), capNote.lastEffort);
2028
+ return { words: wrapUpText(capUsd, capNote.lastModel, stepAndAnswerFor(capNote.lastFigures, (step0Usd) => typicalCost(capNote.costs, step0Usd)), capNote.lastEffort), capUsd };
2029
+ };
2030
+ /** The wrap-up's words alone (wrapUpAt). */
2031
+ const wrapUp = async () => (await wrapUpAt())?.words;
2032
+ // The wrap-up's refusal of a call (the gate's, wrapUp's words): kept on the run's root as a CAP_REFUSED entry, its
2033
+ // call and the cap it was refused under, so the run's view says it wound down for its cap (store-view.ts
2034
+ // windDownOf: `stopped_for`, `budget_refused_calls`). A call refused again (a replay) is the same call: the reader
2035
+ // counts each call once. Not written once the journal is sealed; a write that fails is warned and the call is
2036
+ // refused all the same. The cap kept is the one the refusal was judged under (wrapUpAt's), never one read after it.
2037
+ const wrapUpRefusal = async (callId) => {
2038
+ const refusal = await wrapUpAt();
2039
+ if (refusal === undefined)
2040
+ return undefined;
2041
+ const { words, capUsd } = refusal;
2042
+ if (gate?.sealed)
2043
+ return words;
2044
+ try {
2045
+ await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind: CAP_REFUSED, data: { callId, capUsd } }), context);
2046
+ await deps.flush();
2047
+ }
2048
+ catch (error) {
2049
+ console.warn(`[runner] the wrap-up's refusal of a call was not kept (the call is refused): ${said(error)}`);
2050
+ }
2051
+ return words;
1956
2052
  };
1957
- const gateOf = preIntentGate(spec, hooks, wrapUp);
2053
+ const gateOf = preIntentGate(spec, hooks, wrapUpRefusal);
1958
2054
  // A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
1959
2055
  const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context, now, spec.cwd) : undefined;
1960
2056
  cliRecord = record;
@@ -2003,6 +2099,7 @@ function adapterLoop(specOf, options, deps) {
2003
2099
  return { text: given.deny, isError: true };
2004
2100
  // An ask with its card's own fields is an ask, its card as the gate shows it.
2005
2101
  const shown = typeof given === "object" ? given.ask : undefined;
2102
+ const because = typeof given === "object" ? given.because : undefined;
2006
2103
  const now = shown ? "ask" : given;
2007
2104
  // Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
2008
2105
  // replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
@@ -2010,7 +2107,7 @@ function adapterLoop(specOf, options, deps) {
2010
2107
  // the setting at allow now: the setting answers the ask (allowedBySetting).
2011
2108
  const bySetting = now === "allow" && (await askStands(toolContext.callId));
2012
2109
  if (now === "ask" || bySetting) {
2013
- const call = { callId: toolContext.callId, tool: name, args: cardOf(name, shown, (args ?? {})) };
2110
+ const call = { callId: toolContext.callId, tool: name, args: cardOf(name, shown, (args ?? {})), ...(because !== undefined ? { because } : {}) };
2014
2111
  const price = mcp?.priceOf(name) ?? null;
2015
2112
  const answer = bySetting ? await allowedBySetting(call, price, asked) : await answerOf(call, price, asked);
2016
2113
  if (answer === "park")
@@ -2036,7 +2133,7 @@ function adapterLoop(specOf, options, deps) {
2036
2133
  // refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
2037
2134
  // The computer protocol calls it makes, kept beside it on the run's root (COMPUTER_CALLS) for its result
2038
2135
  // row's computer_calls, before its result is written.
2039
- route: () => bookedIn({ call: toolContext.callId, paid: paidUnder, pause: ledger.pause }, () => recordingCalls(() => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }), (calls, dropped) => keepCalls(toolContext.callId, calls, dropped))),
2136
+ route: () => bookedIn({ call: toolContext.callId, paid: paidUnder, pause: ledger.pause }, () => recordingCalls(() => projectCall(() => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }), !!spec.projectCheckpoint), (calls, dropped) => keepCalls(toolContext.callId, calls, dropped))),
2040
2137
  beforeResult: async (answer) => {
2041
2138
  const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
2042
2139
  try {
@@ -2245,7 +2342,7 @@ function adapterLoop(specOf, options, deps) {
2245
2342
  if (!gate?.sealed)
2246
2343
  throw error;
2247
2344
  };
2248
- const nestedAsking = preIntentGate(spec, hooks, wrapUp, async (call) => (await nestedRecord()).park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch(unlessSealed));
2345
+ const nestedAsking = preIntentGate(spec, hooks, wrapUpRefusal, async (call) => (await nestedRecord()).park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch(unlessSealed));
2249
2346
  const nestedGate = async (call, hookContext) => {
2250
2347
  if (call.nested !== true)
2251
2348
  return gateOf(call, hookContext);
@@ -2259,7 +2356,7 @@ function adapterLoop(specOf, options, deps) {
2259
2356
  };
2260
2357
  const nestedEnded = async (callId, status, output) => (await nestedRecord()).end(callId, status, output).catch(unlessSealed);
2261
2358
  const askingGate = record
2262
- ? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch((error) => {
2359
+ ? preIntentGate(spec, hooks, wrapUpRefusal, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch((error) => {
2263
2360
  if (!gate?.sealed)
2264
2361
  throw error;
2265
2362
  }))
@@ -2635,7 +2732,7 @@ function adapterLoop(specOf, options, deps) {
2635
2732
  if (ended)
2636
2733
  answer = recorded(ended);
2637
2734
  else {
2638
- const verdict = await preIntentGate(spec, hooks, wrapUp, (asked) => rec.park(asked.callId, asked.tool, asked.args ?? {}, false))(call, context);
2735
+ const verdict = await preIntentGate(spec, hooks, wrapUpRefusal, (asked) => rec.park(asked.callId, asked.tool, asked.args ?? {}, false))(call, context);
2639
2736
  if (verdict !== "allow" && "park" in verdict)
2640
2737
  return "park";
2641
2738
  if (verdict !== "allow") {
@@ -3049,25 +3146,30 @@ function adapterLoop(specOf, options, deps) {
3049
3146
  }
3050
3147
  }
3051
3148
  /** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park).
3052
- * `wrapUp`: once the run has taken its share of the cap, the words every call the model makes is refused in (wrapUpText).
3149
+ * `wrapUp`: once the run has taken its share of the cap, the words every call the model makes is refused in (wrapUpText),
3150
+ * each refusal kept on the run (wrapUpRefusal).
3053
3151
  * `beforeAsk`: what goes on the record of a call the gate asks about, before its ask is written or read (a CLI's call
3054
3152
  * through its tool bridge: its start, marked parked, so its row shows while it waits and reads before its approval). */
3055
3153
  function preIntentGate(spec, hooks, wrapUp, beforeAsk) {
3056
3154
  return async (call, _hookContext) => {
3155
+ if (projectWork.closed)
3156
+ return { deny: "The project is finishing its checkpoint; no new call can start." };
3057
3157
  // An MCP tool is asked about by its catalog name (`mcp:<server>/<tool>`), as its settings and its card name it.
3058
3158
  const tool = mcp?.catalogOf(call.tool) ?? call.tool;
3059
3159
  const kernelCall = { callId: call.callId, tool: tool, args: call.args };
3060
3160
  await hooks.beforeIntent(kernelCall);
3061
3161
  // The cap's wrap-up, the same way: once the run has taken its share of the cap, every call the model makes is refused
3062
3162
  // in its fixed words, and the model answers from what it has. A call a running tool makes is that tool's, let through.
3063
- const wrapUpDeny = call.nested !== true ? await wrapUp() : undefined;
3163
+ const wrapUpDeny = call.nested !== true ? await wrapUp(call.callId) : undefined;
3064
3164
  if (wrapUpDeny !== undefined)
3065
3165
  return { deny: wrapUpDeny };
3066
3166
  // A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
3067
3167
  const replayed = call.replayed === true;
3068
3168
  const given = (await spec.gate?.(kernelCall, { ...(replayed ? { replayed } : {}), ran: ranOf })) ?? "allow";
3069
- // An ask with its card's own fields (a learned workflow's MCP actions set to ask, each with its arguments' shape).
3169
+ // An ask with its card's own fields (a learned workflow's MCP actions set to ask, each with its arguments' shape), or
3170
+ // with the reason a call its setting allows asks anyway (`because`).
3070
3171
  const shown = typeof given === "object" && "ask" in given ? given.ask : undefined;
3172
+ const because = typeof given === "object" && "ask" in given ? given.because : undefined;
3071
3173
  let decision = shown ? "ask" : given;
3072
3174
  // A call nested in a learned_workflow call a person approved, of an MCP tool that call's card named: its ask is
3073
3175
  // answered by that approval, as the card they saw named it (never one built again now). Any other asks for itself.
@@ -3113,7 +3215,8 @@ function adapterLoop(specOf, options, deps) {
3113
3215
  // Marked destructive when the tool is, or when any MCP tool the one allow lets run is (the card's `mcp_calls`, a
3114
3216
  // learned workflow's MCP actions set to ask): that allow takes the second confirm too.
3115
3217
  const destructive = [asked, ...learnedApprovedTools(shown)].some((name) => mcp?.effectOf(name) === "destructive");
3116
- const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked, destructive);
3218
+ const card = { ...call, tool, args, ...(because !== undefined ? { because } : {}) };
3219
+ const answer = bySetting ? await allowedBySetting(card, price, asked) : await answerOf(card, price, asked, destructive);
3117
3220
  if (answer === "park")
3118
3221
  return { park: true };
3119
3222
  if (answer.approved)
@@ -3152,7 +3255,7 @@ function adapterLoop(specOf, options, deps) {
3152
3255
  // run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
3153
3256
  // An MCP tool its run's pin marks destructive (ClaimMcp.effectOf), or a call whose allow covers one (`destructive`):
3154
3257
  // its card asks a second confirm of an allow.
3155
- const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price, ...(destructive ? { destructive: true } : {}) };
3258
+ const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, ...(call.because !== undefined ? { because: call.because } : {}), requestedAt: isoNow(), price, ...(destructive ? { destructive: true } : {}) };
3156
3259
  const entryLands = (kind, data, staged) => landEntry(conversation, kind, data, staged);
3157
3260
  if (first === undefined) {
3158
3261
  // Asked and parked; or held as the parked call is, when another call of the round parked the run first.
@@ -3950,6 +4053,22 @@ function adapterLoop(specOf, options, deps) {
3950
4053
  // their own commits, the end's patch reading the cost they book), and its requests' bookings come first.
3951
4054
  await releaseHost(on);
3952
4055
  await bookingsSettled();
4056
+ let projectCheckpoint;
4057
+ if (specNow?.projectCheckpoint) {
4058
+ const project = specNow.projectCheckpoint;
4059
+ const signal = AbortSignal.any([deps.signal, AbortSignal.timeout(project.timeoutMs ?? 60_000)]);
4060
+ try {
4061
+ await projectWork.close(signal);
4062
+ // Abort asks the bounded backend operations to stop; it is not evidence that they stopped. Keep the actual
4063
+ // capture promise through its cleanup before teardown/end. A capability that ignores cancellation leaves
4064
+ // this claim unresolved, never a published candidate or a falsely completed release.
4065
+ projectCheckpoint = await project.capture(signal);
4066
+ signal.throwIfAborted();
4067
+ }
4068
+ catch {
4069
+ projectCheckpoint = project.uncertain();
4070
+ }
4071
+ }
3953
4072
  // The pull request's checkout goes before the end is committed: a run that reads final never still holds its code.
3954
4073
  await specNow?.endCheckout?.();
3955
4074
  const patch = await endPatchOf(base);
@@ -3962,7 +4081,7 @@ function adapterLoop(specOf, options, deps) {
3962
4081
  if (lateStop)
3963
4082
  take = [...take, lateStop.commandId];
3964
4083
  // An end that keeps the job's takes it too, and stays the job's.
3965
- const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd, ...(patch.costUpperBound ? { costUpperBound: true } : {}) } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop && keptAt === undefined ? stopEnd(lateStop.cancel) : {}) };
4084
+ const data = { ...base, ...(projectCheckpoint ? { projectCheckpoint } : {}), ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd, ...(patch.costUpperBound ? { costUpperBound: true } : {}) } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop && keptAt === undefined ? stopEnd(lateStop.cancel) : {}) };
3966
4085
  const run = {
3967
4086
  state: data.state,
3968
4087
  ...(keptAt !== undefined ? { endedAt: keptAt, keepsEnd: true } : {}),
@@ -186,7 +186,7 @@ export declare function modelRetryOf(routes: Iterable<Pick<ModelRoute, "like">>)
186
186
  export declare function graderRouteOf(body: {
187
187
  readonly modelTiers?: Readonly<Partial<Record<SubagentTier, string>>>;
188
188
  readonly learning?: unknown;
189
- }, keyed: boolean, runKey: ClaimModelKey | undefined, claimed: NodeJS.ProcessEnv, cut: HeldRedact, log: (line: string) => void, deps: Pick<AdapterSpecDeps, "store" | "sealKey" | "env" | "routeOf">, holds?: readonly HeldRedact[]): Promise<ModelRoute | undefined>;
189
+ }, keyed: boolean, runKey: ClaimModelKey | undefined, claimed: NodeJS.ProcessEnv, cut: HeldRedact, log: (line: string) => void, deps: Pick<AdapterSpecDeps, "store" | "sealKey" | "env" | "routeOf">, holds?: readonly HeldRedact[], claim?: Pick<Claim, "runId" | "turn" | "attempt">): Promise<ModelRoute | undefined>;
190
190
  /** What the runner routes a claimed run on: the launch's model as its start pinned it, sent as pinned, with the
191
191
  * revision's own ref beside it (main prices a gateway's id by the provider that ref names); the revision's ref alone
192
192
  * when the start pinned none. Never the pin's provider and id joined into a ref: a gateway refuses the joined id, and