@parcha/agentrun-serve 0.1.0-beta.39 → 0.1.0-beta.41

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 (173) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +129 -16
  3. package/dist/api-only.d.ts +3 -1
  4. package/dist/api-only.js +4 -2
  5. package/dist/api-token.d.ts +30 -0
  6. package/dist/api-token.js +89 -0
  7. package/dist/cli.js +19 -5
  8. package/dist/composio-made.d.ts +54 -0
  9. package/dist/composio-made.js +83 -0
  10. package/dist/composio-preset.d.ts +16 -8
  11. package/dist/composio-preset.js +106 -43
  12. package/dist/composio-triggers.d.ts +7 -2
  13. package/dist/composio-triggers.js +13 -7
  14. package/dist/computer-attach.d.ts +29 -11
  15. package/dist/computer-attach.js +141 -47
  16. package/dist/computer-keys.d.ts +4 -0
  17. package/dist/computer-keys.js +5 -0
  18. package/dist/computers.d.ts +11 -1
  19. package/dist/computers.js +21 -12
  20. package/dist/console/assets/index-C3gNPz58.css +1 -0
  21. package/dist/console/assets/index-COGhx_2Z.js +711 -0
  22. package/dist/console/index.html +2 -2
  23. package/dist/decisions.js +9 -2
  24. package/dist/email/account.d.ts +0 -1
  25. package/dist/email/account.js +3 -3
  26. package/dist/email/answer.d.ts +5 -0
  27. package/dist/email/answer.js +35 -0
  28. package/dist/email/mail.js +19 -26
  29. package/dist/email/names.d.ts +30 -0
  30. package/dist/email/names.js +34 -0
  31. package/dist/email/routes.d.ts +1 -0
  32. package/dist/email/routes.js +1 -1
  33. package/dist/email/tools.d.ts +11 -4
  34. package/dist/email/tools.js +91 -46
  35. package/dist/eval-feed.d.ts +26 -0
  36. package/dist/eval-feed.js +68 -0
  37. package/dist/eval-mailbox.d.ts +5 -2
  38. package/dist/eval-mailbox.js +14 -6
  39. package/dist/exa-keyless.d.ts +1 -1
  40. package/dist/exa-keyless.js +1 -1
  41. package/dist/feed/feed-faux.d.ts +62 -0
  42. package/dist/feed/feed-faux.js +123 -0
  43. package/dist/feed/fetch.d.ts +41 -0
  44. package/dist/feed/fetch.js +128 -0
  45. package/dist/feed/parse.d.ts +41 -0
  46. package/dist/feed/parse.js +300 -0
  47. package/dist/learn/check.d.ts +3 -1
  48. package/dist/learn/check.js +57 -2
  49. package/dist/learn/compile.d.ts +3 -2
  50. package/dist/learn/compile.js +7 -6
  51. package/dist/learn/promote.d.ts +25 -14
  52. package/dist/learn/promote.js +32 -14
  53. package/dist/learned-nodes.d.ts +21 -4
  54. package/dist/learned-nodes.js +21 -8
  55. package/dist/learned-workflow.d.ts +3 -3
  56. package/dist/learned-workflow.js +14 -5
  57. package/dist/learning-cost.d.ts +17 -8
  58. package/dist/learning-cost.js +12 -4
  59. package/dist/local-models.d.ts +7 -1
  60. package/dist/local-models.js +11 -5
  61. package/dist/mcp-oauth.d.ts +15 -1
  62. package/dist/mcp-oauth.js +39 -5
  63. package/dist/mcp-pin-first.d.ts +4 -2
  64. package/dist/mcp-pin-first.js +4 -3
  65. package/dist/mcp-servers-store.d.ts +58 -5
  66. package/dist/mcp-servers-store.js +136 -17
  67. package/dist/mcp.d.ts +2 -2
  68. package/dist/mcp.js +2 -2
  69. package/dist/observation/http.d.ts +4 -1
  70. package/dist/observation/http.js +5 -4
  71. package/dist/openapi.d.ts +1 -1
  72. package/dist/openapi.js +63 -27
  73. package/dist/port-models.d.ts +4 -1
  74. package/dist/port-models.js +1 -0
  75. package/dist/print.d.ts +6 -3
  76. package/dist/print.js +4 -2
  77. package/dist/refusal-words.d.ts +3 -0
  78. package/dist/refusal-words.js +3 -0
  79. package/dist/run-labels.d.ts +23 -0
  80. package/dist/run-labels.js +79 -0
  81. package/dist/run-launch.d.ts +2 -0
  82. package/dist/run-launch.js +2 -0
  83. package/dist/run-secrets.js +12 -4
  84. package/dist/run-view.d.ts +3 -4
  85. package/dist/run-view.js +26 -24
  86. package/dist/runner/adapter-loop.d.ts +6 -2
  87. package/dist/runner/adapter-loop.js +136 -22
  88. package/dist/runner/adapter-run-spec.d.ts +5 -0
  89. package/dist/runner/adapter-run-spec.js +75 -32
  90. package/dist/runner/beside.d.ts +6 -3
  91. package/dist/runner/beside.js +9 -7
  92. package/dist/runner/cli-run-spec.js +33 -26
  93. package/dist/runner/conformance/harness.js +69 -14
  94. package/dist/runner/conformance/subject.d.ts +4 -1
  95. package/dist/runner/journal-kinds.d.ts +22 -0
  96. package/dist/runner/journal-kinds.js +39 -0
  97. package/dist/runner/main.d.ts +1 -1
  98. package/dist/runner/main.js +2 -2
  99. package/dist/runner/mcp-claim.d.ts +3 -0
  100. package/dist/runner/mcp-claim.js +1 -1
  101. package/dist/runner/mcp-run.d.ts +4 -0
  102. package/dist/runner/mcp-run.js +5 -3
  103. package/dist/runner/model-route.d.ts +7 -3
  104. package/dist/runner/model-route.js +24 -9
  105. package/dist/runner/promotion.d.ts +16 -8
  106. package/dist/runner/promotion.js +178 -55
  107. package/dist/runner/workflow-first.d.ts +6 -5
  108. package/dist/runner/workflow-first.js +9 -7
  109. package/dist/runs-over-store.js +5 -2
  110. package/dist/sdk/runs.d.ts +7 -1
  111. package/dist/sdk/runs.js +19 -6
  112. package/dist/secret-cut.js +3 -1
  113. package/dist/secrets.js +3 -1
  114. package/dist/server.d.ts +27 -2
  115. package/dist/server.js +181 -56
  116. package/dist/store/dialect.d.ts +6 -0
  117. package/dist/store/dialect.js +2 -0
  118. package/dist/store/index.d.ts +1 -1
  119. package/dist/store/postgres/connection.d.ts +11 -5
  120. package/dist/store/postgres/connection.js +44 -17
  121. package/dist/store/postgres/dialect.js +6 -0
  122. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  123. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  124. package/dist/store/postgres/store.d.ts +7 -3
  125. package/dist/store/postgres/store.js +1 -0
  126. package/dist/store/schema.d.ts +9 -0
  127. package/dist/store/schema.js +26 -2
  128. package/dist/store/sqlite/connection.js +80 -8
  129. package/dist/store/sqlite/run-launch.d.ts +11 -0
  130. package/dist/store/sqlite/run-launch.js +8 -0
  131. package/dist/store/sqlite/run-patch.d.ts +2 -1
  132. package/dist/store/sqlite/run-patch.js +3 -2
  133. package/dist/store/sqlite/store.js +101 -26
  134. package/dist/store/sqlite/worker.d.ts +2 -0
  135. package/dist/store/sqlite/worker.js +13 -10
  136. package/dist/store/store.d.ts +53 -1
  137. package/dist/store-reads/journal.js +2 -1
  138. package/dist/store-reads/learning.d.ts +30 -13
  139. package/dist/store-reads/learning.js +130 -51
  140. package/dist/store-reads/runs.d.ts +4 -3
  141. package/dist/store-reads/runs.js +3 -2
  142. package/dist/store-view.js +4 -2
  143. package/dist/template-eval.d.ts +4 -0
  144. package/dist/template-eval.js +127 -50
  145. package/dist/templates.d.ts +24 -1
  146. package/dist/templates.js +129 -21
  147. package/dist/timeline/origin.d.ts +1 -1
  148. package/dist/timeline/origin.js +2 -2
  149. package/dist/tool-gate.d.ts +5 -3
  150. package/dist/tool-gate.js +5 -2
  151. package/dist/tools.d.ts +13 -0
  152. package/dist/tools.js +15 -10
  153. package/dist/trigger-adapter.d.ts +12 -36
  154. package/dist/trigger-adapters.js +2 -1
  155. package/dist/trigger-email.js +30 -77
  156. package/dist/trigger-feed.d.ts +12 -0
  157. package/dist/trigger-feed.js +371 -0
  158. package/dist/triggers.d.ts +27 -14
  159. package/dist/triggers.js +121 -80
  160. package/dist/webhooks.js +9 -5
  161. package/dist/workflow/decision-recovery.js +5 -2
  162. package/dist/workflow/decisions.d.ts +7 -0
  163. package/dist/workspace/computer-deps.d.ts +5 -1
  164. package/dist/workspace/computer-deps.js +2 -2
  165. package/dist/workspace/index.d.ts +1 -0
  166. package/dist/workspace/index.js +2 -0
  167. package/dist/workspace/resolve-computer.d.ts +32 -3
  168. package/dist/workspace/resolve-computer.js +47 -9
  169. package/launcher/agentrun-serve +6 -1
  170. package/package.json +10 -9
  171. package/templates/README.md +27 -2
  172. package/dist/console/assets/index-BNhZs-jp.css +0 -1
  173. package/dist/console/assets/index-BQv5aOGB.js +0 -700
