@parcha/agentrun-serve 0.1.0-beta.47 → 0.1.0-beta.48

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 (110) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +84 -14
  3. package/dist/acp-package.d.ts +24 -6
  4. package/dist/adapter-facts.d.ts +0 -4
  5. package/dist/adapter-facts.js +1 -4
  6. package/dist/adapters.d.ts +3 -12
  7. package/dist/adapters.js +1 -70
  8. package/dist/answer-json.d.ts +10 -0
  9. package/dist/answer-json.js +24 -0
  10. package/dist/api-only.d.ts +5 -2
  11. package/dist/api-only.js +10 -2
  12. package/dist/browser-live.d.ts +9 -4
  13. package/dist/browser-live.js +18 -5
  14. package/dist/cap.js +7 -9
  15. package/dist/cli.js +6 -6
  16. package/dist/computer-routes.d.ts +8 -5
  17. package/dist/computer-routes.js +7 -5
  18. package/dist/computers.d.ts +6 -2
  19. package/dist/computers.js +4 -2
  20. package/dist/conformance.d.ts +4 -0
  21. package/dist/conformance.js +6 -0
  22. package/dist/console/assets/index-CTGegcKt.css +1 -0
  23. package/dist/console/assets/{index-BBFzAxLB.js → index-D1Se6mgG.js} +165 -165
  24. package/dist/console/index.html +2 -2
  25. package/dist/harness-check.d.ts +3 -1
  26. package/dist/harness-check.js +99 -70
  27. package/dist/harness-cursor.d.ts +10 -27
  28. package/dist/harness-cursor.js +5 -84
  29. package/dist/harness-goose.d.ts +4 -29
  30. package/dist/harness-goose.js +6 -86
  31. package/dist/harness-module.d.ts +4 -0
  32. package/dist/harness-module.js +1 -0
  33. package/dist/harness-owned.d.ts +52 -0
  34. package/dist/harness-owned.js +92 -0
  35. package/dist/harness-recipe.js +2 -24
  36. package/dist/harness-table.d.ts +109 -6
  37. package/dist/harness-table.js +242 -28
  38. package/dist/harness.js +2 -2
  39. package/dist/key-refusal.d.ts +2 -1
  40. package/dist/key-refusal.js +18 -2
  41. package/dist/learn/promote.d.ts +11 -0
  42. package/dist/learn/secrets.d.ts +4 -0
  43. package/dist/learn/secrets.js +23 -0
  44. package/dist/learning-model.d.ts +18 -0
  45. package/dist/learning-model.js +77 -0
  46. package/dist/llms.txt +1 -0
  47. package/dist/model-form.js +12 -12
  48. package/dist/model.d.ts +5 -4
  49. package/dist/model.js +19 -13
  50. package/dist/openapi.js +35 -5
  51. package/dist/page.d.ts +1 -0
  52. package/dist/page.js +1 -1
  53. package/dist/run-secrets.d.ts +2 -2
  54. package/dist/run-secrets.js +6 -5
  55. package/dist/run-trace.js +6 -3
  56. package/dist/runner/adapter-loop.d.ts +4 -1
  57. package/dist/runner/adapter-loop.js +1 -2
  58. package/dist/runner/adapter-run-spec.d.ts +3 -2
  59. package/dist/runner/adapter-run-spec.js +8 -4
  60. package/dist/runner/adapters/index.d.ts +4 -2
  61. package/dist/runner/adapters/index.js +6 -42
  62. package/dist/runner/cli-run-spec.js +10 -6
  63. package/dist/runner/conformance/host-tools.d.ts +4 -0
  64. package/dist/runner/conformance/host-tools.js +14 -0
  65. package/dist/runner/meta-tools.js +4 -2
  66. package/dist/runner/presence.d.ts +3 -0
  67. package/dist/runner/presence.js +19 -12
  68. package/dist/runner/promotion.d.ts +62 -4
  69. package/dist/runner/promotion.js +146 -15
  70. package/dist/runner/sdk-loop.js +25 -1
  71. package/dist/runner/workflow-spec.js +3 -2
  72. package/dist/runs-over-store.d.ts +2 -1
  73. package/dist/runs-over-store.js +2 -4
  74. package/dist/sdk/check.d.ts +31 -0
  75. package/dist/sdk/check.js +58 -0
  76. package/dist/sdk/runs.d.ts +10 -2
  77. package/dist/sdk/runs.js +87 -17
  78. package/dist/sdk/schema.js +11 -3
  79. package/dist/server.d.ts +3 -0
  80. package/dist/server.js +116 -40
  81. package/dist/store/sqlite/store.js +35 -30
  82. package/dist/store/store.d.ts +20 -18
  83. package/dist/store-view.d.ts +5 -3
  84. package/dist/store-view.js +9 -7
  85. package/dist/template-eval.js +5 -2
  86. package/dist/template-github-permissions.d.ts +5 -1
  87. package/dist/template-github-permissions.js +7 -3
  88. package/dist/timeline/index.d.ts +1 -1
  89. package/dist/timeline/index.js +1 -1
  90. package/dist/timeline/timeline.d.ts +8 -0
  91. package/dist/timeline/timeline.js +18 -6
  92. package/dist/tool-gate.d.ts +8 -4
  93. package/dist/tool-gate.js +6 -7
  94. package/dist/tool-plane.d.ts +4 -0
  95. package/dist/tool-plane.js +10 -10
  96. package/dist/trigger-targets.d.ts +11 -2
  97. package/dist/trigger-targets.js +71 -2
  98. package/dist/validate.js +5 -1
  99. package/dist/viewer-credential.d.ts +25 -0
  100. package/dist/viewer-credential.js +51 -0
  101. package/dist/workspace/resolve-computer.d.ts +5 -0
  102. package/dist/workspace/resolve-computer.js +19 -1
  103. package/package.json +18 -10
  104. package/templates/code-review/agent.md +2 -3
  105. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  106. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  107. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  108. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  109. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  110. package/dist/console/assets/index-BRi-Rgq6.css +0 -1
@@ -20,6 +20,7 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
20
20
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
21
21
  import { checkRaise, followUpOf, freeModelRequestsOf, parkOf, planCapModel } from "@parcha/agentrun-kernel/kernel/cap";
22
22
  import { PLAN_LIMIT_WORDS } from "@parcha/agentrun-kernel";
23
+ import { modelWire } from "../wires.js";
23
24
  import { confineOf, noNewPrivsPrefix, standsIn, thinkingFor } from "../adapters.js";
