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

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 (135) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +94 -13
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +10 -4
  8. package/dist/api-only.d.ts +4 -2
  9. package/dist/api-only.js +5 -3
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/computer-setting.d.ts +8 -0
  13. package/dist/computer-setting.js +11 -0
  14. package/dist/computers.d.ts +6 -2
  15. package/dist/computers.js +2 -2
  16. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  17. package/dist/console/assets/index-DlQepP2J.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/fal-price.d.ts +76 -0
  20. package/dist/fal-price.js +368 -0
  21. package/dist/learn/commit.d.ts +5 -0
  22. package/dist/learn/commit.js +4 -1
  23. package/dist/learn/compile.d.ts +13 -5
  24. package/dist/learn/compile.js +24 -7
  25. package/dist/learn/delete.d.ts +12 -6
  26. package/dist/learn/delete.js +17 -11
  27. package/dist/learn/folder.d.ts +11 -0
  28. package/dist/learn/folder.js +20 -3
  29. package/dist/learn/learning-of.d.ts +8 -0
  30. package/dist/learn/learning-of.js +8 -0
  31. package/dist/learn/learning.sh +14 -1
  32. package/dist/learn/promote.d.ts +51 -7
  33. package/dist/learn/promote.js +51 -8
  34. package/dist/learning-reset.d.ts +18 -0
  35. package/dist/learning-reset.js +115 -0
  36. package/dist/learning-routes.d.ts +1 -1
  37. package/dist/learning-words.d.ts +5 -0
  38. package/dist/learning-words.js +5 -0
  39. package/dist/learning.d.ts +8 -6
  40. package/dist/learning.js +5 -4
  41. package/dist/llms.txt +1 -0
  42. package/dist/mcp-gateway.d.ts +39 -2
  43. package/dist/mcp-gateway.js +41 -10
  44. package/dist/mcp-pin-first.js +1 -1
  45. package/dist/mcp-servers-store.d.ts +1 -0
  46. package/dist/mcp-servers-store.js +2 -1
  47. package/dist/media-duration.d.ts +2 -0
  48. package/dist/media-duration.js +136 -0
  49. package/dist/openapi.js +45 -12
  50. package/dist/provider.d.ts +8 -0
  51. package/dist/provider.js +14 -2
  52. package/dist/refusal-words.d.ts +0 -3
  53. package/dist/refusal-words.js +0 -3
  54. package/dist/request-metadata.d.ts +20 -0
  55. package/dist/request-metadata.js +24 -0
  56. package/dist/run-launch.d.ts +13 -4
  57. package/dist/run-launch.js +14 -3
  58. package/dist/run-learning-served.d.ts +2 -2
  59. package/dist/run-usage.d.ts +48 -4
  60. package/dist/run-usage.js +156 -39
  61. package/dist/run-view.d.ts +1 -1
  62. package/dist/run-view.js +3 -7
  63. package/dist/runner/adapter-loop.d.ts +3 -1
  64. package/dist/runner/adapter-loop.js +12 -9
  65. package/dist/runner/adapter-run-spec.d.ts +1 -1
  66. package/dist/runner/adapter-run-spec.js +13 -13
  67. package/dist/runner/audit.d.ts +8 -3
  68. package/dist/runner/audit.js +21 -6
  69. package/dist/runner/claim-secrets.d.ts +2 -1
  70. package/dist/runner/claim-secrets.js +5 -3
  71. package/dist/runner/cli-run-spec.d.ts +1 -1
  72. package/dist/runner/cli-run-spec.js +12 -11
  73. package/dist/runner/conformance/harness.js +4 -2
  74. package/dist/runner/dispatch.js +4 -2
  75. package/dist/runner/harness-loops.js +5 -2
  76. package/dist/runner/journal-kinds.d.ts +3 -0
  77. package/dist/runner/learning-end.d.ts +2 -1
  78. package/dist/runner/learning-end.js +47 -22
  79. package/dist/runner/mcp-claim.js +1 -1
  80. package/dist/runner/mcp-run.d.ts +9 -0
  81. package/dist/runner/mcp-run.js +16 -1
  82. package/dist/runner/model-route.js +7 -4
  83. package/dist/runner/promotion.d.ts +40 -21
  84. package/dist/runner/promotion.js +130 -59
  85. package/dist/runner/run-child-host.js +6 -4
  86. package/dist/runner/runner.js +15 -3
  87. package/dist/runner/sdk-loop.d.ts +2 -2
  88. package/dist/runner/sdk-loop.js +3 -3
  89. package/dist/runner/store-port.d.ts +3 -0
  90. package/dist/runner/workflow-spec.js +3 -3
  91. package/dist/runs-over-store.d.ts +5 -2
  92. package/dist/runs-over-store.js +14 -7
  93. package/dist/sdk/check.d.ts +6 -5
  94. package/dist/sdk/check.js +17 -16
  95. package/dist/sdk/runs.js +81 -65
  96. package/dist/server.js +84 -20
  97. package/dist/store/agent-body.d.ts +4 -0
  98. package/dist/store/agent-body.js +4 -1
  99. package/dist/store/index.d.ts +1 -1
  100. package/dist/store/journal/storage.d.ts +2 -0
  101. package/dist/store/journal/storage.js +2 -1
  102. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  103. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  104. package/dist/store/schema.d.ts +14 -1
  105. package/dist/store/schema.js +42 -4
  106. package/dist/store/sqlite/run-launch.d.ts +22 -0
  107. package/dist/store/sqlite/run-launch.js +72 -7
  108. package/dist/store/sqlite/run-patch.d.ts +2 -1
  109. package/dist/store/sqlite/run-patch.js +4 -3
  110. package/dist/store/sqlite/store.js +141 -29
  111. package/dist/store/store-schema.js +2 -2
  112. package/dist/store/store.d.ts +67 -4
  113. package/dist/store-reads/learning.d.ts +12 -8
  114. package/dist/store-reads/learning.js +33 -24
  115. package/dist/store-reads/loop.d.ts +4 -3
  116. package/dist/store-reads/loop.js +7 -5
  117. package/dist/template-eval.js +4 -4
  118. package/dist/templates.d.ts +3 -0
  119. package/dist/templates.js +7 -5
  120. package/dist/timeline/labels.js +1 -1
  121. package/dist/tools.js +1 -1
  122. package/dist/uploads-archil.js +2 -1
  123. package/dist/uploads.d.ts +0 -3
  124. package/dist/uploads.js +2 -11
  125. package/dist/validate.js +5 -1
  126. package/dist/web-save.d.ts +3 -0
  127. package/dist/web-save.js +17 -2
  128. package/dist/workspace/archil-exec.js +1 -1
  129. package/dist/workspace/archil.js +1 -1
  130. package/dist/workspace/revision-skills.js +24 -11
  131. package/dist/workspace/synced-folder.d.ts +3 -3
  132. package/dist/workspace/synced-folder.js +7 -6
  133. package/package.json +10 -10
  134. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  135. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -490,7 +490,7 @@ async function pinOf({ store, claim, grants, githubMcpOrigin = GITHUB_MCP_ORIGIN
490
490
  const listed = at?.tools.find((one) => one.name === tool);
491
491
  if (!at || !listed)
492
492
  throw new McpClaimRefused(`The MCP tool ${name} was not pinned when this agent's revision was saved, so this run cannot call it. Save the agent again to pin it. Nothing was sent.`);
493
- const kept = (pinned[server] ??= { url: at.url, tools: [] });
493
+ const kept = (pinned[server] ??= { url: at.url, tools: [], ...(at.meter ? { meter: at.meter } : {}) });
494
494
  if (!kept.tools.some((one) => one.name === listed.name))
495
495
  kept.tools.push(listed);
496
496
  const price = at.prices && Object.hasOwn(at.prices, listed.name) ? at.prices[listed.name] : undefined;
@@ -1,6 +1,9 @@
1
1
  import type { HostTool } from "@parcha/agentrun-kernel";
2
2
  import type { Harness } from "@earendil-works/pi-durable";
3
3
  import { type McpGatewayOptions } from "../mcp-gateway.js";
4
+ import { type MediaReader } from "../fal-price.js";
5
+ import { type WebFake } from "../web-fake.js";
6
+ import type { SaveSlots } from "../web-save.js";
4
7
  import { type OAuthNetwork } from "../mcp-oauth.js";
5
8
  import type { Store, TriggerSettings } from "../store/index.js";
6
9
  import { type ApprovalPrice, type ToolEffect } from "../tool-gate.js";
@@ -56,6 +59,9 @@ export interface McpForClaimOptions {
56
59
  connectMs?: number;
57
60
  };
58
61
  readonly githubTimer?: GithubTimer;
62
+ /** Whether the run has a spend cap, and the reader of a metered job's input media (McpGatewayOptions). */
63
+ readonly capped?: McpGatewayOptions["capped"];
64
+ readonly media?: McpGatewayOptions["media"];
59
65
  /** Each credential value the claim opens, refreshes or mints, for the run's redactors (mcp-claim.ts `hold`). */
60
66
  readonly hold?: (values: string[]) => void;
61
67
  }
@@ -83,6 +89,9 @@ export interface ClaimMcp {
83
89
  /** Drops every credential held: the pass ended, the claim is lost, or its signal aborted. */
84
90
  release(): void;
85
91
  }
92
+ /** A claim's reader of a metered job's input media: through the guard web_save downloads by (an eval's web fake, a faux
93
+ * module, else the public network), in `slots`. */
94
+ export declare const mediaForClaim: (env: NodeJS.ProcessEnv, web?: WebFake, slots?: SaveSlots) => MediaReader;
86
95
  /** The wire names a subagent's `grant` gives of the run's MCP and monid tools, by the gate's keys; else the grant's own. */
87
96
  export declare function catalogSessionNames(catalog: Pick<ClaimMcp, "tools" | "catalogOf"> | undefined, grant: string): string[];
88
97
  /** The run's MCP for one claim: undefined when it grants no MCP tool. Throws McpClaimRefused (a granted tool its pin lacks,
@@ -1,6 +1,10 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { wireName } from "../catalog.js";
3
3
  import { mcpGateway } from "../mcp-gateway.js";
4
+ import { meterFor, publicMedia } from "../fal-price.js";
5
+ import { FAUX_ENV } from "../model.js";
6
+ import { fetchOptions } from "../web-fetch-direct.js";
7
+ import { fakeSaveOptions } from "../web-fake.js";
4
8
  import { dialAt, mcpServerAt, systemNetwork } from "../mcp-oauth.js";
5
9
  import { privateOAuthHosts } from "../mcp-private-hosts.js";
6
10
  import { mcpNameOf } from "../tool-names.js";
@@ -9,6 +13,9 @@ import { mcpClaim } from "./mcp-claim.js";
9
13
  import { registryListing } from "../mcp-pin-first.js";
10
14
  import { heldOrThrow } from "./held.js";
11
15
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
16
+ /** A claim's reader of a metered job's input media: through the guard web_save downloads by (an eval's web fake, a faux
17
+ * module, else the public network), in `slots`. */
18
+ export const mediaForClaim = (env, web, slots) => publicMedia(async () => (web ? fakeSaveOptions(web) : fetchOptions(env, FAUX_ENV)), slots);
12
19
  /** The wire names a subagent's `grant` gives of the run's MCP and monid tools, by the gate's keys; else the grant's own. */
13
20
  export function catalogSessionNames(catalog, grant) {
14
21
  const given = (catalog?.tools ?? []).flatMap((tool) => (permissionKeys(catalog.catalogOf(tool.name) ?? "").includes(grant) ? [tool.name] : []));
@@ -68,9 +75,14 @@ export async function mcpForClaim(options) {
68
75
  },
69
76
  beforeCall: step.beforeCall,
70
77
  work: options.work,
78
+ // fal's submission keys are scoped to the run (fal-price.ts falKeys): the same on every claim of it, so a retry after
79
+ // a resume still dedupes.
80
+ run: options.claim.runId,
71
81
  commit: () => (change) => options.harness.commit(change, BACKGROUND_CONTEXT),
72
82
  ...(options.fetch ? { fetch: options.fetch } : {}),
73
83
  ...(options.callBounds ? { bounds: options.callBounds } : {}),
84
+ ...(options.capped ? { capped: options.capped } : {}),
85
+ ...(options.media ? { media: options.media } : {}),
74
86
  });