@@ -9,6 +9,7 @@ import { llmTiers, nodeTiers, thinkingLevel, TIERS, tierModelOf, workflowNodes }
9
9
  import { firstMessage, inputMessage, messageText } from "../run-manifest.js";
10
10
  import { learningStartOf, seedFailed } from "../run-launch.js";
11
11
  import { isWebHostTool } from "../tool-list.js";
12
+ import { ASKED_BECAUSE } from "../refusal-words.js";
12
13
  import { deniedText, noApproverText, runGate } from "../tool-gate.js";
13
14
  import { DECISION_PROVIDER_KEYS, loadToolSettings, recheckPlane, TOOL_PLANE_ENV } from "../tool-plane.js";
14
15
  import { readApprovers } from "../server-approvers.js";
@@ -44,8 +45,8 @@ import { ClaimRefused } from "./loop-contract.js";
44
45
  import { bookedSpend, cliRunMetrics, endCostOf, runCostOf, runMetrics } from "./metrics.js";
45
46
  import { journalEntries } from "./journal-reader.js";
46
47
  import { hashedMcpOf, piShaped } from "../store-reads/journal.js";
47
- import { claimPromotion, promotionGate, replayCallsFor, replayClaimed, replayLaid } from "./promotion.js";
48
- import { laidFor, pathMetrics, servedOf, workflowFirstOf } from "./workflow-first.js";
48
+ import { claimPromotion, promotionGate, replayCallsFor, replayClaimed, replayLaid, toolFlowsFor } from "./promotion.js";
49
+ import { pathMetrics, servedOf, workflowFirstOf } from "./workflow-first.js";
49
50
  import { pastRunsOverStore, runPathOverStore } from "../store-reads/learning.js";
50
51
  import { specBuilt } from "./spec-holds.js";
51
52
  import { archilClaim, MOUNT_TTL_MS } from "../workspace/archil-claim.js";