24
25
  import { claimSettled, claudeCliIn, installDirOf, installForClaim, installingWords } from "../harness-install.js";
25
26
  import { HarnessUnavailable } from "../provider.js";
@@ -27,7 +28,7 @@ import { effortGuidance } from "../effort-guidance.js";
27
28
  import { outputContract } from "../answer-json.js";
28
29
  import { wireName } from "../catalog.js";
29
30
  import { environmentLine, runZone } from "../environment.js";
30
- import { harnessOf } from "../harness-table.js";
31
+ import { factsOf, harnessOf } from "../harness-table.js";
31
32
  import { laidLearned, learningFolderOf, secretsShown } from "../learning.js";
32
33
  import { laidOf, layLearningSeed } from "./learning-seed.js";
33
34
  import { learningWorkspace } from "../learn/folder.js";
@@ -121,12 +122,12 @@ export function capModelOf(id, wire, listed, unpriced, plan = false) {
121
122
  return { id, api: wire, price, outputCeiling: typeof listed?.maxTokens === "number" ? listed.maxTokens : null };
122
123
  }
123
124
  /** The model a CLI run of `entry` on `chosen` (modelsOf) is capped at, on its `wire`: the catalog entry that bills it
124
- * (its entry's priceModel), priced by capModelOf. A harness its vendor bills to its owner's plan (its promises' billing,
125
- * Cursor's) is the plan rule's, as a ChatGPT plan's model is. */
125
+ * (its entry's priceModel), priced by capModelOf. A harness its vendor bills to its owner's plan (no model wire of ours:
126
+ * modelWire, Cursor's) is the plan rule's, as a ChatGPT plan's model is. */
126
127
  function chosenCapModel(entry, env, chosen, wire) {
127
128
  const priced = entry.priceModel(env, chosen.model);
128
129
  const listed = chosen.models.getModel(priced.provider, priced.modelId);
129
- return capModelOf(priced.modelId, wire, listed, chosen.unpriced.has(priced.modelId) || listed === undefined, priced.provider === PLAN_PROVIDER || priced.provider === CLAUDE_LOGIN_PROVIDER || entry.promises?.billing === "plan");
130
+ return capModelOf(priced.modelId, wire, listed, chosen.unpriced.has(priced.modelId) || listed === undefined, priced.provider === PLAN_PROVIDER || priced.provider === CLAUDE_LOGIN_PROVIDER || !modelWire(wire));
130
131
  }
131
132
  /** The model a run of the CLI harness `entry` on `ref` (a revision's model; none, this host's default for it) is capped
132
133
  * at here, as its run's spec prices it (modelsOf, chosenCapModel), before any run: a save's cap warning (cap-short.ts)
@@ -546,8 +547,10 @@ async function cliSpec(launch, run, deps, claim, holds) {
546
547
  // The gate before a call's intent, the same as the pi spec: the revision's tool settings over the store's, read from the
547
548
  // store at each decide — adapterRunGate (RunGate.decide: deny with its words, a pin, allow, ask). The end-of-run turn's
548
549
  // refusal of writes under .learning/ is the adapter loop's own (it knows the turn), never a file's.
549
- // A pinned MCP tool is held to the arguments its listing in the run's pin declares (mcp.argumentsOf).
550
- const gate = await adapterRunGate(deps.store, claim, revision, ws.workspace, tools.shell, mcp ? { effectOf: (name) => mcp.effectOf(name), argumentsOf: (name) => mcp.argumentsOf(name) } : {});
550
+ // A pinned MCP tool is held to the arguments its listing in the run's pin declares (mcp.argumentsOf). The harness's
551
+ // native tools are named by its facts on the owner's table (factsOf: a module's harness's too).
552
+ const ownerFacts = factsOf(deps.env, name);
553
+ const gate = await adapterRunGate(deps.store, claim, revision, ws.workspace, tools.shell, { ...(mcp ? { effectOf: (name) => mcp.effectOf(name), argumentsOf: (name) => mcp.argumentsOf(name) } : {}), facts: ownerFacts });
551
554
  // The run's tools: the kernel registry's hands on its Workspace (and computer); the web host tools it is granted
552
555
  // (web_fetch, web_search, monid), bound by the binding the pi spec uses (webHostTools) on the ToolHost the pi spec builds
553
556
  // (buildToolHost); and the learned_workflow tool when the run has it (learnsWorkflows: its revision is agentic and the
@@ -690,6 +693,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
690
693
  }), { ...audits, launch, ...(run.redact ? { redact: run.redact } : {}) });
691
694
  return {
692
695
  adapter,
696
+ facts: ownerFacts,
693
697
  session,
694
698
  input,
695
699
  // A trigger's first input is its origin's, the launch's own owner flag kept (run-launch.ts keepInputOrigin).
@@ -0,0 +1,4 @@
1
+ import type { HostTool } from "@parcha/agentrun-kernel";
2
+ import type { SuiteTool } from "./subject.js";
3
+ /** The suite's `tools` (setup.tools) as host tools, in their order. */
4
+ export declare function suiteHostTools(tools: Readonly<Record<string, SuiteTool>>): HostTool[];
@@ -0,0 +1,14 @@
1
+ /** The suite's `tools` (setup.tools) as host tools, in their order. */
2
+ export function suiteHostTools(tools) {
3
+ return Object.values(tools).map((tool) => ({
4
+ name: tool.name,
5
+ description: `The suite's ${tool.name} tool.`,
6
+ inputSchema: { type: "object", properties: {} },
7
+ replay: tool.replaySafe ? "safe" : "never",
8
+ call: async (args, context) => ({
9
+ text: String(await tool.run((args ?? {}), context.signal)),
10
+ ...(tool.images ? { images: tool.images } : {}),
11
+ ...(tool.structured !== undefined ? { structured: tool.structured } : {}),
12
+ }),
13
+ }));
14
+ }
@@ -158,7 +158,9 @@ export function metaTools(options) {
158
158
  * value is null (an op that answers none: a computer's files.write) is told by its answer's words ("wrote <path>"), as
159
159
  * it answered, never as null. */
160
160
  function lineOf(index, name, result) {
161
- const quoted = (text) => JSON.stringify(text.length > 2_000 ? `${text.slice(0, 2_000)}…` : text);
161
+ // Whole: the model reads these values nowhere else (the script's own output went with the stop), and the answer is held
162
+ // to the host's bound as every tool answer is (boundResult). A cut here once hid an approved call's title from it.
163
+ const quoted = (text) => JSON.stringify(text);
162
164
  const label = `${index}. ${name}`;
163
165
  if (result.refused)
164
166
  return `${label} was refused: ${quoted(result.text)}. It did not run.`;
@@ -168,7 +170,7 @@ function lineOf(index, name, result) {
168
170
  return `${label} failed: ${quoted(result.text)}. It was not run again.`;
169
171
  const value = result.structured === null ? result.text : scriptValue(result);
170
172
  const json = typeof value === "string" ? undefined : JSON.stringify(withoutImageData(value));
171
- const said = json === undefined ? quoted(value) : json.length > 2_000 ? `${json.slice(0, 2_000)}…` : json;
173
+ const said = json === undefined ? quoted(value) : json;
172
174
  return `${label} completed: ${said}. Its effect is done; it was not run again.`;
173
175
  }
174
176
  /** The script's output and value, as the model reads them, and the images: the returned value's own first, then the ones
@@ -33,6 +33,9 @@ export declare function keepPresence(runners: Runners, runner: string, refused:
33
33
  /** Why no runner here can take a run, in the runners' own words, or undefined while one can (or none is there): the rows
34
34
  * seen within `staleMs` on the store's clock (Runners.live), when there is one at least and every one refused. */
35
35
  export declare function runnersRefused(runners: Pick<Runners, "live">, staleMs?: number): Promise<string | undefined>;
36
+ /** Refuses a run no runner here can take (runner_refused, in the runners' words: runnersRefused), before anything is made
37
+ * for it; nothing while one can, or none is there yet. Every refusal of a start or a message is this one throw. */
38
+ export declare function refuseWhileNoRunner(runners: Pick<Runners, "live">): Promise<void>;
36
39
  /** The code a run fails with when no runner here could take it (its error's code, and a launch's refusal's). */
37
40
  export declare const RUNNER_REFUSED_CODE = "runner_refused";
38
41
  /** The summary of a queued run failed because no runner here can take it (Runs.failUnclaimed): the code, then `words`. */
@@ -10,6 +10,7 @@
10
10
  // runs still queued (server.ts). With no runner there at all (a server with --no-runner and its runner not started yet),
11
11
  // it refuses nothing: runs queue for the runner to come, as before.
12
12
  import { randomUUID } from "node:crypto";
13
+ import { ApiError } from "../errors.js";
13
14
  /** How often a runner says again that it is there. */
14
15
  export const PRESENCE_RENEW_MS = 10_000;
15
16
  /** How old a runner's word can be and still count: three renewals missed. */
@@ -29,16 +30,18 @@ export function keepPresence(runners, runner, refused, { renewMs = PRESENCE_RENE
29
30
  };
30
31
  let at = null;
31
32
  const row = () => ({ runner, incarnation, refused, host: at?.host ?? null, port: at?.port ?? null });
32
- // Its first put takes the name over from an earlier process's row. Every write after it (a renewal's put again, the
33
- // relay's place) touches its own row only, or puts one where no other process of the name is live (Runners
34
- // putUnlessLive): an older process overlapping a restart never takes the later one's row back, nor clears its relay.
35
- const again = () => runners.putUnlessLive(row(), PRESENCE_STALE_MS);
33
+ // Its first put takes the name over from an earlier process's row. Every write after it (a renewal, the relay's place:
34
+ // one Runners.renew, with the place it holds now) touches its own row only, or puts one where no other process of the
35
+ // name is live (Runners.put unlessLiveMs): an older process overlapping a restart never takes the later one's row back,
36
+ // nor clears its relay.
37
+ const again = () => runners.put(row(), { unlessLiveMs: PRESENCE_STALE_MS });
38
+ const renew = async () => {
39
+ if (!(await runners.renew(runner, incarnation, at)))
40
+ await again();
41
+ };
36
42
  let writing = runners.put(row()).catch(failed);
37
43
  const timer = setInterval(() => {
38
- writing = writing.then(async () => {
39
- if (!(await runners.seen(runner, incarnation)))
40
- await again();
41
- }).catch(failed);
44
+ writing = writing.then(renew).catch(failed);
42
45
  }, renewMs);
43
46
  timer.unref();
44
47
  let stopped = false;
@@ -50,10 +53,7 @@ export function keepPresence(runners, runner, refused, { renewMs = PRESENCE_RENE
50
53
  if (stopped)
51
54
  return Promise.resolve();
52
55
  // After any write in flight, so a renewal's put never lands over it with the place before.
53
- const wrote = writing.then(async () => {
54
- if (!(await runners.relayAt(runner, incarnation, next)))
55
- await again();
56
- });
56
+ const wrote = writing.then(renew);
57
57
  writing = wrote.catch(failed);
58
58
  return wrote;
59
59
  },
@@ -80,6 +80,13 @@ export async function runnersRefused(runners, staleMs = PRESENCE_STALE_MS) {
80
80
  const reasons = [...new Set(live.map((row) => row.refused))];
81
81
  return `No runner of this server can take a run: ${reasons.join(" ")}`;
82
82
  }
83
+ /** Refuses a run no runner here can take (runner_refused, in the runners' words: runnersRefused), before anything is made
84
+ * for it; nothing while one can, or none is there yet. Every refusal of a start or a message is this one throw. */
85
+ export async function refuseWhileNoRunner(runners) {
86
+ const refused = await runnersRefused(runners);
87
+ if (refused !== undefined)
88
+ throw new ApiError(RUNNER_REFUSED_CODE, refused);
89
+ }
83
90
  /** The code a run fails with when no runner here could take it (its error's code, and a launch's refusal's). */
84
91
  export const RUNNER_REFUSED_CODE = "runner_refused";
85
92
  const REFUSED_END = `${RUNNER_REFUSED_CODE}: `;
@@ -4,7 +4,7 @@ import { type RunLaunch } from "../run-launch.js";
4
4
  import { type Store } from "../store/store.js";
5
5
  import { type Recorded, type ReplayCalls, type Skipped } from "../learn/replay-calls.js";
6
6
  import { type Json } from "../validate.js";
7
- import { type CheckBar, type Compared, type PromotionRecord, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
7
+ import { type CheckBar, type Compared, type PromotionRecord, recordPromotion, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
8
8
  import { type FirstChoice, type Promoted, type ReplayOutcome } from "./workflow-first.js";
9
9
  import type { LearningFolder } from "../learn/folder.js";
10
10
  import type { Shown } from "../learning.js";
@@ -50,6 +50,9 @@ export interface PromotionDeps {
50
50
  * they are shortened (decideCheck). */
51
51
  readonly shown: () => Promise<Shown>;
52
52
  }
53
+ /** What deciding a check needs (decideCheck, stopUnchecked): a claim's ports, or those of a connected agent's start or
54
+ * run end, whose record names its commit (no claimed launch to read a seed from). */
55
+ type DecideDeps = Pick<PromotionDeps, "store" | "agentId" | "log" | "shown"> & Partial<Pick<PromotionDeps, "launch" | "now">>;
53
56
  /** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a champion read
54
57
  * from it at its record's commit, cut of the server's secrets (`shown`) as the claim's lay is; and the workflow an earlier
55
58
  * claim of this run served (`kept`, from its journal: none on a first claim). */
@@ -71,9 +74,17 @@ export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWork
71
74
  * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
72
75
  * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
73
76
  * promoted yet, or the champion held): a revision replaying, held or never decided is never handed to the agent to run
74
- * in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A replay run's as
77
+ * in its place. One the records never named is an unchecked draft and is not offered. A replay run's as
75
78
  * laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
76
79
  export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
80
+ /** `flow`'s champion (championOf) and the text it serves from: `flow` itself when it is the champion, else the
81
+ * champion's text read at its record's commit (`read`), kept only when its digest is the champion's. No text: none is
82
+ * promoted, or its text cannot be read. The one champion lookup a claim's gate (servingNow), the learned_workflow tool
83
+ * (toolFlowsFor) and a connected agent's start (sdk/runs.ts) share. */
84
+ export declare function championTextOf(records: readonly PromotionRecord[], flow: LearnedWorkflow, read?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>): Promise<{
85
+ champion?: PromotionRecord;
86
+ text?: LearnedWorkflow;
87
+ }>;
77
88
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
78
89
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
79
90
  * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its check moved on (decide:
@@ -83,6 +94,12 @@ export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentI
83
94
  export declare const promotionGate: (deps: PromotionDeps) => Promoted;
84
95
  /** The words a hold of a serving revision this release's workflow DSL refuses starts with (holdRefused). */
85
96
  export declare const DSL_REFUSES = "this release's workflow DSL refuses it";
97
+ /** Which check of a compile a new revision's is: 2 when the workflow's newest record of another revision is a first
98
+ * check's hold, an audit's hold or a hold by its reason alone (holdRefused: the DSL refuses a serving revision), or a
99
+ * first compile's failed draft (this revision is its one recompile), else 1. A stop with nothing checked
100
+ * (stopUnchecked) is no first check's hold: it spends no recompile. A workflow's first revision after a first compile
101
+ * whose drafts failed under another name (learn/compile.ts newCompileAttempt) is that compile's recompile too. */
102
+ export declare function attemptOf(records: readonly PromotionRecord[], name: string, digest: string): 1 | 2;
86
103
  /** The words a stopped check's record starts with when it had nothing to check its draft on. */
87
104
  export declare const NOTHING_TO_CHECK = "nothing to check it on";
88
105
  /** What a held check compared on the whole answer says when it answered some inputs alone and agreed on none: only a
@@ -112,12 +129,53 @@ type CheckRow = {
112
129
  * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
113
130
  * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
114
131
  * (the one write: of two claims at once, one decides). */
115
- export declare function decideCheck(deps: PromotionDeps, name: string, digest: string, bar: CheckBar, read: {
132
+ export declare function decideCheck(deps: DecideDeps, name: string, digest: string, bar: CheckBar, read: {
116
133
  rows: readonly CheckRow[];
117
134
  cost: number | null;
118
135
  outcomes: ReplayOutcomes;
119
136
  unstarted: number;
120
- }, still: (was: PromotionRecord | undefined) => boolean, extra: Partial<PromotionRecord>): Promise<import("../learn/promote.js").Recorded>;
137
+ exactMismatchReason?: string;
138
+ fresh_reads?: number;
139
+ }, still: Parameters<typeof recordPromotion>[3], extra: Partial<PromotionRecord>): Promise<import("../learn/promote.js").Recorded>;
140
+ /** How many of a connected agent's reserved native turns its check gives back before it stops. A turn is given back
141
+ * when it cannot be the check's baseline: cancelled or failed, a learned workflow or nested call in it, redacted
142
+ * evidence, no shadow report, or a shadow that did not answer. One or two are ordinary (a person cancels a task, an
143
+ * input carries a secret); five say the integration cannot give one (a client with no shadow check, inputs it never
144
+ * resolves, a draft whose shadow always refuses), and each reserved turn runs without the champion. The fifth stops it
145
+ * with nothing checked (stopUnchecked), which asks no recompile: a revision would have no baseline either. */
146
+ export declare const SDK_CHECK_RELEASES = 5;
147
+ /** A connected agent's draft reserved on one native turn: what its start hands the caller (sdk/runs.ts receipt). */
148
+ export type SdkWorkflowCheck = {
149
+ id: string;
150
+ revision: string;
151
+ digest: string;
152
+ workflow: LearnedWorkflow;
153
+ };
154
+ /** A connected agent's run input as a check row quotes it: the task text its start was given. */
155
+ export declare const sdkInputText: (launch: RunLaunch | undefined) => string;
156
+ /** Reserves one of `flows` (a connected agent's start's candidates, each its folder's newest revision) for a shadow
157
+ * check on the native turn `runId`: the first the turn takes (`takes`) with no decision yet, or one waiting for a turn,
158
+ * while no other revision of its workflow is checked; the guarded write keeps one reservation per workflow across
159
+ * concurrent starts. First each SDK check of a candidate's workflow is moved on: one whose turn is past
160
+ * REPLAY_DEADLINE_MS is decided as one failed row (sdkCheckDeadline), and one waiting at a revision the folder moved
161
+ * past is set aside. A managed replay's record (no `via`) is never touched here. */
162
+ export declare function reserveSdkCheck(deps: DecideDeps, turn: {
163
+ readonly runId: string;
164
+ readonly revision: string | null;
165
+ readonly learning: unknown;
166
+ readonly flows: readonly LearnedWorkflow[];
167
+ readonly takes: (flow: LearnedWorkflow) => boolean;
168
+ }): Promise<SdkWorkflowCheck | undefined>;
169
+ /** A connected agent's check whose native turn did not settle it by REPLAY_DEADLINE_MS (the backend never completed the
170
+ * turn, or the server stopped before the run's end): decided as every check is (decideCheck), on one failed row. Its
171
+ * hold asks the one recompile, and a recompile's check that ends here stops (`stopped`): an abandoned check never
172
+ * restarts its budget. */
173
+ export declare function sdkCheckDeadline(deps: DecideDeps, pending: PromotionRecord): Promise<import("../learn/promote.js").Recorded | undefined>;
174
+ /** Gives back a connected agent's reserved native turn that cannot be its check's baseline (`cause`): the check waits for
175
+ * the next turn the draft takes, nothing decided or promoted, and the turn counts toward SDK_CHECK_RELEASES, whose last
176
+ * stops it with nothing checked (stopUnchecked: no recompile). `counted` false: no turn ran (its start was not
177
+ * admitted). Kept only while the record is still this reservation. */
178
+ export declare function releaseSdkCheck(deps: DecideDeps, record: PromotionRecord, cause: string, counted?: boolean): Promise<import("../learn/promote.js").Recorded | undefined>;
121
179
  /** A run's final answer row, its text whole (its last final answer row that is not its end-of-run turn's), or null: none,
122
180
  * or its record could not be read. `turn`: the row of that id instead (the answer an audit is of, runner/audit.ts), so an
123
181
  * answer a follow-up gave since is never read for it. */
@@ -78,7 +78,7 @@ export function replayLaid(launch, laid) {
78
78
  * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
79
79
  * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
80
80
  * promoted yet, or the champion held): a revision replaying, held or never decided is never handed to the agent to run
81
- * in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A replay run's as
81
+ * in its place. One the records never named is an unchecked draft and is not offered. A replay run's as
82
82
  * laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
83
83
  export async function toolFlowsFor(deps, launch, laid, choice) {
84
84
  const chosen = laidFor(laid, choice);
@@ -95,18 +95,15 @@ export async function toolFlowsFor(deps, launch, laid, choice) {
95
95
  }
96
96
  const out = [];
97
97
  for (const one of chosen) {
98
- if (one.name === name || !records.some((record) => record.workflow === one.name)) {
98
+ if (one.name === name) {
99
99
  out.push(one);
100
100
  continue;
101
101
  }
102
102
  const digest = workflowDigest(one);
103
- const champion = championOf(records, one.name);
104
- if (champion?.digest === digest) {
103
+ const { champion, text } = await championTextOf(records, one, deps.champion);
104
+ if (text === one)
105
105
  out.push(one);
106
- continue;
107
- }
108
- const text = champion?.commit && deps.champion ? await deps.champion(one.name, champion.commit).catch(() => undefined) : undefined;
109
- if (text && workflowDigest(text) === champion.digest) {
106
+ else if (text) {
110
107
  deps.log(`workflow-first: the learned_workflow tool runs ${one.name}'s champion at ${champion.digest}, not ${digest}, which is not promoted`);
111
108
  out.push(text);
112
109
  }
@@ -115,9 +112,22 @@ export async function toolFlowsFor(deps, launch, laid, choice) {
115
112
  }
116
113
  return out;
117
114
  }
115
+ /** `flow`'s champion (championOf) and the text it serves from: `flow` itself when it is the champion, else the
116
+ * champion's text read at its record's commit (`read`), kept only when its digest is the champion's. No text: none is
117
+ * promoted, or its text cannot be read. The one champion lookup a claim's gate (servingNow), the learned_workflow tool
118
+ * (toolFlowsFor) and a connected agent's start (sdk/runs.ts) share. */
119
+ export async function championTextOf(records, flow, read) {
120
+ const champion = championOf(records, flow.name);
121
+ if (!champion)
122
+ return {};
123
+ if (champion.digest === workflowDigest(flow))
124
+ return { champion, text: flow };
125
+ const text = champion.commit && read ? await read(flow.name, champion.commit).catch(() => undefined) : undefined;
126
+ return text && workflowDigest(text) === champion.digest ? { champion, text } : { champion };
127
+ }
118
128
  const iso = (ms) => new Date(ms).toISOString();
119
129
  /** The claim's seed as a record's `commit`: the learning commit the laid workflow's text was read from. */
120
- const seedOf = (deps) => (deps.launch.learning?.seed ? { commit: deps.launch.learning.seed } : {});
130
+ const seedOf = (deps) => (deps.launch?.learning?.seed ? { commit: deps.launch.learning.seed } : {});
121
131
  const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
122
132
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
123
133
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
@@ -162,7 +172,7 @@ export const promotionGate = (deps) => {
162
172
  * serves: none promoted, the champion held, or its text cannot be read (the agent takes the run). */
163
173
  async function servingNow(deps, workflow, digest, laid) {
164
174
  const records = await promotionsOf(deps.store.settings, deps.agentId);
165
- const champion = championOf(records, workflow.name);
175
+ const { champion, text } = await championTextOf(records, workflow, deps.champion);
166
176
  const own = promotionOf(records, workflow.name, digest);
167
177
  if (!champion) {
168
178
  if (own?.decided === "promote")
@@ -173,8 +183,7 @@ async function servingNow(deps, workflow, digest, laid) {
173
183
  return laid ? { workflow } : undefined;
174
184
  if (!deps.champion)
175
185
  return undefined;
176
- const text = champion.commit ? await deps.champion(workflow.name, champion.commit).catch(() => undefined) : undefined;
177
- if (!text || workflowDigest(text) !== champion.digest) {
186
+ if (!text) {
178
187
  deps.log(`workflow-first: ${workflow.name}'s champion at ${champion.digest} could not be read from its learning commit; the agent takes this run`);
179
188
  return undefined;
180
189
  }
@@ -263,7 +272,7 @@ async function loopOfRevision(deps) {
263
272
  * first compile's failed draft (this revision is its one recompile), else 1. A stop with nothing checked
264
273
  * (stopUnchecked) is no first check's hold: it spends no recompile. A workflow's first revision after a first compile
265
274
  * whose drafts failed under another name (learn/compile.ts newCompileAttempt) is that compile's recompile too. */
266
- function attemptOf(records, name, digest) {
275
+ export function attemptOf(records, name, digest) {
267
276
  const before = records.findLast((one) => one.workflow === name && one.digest !== digest);
268
277
  if (!before)
269
278
  return newCompileAttempt(records.filter((one) => one.digest !== digest));
@@ -503,7 +512,7 @@ export async function decideCheck(deps, name, digest, bar, read, still, extra) {
503
512
  const tools = skippedToolsOf(read.rows);
504
513
  const { skipped_write: skipped, failed } = read.outcomes;
505
514
  const { hint, why: skipWhy } = skipWordsOf(tools, skipped);
506
- const numbers = { of: read.rows.map((row) => row.of), cost_usd: read.cost, outcomes: read.outcomes, ...(read.unstarted ? { unstarted: read.unstarted } : {}), ...(tools.length ? { skipped_tools: tools } : {}) };
515
+ const numbers = { of: read.rows.map((row) => row.of), cost_usd: read.cost, outcomes: read.outcomes, ...(read.unstarted ? { unstarted: read.unstarted } : {}), ...(tools.length ? { skipped_tools: tools } : {}), ...(read.fresh_reads ? { fresh_reads: read.fresh_reads } : {}) };
507
516
  // Every input skipped at a write (each reserved input counts: one never created or never ended failed, so this is the
508
517
  // only way to none): nothing to check it on, so it stops, never promoted unchecked, and asks no recompile.
509
518
  if (!score.n) {
@@ -522,7 +531,7 @@ export async function decideCheck(deps, name, digest, bar, read, still, extra) {
522
531
  // once the same (no grader): free text two runs never repeat, most likely, so the owner is told what to set.
523
532
  const differed = score.alone - score.agreed;
524
533
  const example = disagreements.find((one) => one.differs_on !== undefined)?.differs_on;
525
- const verbatim = ok || bar.agree_on?.length ? "" : grader ? (differed > 0 ? `; ${differentDecisionWords(differed, score.alone, example)}` : "") : score.alone > 0 && score.agreed === 0 ? `; ${NEVER_WORD_FOR_WORD}` : "";
534
+ const verbatim = ok || bar.agree_on?.length ? "" : grader ? (differed > 0 ? `; ${differentDecisionWords(differed, score.alone, example)}` : "") : score.alone > 0 && score.agreed === 0 ? `; ${read.exactMismatchReason ?? NEVER_WORD_FOR_WORD}` : "";
526
535
  const reason = ok ? `${said}: promoted` : stopped ? `${said}: held${verbatim}, and this was the recompile's check, so it stops: nothing compiles again until a hold or its owner acts` : `${said}: held${verbatim}; the agent's next run recompiles it once with the inputs it did not agree on`;
527
536
  const check = { ...bar, ...score, ...numbers, ...(disagreements.length ? { disagreements } : {}), ...(stopped ? { stopped: true } : {}), ...(grader ? { grader } : {}) };
528
537
  const decided = await recordPromotion(deps.store.settings, deps.agentId, { workflow: name, digest, at: iso(now()), decided: ok ? "promote" : "hold", reason, check, ...seedOf(deps), ...extra }, still);
@@ -545,6 +554,128 @@ async function reserve(deps, workflow, digest, inputs, reason, still, check) {
545
554
  await startReplay(deps, workflow, digest, one.run, one.launch, ids[i], launch);
546
555
  return reserved;
547
556
  }
557
+ /** How many of a connected agent's reserved native turns its check gives back before it stops. A turn is given back
558
+ * when it cannot be the check's baseline: cancelled or failed, a learned workflow or nested call in it, redacted
559
+ * evidence, no shadow report, or a shadow that did not answer. One or two are ordinary (a person cancels a task, an
560
+ * input carries a secret); five say the integration cannot give one (a client with no shadow check, inputs it never
561
+ * resolves, a draft whose shadow always refuses), and each reserved turn runs without the champion. The fifth stops it
562
+ * with nothing checked (stopUnchecked), which asks no recompile: a revision would have no baseline either. */
563
+ export const SDK_CHECK_RELEASES = 5;
564
+ /** A connected agent's check waiting for a native turn (`via` sdk, replaying, no turn reserved). */
565
+ const waitingSdk = (record) => record?.decided === "replaying" && record.via === "sdk" && !record.runs?.length;
566
+ /** Whether a connected agent's check was overtaken: a record of another revision of its workflow came after its own
567
+ * newest (a newer revision reserved, held by its owner, or promoted). An overtaken check is given no record of its own
568
+ * on a release, a deadline or a set-aside, so it never hides that newer record from the compile (learn/compile.ts
569
+ * heldNamesOf reads the workflow's newest), and it blocks no newer revision's reservation. A report that reached it
570
+ * still decides it (decideCheck), as an older check's verdict stands. */
571
+ const overtaken = (records, record) => {
572
+ const own = promotionOf(records, record.workflow, record.digest);
573
+ const at = own ? records.lastIndexOf(own) : -1;
574
+ return at >= 0 && records.slice(at + 1).some((one) => one.workflow === record.workflow && one.digest !== record.digest);
575
+ };
576
+ /** The checks of `name` other than at `digest` that block reserving it: every replaying one but an overtaken SDK one. */
577
+ const blocking = (records, name, digest) => replayingOf(records, name, digest).filter((one) => one.via !== "sdk" || !overtaken(records, one));
578
+ /** What every record of a connected agent's check carries on from its reservation. */
579
+ const sdkExtra = (record) => ({ via: "sdk", ...(record.runs ? { runs: record.runs } : {}), ...(record.replay_id ? { replay_id: record.replay_id } : {}), ...(record.commit ? { commit: record.commit } : {}) });
580
+ /** A connected agent's run input as a check row quotes it: the task text its start was given. */
581
+ export const sdkInputText = (launch) => {
582
+ const input = launch?.input;
583
+ return isObject(input) && typeof input.content === "string" ? input.content : inputText(input);
584
+ };
585
+ /** Reserves one of `flows` (a connected agent's start's candidates, each its folder's newest revision) for a shadow
586
+ * check on the native turn `runId`: the first the turn takes (`takes`) with no decision yet, or one waiting for a turn,
587
+ * while no other revision of its workflow is checked; the guarded write keeps one reservation per workflow across
588
+ * concurrent starts. First each SDK check of a candidate's workflow is moved on: one whose turn is past
589
+ * REPLAY_DEADLINE_MS is decided as one failed row (sdkCheckDeadline), and one waiting at a revision the folder moved
590
+ * past is set aside. A managed replay's record (no `via`) is never touched here. */
591
+ export async function reserveSdkCheck(deps, turn) {
592
+ const { revision } = turn;
593
+ if (!revision)
594
+ return;
595
+ const now = deps.now ?? Date.now;
596
+ for (const flow of turn.flows) {
597
+ const digest = workflowDigest(flow);
598
+ const before = await promotionsOf(deps.store.settings, deps.agentId);
599
+ for (const pending of replayingOf(before, flow.name, null)) {
600
+ if (pending.via !== "sdk" || overtaken(before, pending))
601
+ continue;
602
+ if (pending.runs?.length) {
603
+ if (now() - Date.parse(pending.at) > REPLAY_DEADLINE_MS)
604
+ await sdkCheckDeadline(deps, pending);
605
+ }
606
+ else if (pending.digest !== digest)
607
+ await setAside(deps, pending);
608
+ }
609
+ if (!turn.takes(flow))
610
+ continue;
611
+ const records = await promotionsOf(deps.store.settings, deps.agentId);
612
+ const own = promotionOf(records, flow.name, digest);
613
+ if ((own && !waitingSdk(own)) || blocking(records, flow.name, digest).length)
614
+ continue;
615
+ const id = uuidv7();
616
+ const reserved = await recordPromotion(deps.store.settings, deps.agentId, {
617
+ workflow: flow.name, digest, at: iso(now()), decided: "replaying", via: "sdk",
618
+ reason: "Checking it in the connected agent against one independent native turn before it can be reused.",
619
+ replay_id: id, runs: [turn.runId], inputs: [turn.runId], commit: revision,
620
+ check: own?.check ?? { ...loopOf(turn.learning), attempt: attemptOf(records, flow.name, digest) },
621
+ }, (was, current) => (own ? waitingSdk(was) && was.replay_id === own.replay_id : was === undefined) && blocking(current, flow.name, digest).length === 0);
622
+ if (reserved.won)
623
+ return { id, revision, digest, workflow: flow };
624
+ }
625
+ }
626
+ /** A connected agent's check whose native turn did not settle it by REPLAY_DEADLINE_MS (the backend never completed the
627
+ * turn, or the server stopped before the run's end): decided as every check is (decideCheck), on one failed row. Its
628
+ * hold asks the one recompile, and a recompile's check that ends here stops (`stopped`): an abandoned check never
629
+ * restarts its budget. */
630
+ export async function sdkCheckDeadline(deps, pending) {
631
+ const runId = pending.runs?.[0];
632
+ if (!runId || !pending.check || overtaken(await promotionsOf(deps.store.settings, deps.agentId), pending))
633
+ return;
634
+ const launch = await deps.store.runs.launch(runId).then((one) => readLaunchBody(one.body), () => undefined);
635
+ return decideCheck(deps, pending.workflow, pending.digest, pending.check, {
636
+ rows: [{ of: runId, input: sdkInputText(launch), agent: null, outcome: "failed", answer: null }],
637
+ cost: null, outcomes: { ...NO_OUTCOMES, failed: 1 }, unstarted: 0,
638
+ }, (was, current) => sameReplay(was, pending) && !overtaken(current, was), sdkExtra(pending));
639
+ }
640
+ /** Gives back a connected agent's reserved native turn that cannot be its check's baseline (`cause`): the check waits for
641
+ * the next turn the draft takes, nothing decided or promoted, and the turn counts toward SDK_CHECK_RELEASES, whose last
642
+ * stops it with nothing checked (stopUnchecked: no recompile). `counted` false: no turn ran (its start was not
643
+ * admitted). Kept only while the record is still this reservation. */
644
+ export async function releaseSdkCheck(deps, record, cause, counted = true) {
645
+ if (!record.check)
646
+ return;
647
+ if (overtaken(await promotionsOf(deps.store.settings, deps.agentId), record)) {
648
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest} gave back its native turn (${cause}); a newer revision has a record since, so it is left as it is`);
649
+ return;
650
+ }
651
+ const released = (record.check.released ?? 0) + (counted ? 1 : 0);
652
+ const why = excerptShown(cause, await deps.shown(), CHECK_TEXT_MAX);
653
+ // Overtaken is read again inside the write: a newer revision's record can land while the cause is being cut.
654
+ const still = (was, current) => sameReplay(was, record) && !overtaken(current, was);
655
+ const bar = { ...record.check, ...(released ? { released } : {}) };
656
+ if (released >= SDK_CHECK_RELEASES)
657
+ return stopUnchecked(deps, record.workflow, record.digest, bar, `the connected agent gave back ${plural(released, "reserved native turn")} with no answer to check it against (the last: ${why})`, still, {}, sdkExtra(record));
658
+ const { runs: _runs, inputs: _inputs, ...rest } = record;
659
+ const kept = await recordPromotion(deps.store.settings, deps.agentId, {
660
+ ...rest, at: iso((deps.now ?? Date.now)()), check: bar,
661
+ reason: `Waiting for a native turn of the connected agent that it takes: ${why}, so that turn was given back${counted ? ` (${released} of ${SDK_CHECK_RELEASES} before the check stops)` : ""}. Nothing was promoted.`,
662
+ }, still);
663
+ if (kept.won)
664
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest} waits for another native turn: ${why}`);
665
+ return kept;
666
+ }
667
+ /** A connected agent's check waiting at a revision the folder moved past (an owner's edit landed a newer one): set aside
668
+ * with nothing checked, never promoted, and `stopped` as any stop with nothing checked, so it spends no recompile
669
+ * (attemptOf): the newer revision is the one checked next. */
670
+ async function setAside(deps, pending) {
671
+ if (!pending.check)
672
+ return;
673
+ await recordPromotion(deps.store.settings, deps.agentId, {
674
+ ...pending, at: iso((deps.now ?? Date.now)()), decided: "hold",
675
+ reason: `${NOTHING_TO_CHECK}: a newer revision of it landed before a native turn of the connected agent checked it. It is not promoted; the newer revision is checked instead`,
676
+ check: { ...pending.check, n: 0, agreed: 0, alone: 0, of: [], stopped: true },
677
+ }, (was, current) => waitingSdk(was) && was.replay_id === pending.replay_id && !overtaken(current, was));
678
+ }
548
679
  /** The launch a replay's runs all run with (PromotionRecord.launch), chosen once by the claim or person reserving it:
549
680
  * `deps.launch` as a replay run takes it (a claim's claimed run's; a person's ask makes one now), the revision it runs,
550
681
  * and the claimed run as the one whose per_run MCP credentials its runs are handed, when the server can seal them. A
@@ -5,9 +5,10 @@ import { setTimeout as delay } from "node:timers/promises";
5
5
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
6
6
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
7
7
  import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
8
- import { learningFolderOf } from "../learning.js";
8
+ import { learningFolderOf, secretsShown } from "../learning.js";
9
9
  import { said, STOPPED } from "../learning-words.js";
10
10
  import { closeSdkInbox, sdkInbox } from "../sdk/runs.js";
11
+ import { settleSdkCheck } from "../sdk/check.js";
11
12
  import { runPathOverStore } from "../store-reads/learning.js";
12
13
  import { capSpendOf, learningEndOfRun } from "./learning-end.js";
13
14
  import { AskOverCap, bookedAsk } from "./sdk-ask.js";
@@ -89,6 +90,23 @@ export function createSdkLoop(launch, host, route) {
89
90
  },
90
91
  },
91
92
  }] : undefined;
93
+ // A connected agent's check settles at its run's end (sdk/check.ts), its error logged: never one that skips the
94
+ // run's own end or its learning.
95
+ const settleCheck = async (inbox, agentId) => {
96
+ try {
97
+ const agent = agentId ?? (await host.store.runs.get(claim.runId))?.agentId;
98
+ if (!agent)
99
+ return;
100
+ await settleSdkCheck({
101
+ store: host.store, agentId: agent, launch, inbox,
102
+ shown: async () => secretsShown(Object.values(await storeSecrets(host.store, host.sealKey, host.data)), { local: true }),
103
+ log: (line) => host.log?.(line),
104
+ });
105
+ }
106
+ catch (error) {
107
+ host.log?.(`workflow-first: the connected agent's check on run ${claim.runId} could not be settled (${error instanceof Error ? error.message : String(error)}); it is decided at its deadline`);
108
+ }
109
+ };
92
110
  let endPatch = END_PATCH_UNKNOWN;
93
111
  // The end keeps cost and path together, under the same bound as the other loops. A failed or late read
94
112
  // leaves both unknown; the completed backend task is still completed. No read writes after this end.
@@ -161,6 +179,8 @@ export function createSdkLoop(launch, host, route) {
161
179
  partial = (partial + event.text).slice(-16_000);
162
180
  else if (event.type === "session")
163
181
  entries.push({ kind: `${MARK}.session`, data: { session_id: event.session_id } });
182
+ else if (event.type === "workflow_check")
183
+ entries.push({ kind: `${MARK}.workflow_check`, data: event });
164
184
  else if (event.type === "tool") {
165
185
  if (event.status === "started") {
166
186
  liveTools.set(event.id, { callId: event.id, name: event.name, args: event.input });
@@ -251,6 +271,7 @@ export function createSdkLoop(launch, host, route) {
251
271
  },
252
272
  },
253
273
  ]);
274
+ await settleCheck(inbox, source.agentId);
254
275
  if (result.status === "completed") {
255
276
  const end = learningEndOfRun(launch, {
256
277
  store: host.store,
@@ -422,6 +443,9 @@ export function createSdkLoop(launch, host, route) {
422
443
  const inbox = await closeSdkInbox(host.store, claim, stopped?.kind === "command" ? "cancelled" : "failed");
423
444
  if (inbox.completion && stopped?.kind !== "command")
424
445
  return { state: "interrupted" };
446
+ // No completion: a stopped or failed turn gives its check back, an expired one is its deadline.
447
+ if (!inbox.completion)
448
+ await settleCheck(inbox);
425
449
  if (stopped?.kind === "command") {
426
450
  const end = stopEnd(stopped.cancel);
427
451
  await append([{ kind: KINDS.end, data: end }], { ...end, ...endPatch }, droppedLearning(true), stopped.commandId);
@@ -706,8 +706,9 @@ export const releaseCallHold = async () => {
706
706
  function callPolicyOf(store, runId, claimed) {
707
707
  // Nothing read yet: unread, so a policy asked before the first read fails closed too.
708
708
  let current = { settings: {}, problems: [], unreadable: true };
709
- // Only the permission is read here: a workflow never parks, so whether anyone can answer an ask plays no part.
710
- const gate = runGate({ root: claimed.workRoot, work: claimed.workRoot }, runId, claimed.revision, () => current, true);
709
+ // Only the permission is read here: a workflow never parks, so whether anyone can answer an ask plays no part. A
710
+ // workflow runs on no harness's adapter, so no facts name its tools.
711
+ const gate = runGate({ root: claimed.workRoot, work: claimed.workRoot, facts: undefined }, runId, claimed.revision, () => current, true);
711
712
  return async (tool) => {
712
713
  current = await storeSettings(store);
713
714
  return { permission: gate.policy(tool), denyFrom: gate.denyFrom(tool) };
@@ -107,7 +107,8 @@ export interface StartDeps {
107
107
  /** A new run id; defaults to a UUIDv7. */
108
108
  readonly newRunId?: () => string;
109
109
  /** Why no runner here can take a run, in their words, while every runner there refused to claim (runner/presence.ts
110
- * runnersRefused); undefined while one can, or none is there yet. A start is refused with it (runner_refused). */
110
+ * runnersRefused); undefined while one can, or none is there yet. prepareLaunch, which holds no store, refuses a start
111
+ * with it (runner_refused); a reader that holds the store calls refuseWhileNoRunner on its runners instead. */
111
112
  runnersRefused?(): Promise<string | undefined>;
112
113
  /** The create body's field issues, before the agent is read (server.ts runBodyIssues). */
113
114
  runBodyIssues(body: Json): InputIssue[];
@@ -29,7 +29,7 @@ import { launchBody } from "./run-launch.js";
29
29
  import { modelKeyRequired, serverKeyMissing } from "./run-model-key.js";
30
30
  import { raiseFollowUpId } from "./run-view.js";
31
31
  import { sendCommand } from "./runner/commands.js";
32
- import { runnersRefused } from "./runner/presence.js";
32
+ import { refuseWhileNoRunner } from "./runner/presence.js";
33
33
  import { AgentDeleting, AnswerTaken, ExternalBodyConflict, RunFinal, StoreConstraint, StoreLaunchMissing } from "./store/index.js";
34
34
  import { canonical } from "./store/agent-body.js";
35
35
  import { toolingOf } from "./tools.js";
@@ -158,9 +158,7 @@ export const resume = (store, moment) => pauseOrResume(store, moment, false);
158
158
  * which may skip it, in words. A runner applies every message, so while every runner here refused to claim, any message
159
159
  * (a person's or a trigger's) is refused in their words first, as a start is (prepareLaunch, runner/presence.ts). */
160
160
  export async function message(store, moment, content, { requestId, answers = true, origin, queue, launchSealed, beforeSubmit } = {}) {
161
- const refused = await runnersRefused(store.runners);
162
- if (refused !== undefined)
163
- throw new ApiError("runner_refused", refused);
161
+ await refuseWhileNoRunner(store.runners);
164
162
  if (moment.importedSource !== undefined)
165
163
  throw importedRefusal(moment);
166
164
  const launchBody = await controlLaunchBody(store, moment.id);