75
87
  const catalog = new Map();
76
88
  const declared = new Map();
@@ -105,7 +117,10 @@ export async function mcpForClaim(options) {
105
117
  const pinned = parsed && Object.hasOwn(pin, parsed.server) ? pin[parsed.server] : undefined;
106
118
  if (!pinned?.tools.some((tool) => tool.name === parsed.tool))
107
119
  return undefined;
108
- return pinned.prices && Object.hasOwn(pinned.prices, parsed.tool) ? pinned.prices[parsed.tool] : "not metered";
120
+ if (pinned.prices && Object.hasOwn(pinned.prices, parsed.tool))
121
+ return pinned.prices[parsed.tool];
122
+ // A metered server's job is priced from its input, when the call runs: no price to show before it.
123
+ return meterFor(pinned)?.bills(parsed.tool) ? undefined : "not metered";
109
124
  },
110
125
  effectOf: (name) => pinnedEffect(pin, name),
111
126
  fresh: () => step.fresh(),
@@ -17,7 +17,7 @@ import { randomUUID } from "node:crypto";
17
17
  import { calculateCost } from "@earendil-works/pi-ai";
18
18
  import { onOpenRouter, openRouterAttribution, ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
19
19
  import { chooseModel, MODEL_PROVIDER, runModels } from "../model.js";
20
- import { providerFor } from "../provider.js";
20
+ import { gatewayHeadersAt, providerFor } from "../provider.js";
21
21
  import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
22
22
  import { callsOfText, toolsAsText } from "./text-tools.js";
23
23
  /** The wires a caller of routeOf speaks when it names none: Anthropic's Messages alone. */
@@ -50,14 +50,17 @@ export async function routeOf(model, env = process.env, tier = "default", wires
50
50
  const settings = { ...sees, ...(target.reasoning !== undefined ? { reasoning: target.reasoning } : {}), ...(target.contextWindow ? { contextWindow: target.contextWindow } : {}), ...(target.maxTokens ? { maxTokens: target.maxTokens } : {}), ...(target.thinkingLevelMap ? { thinkingLevelMap: target.thinkingLevelMap } : {}) };
51
51
  const route = { model: chosen.model.modelId, named: `${chosen.model.provider}/${chosen.model.modelId}`, price, cost: target.cost, ...(unpriced.has(chosen.model.modelId) ? { unpriced: true } : {}), outputCeiling: target.maxTokens ?? null, like: sees };
52
52
  // An Anthropic model speaks Messages itself: the network, at its catalog origin, its key read by name per request.
53
+ // Its requests name the claim's run, turn and attempt only where that origin is serve's own gateway (gatewayHeadersAt).
53
54
  if (chosen.model.provider === "anthropic") {
54
- return { ...route, provider: { api: "anthropic-messages", origin: target.baseUrl ?? "https://api.anthropic.com", credential: () => env.ANTHROPIC_API_KEY ?? env.ANTHROPIC_AUTH_TOKEN ?? "" } };
55
+ const origin = target.baseUrl ?? "https://api.anthropic.com";
56
+ const headers = gatewayHeadersAt(env, origin);
57
+ return { ...route, provider: { api: "anthropic-messages", origin, credential: () => env.ANTHROPIC_API_KEY ?? env.ANTHROPIC_AUTH_TOKEN ?? "", ...(headers ? { headers } : {}) } };
55
58
  }
56
59
  // A Claude model of serve's gateway (model.ts gatewayWire), for a caller that speaks Messages: the gateway itself, on
57
60
  // Messages, so the prompt cache marks pi-ai puts on the request reach it (provider.ts).
58
61
  if (target.api === "anthropic-messages" && chosen.model.provider === MODEL_PROVIDER && wires.includes("anthropic-messages")) {
59
62
  const to = providerFor("anthropic-messages", env, chosen.model, "pi");
60
- return { ...route, model: to.modelId, provider: { api: "anthropic-messages", origin: to.origin, credential: to.credential, auth: to.auth }, like: settings };
63
+ return { ...route, model: to.modelId, provider: { api: "anthropic-messages", origin: to.origin, credential: to.credential, auth: to.auth, ...(to.headers ? { headers: to.headers } : {}) }, like: settings };
61
64
  }
62
65
  // A model pi-ai speaks Responses to, for a caller that speaks it: that wire itself, where main sends it (provider.ts).
63
66
  if (target.api === "openai-responses" && wires.includes("openai-responses")) {
@@ -68,7 +71,7 @@ export async function routeOf(model, env = process.env, tier = "default", wires
68
71
  const plan = onPlan ? { price: () => null, unpriced: true } : {};
69
72
  return {
70
73
  ...route, model: to.modelId, ...plan,
71
- provider: { api: "openai-responses", origin: to.origin, credential: to.credential, auth: to.auth, ...(onPlan ? { plan: true } : {}), ...(to.refused ? { refused: to.refused } : {}) },
74
+ provider: { api: "openai-responses", origin: to.origin, credential: to.credential, auth: to.auth, ...(to.headers ? { headers: to.headers } : {}), ...(onPlan ? { plan: true } : {}), ...(to.refused ? { refused: to.refused } : {}) },
72
75
  like: onPlan ? { ...settings, developerRole: true } : settings,
73
76
  };
74
77
  }
@@ -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, recordPromotion, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
7
+ import { type CheckBar, type CheckRecord, type CheckTurns, 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";
@@ -97,8 +97,9 @@ export declare const DSL_REFUSES = "this release's workflow DSL refuses it";
97
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
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
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. */
100
+ * (stopUnchecked) is no first check's hold: it spends no recompile, and neither does a connected agent's hold on its
101
+ * give-backs (heldOnGiveBacks: the revision after it is the same attempt). A workflow's first revision after a first
102
+ * compile whose drafts failed under another name (learn/compile.ts newCompileAttempt) is that compile's recompile too. */
102
103
  export declare function attemptOf(records: readonly PromotionRecord[], name: string, digest: string): 1 | 2;
103
104
  /** The words a stopped check's record starts with when it had nothing to check its draft on. */
104
105
  export declare const NOTHING_TO_CHECK = "nothing to check it on";
@@ -111,7 +112,7 @@ export declare const differentDecisionWords: (k: number, n: number, example: str
111
112
  * draft did: its answer when it answered alone, why it handed the input back, or failed (or skipped a write). A
112
113
  * reserved input whose replay run was never created, or never ended, by the check's deadline failed (`unstarted` for
113
114
  * the first). */
114
- type CheckRow = {
115
+ export type CheckRow = {
115
116
  readonly of: string;
116
117
  readonly input: string;
117
118
  readonly agent: string | null;
@@ -122,10 +123,8 @@ type CheckRow = {
122
123
  readonly unstarted?: true;
123
124
  readonly compared?: Compared;
124
125
  };
125
- /** Decides a check on its rows: each input it ran on (a skipped write is none) agreed when the draft answered it alone
126
- * with the agent's recorded answer (learn/promote.ts compareAnswers, the audit's one comparison: on the bar's agree_on
127
- * when it names fields, else equal, or the same decision by the grader's verdict its replay run kept), alone
128
- * when it answered it with no escalate and no failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
126
+ /** Decides a check on its rows, with a connected agent's turns checked before them (`before`), scored on its bar
127
+ * (scoreRows). Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
129
128
  * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
130
129
  * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
131
130
  * (the one write: of two claims at once, one decides). */
@@ -136,14 +135,20 @@ export declare function decideCheck(deps: DecideDeps, name: string, digest: stri
136
135
  unstarted: number;
137
136
  exactMismatchReason?: string;
138
137
  fresh_reads?: number;
138
+ before?: CheckTurns;
139
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. */
140
+ /** How many of a connected agent's reserved native turns its check gives back in a row (failed, a learned workflow or
141
+ * nested call in it, redacted evidence, no shadow report, or a shadow that did not answer; never a cancel, and a turn
142
+ * that lands starts the count again) before it holds the draft, never promoted and never stopped for good, for the next
143
+ * compile to revise and check afresh: five in a row say the integration cannot give a baseline now, not that it never will. */
146
144
  export declare const SDK_CHECK_RELEASES = 5;
145
+ /** Which attempt a revision compile of `held` is when its draft fails its checks (runner/learning-end.ts
146
+ * recordDraftFailed): 2, the recompile, for any hold but a connected agent's on give-backs, which spends none: its
147
+ * check's own attempt, until a revise of it has failed once already (the workflow's newest record that failed draft). */
148
+ export declare function reviseAttemptOf(records: readonly PromotionRecord[], held: {
149
+ readonly workflow: string;
150
+ readonly check?: CheckRecord;
151
+ }): 1 | 2;
147
152
  /** A connected agent's draft reserved on one native turn: what its start hands the caller (sdk/runs.ts receipt). */
148
153
  export type SdkWorkflowCheck = {
149
154
  id: string;
@@ -157,7 +162,7 @@ export declare const sdkInputText: (launch: RunLaunch | undefined) => string;
157
162
  * check on the native turn `runId`: the first the turn takes (`takes`) with no decision yet, or one waiting for a turn,
158
163
  * while no other revision of its workflow is checked; the guarded write keeps one reservation per workflow across
159
164
  * 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
165
+ * REPLAY_DEADLINE_MS is one failed row of its turns (sdkCheckDeadline), and one waiting at a revision the folder moved
161
166
  * past is set aside. A managed replay's record (no `via`) is never touched here. */
162
167
  export declare function reserveSdkCheck(deps: DecideDeps, turn: {
163
168
  readonly runId: string;
@@ -166,15 +171,29 @@ export declare function reserveSdkCheck(deps: DecideDeps, turn: {
166
171
  readonly flows: readonly LearnedWorkflow[];
167
172
  readonly takes: (flow: LearnedWorkflow) => boolean;
168
173
  }): Promise<SdkWorkflowCheck | undefined>;
174
+ /** One native turn's row of a connected agent's check: its shadow answered or handed back (sdk/check.ts settleSdkCheck),
175
+ * or the turn did not settle by REPLAY_DEADLINE_MS, a failed row (sdkCheckDeadline). A managed check decides once, on
176
+ * its compile_after inputs, and so does this one: the turn that makes compile_after decides on every turn collected
177
+ * (decideCheck, the same bar); a turn before it is scored and kept (check.turns), the record gives back its reserved
178
+ * turn, and the check waits for the next turn the draft takes, nothing decided or promoted, the agent answering
179
+ * meanwhile. No turn holds it early, as no input of a managed check does. Its rows are never skipped (a shadow stopped
180
+ * at a write gives its turn back), so each is one of the n. Kept only while `still` holds of the digest's record; a
181
+ * check a newer revision overtook keeps no turn (it would hide the newer record), as a release does. */
182
+ export declare function sdkCheckTurn(deps: DecideDeps, record: PromotionRecord & {
183
+ readonly check: CheckRecord;
184
+ }, row: CheckRow, still: Parameters<typeof recordPromotion>[3], read?: {
185
+ exactMismatchReason?: string;
186
+ fresh_reads?: number;
187
+ }): Promise<import("../learn/promote.js").Recorded | undefined>;
169
188
  /** 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. */
189
+ * turn, or the server stopped before the run's end): one failed row of its turns (sdkCheckTurn), as a managed check's
190
+ * replay run not ended by its deadline is a failed input. The hold the turns end in asks the one recompile, and a
191
+ * recompile's check held so stops (`stopped`): an abandoned check never restarts its budget. */
173
192
  export declare function sdkCheckDeadline(deps: DecideDeps, pending: PromotionRecord): Promise<import("../learn/promote.js").Recorded | undefined>;
174
193
  /** 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. */
194
+ * the next turn the draft takes, nothing decided or promoted, the turns it checked kept on the record. A `counted` turn
195
+ * (not a cancel, not a start that was never admitted) counts toward SDK_CHECK_RELEASES in a row, whose last holds the
196
+ * draft for the next compile, whose revision is checked afresh. Kept only while the record is still this reservation. */
178
197
  export declare function releaseSdkCheck(deps: DecideDeps, record: PromotionRecord, cause: string, counted?: boolean): Promise<import("../learn/promote.js").Recorded | undefined>;
179
198
  /** 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,
180
199
  * 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
@@ -9,7 +9,7 @@ import { isCliRecord, piShaped, runEntries, runTimeline } from "../store-reads/j
9
9
  import { pinAnnotations, recordedCalls, replayCalls, SKIPPED_WRITE, toolClassOf, toolWord, unmarkedWords } from "../learn/replay-calls.js";
10
10
  import { listed } from "../learning-words.js";
11
11
  import { isObject } from "../validate.js";
12
- import { agentRun, lastOwnRuns, newCompileAttempt } from "../learn/compile.js";
12
+ import { agentRun, lastOwnRuns, newCompileAttempt, sinceReset } from "../learn/compile.js";
13
13
  import { checkPasses, checkShares, CHECK_TEXT_MAX, championOf, compareAnswers, comparedOf, promotionOf, promotionsOf, recordPromotion, replayingOf, skippedToolsOf } from "../learn/promote.js";
14
14
  import { sendCommand } from "./commands.js";
15
15
  import { ClaimRefused } from "./loop-contract.js";
@@ -270,8 +270,9 @@ async function loopOfRevision(deps) {
270
270
  /** Which check of a compile a new revision's is: 2 when the workflow's newest record of another revision is a first
271
271
  * check's hold, an audit's hold or a hold by its reason alone (holdRefused: the DSL refuses a serving revision), or a
272
272
  * first compile's failed draft (this revision is its one recompile), else 1. A stop with nothing checked
273
- * (stopUnchecked) is no first check's hold: it spends no recompile. A workflow's first revision after a first compile
274
- * whose drafts failed under another name (learn/compile.ts newCompileAttempt) is that compile's recompile too. */
273
+ * (stopUnchecked) is no first check's hold: it spends no recompile, and neither does a connected agent's hold on its
274
+ * give-backs (heldOnGiveBacks: the revision after it is the same attempt). A workflow's first revision after a first
275
+ * compile whose drafts failed under another name (learn/compile.ts newCompileAttempt) is that compile's recompile too. */
275
276
  export function attemptOf(records, name, digest) {
276
277
  const before = records.findLast((one) => one.workflow === name && one.digest !== digest);
277
278
  if (!before)
@@ -280,6 +281,8 @@ export function attemptOf(records, name, digest) {
280
281
  return 1;
281
282
  if (before.audit)
282
283
  return before.audit.stopped ? 1 : 2;
284
+ if (before.check && heldOnGiveBacks(before.check))
285
+ return before.check.attempt;
283
286
  return !before.check || (before.check.attempt === 1 && !before.check.stopped) ? 2 : 1;
284
287
  }
285
288
  /** The shadow runs a recompile's check runs on beside the agent's last runs: the disagreeing audit rows the workflow's
@@ -300,16 +303,19 @@ const checkable = (deps, row) => row.id !== deps.runId && agentRun(row) && row.a
300
303
  * never push them out of the read. And `audited`: an audit hold's disagreeing shadow runs (auditInputsOf), each ended.
301
304
  * Of those, the ones whose input `workflow` takes (fits), each with its launch read back; one with an uploaded file is
302
305
  * never an input. With how many of the agent's runs it looked at (`looked`) and why each it looked at is no input
303
- * (`unfit`, `files`). */
306
+ * (`unfit`, `files`). Every one of them a run on no named disk (one on a named disk learns nothing, learn/learning-of.ts)
307
+ * since the agent's learning's reset (sinceReset), the named and audited ones included. */
304
308
  async function checkInputs(deps, workflow, pick, audited = []) {
305
309
  const { resolveSchemaForWorkflow } = await import("@parcha/agentrun-dsl");
306
- const named = (await Promise.all(pick.of.map((id) => deps.store.runs.get(id)))).filter((row) => row !== undefined && checkable(deps, row));
310
+ const since = await sinceReset(deps.store, deps.agentId);
311
+ const learns = (row) => (row.disk ?? null) === null && since(row);
312
+ const named = (await Promise.all(pick.of.map((id) => deps.store.runs.get(id)))).filter((row) => row !== undefined && checkable(deps, row) && learns(row));
307
313
  const last = pick.n ? await lastOwnRuns(deps.store, deps.agentId, pick.n + pick.of.length, deps.runId) : [];
308
314
  const own = [...named, ...last.filter((row) => !pick.of.includes(row.id)).slice(0, pick.n)];
309
315
  // And an audit hold's disagreeing shadow runs: the agent's answers the recompile must say too.
310
316
  for (const id of audited) {
311
317
  const row = await deps.store.runs.get(id);
312
- if (row && row.state === "ended" && !own.some((one) => one.id === id))
318
+ if (row && row.state === "ended" && learns(row) && !own.some((one) => one.id === id))
313
319
  own.push(row);
314
320
  }
315
321
  const out = [];
@@ -474,45 +480,56 @@ async function settleCheck(deps, workflow, digest, record) {
474
480
  }
475
481
  return decided.record?.decided === "replaying" ? undefined : decided.record;
476
482
  }
477
- /** Decides a check on its rows: each input it ran on (a skipped write is none) agreed when the draft answered it alone
478
- * with the agent's recorded answer (learn/promote.ts compareAnswers, the audit's one comparison: on the bar's agree_on
479
- * when it names fields, else equal, or the same decision by the grader's verdict its replay run kept), alone
480
- * when it answered it with no escalate and no failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
481
- * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
482
- * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
483
- * (the one write: of two claims at once, one decides). */
484
- export async function decideCheck(deps, name, digest, bar, read, still, extra) {
485
- const now = deps.now ?? Date.now;
486
- const ran = read.rows.filter((row) => row.outcome !== "skipped_write");
483
+ /** A check's rows scored on its bar, added to `before` (a connected agent's turns checked so far): each input it ran on
484
+ * (a skipped write is none) agreed when the draft answered it alone with the agent's recorded answer (learn/promote.ts
485
+ * compareAnswers, the audit's one comparison: on the bar's agree_on when it names fields, else equal, or the same
486
+ * decision by the grader's verdict its replay run kept), alone when it answered it with no escalate and no failed step;
487
+ * the inputs it did not agree on, each text cut of the host's secrets whole, then shortened (learn/secrets.ts
488
+ * excerptShown); and the fast model that compared, when it read any input's answers. */
489
+ async function scoreRows(deps, bar, rows, before) {
490
+ const ran = rows.filter((row) => row.outcome !== "skipped_write");
487
491
  const alone = (row) => row.outcome === "answered";
488
492
  // Compared on the bar's agree_on when it names paths (the definition's), else equal answers agree and the grader's
489
493
  // verdict decides the rest; with no grader (no fast model), the whole answer.
490
494
  const compared = new Map(ran.map((row) => [row, compareAnswers(row.answer, row.agent, bar.agree_on, row.compared)]));
491
495
  const agrees = (row) => alone(row) && compared.get(row).same;
492
- const score = { n: ran.length, agreed: ran.filter(agrees).length, alone: ran.filter(alone).length };
493
- const ok = checkPasses(score, bar);
494
- // The fast model that compared, when it read any input's answers.
496
+ const score = { n: (before?.n ?? 0) + ran.length, agreed: (before?.agreed ?? 0) + ran.filter(agrees).length, alone: (before?.alone ?? 0) + ran.filter(alone).length };
495
497
  const grader = [...compared.values()].find((one) => one.grader !== undefined)?.grader;
496
- // Each text is cut of the host's secrets whole, then shortened (learn/secrets.ts excerptShown).
497
498
  const shown = await deps.shown();
498
499
  const cut = (text) => excerptShown(text, shown, CHECK_TEXT_MAX);
499
- const disagreements = ran.filter((row) => !agrees(row)).map((row) => {
500
- const differs = row.outcome === "answered" ? compared.get(row).differs_on : undefined;
501
- return {
502
- run: row.of, input: cut(row.input), agent: row.agent === null ? null : cut(row.agent),
503
- ...(row.outcome === "answered" ? { draft: cut(row.answer ?? "") } : row.outcome === "handed_back" ? { escalated: cut(row.escalated ?? "") } : { failed: true }),
504
- ...(differs ? { differs_on: cut(differs) } : {}),
505
- };
506
- });
500
+ const disagreements = [...(before?.disagreements ?? []), ...ran.filter((row) => !agrees(row)).map((row) => {
501
+ const differs = row.outcome === "answered" ? compared.get(row).differs_on : undefined;
502
+ return {
503
+ run: row.of, input: cut(row.input), agent: row.agent === null ? null : cut(row.agent),
504
+ ...(row.outcome === "answered" ? { draft: cut(row.answer ?? "") } : row.outcome === "handed_back" ? { escalated: cut(row.escalated ?? "") } : { failed: true }),
505
+ ...(differs ? { differs_on: cut(differs) } : {}),
506
+ };
507
+ })];
508
+ return { score, disagreements, grader };
509
+ }
510
+ /** Two outcome counts added. */
511
+ const outcomesAdded = (a, b) => b ? { answered: a.answered + b.answered, handed_back: a.handed_back + b.handed_back, failed: a.failed + b.failed, skipped_write: a.skipped_write + b.skipped_write } : a;
512
+ /** Decides a check on its rows, with a connected agent's turns checked before them (`before`), scored on its bar
513
+ * (scoreRows). Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
514
+ * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
515
+ * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
516
+ * (the one write: of two claims at once, one decides). */
517
+ export async function decideCheck(deps, name, digest, bar, read, still, extra) {
518
+ const now = deps.now ?? Date.now;
519
+ const { before } = read;
520
+ const { score, disagreements, grader } = await scoreRows(deps, bar, read.rows, before);
521
+ const ok = checkPasses(score, bar);
507
522
  const stopped = !ok && bar.attempt === 2;
508
523
  const pct = (value) => `${(value * 100).toFixed(1)}%`;
509
524
  const shares = checkShares(score);
510
525
  // Inputs stopped at a write the recording lacks are no evidence either way; one stopped at an MCP tool its server listed
511
526
  // with no readOnlyHint names that tool (skipWordsOf), never a data problem.
512
527
  const tools = skippedToolsOf(read.rows);
513
- const { skipped_write: skipped, failed } = read.outcomes;
528
+ const outcomes = outcomesAdded(read.outcomes, before?.outcomes);
529
+ const { skipped_write: skipped, failed } = outcomes;
514
530
  const { hint, why: skipWhy } = skipWordsOf(tools, skipped);
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 } : {}) };
531
+ const fresh = (read.fresh_reads ?? 0) + (before?.fresh_reads ?? 0);
532
+ const numbers = { of: [...read.rows.map((row) => row.of), ...(before?.of ?? [])], cost_usd: read.cost, outcomes, ...(read.unstarted ? { unstarted: read.unstarted } : {}), ...(tools.length ? { skipped_tools: tools } : {}), ...(fresh ? { fresh_reads: fresh } : {}) };
516
533
  // Every input skipped at a write (each reserved input counts: one never created or never ended failed, so this is the
517
534
  // only way to none): nothing to check it on, so it stops, never promoted unchecked, and asks no recompile.
518
535
  if (!score.n) {
@@ -554,13 +571,22 @@ async function reserve(deps, workflow, digest, inputs, reason, still, check) {
554
571
  await startReplay(deps, workflow, digest, one.run, one.launch, ids[i], launch);
555
572
  return reserved;
556
573
  }
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. */
574
+ /** How many of a connected agent's reserved native turns its check gives back in a row (failed, a learned workflow or
575
+ * nested call in it, redacted evidence, no shadow report, or a shadow that did not answer; never a cancel, and a turn
576
+ * that lands starts the count again) before it holds the draft, never promoted and never stopped for good, for the next
577
+ * compile to revise and check afresh: five in a row say the integration cannot give a baseline now, not that it never will. */
563
578
  export const SDK_CHECK_RELEASES = 5;
579
+ /** Whether a hold's check is a connected agent's held on SDK_CHECK_RELEASES give-backs in a row (releaseSdkCheck): only
580
+ * a connected agent's check counts give-backs. */
581
+ const heldOnGiveBacks = (check) => (check?.released ?? 0) >= SDK_CHECK_RELEASES;
582
+ /** Which attempt a revision compile of `held` is when its draft fails its checks (runner/learning-end.ts
583
+ * recordDraftFailed): 2, the recompile, for any hold but a connected agent's on give-backs, which spends none: its
584
+ * check's own attempt, until a revise of it has failed once already (the workflow's newest record that failed draft). */
585
+ export function reviseAttemptOf(records, held) {
586
+ if (!held.check || !heldOnGiveBacks(held.check))
587
+ return 2;
588
+ return newCompileAttempt(records.filter((one) => one.workflow === held.workflow)) === 2 ? 2 : held.check.attempt;
589
+ }
564
590
  /** A connected agent's check waiting for a native turn (`via` sdk, replaying, no turn reserved). */
565
591
  const waitingSdk = (record) => record?.decided === "replaying" && record.via === "sdk" && !record.runs?.length;
566
592
  /** Whether a connected agent's check was overtaken: a record of another revision of its workflow came after its own
@@ -586,7 +612,7 @@ export const sdkInputText = (launch) => {
586
612
  * check on the native turn `runId`: the first the turn takes (`takes`) with no decision yet, or one waiting for a turn,
587
613
  * while no other revision of its workflow is checked; the guarded write keeps one reservation per workflow across
588
614
  * 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
615
+ * REPLAY_DEADLINE_MS is one failed row of its turns (sdkCheckDeadline), and one waiting at a revision the folder moved
590
616
  * past is set aside. A managed replay's record (no `via`) is never touched here. */
591
617
  export async function reserveSdkCheck(deps, turn) {
592
618
  const { revision } = turn;
@@ -613,34 +639,68 @@ export async function reserveSdkCheck(deps, turn) {
613
639
  if ((own && !waitingSdk(own)) || blocking(records, flow.name, digest).length)
614
640
  continue;
615
641
  const id = uuidv7();
642
+ const check = own?.check ?? { ...loopOf(turn.learning), attempt: attemptOf(records, flow.name, digest) };
616
643
  const reserved = await recordPromotion(deps.store.settings, deps.agentId, {
617
644
  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) },
645
+ reason: `Checking it in the connected agent against an independent native turn before it can be reused: ${sdkTurnsWords(check)}.`,
646
+ replay_id: id, runs: [turn.runId], inputs: [turn.runId], commit: revision, check,
621
647
  }, (was, current) => (own ? waitingSdk(was) && was.replay_id === own.replay_id : was === undefined) && blocking(current, flow.name, digest).length === 0);
622
648
  if (reserved.won)
623
649
  return { id, revision, digest, workflow: flow };
624
650
  }
625
651
  }
652
+ /** How far a connected agent's check is: its turns checked of the compile_after it decides on. */
653
+ const sdkTurnsWords = (check) => `${check.turns?.n ?? 0} of ${plural(check.compile_after, "native turn")} checked so far; it decides once on all of them, as a managed check does on the agent's inputs`;
654
+ /** One native turn's row of a connected agent's check: its shadow answered or handed back (sdk/check.ts settleSdkCheck),
655
+ * or the turn did not settle by REPLAY_DEADLINE_MS, a failed row (sdkCheckDeadline). A managed check decides once, on
656
+ * its compile_after inputs, and so does this one: the turn that makes compile_after decides on every turn collected
657
+ * (decideCheck, the same bar); a turn before it is scored and kept (check.turns), the record gives back its reserved
658
+ * turn, and the check waits for the next turn the draft takes, nothing decided or promoted, the agent answering
659
+ * meanwhile. No turn holds it early, as no input of a managed check does. Its rows are never skipped (a shadow stopped
660
+ * at a write gives its turn back), so each is one of the n. Kept only while `still` holds of the digest's record; a
661
+ * check a newer revision overtook keeps no turn (it would hide the newer record), as a release does. */
662
+ export async function sdkCheckTurn(deps, record, row, still, read = {}) {
663
+ // A turn that lands starts the give-back count again (SDK_CHECK_RELEASES counts them in a row).
664
+ const { turns: before, released: _released, ...bar } = record.check;
665
+ const outcomes = { ...NO_OUTCOMES, [row.outcome]: 1 };
666
+ // The turn lands once: its completion and its deadline can both read the reservation, and the first to write takes
667
+ // the turn off it, so the second finds it gone (heldTurn) and never adds the turn twice or replaces the first's row.
668
+ const turnStill = (was, current) => still(was, current) && heldTurn(was, record);
669
+ if ((before?.n ?? 0) + 1 >= bar.compile_after)
670
+ return decideCheck(deps, record.workflow, record.digest, bar, { rows: [row], cost: null, outcomes, unstarted: 0, ...read, ...(before ? { before } : {}) }, turnStill, sdkExtra(record));
671
+ if (overtaken(await promotionsOf(deps.store.settings, deps.agentId), record)) {
672
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest} checked a native turn; a newer revision has a record since, so it is left as it is`);
673
+ return;
674
+ }
675
+ const { score, disagreements } = await scoreRows(deps, bar, [row], before);
676
+ const fresh = (before?.fresh_reads ?? 0) + (read.fresh_reads ?? 0);
677
+ const turns = { ...score, of: [row.of, ...(before?.of ?? [])], outcomes: outcomesAdded(outcomes, before?.outcomes), ...(disagreements.length ? { disagreements } : {}), ...(fresh ? { fresh_reads: fresh } : {}) };
678
+ const check = { ...bar, turns };
679
+ const { runs: _runs, inputs: _inputs, ...rest } = record;
680
+ const kept = await recordPromotion(deps.store.settings, deps.agentId, {
681
+ ...rest, at: iso((deps.now ?? Date.now)()), check,
682
+ reason: `Waiting for the next native turn of the connected agent that it takes: ${sdkTurnsWords(check)}. Nothing was promoted.`,
683
+ }, (was, current) => turnStill(was, current) && !overtaken(current, was));
684
+ if (kept.won)
685
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest}: ${sdkTurnsWords(check)}`);
686
+ return kept;
687
+ }
626
688
  /** 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. */
689
+ * turn, or the server stopped before the run's end): one failed row of its turns (sdkCheckTurn), as a managed check's
690
+ * replay run not ended by its deadline is a failed input. The hold the turns end in asks the one recompile, and a
691
+ * recompile's check held so stops (`stopped`): an abandoned check never restarts its budget. */
630
692
  export async function sdkCheckDeadline(deps, pending) {
631
693
  const runId = pending.runs?.[0];
632
- if (!runId || !pending.check || overtaken(await promotionsOf(deps.store.settings, deps.agentId), pending))
694
+ const { check } = pending;
695
+ if (!runId || !check || overtaken(await promotionsOf(deps.store.settings, deps.agentId), pending))
633
696
  return;
634
697
  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));
698
+ return sdkCheckTurn(deps, { ...pending, check }, { of: runId, input: sdkInputText(launch), agent: null, outcome: "failed", answer: null }, (was, current) => sameReplay(was, pending) && !overtaken(current, was));
639
699
  }
640
700
  /** 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. */
701
+ * the next turn the draft takes, nothing decided or promoted, the turns it checked kept on the record. A `counted` turn
702
+ * (not a cancel, not a start that was never admitted) counts toward SDK_CHECK_RELEASES in a row, whose last holds the
703
+ * draft for the next compile, whose revision is checked afresh. Kept only while the record is still this reservation. */
644
704
  export async function releaseSdkCheck(deps, record, cause, counted = true) {
645
705
  if (!record.check)
646
706
  return;
@@ -651,28 +711,35 @@ export async function releaseSdkCheck(deps, record, cause, counted = true) {
651
711
  const released = (record.check.released ?? 0) + (counted ? 1 : 0);
652
712
  const why = excerptShown(cause, await deps.shown(), CHECK_TEXT_MAX);
653
713
  // 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);
714
+ const still = (was, current) => sameReplay(was, record) && heldTurn(was, record) && !overtaken(current, was);
655
715
  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));
716
+ const at = iso((deps.now ?? Date.now)());
717
+ if (released >= SDK_CHECK_RELEASES) {
718
+ // A hold, never `stopped`: it asks the next compile for a revision (learn/compile.ts heldNamesOf), checked afresh.
719
+ const reason = `the connected agent gave back ${plural(released, "reserved native turn")} in a row with no answer to check it against (the last: ${why}). It is not promoted; the agent's next compile revises it, and the revision is checked afresh`;
720
+ const held = await recordPromotion(deps.store.settings, deps.agentId, { workflow: record.workflow, digest: record.digest, at, decided: "hold", reason, check: { ...bar, n: 0, agreed: 0, alone: 0, of: [] }, ...seedOf(deps), ...sdkExtra(record) }, still);
721
+ if (held.won)
722
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest} held: ${reason}`);
723
+ return held;
724
+ }
658
725
  const { runs: _runs, inputs: _inputs, ...rest } = record;
659
726
  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.`,
727
+ ...rest, at, check: bar,
728
+ 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} in a row before it is held for a recompile)` : ""}. Nothing was promoted.`,
662
729
  }, still);
663
730
  if (kept.won)
664
731
  deps.log(`workflow-first: ${record.workflow} at ${record.digest} waits for another native turn: ${why}`);
665
732
  return kept;
666
733
  }
667
734
  /** 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. */
735
+ * with nothing decided, never promoted (the turns it checked kept on the record), and `stopped` as any stop with
736
+ * nothing checked, so it spends no recompile (attemptOf): the newer revision is the one checked next. */
670
737
  async function setAside(deps, pending) {
671
738
  if (!pending.check)
672
739
  return;
673
740
  await recordPromotion(deps.store.settings, deps.agentId, {
674
741
  ...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`,
742
+ reason: `${NOTHING_TO_CHECK}: a newer revision of it landed before the connected agent's native turns finished checking it. It is not promoted; the newer revision is checked instead`,
676
743
  check: { ...pending.check, n: 0, agreed: 0, alone: 0, of: [], stopped: true },
677
744
  }, (was, current) => waitingSdk(was) && was.replay_id === pending.replay_id && !overtaken(current, was));
678
745
  }
@@ -704,6 +771,10 @@ function replayLaunchOf(deps) {
704
771
  * id. A replay settled meanwhile, and a newer replay of the same revision its owner started since (a held revision may
705
772
  * be replayed again), are not: an older replay's late decision never lands over a newer one. */
706
773
  const sameReplay = (was, record) => was?.decided === "replaying" && was.replay_id === record.replay_id;
774
+ /** Whether `was` still reserves `record`'s native turn (a connected agent's check: one turn reserved at a time, its run
775
+ * first in `runs`). A turn's row (sdkCheckTurn) and its give-back (releaseSdkCheck) each take the turn off the record, so
776
+ * a second writer that read the same reservation finds it gone. */
777
+ const heldTurn = (was, record) => record.runs?.[0] !== undefined && was?.runs?.[0] === record.runs[0];
707
778
  /** Cancels each of `record`'s replay runs not ended, as a person's cancel is (an in-flight one stops, what it spent booked
708
779
  * on its row): once its check is decided with runs still at work (past its deadline). How many were sent their cancel. The
709
780
  * record is the durable half: a cancel that is lost (a crash after the record, a write that fails) leaves a run whose