@@ -118,9 +119,43 @@ export async function adapterRunGate(store, claim, revision, root, shell, option
118
119
  const gate = runGate({ ...where, ...(shell === undefined ? {} : { computer: shell === "computer" }) }, claim.runId, revision, () => current, approvers);
119
120
  // The run's learned workflows, once its spec has read them (learn): a learned_workflow call is asked about its MCP nodes.
120
121
  let learned = [];
122
+ // The host the run's tools bind through, once the spec has made it (askedOn): a tool's own ask reads it.
123
+ let host;
124
+ // A tool's own ask counts its calls (AskContext.ran): the journal's, run to a good end, and the calls of it this gate let
125
+ // through in this claim that have no result yet (reserved, by tool), so calls made at once never all read the same
126
+ // count. Its calls are asked about one at a time (asking, a chain by tool): the count read and the reservation with
127
+ // nothing between. A reserved call whose result is in the journal leaves it: counted there, or its slot freed (an
128
+ // error, a deny). A new claim's gate starts with none: what finished is the journal's.
129
+ const reserved = new Map();
130
+ const asking = new Map();
131
+ const counted = (ran) => async (tool) => {
132
+ const calls = await ran(tool);
133
+ const held = reserved.get(tool);
134
+ for (const id of held ?? [])
135
+ if (calls.ran.has(id) || calls.ended.has(id))
136
+ held.delete(id);
137
+ return calls.ran.size + calls.unnamed + (held?.size ?? 0);
138
+ };
139
+ const askedOne = (call, asks, made, ran) => {
140
+ const turn = (asking.get(call.tool) ?? Promise.resolve()).then(async () => {
141
+ const because = await asks((call.args ?? {}), { host: made, ran: counted(ran) });
142
+ if (because === undefined && call.callId)
143
+ reserved.set(call.tool, (reserved.get(call.tool) ?? new Set()).add(call.callId));
144
+ return because;
145
+ });
146
+ asking.set(call.tool, turn.catch(() => undefined));
147
+ return turn;
148
+ };
121
149
  const decide = async (call, options = {}) => {
122
150
  current = await storeSettings(store);
123
151
  const decision = await gate.decide(call.tool, call.args, options);
152
+ // A call its setting allows that its tool asks about itself (ToolEntry.asks: email_send past its cap, or to someone
153
+ // outside the run's thread): put to a person with the tool's reason on its card, whatever the setting; where no one
154
+ // can approve, refused in those words. No tool's name is read here: the reason is the tool's.
155
+ const asksOf = decision === "allow" && host && options.ran ? toolOf(call.tool)?.asks : undefined;
156
+ const because = asksOf ? await askedOne(call, asksOf, host, options.ran) : undefined;
157
+ if (because !== undefined)
158
+ return approvers ? { ask: { [ASKED_BECAUSE]: because } } : { deny: noApproverText(gate.askedAs(call.tool, call.args), options.replayed ? "unknown" : "no", because) };
124
159
  // A learned workflow's MCP nodes are the run's own MCP calls, held to the same settings: one set to deny refuses the
125
160
  // whole call in the gate's words before any node runs, nothing sent; the actions set to ask are put to a person on the
126
161
  // call's one card, up front, each with its arguments' shape (learnedAskShown), and the person's allow passes the
@@ -155,7 +190,7 @@ export async function adapterRunGate(store, claim, revision, root, shell, option
155
190
  current = await storeSettings(store);
156
191
  return current.unreadable ? "deny" : gate.policy(tool);
157
192
  };
158
- return Object.assign(decide, { askedAs: (tool, args) => gate.askedAs(tool, args), permissions, permission, learn: (flows) => void (learned = flows) });
193
+ return Object.assign(decide, { askedAs: (tool, args) => gate.askedAs(tool, args), permissions, permission, learn: (flows) => void (learned = flows), askedOn: (made) => void (host = made) });
159
194
  }
160
195
  /** The server's tool settings from the store now; a read that throws is unread (no value of it said). A workflow's call
161
196
  * and model nodes read theirs through it too (workflow-spec.ts callPolicyOf), so both gates fail closed alike. */
@@ -227,13 +262,43 @@ async function adapterSpec(launch, run, deps, claim, holds) {
227
262
  // person's stop ends the fetch at once (run.stopped).
228
263
  const checkout = body.checkout === "pull_request" ? await prCheckoutForClaim(deps, ws.workspace, launch, cut, run.stopped ?? run.signal, (part) => holds.hold({ checkout: part })) : undefined;
229
264
  holds.hold({ checkout });
265
+ // The run's skills and its learning seed, laid in its folder through the run's Workspace now, before its computer
266
+ // exists: on Archil the computer's mount of the folder takes the disk's write delegation, and from then on every write
267
+ // over the disk's file API is refused (409) while the mount holds it, so a lay after the mount fails the run. The lay
268
+ // reads nothing of the computer: the kind skill is the revision's computer setting's kind. A later claim lays only what
269
+ // is not there yet (layOwnSkills keeps every folder an earlier claim laid).
270
+ // The launch's learning start (none: the run does not learn), decided once at launch.
271
+ const start = learningStartOf(launch);
272
+ // The revision's own skills are laid in the run's .agents/skills/ before they are read (main's server start laid them;
273
+ // on the one store the claim does), from the revision row's texts (the body keeps only each file's SHA-256): each
274
+ // folder not there yet, never over a learned skill or an earlier claim's. A desktop or a phone (the revision's computer
275
+ // setting, the one computerForClaim starts) brings its kind's skill, named in the prompt beside the revision's own.
276
+ const kindSkills = await layOwnSkills(ws.workspace, (revisionRow.skills ?? {}), { computer: settingOfDefinition(body)?.computer.kind });
277
+ // A learning run's seed, read once from its learning folder where the run's place keeps it: its notes in .learning/
278
+ // and its learned skills beside the revision's own (runner/learning-seed.ts), cut of the server's secrets, the learned
279
+ // skills then in the skill list the prompt names, its learned workflows the ones its learned_workflow tool runs. Laid
280
+ // before the run's tools are bound. A learning fault, or a seed that failed (seedFailed), lays nothing.
281
+ const shown = async () => secretsShown(runnerSecrets(deps.env, await storeSecrets(deps.store, deps.sealKey, deps.data)), { local: true });
282
+ const learningFolder = () => (archil === undefined ? learningFolderOf(deps.data, runRow.agentId) : learningWorkspace({ mode: "archil", agentId: runRow.agentId, archil }));
283
+ const seedLaid = start && !seedFailed(start)
284
+ ? await layLearningSeed({
285
+ work: ws.workspace,
286
+ seed: start.seed,
287
+ folder: learningFolder,
288
+ own: Object.keys(revisionRow.skills ?? {}),
289
+ shown,
290
+ log,
291
+ ...(start.notesOnly ? { workflows: false } : {}),
292
+ ...(start.notesLeftOut?.length ? { notesLeftOut: start.notesLeftOut } : {}),
293
+ })
294
+ : undefined;
230
295
  // The run's MCP for this claim (mcp-run.ts mcpForClaim): its pin, the one its revision's save made, read, its
231
296
  // credentials opened under the server's seal key into this claim's memory, one gateway for the claim. First, before
232
297
  // anything the spec would have to let go: a refusal (a granted tool its pin does not hold, a pinned meta tool) ends the run in its
233
298
  // words before the session opens. The seal key is the runner's own (deps.sealKey), not re-read from the environment.
234
299
  // A credential the claim opens mid-run (a GitHub App token, a saved or per_run server's) joins the run's redactor.
235
300
  const hold = (values) => cut.hold(values);
236
- const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => ws.workspace, launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...(deps.mcpLoopback ? { loopback: true } : {}) });
301
+ const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => ws.workspace, launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...(deps.mcpLoopback ? { loopback: true } : {}), ...(deps.mcpOwn ? { own: deps.mcpOwn } : {}) });
237
302
  // The claim's MCP goes to the loop, which lets it go; a build that throws lets it go itself.
238
303
  holds.hold({ passed: mcp });
239
304
  // The run's computer, from the one shared claim-time function (the CLI spec takes the same): none for a runner place, a
@@ -385,31 +450,6 @@ async function adapterSpec(launch, run, deps, claim, holds) {
385
450
  delete toolEnv[TOOL_PLANE_ENV];
386
451
  if (launch.plane && Object.keys(launch.plane).length)
387
452
  toolEnv[TOOL_PLANE_ENV] = JSON.stringify(launch.plane);
388
- // The launch's learning start (none: the run does not learn), decided once at launch.
389
- const start = learningStartOf(launch);
390
- // The revision's own skills are laid in the run's .agents/skills/ before they are read (main's server start laid them;
391
- // on the one store the claim does), from the revision row's texts (the body keeps only each file's SHA-256): each
392
- // folder not there yet, never over a learned skill or an earlier claim's. A desktop or a phone (the revision's computer
393
- // setting, the one computerForClaim starts) brings its kind's skill, named in the prompt beside the revision's own.
394
- const kindSkills = await layOwnSkills(ws.workspace, (revisionRow.skills ?? {}), { computer: settingOfDefinition(body)?.computer.kind });
395
- // A learning run's seed, read once from its learning folder where the run's place keeps it: its notes in .learning/
396
- // and its learned skills beside the revision's own (runner/learning-seed.ts), cut of the server's secrets, the learned
397
- // skills then in the skill list the prompt names, its learned workflows the ones its learned_workflow tool runs. Laid
398
- // before the run's tools are bound. A learning fault, or a seed that failed (seedFailed), lays nothing.
399
- const shown = async () => secretsShown(runnerSecrets(deps.env, await storeSecrets(deps.store, deps.sealKey, deps.data)), { local: true });
400
- const learningFolder = () => (archil === undefined ? learningFolderOf(deps.data, runRow.agentId) : learningWorkspace({ mode: "archil", agentId: runRow.agentId, archil }));
401
- const seedLaid = start && !seedFailed(start)
402
- ? await layLearningSeed({
403
- work: ws.workspace,
404
- seed: start.seed,
405
- folder: learningFolder,
406
- own: Object.keys(revisionRow.skills ?? {}),
407
- shown,
408
- log,
409
- ...(start.notesOnly ? { workflows: false } : {}),
410
- ...(start.notesLeftOut?.length ? { notesLeftOut: start.notesLeftOut } : {}),
411
- })
412
- : undefined;
413
453
  // The decision keys its learned workflows' typed questions need (claim-secrets.ts learnedDecisionKeys), read once the lay
414
454
  // chose them, scoped as the revision's own: each provider the run's gate does not deny, held by the run's one redactor,
415
455
  // onto the tools' environment alone. The model's route was built on the revision's keys above, so a decision key never
@@ -421,16 +461,18 @@ async function adapterSpec(launch, run, deps, claim, holds) {
421
461
  // serves (runner/promotion.ts: replayed on the agent's graded inputs first, or promoted on its dry run with fewer than
422
462
  // five); while the folder's revision replays or is held, the champion (the digest promoted last) serves in its place
423
463
  // (laidFor). Or the one the money rule stopped, over the agent's past runs (costLineOf): the run asks for its revision.
424
- const firstChoice = learnsWorkflows(revision.kind, laidFlows) ? await workflowFirstOf(revision.kind, laidFlows, launch, log, () => pastRunsOverStore(deps.store, runRow.agentId), promotionGate(claimPromotion({
464
+ const promotion = claimPromotion({
425
465
  store: deps.store, agentId: runRow.agentId, runId: claim.runId, revisionId: runRow.revisionId, launch, context, log, folder: learningFolder, shown, sealKey: deps.sealKey,
426
- })), revision.body.outputSchema) : {};
466
+ });
467
+ const firstChoice = learnsWorkflows(revision.kind, laidFlows) ? await workflowFirstOf(revision.kind, laidFlows, launch, log, () => pastRunsOverStore(deps.store, runRow.agentId), promotionGate(promotion), revision.body.outputSchema) : {};
427
468
  // A replay run runs only its revision, while it still replays: else its claim is refused (the run ends failed, no agent).
428
469
  await replayClaimed(deps.store, runRow.agentId, claim.runId, launch, firstChoice);
429
470
  // A replay run's call nodes: reads live through a cache seeded from the graded run's recorded calls, writes only ever
430
471
  // answered from that recording (runner/promotion.ts replayCallsFor, learn/replay-calls.ts).
431
472
  const replay = await replayCallsFor(deps.store, claim.runId, launch, context);
432
473
  const { serve: workflowFirst, revise: workflowRevise } = firstChoice;
433
- const workflows = laidFor(laidFlows, firstChoice);
474
+ // The tool runs what serves, never a revision not promoted (runner/promotion.ts toolFlowsFor).
475
+ const workflows = await toolFlowsFor(promotion, launch, laidFlows, firstChoice);
434
476
  // A tier a learned workflow's node names and the host has a model of: none can't be reached is left as `why`, and its
435
477
  // node fails in those words (learnedWorkflowHostTool), never on another model.
436
478
  const tierUnreachable = new Map();
@@ -461,6 +503,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
461
503
  const claimBrowser = computer.computer?.kind === "browser" ? computer.computer.browser : undefined;
462
504
  const fakes = deps.evalFakes?.(runRow.agentId);
463
505
  const host = { ...buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: cut, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}) }), ...(claimBrowser ? { browserComputer: claimBrowser } : {}) };
506
+ gate.askedOn(host);
464
507
  // The run's tools. The hands (read/write/edit/bash and the background tools) are the kernel registry's over the run's
465
508
  // Workspace and computer (runTools.hostTools); the gate is the adapter loop's own (spec.gate), so they run as asked.
466
509
  const results = new Map();
@@ -27,15 +27,18 @@ export declare function besideStopping(server: {
27
27
  * caller hands its own: the template eval's in-process server, its faux's). `loops` and `drainMs`: the runner's
28
28
  * (RunnerOptions), the CLI start's from the server's flags (besideRunnerOptions). `janitor`: run the computer janitor
29
29
  * too (workspace/computer-janitor.ts), as the CLI's start asks. `hub`: the server's AttachHub (Serve.attachHub), which
30
- * holds each paired computer's socket in this process, so a run here takes one. Returns the runner and a close() that
31
- * stops both and closes its store. */
32
- export declare function runnerBeside(dataDir: string, { loops, drainMs, env, janitor, hub, mcpLoopback, evalFakes, harnessInstall, onLine }?: {
30
+ * holds each paired computer's socket in this process, so a run here takes one. `dial`: the server's (Serve.dial), which
31
+ * a remote provider's create takes, so a machine that dials the server lands in this process's hub. Returns the runner
32
+ * and a close() that stops both and closes its store. */
33
+ export declare function runnerBeside(dataDir: string, { loops, drainMs, env, janitor, hub, dial, mcpLoopback, mcpOwn, evalFakes, harnessInstall, onLine }?: {
33
34
  loops?: number;
34
35
  drainMs?: number;
35
36
  env?: NodeJS.ProcessEnv;
36
37
  janitor?: boolean;
37
38
  hub?: import("@parcha/agentrun-computer").AttachHub;
39
+ dial?: import("@parcha/agentrun-computer").HostedDial;
38
40
  mcpLoopback?: boolean;
41
+ mcpOwn?: readonly string[];
39
42
  evalFakes?: (agentId: string) => import("./adapter-run-spec.js").EvalFakes | undefined;
40
43
  harnessInstall?: import("../harness-install.js").HarnessInstaller;
41
44
  onLine?: (line: string) => void;
@@ -28,9 +28,10 @@ export function besideStopping(server, held, drainMs) {
28
28
  * caller hands its own: the template eval's in-process server, its faux's). `loops` and `drainMs`: the runner's
29
29
  * (RunnerOptions), the CLI start's from the server's flags (besideRunnerOptions). `janitor`: run the computer janitor
30
30
  * too (workspace/computer-janitor.ts), as the CLI's start asks. `hub`: the server's AttachHub (Serve.attachHub), which
31
- * holds each paired computer's socket in this process, so a run here takes one. Returns the runner and a close() that
32
- * stops both and closes its store. */
33
- export async function runnerBeside(dataDir, { loops, drainMs, env, janitor, hub, mcpLoopback, evalFakes, harnessInstall, onLine } = {}) {
31
+ * holds each paired computer's socket in this process, so a run here takes one. `dial`: the server's (Serve.dial), which
32
+ * a remote provider's create takes, so a machine that dials the server lands in this process's hub. Returns the runner
33
+ * and a close() that stops both and closes its store. */
34
+ export async function runnerBeside(dataDir, { loops, drainMs, env, janitor, hub, dial, mcpLoopback, mcpOwn, evalFakes, harnessInstall, onLine } = {}) {
34
35
  const { runnerName, startRunner } = await import("./runner.js");
35
36
  const { dispatchRunner } = await import("./harness-loops.js");
36
37
  const { routeOf } = await import("./model-route.js");
@@ -60,14 +61,15 @@ export async function runnerBeside(dataDir, { loops, drainMs, env, janitor, hub,
60
61
  const { hostAddressesOnce } = await import("../docker-host-addresses.js");
61
62
  const { PROVIDERS } = await import("@parcha/agentrun-computer");
62
63
  const { hostCommandRefusals } = await import("../computers.js");
63
- const computers = runnerComputers(store, runs, seal.key, { dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs), hostWhy: hostCommandRefusals(PROVIDERS, process.env.PATH), ...(hub ? { hub } : {}) });
64
+ const computers = runnerComputers(store, runs, seal.key, { dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs), hostWhy: hostCommandRefusals(PROVIDERS, process.env.PATH), ...(hub ? { hub } : {}), ...(dial ? { dial } : {}) });
64
65
  // `mcpLoopback`: the server beside it is a local install (Serve.localInstall), so its runs may reach an MCP server on
65
- // loopback; any other runner's runs never do. A run's log lines (a learning run's skipped generality check) go to
66
+ // loopback; any other runner's runs never do. `mcpOwn`: that server's own addresses (Serve.own), whose ports a run's
67
+ // loopback read never goes to. A run's log lines (a learning run's skipped generality check) go to
66
68
  // stderr with the runner's other lines. `evalFakes`: the template eval's fakes (EvalFakes: a case's web, now, monid and
67
69
  // email), by the agent each of its runs is of; only the eval, in its own process, hands them. `harnessInstall`: what a
68
70
  // claim's first-use install installs with (the eval's sharedInstaller, which the server beside it takes too).
69
71
  const { installForClaim } = await import("../harness-install.js");
70
- const createLoop = dispatchRunner({ env: runs, data: dataDir, journal: (claim) => store.journal(claim), store, sealKey: seal.key, routeOf, computerForClaim: computers.computerForClaim, computerDeps: computers.computerDeps, ...(mcpLoopback ? { mcpLoopback: true } : {}), ...(evalFakes ? { evalFakes } : {}), ...(harnessInstall ? { installForClaim: (entry, dir, pins, given) => installForClaim(entry, dir, pins, { ...given, install: harnessInstall }) } : {}), log: (line) => console.error(`agentrun-serve runner: ${line}`) });
72
+ const createLoop = dispatchRunner({ env: runs, data: dataDir, journal: (claim) => store.journal(claim), store, sealKey: seal.key, routeOf, computerForClaim: computers.computerForClaim, computerDeps: computers.computerDeps, ...(mcpLoopback ? { mcpLoopback: true } : {}), ...(mcpOwn ? { mcpOwn } : {}), ...(evalFakes ? { evalFakes } : {}), ...(harnessInstall ? { installForClaim: (entry, dir, pins, given) => installForClaim(entry, dir, pins, { ...given, install: harnessInstall }) } : {}), log: (line) => console.error(`agentrun-serve runner: ${line}`) });
71
73
  // It claims by the host's memory as well as by --max-runs (memory-claim.ts): a heavy harness's run waits queued for room.
72
74
  const { runnerMemory } = await import("./memory-claim.js");
73
75
  // Before it claims: the scratch folders of runs that ended after their runner died (scratch-sweep.ts).
@@ -109,7 +111,7 @@ export async function serveWithRunner(options) {
109
111
  const { besideRunEnv } = await import("./main.js");
110
112
  const { loops, drainMs } = besideRunnerOptions(options, process.env);
111
113
  const serve = await startServe(options);
112
- const beside = await runnerBeside(options.data, { loops, drainMs, env: besideRunEnv(process.env, fauxEnvOf(options)), hub: serve.attachHub, mcpLoopback: serve.localInstall, ...(options.log ? { onLine: options.log } : {}) }).catch(async (error) => {
114
+ const beside = await runnerBeside(options.data, { loops, drainMs, env: besideRunEnv(process.env, fauxEnvOf(options)), hub: serve.attachHub, dial: serve.dial, mcpLoopback: serve.localInstall, mcpOwn: serve.own, ...(options.log ? { onLine: options.log } : {}) }).catch(async (error) => {
113
115
  await serve.close();
114
116
  throw error;
115
117
  });
@@ -63,8 +63,8 @@ import { entriesOf } from "./loop.js";
63
63
  import { bookedSpend, cliModelWorked, cliRunMetrics, endCostOf, runCostOf } from "./metrics.js";
64
64
  import { journalEntries } from "./journal-reader.js";
65
65
  import { hashedMcpOf, piShaped } from "../store-reads/journal.js";
66
- import { claimPromotion, promotionGate, replayCallsFor, replayClaimed, replayLaid } from "./promotion.js";
67
- import { laidFor, pathMetrics, workflowFirstOf } from "./workflow-first.js";
66
+ import { claimPromotion, promotionGate, replayCallsFor, replayClaimed, replayLaid, toolFlowsFor } from "./promotion.js";
67
+ import { pathMetrics, workflowFirstOf } from "./workflow-first.js";
68
68
  import { pastRunsOverStore, runPathOverStore } from "../store-reads/learning.js";
69
69
  import { specBuilt } from "./spec-holds.js";
70
70
  import { heldRedactor, holdClaimed, runnerSecrets, secretRedactor } from "./redact.js";
@@ -314,7 +314,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
314
314
  // A credential the claim opens mid-run (a GitHub App token, a saved or per_run server's) joins the run's redactors.
315
315
  const hold = (values) => { for (const redact of [...(run.redact ? [heldRedactor(run.redact)] : []), cut])
316
316
  redact.hold(values); };
317
- const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => runFolder(deps.data, runRow.agentId, claim.runId), launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...(deps.mcpLoopback ? { loopback: true } : {}) });
317
+ const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => runFolder(deps.data, runRow.agentId, claim.runId), launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...(deps.mcpLoopback ? { loopback: true } : {}), ...(deps.mcpOwn ? { own: deps.mcpOwn } : {}) });
318
318
  // The claim's MCP goes to the loop, which lets it go; a build that throws lets it go itself.
319
319
  holds.hold({ passed: mcp });
320
320
  // The run's mode is the server's: Mode 2 where its Archil settings are saved (archil-settings.ts), the run's folder then
@@ -343,6 +343,30 @@ async function cliSpec(launch, run, deps, claim, holds) {
343
343
  const checkout = body.checkout === "pull_request" ? await prCheckoutForClaim(deps, ws.workspace, launch, cut, run.stopped ?? run.signal, (part) => holds.hold({ checkout: part })) : undefined;
344
344
  holds.hold({ checkout });
345
345
  await placeRunInputs(deps.data, claim.runId, ws.workspace, launch.files ?? [], messageText(launch.input));
346
+ // The run's skills and its learning seed laid before its computer exists, as the pi spec lays them (adapter-run-spec.ts):
347
+ // on Archil the computer's mount takes the disk's write delegation, and a lay over the disk's file API after it is
348
+ // refused (409) while the mount holds it.
349
+ // The launch's learning start (none: the run does not learn), decided once at launch.
350
+ const start = learningStartOf(launch);
351
+ // The revision's own skills laid before they are read, as the pi spec lays them (adapter-run-spec.ts), with the kind's
352
+ // skill of a desktop or a phone (the revision's computer setting), in the harness's skill list beside the revision's.
353
+ const kindSkills = await layOwnSkills(ws.workspace, (revisionRow.skills ?? {}), { computer: settingOfDefinition(body)?.computer.kind });
354
+ // A learning run's seed laid as the pi spec lays it (runner/learning-seed.ts), its learned skills then in the skill list
355
+ // the harness is handed (its native skills, or the prompt's), its learned workflows the ones learned_workflow runs.
356
+ const shown = async () => secretsShown(runnerSecrets(deps.env, await storeSecrets(deps.store, deps.sealKey, deps.data)), { local: true });
357
+ const learningFolder = () => (archil === undefined ? learningFolderOf(deps.data, runRow.agentId) : learningWorkspace({ mode: "archil", agentId: runRow.agentId, archil }));
358
+ const seedLaid = start && !seedFailed(start)
359
+ ? await layLearningSeed({
360
+ work: ws.workspace,
361
+ seed: start.seed,
362
+ folder: learningFolder,
363
+ own: Object.keys(revisionRow.skills ?? {}),
364
+ shown,
365
+ log,
366
+ ...(start.notesOnly ? { workflows: false } : {}),
367
+ ...(start.notesLeftOut?.length ? { notesLeftOut: start.notesLeftOut } : {}),
368
+ })
369
+ : undefined;
346
370
  // The run's computer, from the one shared claim-time function (the pi spec takes the same): none for a runner place.
347
371
  // It throws computer_unavailable (nothing made) when the computer cannot be had: the run fails in its words.
348
372
  const claimSignal = run.stopped ?? run.signal;
@@ -388,29 +412,9 @@ async function cliSpec(launch, run, deps, claim, holds) {
388
412
  // own skills through systemOf with the harness's own check (a harness that loads skills itself keeps in the prompt only
389
413
  // those it would refuse, and is handed the rest), the output schema it answers in (answer-json.ts outputContract, as the
390
414
  // pi spec gives it), then the effort guidance.
391
- const start = learningStartOf(launch);
392
415
  // A start whose seed failed tells the run nothing: it is never asked what to keep (learning-end.ts drops it).
393
416
  const laid = start && !seedFailed(start) ? laidLearned(body.instructions ?? "", start.section, start.use === true) : (body.instructions ?? "");
394
417
  const check = await entry.skillCheck?.();
395
- // The revision's own skills laid before they are read, as the pi spec lays them (adapter-run-spec.ts), with the kind's
396
- // skill of a desktop or a phone (the revision's computer setting), in the harness's skill list beside the revision's.
397
- const kindSkills = await layOwnSkills(ws.workspace, (revisionRow.skills ?? {}), { computer: settingOfDefinition(body)?.computer.kind });
398
- // A learning run's seed laid as the pi spec lays it (runner/learning-seed.ts), its learned skills then in the skill list
399
- // the harness is handed (its native skills, or the prompt's), its learned workflows the ones learned_workflow runs.
400
- const shown = async () => secretsShown(runnerSecrets(deps.env, await storeSecrets(deps.store, deps.sealKey, deps.data)), { local: true });
401
- const learningFolder = () => (archil === undefined ? learningFolderOf(deps.data, runRow.agentId) : learningWorkspace({ mode: "archil", agentId: runRow.agentId, archil }));
402
- const seedLaid = start && !seedFailed(start)
403
- ? await layLearningSeed({
404
- work: ws.workspace,
405
- seed: start.seed,
406
- folder: learningFolder,
407
- own: Object.keys(revisionRow.skills ?? {}),
408
- shown,
409
- log,
410
- ...(start.notesOnly ? { workflows: false } : {}),
411
- ...(start.notesLeftOut?.length ? { notesLeftOut: start.notesLeftOut } : {}),
412
- })
413
- : undefined;
414
418
  const { system: instructions, native } = await systemOf(laid, [...Object.keys(body.skills ?? {}), ...kindSkills, ...(seedLaid?.skills ?? [])], ws.workspace, check, { onDemand: readsFiles(granted) });
415
419
  const guidance = effortGuidance(launch.effort);
416
420
  // The run's model (the launch's, pinned at start, else the revision's) and its adapter, as main builds them, on the
@@ -547,16 +551,18 @@ async function cliSpec(launch, run, deps, claim, holds) {
547
551
  // serves (runner/promotion.ts: replayed on the agent's graded inputs first, or promoted on its dry run with fewer than
548
552
  // five); while the folder's revision replays or is held, the champion (the digest promoted last) serves in its place
549
553
  // (laidFor). Or the one the money rule stopped, over the agent's past runs (costLineOf): the run asks for its revision.
550
- const firstChoice = learnsWorkflows(revision.kind, laidFlows) ? await workflowFirstOf(revision.kind, laidFlows, launch, log, () => pastRunsOverStore(deps.store, runRow.agentId), promotionGate(claimPromotion({
554
+ const promotion = claimPromotion({
551
555
  store: deps.store, agentId: runRow.agentId, runId: claim.runId, revisionId: runRow.revisionId, launch, context, log, folder: learningFolder, shown, sealKey: deps.sealKey,
552
- })), revision.body.outputSchema) : {};
556
+ });
557
+ const firstChoice = learnsWorkflows(revision.kind, laidFlows) ? await workflowFirstOf(revision.kind, laidFlows, launch, log, () => pastRunsOverStore(deps.store, runRow.agentId), promotionGate(promotion), revision.body.outputSchema) : {};
553
558
  // A replay run runs only its revision, while it still replays: else its claim is refused (the run ends failed, no agent).
554
559
  await replayClaimed(deps.store, runRow.agentId, claim.runId, launch, firstChoice);
555
560
  // A replay run's call nodes: reads live through a cache seeded from the graded run's recorded calls, writes only ever
556
561
  // answered from that recording (runner/promotion.ts replayCallsFor, learn/replay-calls.ts).
557
562
  const replay = await replayCallsFor(deps.store, claim.runId, launch, context);
558
563
  const { serve: workflowFirst, revise: workflowRevise } = firstChoice;
559
- const workflows = laidFor(laidFlows, firstChoice);
564
+ // The tool runs what serves, never a revision not promoted (runner/promotion.ts toolFlowsFor).
565
+ const workflows = await toolFlowsFor(promotion, launch, laidFlows, firstChoice);
560
566
  const learns = learnsWorkflows(revision.kind, workflows);
561
567
  if (webNames.length || learns) {
562
568
  // The claim's keys (above, already held by the redactors), a copy of its own for the tools' plane below.
@@ -578,6 +584,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
578
584
  if (webNames.length) {
579
585
  life = hostLifecycle();
580
586
  const host = buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: held, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}) });
587
+ gate.askedOn(host);
581
588
  webTools = await webHostTools(host, granted, ctx);
582
589
  }
583
590
  if (learns) {
@@ -132,6 +132,7 @@ function crashAt(point, holder) {
132
132
  beforeIntent: async () => (point === "beforeIntent" ? crash() : undefined),
133
133
  beforeResult: async () => (point === "beforeResult" ? crash() : undefined),
134
134
  afterMessageSent: async () => (point === "afterMessageSent" ? crash() : undefined),
135
+ afterSteerPlaced: async () => (point === "afterSteerPlaced" ? crash() : undefined),
135
136
  };
136
137
  }
137
138
  /** The Postgres store each registered subject's worlds open (registerHarnessConformance's `storeUrl`), by the subject
@@ -206,6 +207,8 @@ async function world(subject, t, timing = STEADY) {
206
207
  await settled(() => server.runs.create({ id: RUN, agentId: "agent-1", revisionId: "rev-1" }), () => server.runs.get(RUN));
207
208
  /** The command rows a runner has handed to a loop's command(): with the loop, whether or not taken yet. */
208
209
  const handed = new Set();
210
+ /** The command rows a loop's command() has answered: a steer it took is with the session by then (a CLI's has it). */
211
+ const answered = new Set();
209
212
  /** Each runner's claims in flight (store.runs.claimMany), by its name: what claimsSettled waits for. */
210
213
  const claiming = new Map();
211
214
  /** `store` as runner `name` is handed it: the same store, its claims in flight counted (claiming). */
@@ -274,7 +277,15 @@ async function world(subject, t, timing = STEADY) {
274
277
  },
275
278
  }),
276
279
  });
277
- return { ...loop, command: (command) => (handed.add(command.id), loop.command(command)) };
280
+ return {
281
+ ...loop,
282
+ command: (command) => {
283
+ handed.add(command.id);
284
+ const outcome = loop.command(command);
285
+ void Promise.resolve(outcome).then(() => answered.add(command.id), () => undefined);
286
+ return outcome;
287
+ },
288
+ };
278
289
  };
279
290
  const runner = startRunner({ store: claimsCounted(store, name), createLoop: observedLoop, name, ...TIMING, ...timing, onEvent: (event) => events.push({ runner: name, at: Date.now(), ...event }) });
280
291
  runners.push(runner);
@@ -371,7 +382,7 @@ async function world(subject, t, timing = STEADY) {
371
382
  assert.ok(ask, "the run wrote its ask");
372
383
  return String(ask.data.callId);
373
384
  };
374
- return { dir, storeUrl: url, storeEnv, clockFile, runOut, runOutUnknown, claimsSettled, server, start, run, read, ended, began, commandRow, askedCall, events, handedOver: (id) => handed.has(id), liveRows, servedRows };
385
+ return { dir, storeUrl: url, storeEnv, clockFile, runOut, runOutUnknown, claimsSettled, server, start, run, read, ended, began, commandRow, askedCall, events, handedOver: (id) => handed.has(id), answered: (id) => answered.has(id), liveRows, servedRows };
375
386
  }
376
387
  /**
377
388
  * The claim's fence, as the stalled process's own events show it: once it went on (`continuedAt`, its lease run out and no
@@ -697,11 +708,13 @@ const CASES = [
697
708
  const { calls, messages } = await w.read();
698
709
  const slow = calls.find((call) => call.tool === "slow");
699
710
  const steered = messages.find((message) => message.role === "steer");
700
- const said = messages.filter((message) => message.role === "model");
701
711
  assert.ok(slow?.endEntry !== undefined && slow.status === "done", `slow ran to its end: ${JSON.stringify(calls)}`);
712
+ // Everything the model said once the call started. What it said with the call, before the call's row (a CLI's
713
+ // "Calling slow."), is that step's, as deny-note reads it; the step after the call said only the steer.
714
+ const said = messages.filter((message) => message.role === "model" && message.entry > slow.startEntry);
702
715
  assert.equal(steered?.text, "check the totals", `the steer is in the journal: ${JSON.stringify(messages)}`);
703
716
  assert.ok(steered.entry > slow.endEntry, "after the tool's end: mid-turn, not lost");
704
- assert.deepEqual(said.map((message) => message.text), ["check the totals"], "the next step saw it");
717
+ assert.deepEqual(said.map((message) => message.text), ["check the totals"], `the next step saw it: ${JSON.stringify(messages)}`);
705
718
  assert.ok(said[0].entry > steered.entry);
706
719
  assert.ok((await w.commandRow(steer.id)).takenAt !== null, "the steer row is taken");
707
720
  },
@@ -725,8 +738,9 @@ const CASES = [
725
738
  const rows = [];
726
739
  for (const text of texts)
727
740
  rows.push(await sendCommand(w.server, RUN, { kind: "steer", body: { text } }));
728
- // The tool goes on once every message is with the loop: the turn in flight has them, never a timer.
729
- await until(() => rows.every((row) => w.handedOver(row.id)), "the messages handed to the loop mid-turn");
741
+ // The tool goes on once the loop has answered every message: the turn in flight has them, never a timer. (Handed to
742
+ // the loop is not enough: a CLI's steer is with the CLI only once the loop's steer() returns.)
743
+ await until(() => rows.every((row) => w.answered(row.id)), "the messages placed by the loop mid-turn");
730
744
  letSlowGo();
731
745
  await w.ended("ended");
732
746
  const { calls, messages } = await w.read();
@@ -788,6 +802,37 @@ const CASES = [
788
802
  assert.ok(!rows.slice(0, at).some((one) => one.kind === "user_message" && one.text === text), `no row of the message before the notice: ${shown}`);
789
803
  },
790
804
  },
805
+ {
806
+ id: "steer-placed-crash",
807
+ title: "a steer placed by a runner lost before its row was taken reaches the model once, and the next runner takes its row",
808
+ async body(subject, t) {
809
+ const w = await world(subject, t);
810
+ const { tools, letSlowGo, slowStarted } = suiteTools();
811
+ const text = "check the totals";
812
+ // The call, then what the model says after it, then what it says on the resume that follows the crash: each the
813
+ // steer it was given, when it was given one.
814
+ const script = [{ call: "slow" }, { sayLastSteer: true }, { sayLastSteer: true }];
815
+ const holder = {};
816
+ await w.start("runner-a", { script, tools, hooks: crashAt("afterSteerPlaced", holder) }, holder);
817
+ await w.began(slowStarted, "the slow tool to start");
818
+ const row = await sendCommand(w.server, RUN, { kind: "steer", body: { text } });
819
+ // runner-a dies once its session holds the steer, while the tool it was sent during still runs, before the commit
820
+ // that records it and takes its row.
821
+ await until(() => (w.runOutUnknown(), holder.crashed), "the crash after the steer was placed", EVENT_WAIT_MS);
822
+ assert.equal((await w.commandRow(row.id)).takenAt, null, "the row is untaken when runner-a is lost");
823
+ await w.claimsSettled("runner-a");
824
+ w.runOut();
825
+ letSlowGo();
826
+ await w.start("runner-b", { script, tools, hooks: quiet });
827
+ await w.ended("ended", EVENT_WAIT_MS);
828
+ const { messages } = await w.read();
829
+ const sent = messages.filter((message) => message.role !== "model" && message.text === text);
830
+ assert.equal(sent.length, 1, `the steer is on the record once: ${JSON.stringify(messages)}`);
831
+ assert.ok(messages.some((message) => message.role === "model" && message.text.includes(text) && message.entry > sent[0].entry), `the model answered it: ${JSON.stringify(messages)}`);
832
+ const taken = await w.commandRow(row.id);
833
+ assert.ok(taken.takenAt !== null && taken.refused === null, `its row is taken by runner-b: ${JSON.stringify(taken)}`);
834
+ },
835
+ },
791
836
  {
792
837
  id: "stop-ends-turn",
793
838
  title: "stop ends the turn; the run says why",
@@ -891,15 +936,20 @@ const CASES = [
891
936
  await w.began(slowStarted, "the slow tool to start");
892
937
  const origin = { kind: "trigger", trigger_id: "trigger-1", source: "webhook", owner: false };
893
938
  const steer = await sendCommand(w.server, RUN, { kind: "steer", body: { text: "a new order came in", origin } });
894
- // The tool goes on once the steer is with the loop: the turn in flight has it, never a timer.
895
- await until(() => w.handedOver(steer.id), "the steer handed to the loop");
939
+ // The tool goes on once the loop has answered the steer: the turn in flight has it, never a timer.
940
+ await until(() => w.answered(steer.id), "the steer placed by the loop");
896
941
  letSlowGo();
897
942
  await w.ended("ended");
898
- const { messages } = await w.read();
943
+ const { calls, messages } = await w.read();
899
944
  const steered = messages.find((message) => message.text === "a new order came in" && message.role !== "model");
900
945
  assert.deepEqual(steered?.origin, origin, `the message keeps its origin: ${JSON.stringify(messages)}`);
901
- const said = messages.filter((message) => message.role === "model").map((message) => message.text);
902
- assert.deepEqual(said, ["a new order came in"], "the model read it as any message");
946
+ // Everything the model said once the call started (what it said with the call, before its row, is that step's, as in
947
+ // steer-mid-turn): only its answer to the steer, after it.
948
+ const slow = calls.find((call) => call.tool === "slow");
949
+ assert.ok(slow, `slow is on the record: ${JSON.stringify(calls)}`);
950
+ const said = messages.filter((message) => message.role === "model" && message.entry > slow.startEntry);
951
+ assert.deepEqual(said.map((message) => message.text), ["a new order came in"], `the model read it as any message: ${JSON.stringify(messages)}`);
952
+ assert.ok(said[0].entry > steered.entry, `it answered after the steer: ${JSON.stringify(messages)}`);
903
953
  },
904
954
  },
905
955
  {
@@ -1192,7 +1242,8 @@ async function modelSaid(w) {
1192
1242
  const { messages } = await w.read();
1193
1243
  return messages.filter((message) => message.role === "model").map((message) => message.text).join("\n");
1194
1244
  }
1195
- const STEERS_IN_TURN = "it places a message sent mid-turn in the turn in flight, its row taken in its submission's commit, so it never sends one as a turn of its own (message-resent-after-crash)";
1245
+ const STEERS_IN_TURN = "it places a message sent mid-turn in the turn in flight, so it never sends one as a turn of its own (message-resent-after-crash; a runner lost after placing a steer is steer-placed-crash)";
1246
+ const STEER_TAKEN_WITH_PLACEMENT = "it takes a steer's row in the commit that places it (its submission's), so no runner is lost between the placement and the take (steer-placed-crash)";
1196
1247
  const CLI_NEVER_RERUNS = "a CLI never reruns a call that started; only the model calls again (its adapter's facts: rerunsStarted false)";
1197
1248
  /** The cases a harness's declared facts rule out, each with why: what it does by design, not what it cannot model yet. */
1198
1249
  export function factsRuleOut(facts) {
@@ -1201,7 +1252,7 @@ export function factsRuleOut(facts) {
1201
1252
  const noSteer = `${facts.id} takes no message mid-turn (its adapter's facts: steer false), so a message sent while it works is never placed in the turn in flight: it is the run's next turn (message-mid-turn-kept)`;
1202
1253
  return {
1203
1254
  // steer-origin steers the turn in flight too: its message is taken mid-turn, or never.
1204
- ...(facts.steer ? {} : { "steer-mid-turn": noSteer, "steer-origin": noSteer }),
1255
+ ...(facts.steer ? {} : { "steer-mid-turn": noSteer, "steer-origin": noSteer, "steer-placed-crash": noSteer }),
1205
1256
  ...(facts.rerunsStarted === false ? { "replay-safe-rerun": CLI_NEVER_RERUNS, "fault-restarts-bounded": CLI_NEVER_RERUNS } : {}),
1206
1257
  // A harness that resumes a cut answer itself never ends a turn on the cut; one whose cut ends its turn never goes on
1207
1258
  // from it in the same turn.
@@ -1242,7 +1293,11 @@ export function registerHarnessConformance(given, { test, storeUrl }) {
1242
1293
  const processCase = entry.id.endsWith("-process");
1243
1294
  // A harness that steers (any whose facts do not say steer false, as message-mid-turn-kept reads them) places a message
1244
1295
  // in the turn in flight, its row taken in the commit of its submission: it never sends one as a turn of its own.
1245
- const byFacts = ruledOut[entry.id] ?? (entry.id === "message-resent-after-crash" && subject.facts?.steer !== false ? STEERS_IN_TURN : undefined);
1296
+ // A harness that steers and is no CLI (whose started calls a restart may run again) takes a steer's row as it places it:
1297
+ // only a CLI's record, written once its model took the steer, leaves a runner to lose between the two.
1298
+ const byFacts = ruledOut[entry.id]
1299
+ ?? (entry.id === "message-resent-after-crash" && subject.facts?.steer !== false ? STEERS_IN_TURN : undefined)
1300
+ ?? (entry.id === "steer-placed-crash" && subject.facts?.rerunsStarted !== false ? STEER_TAKEN_WITH_PLACEMENT : undefined);
1246
1301
  const notYet = subject.unsupported?.[entry.id] ?? (processCase && !subject.process ? "it names no module a runner process can load (subject.process)" : undefined) ?? (subject.metaTools === false && META_CASES.has(entry.id) ? "its loop gives its sessions no tools_search, tools_call or codemode (they are the adapter loop's: runner/meta-tools.ts)" : undefined);
1247
1302
  const onPostgres = storeUrl ? POSTGRES_PENDING[entry.id] : undefined;
1248
1303
  const skip = byFacts ? `${subject.name} does not do this by design: ${byFacts}` : notYet ? `${subject.name} cannot model this yet: ${notYet}` : onPostgres ? `on Postgres, ${onPostgres}` : undefined;
@@ -51,6 +51,9 @@ export interface KernelHooks {
51
51
  /** A message taken mid-turn was sent as a turn of its own (the adapter loop's sendAfterTurn): the session holds it, and
52
52
  * the commit that records it and takes its row has not run yet. */
53
53
  afterMessageSent?(): Promise<void>;
54
+ /** A message steered into the turn in flight was placed (the session holds it under the row's request id), and the
55
+ * commit that takes its row has not run yet: a CLI's waits for its model to take it (the adapter loop's steerCli). */
56
+ afterSteerPlaced?(): Promise<void>;
54
57
  }
55
58
  export interface ConformanceSetup {
56
59
  readonly script: readonly ScriptStep[];
@@ -59,7 +62,7 @@ export interface ConformanceSetup {
59
62
  /** The run's agent, for the subject's spec to name (AdapterRunSpec.agentId): the end-of-run step is asked with it. */
60
63
  readonly agentId?: string;
61
64
  }
62
- export type ConformanceCase = "crash-before-intent" | "crash-after-intent" | "crash-before-intent-process" | "crash-after-intent-process" | "stalled-past-lease-process" | "replay-safe-rerun" | "steer-mid-turn" | "message-mid-turn-kept" | "message-resent-after-crash" | "cancel-ends-for-good" | "cancel-parked" | "deny-note" | "steer-origin" | "stop-ends-turn" | "park-on-ask" | "approval-names-its-call" | "approval-double-click" | "approval-race" | "message-never-answers" | "end-of-run-answer" | "fault-effects-once" | "fault-restarts-bounded" | "length-ends-failed" | "length-mid-run" | "meta-search" | "meta-call-park" | "meta-call-deny" | "meta-codemode-park" | "meta-codemode-stop" | "meta-codemode-crash";
65
+ export type ConformanceCase = "crash-before-intent" | "crash-after-intent" | "crash-before-intent-process" | "crash-after-intent-process" | "stalled-past-lease-process" | "replay-safe-rerun" | "steer-mid-turn" | "message-mid-turn-kept" | "message-resent-after-crash" | "steer-placed-crash" | "cancel-ends-for-good" | "cancel-parked" | "deny-note" | "steer-origin" | "stop-ends-turn" | "park-on-ask" | "approval-names-its-call" | "approval-double-click" | "approval-race" | "message-never-answers" | "end-of-run-answer" | "fault-effects-once" | "fault-restarts-bounded" | "length-ends-failed" | "length-mid-run" | "meta-search" | "meta-call-park" | "meta-call-deny" | "meta-codemode-park" | "meta-codemode-stop" | "meta-codemode-crash";
63
66
  export interface ConformanceSubject {
64
67
  /** The harness's name, as the suite's tests are titled. */
65
68
  readonly name: string;
@@ -289,6 +289,28 @@ export interface AnswerData {
289
289
  readonly answeredAt?: string;
290
290
  };
291
291
  }
292
+ /** The calls of a tool a run's journal shows (toolCalls): `ran`, the ids run to a good end, and `unnamed`, those pi
293
+ * recorded with no id; `ended`, every id with a result of any kind (done, an error, a refusal or a deny). */
294
+ export type ToolCalls = {
295
+ readonly ran: ReadonlySet<string>;
296
+ readonly unnamed: number;
297
+ readonly ended: ReadonlySet<string>;
298
+ };
299
+ /** The calls of `tool` `entries` show: a CLI's (agentrun.call.start and its end) and pi's (a pi.tool-result of it), each
300
+ * call id once, however many records say it. Run to a good end: a CLI's end done, a pi result that is no error. */
301
+ export declare function toolCalls(entries: readonly {
302
+ readonly kind: string;
303
+ readonly data?: unknown;
304
+ readonly model?: unknown;
305
+ }[], tool: string): ToolCalls;
306
+ /** How many calls of `tool` `entries` show run to a good end (toolCalls): a call refused, denied, failed or not ended is
307
+ * not counted. What a tool's own ask counts (tools.ts AskContext.ran), with the calls its gate let through and that
308
+ * have no result yet (adapterRunGate). */
309
+ export declare function ranCalls(entries: readonly {
310
+ readonly kind: string;
311
+ readonly data?: unknown;
312
+ readonly model?: unknown;
313
+ }[], tool: string): number;
292
314
  /** The withdrawn answers a stopped end writes in `entries`: for every call still waiting (an ask with no answer), and
293
315
  * for every approved call that had not finished (no result, or one its abort wrote), which the stop overrides, keeping
294
316
  * the allow it was given (main's supersede: an answer the run had not acted on to the end is withdrawn by the stop). A