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

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 (185) hide show
  1. package/CHANGELOG.md +68 -1
  2. package/README.md +218 -20
  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/agent-delete.d.ts +33 -10
  9. package/dist/agent-delete.js +184 -26
  10. package/dist/agents-store.d.ts +6 -2
  11. package/dist/agents-store.js +18 -5
  12. package/dist/agents.d.ts +8 -1
  13. package/dist/agents.js +14 -4
  14. package/dist/answer-json.d.ts +10 -0
  15. package/dist/answer-json.js +23 -0
  16. package/dist/api-only.d.ts +5 -2
  17. package/dist/api-only.js +10 -2
  18. package/dist/archil-routes.d.ts +1 -1
  19. package/dist/archil-routes.js +4 -3
  20. package/dist/browser-live.d.ts +9 -4
  21. package/dist/browser-live.js +18 -5
  22. package/dist/browser-sessions.d.ts +56 -0
  23. package/dist/browser-sessions.js +117 -0
  24. package/dist/cap.js +7 -9
  25. package/dist/cli.js +6 -6
  26. package/dist/computer-routes.d.ts +6 -14
  27. package/dist/computer-routes.js +8 -10
  28. package/dist/computers.d.ts +6 -2
  29. package/dist/computers.js +4 -2
  30. package/dist/conformance.d.ts +4 -0
  31. package/dist/conformance.js +6 -0
  32. package/dist/console/assets/index-Bzn4eUYF.js +715 -0
  33. package/dist/console/assets/index-CR2ZGei1.css +1 -0
  34. package/dist/console/index.html +2 -2
  35. package/dist/errors.d.ts +4 -1
  36. package/dist/errors.js +15 -5
  37. package/dist/harness-check.d.ts +3 -1
  38. package/dist/harness-check.js +99 -70
  39. package/dist/harness-cursor.d.ts +10 -27
  40. package/dist/harness-cursor.js +5 -84
  41. package/dist/harness-goose.d.ts +4 -29
  42. package/dist/harness-goose.js +6 -86
  43. package/dist/harness-module.d.ts +4 -0
  44. package/dist/harness-module.js +1 -0
  45. package/dist/harness-owned.d.ts +52 -0
  46. package/dist/harness-owned.js +92 -0
  47. package/dist/harness-recipe.js +2 -24
  48. package/dist/harness-table.d.ts +109 -6
  49. package/dist/harness-table.js +242 -28
  50. package/dist/harness.js +2 -2
  51. package/dist/import.js +4 -3
  52. package/dist/key-refusal.d.ts +2 -1
  53. package/dist/key-refusal.js +18 -2
  54. package/dist/learn/check.d.ts +11 -2
  55. package/dist/learn/check.js +12 -9
  56. package/dist/learn/promote.d.ts +18 -1
  57. package/dist/learn/promote.js +47 -0
  58. package/dist/learn/repick.d.ts +34 -0
  59. package/dist/learn/repick.js +201 -0
  60. package/dist/learn/secrets.d.ts +4 -0
  61. package/dist/learn/secrets.js +23 -0
  62. package/dist/learned-workflow.d.ts +2 -0
  63. package/dist/learned-workflow.js +18 -1
  64. package/dist/learning-model.d.ts +18 -0
  65. package/dist/learning-model.js +77 -0
  66. package/dist/learning-setting.d.ts +13 -0
  67. package/dist/learning-setting.js +23 -1
  68. package/dist/llms.txt +1 -0
  69. package/dist/model-form.js +12 -12
  70. package/dist/model.d.ts +5 -4
  71. package/dist/model.js +19 -13
  72. package/dist/openapi.js +203 -15
  73. package/dist/page.d.ts +1 -0
  74. package/dist/page.js +1 -1
  75. package/dist/paid-calls.d.ts +4 -1
  76. package/dist/paid-calls.js +1 -1
  77. package/dist/run-learning-served.d.ts +1 -1
  78. package/dist/run-secrets.d.ts +2 -2
  79. package/dist/run-secrets.js +6 -5
  80. package/dist/run-trace.js +6 -3
  81. package/dist/run-usage.d.ts +110 -0
  82. package/dist/run-usage.js +312 -0
  83. package/dist/runner/adapter-loop.d.ts +4 -1
  84. package/dist/runner/adapter-loop.js +52 -22
  85. package/dist/runner/adapter-run-spec.d.ts +3 -2
  86. package/dist/runner/adapter-run-spec.js +8 -4
  87. package/dist/runner/adapters/index.d.ts +4 -2
  88. package/dist/runner/adapters/index.js +6 -42
  89. package/dist/runner/cli-run-spec.js +10 -6
  90. package/dist/runner/conformance/harness.d.ts +2 -0
  91. package/dist/runner/conformance/harness.js +18 -4
  92. package/dist/runner/conformance/host-tools.d.ts +4 -0
  93. package/dist/runner/conformance/host-tools.js +14 -0
  94. package/dist/runner/feedback-round.d.ts +29 -1
  95. package/dist/runner/feedback-round.js +54 -3
  96. package/dist/runner/journal-kinds.d.ts +3 -1
  97. package/dist/runner/learning-end.js +49 -18
  98. package/dist/runner/loop-contract.d.ts +3 -0
  99. package/dist/runner/meta-tools.js +4 -2
  100. package/dist/runner/monid-run.js +2 -2
  101. package/dist/runner/presence.d.ts +3 -0
  102. package/dist/runner/presence.js +19 -12
  103. package/dist/runner/promotion.d.ts +62 -4
  104. package/dist/runner/promotion.js +154 -17
  105. package/dist/runner/reflect-hook.js +3 -2
  106. package/dist/runner/sdk-loop.js +25 -1
  107. package/dist/runner/workflow-spec.js +3 -2
  108. package/dist/runs-over-store.d.ts +5 -3
  109. package/dist/runs-over-store.js +11 -11
  110. package/dist/sdk/check.d.ts +31 -0
  111. package/dist/sdk/check.js +58 -0
  112. package/dist/sdk/runs.d.ts +10 -2
  113. package/dist/sdk/runs.js +87 -17
  114. package/dist/sdk/schema.js +11 -3
  115. package/dist/server.d.ts +6 -3
  116. package/dist/server.js +297 -98
  117. package/dist/store/index.d.ts +2 -2
  118. package/dist/store/index.js +1 -1
  119. package/dist/store/journal/storage.js +1 -1
  120. package/dist/store/open.d.ts +1 -1
  121. package/dist/store/open.js +1 -1
  122. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  123. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  124. package/dist/store/schema.d.ts +15 -1
  125. package/dist/store/schema.js +50 -5
  126. package/dist/store/sqlite/connection.d.ts +4 -1
  127. package/dist/store/sqlite/connection.js +5 -0
  128. package/dist/store/sqlite/run-patch.d.ts +8 -3
  129. package/dist/store/sqlite/run-patch.js +15 -7
  130. package/dist/store/sqlite/store.d.ts +5 -2
  131. package/dist/store/sqlite/store.js +283 -77
  132. package/dist/store/sqlite/worker.d.ts +9 -0
  133. package/dist/store/sqlite/worker.js +18 -1
  134. package/dist/store/store.d.ts +162 -27
  135. package/dist/store/store.js +63 -0
  136. package/dist/store-reads/analytics.js +2 -1
  137. package/dist/store-reads/cap.d.ts +8 -2
  138. package/dist/store-reads/cap.js +27 -3
  139. package/dist/store-reads/learning.d.ts +1 -1
  140. package/dist/store-reads/learning.js +5 -2
  141. package/dist/store-reads/runs.js +2 -0
  142. package/dist/store-reads/stats.js +4 -2
  143. package/dist/store-view.d.ts +12 -3
  144. package/dist/store-view.js +70 -27
  145. package/dist/template-eval.js +5 -2
  146. package/dist/template-github-permissions.d.ts +5 -1
  147. package/dist/template-github-permissions.js +7 -3
  148. package/dist/timeline/index.d.ts +1 -1
  149. package/dist/timeline/index.js +1 -1
  150. package/dist/timeline/timeline.d.ts +8 -0
  151. package/dist/timeline/timeline.js +18 -6
  152. package/dist/tool-gate.d.ts +8 -4
  153. package/dist/tool-gate.js +6 -7
  154. package/dist/tool-plane.d.ts +4 -0
  155. package/dist/tool-plane.js +10 -10
  156. package/dist/tools.js +9 -0
  157. package/dist/trigger-targets.d.ts +14 -2
  158. package/dist/trigger-targets.js +73 -4
  159. package/dist/triggers.d.ts +2 -1
  160. package/dist/triggers.js +5 -2
  161. package/dist/validate.d.ts +4 -2
  162. package/dist/validate.js +18 -4
  163. package/dist/viewer-credential.d.ts +24 -0
  164. package/dist/viewer-credential.js +53 -0
  165. package/dist/workspace/computer-for-claim.d.ts +5 -1
  166. package/dist/workspace/computer-for-claim.js +47 -18
  167. package/dist/workspace/computer-intervals.d.ts +20 -0
  168. package/dist/workspace/computer-intervals.js +49 -0
  169. package/dist/workspace/computer-janitor.d.ts +7 -3
  170. package/dist/workspace/computer-janitor.js +14 -6
  171. package/dist/workspace/computer-kept.d.ts +7 -2
  172. package/dist/workspace/computer-kept.js +9 -2
  173. package/dist/workspace/resolve-computer.d.ts +9 -1
  174. package/dist/workspace/resolve-computer.js +29 -22
  175. package/dist/workspace/run-end-computers.d.ts +1 -0
  176. package/dist/workspace/run-end-computers.js +4 -1
  177. package/package.json +18 -10
  178. package/templates/code-review/agent.md +2 -3
  179. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  180. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  181. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  182. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  183. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  184. package/dist/console/assets/index-BBFzAxLB.js +0 -715
  185. package/dist/console/assets/index-BRi-Rgq6.css +0 -1
@@ -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) };
@@ -24,8 +24,9 @@ export declare const WAITS_ON_A_PERSON = "The run is waiting on a person.";
24
24
  export declare function archiveRun(store: RunsStore, runId: string, archived: boolean): Promise<void>;
25
25
  /** Stops the run: one stop command row, which the run's runner reads and applies (it aborts the turn in flight, withdraws a
26
26
  * tool call waiting for approval, and ends the run stopped). A stop always lands — one command, no second path. An imported
27
- * or already-ended run has none to stop: `false`, nothing written (store.command refuses a final run, RunFinal). */
28
- export declare function stop(store: RunsStore, runId: string): Promise<boolean>;
27
+ * run, or one that reads ended (`moment.terminal`: one looking back after its job's end among them, whose end its
28
+ * look-back never undoes), has none to stop: `false`, nothing written (and store.command refuses a final run, RunFinal). */
29
+ export declare function stop(store: RunsStore, moment: RunMoment): Promise<boolean>;
29
30
  /** Cancels the run: one cancel command row, which the run's runner reads and applies (it ends the run cancelled, aborting
30
31
  * the turn in flight and cancelling a tool call waiting for approval). Returns whether a cancel was requested — the old
31
32
  * cancel's checks and their result, verbatim: an imported run, or one already ended or ending, has none to cancel (false,
@@ -107,7 +108,8 @@ export interface StartDeps {
107
108
  /** A new run id; defaults to a UUIDv7. */
108
109
  readonly newRunId?: () => string;
109
110
  /** 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). */
111
+ * runnersRefused); undefined while one can, or none is there yet. prepareLaunch, which holds no store, refuses a start
112
+ * with it (runner_refused); a reader that holds the store calls refuseWhileNoRunner on its runners instead. */
111
113
  runnersRefused?(): Promise<string | undefined>;
112
114
  /** The create body's field issues, before the agent is read (server.ts runBodyIssues). */
113
115
  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";
@@ -78,14 +78,16 @@ export async function archiveRun(store, runId, archived) {
78
78
  }
79
79
  /** Stops the run: one stop command row, which the run's runner reads and applies (it aborts the turn in flight, withdraws a
80
80
  * tool call waiting for approval, and ends the run stopped). A stop always lands — one command, no second path. An imported
81
- * or already-ended run has none to stop: `false`, nothing written (store.command refuses a final run, RunFinal). */
82
- export async function stop(store, runId) {
83
- const row = await store.runs.get(runId);
84
- if (!row || row.importedFrom)
81
+ * run, or one that reads ended (`moment.terminal`: one looking back after its job's end among them, whose end its
82
+ * look-back never undoes), has none to stop: `false`, nothing written (and store.command refuses a final run, RunFinal). */
83
+ export async function stop(store, moment) {
84
+ if (moment.importedSource !== undefined)
85
+ return false;
86
+ await refuseSdkStop(store, moment.id);
87
+ if (moment.terminal)
85
88
  return false;
86
- await refuseSdkStop(store, runId);
87
89
  try {
88
- await sendCommand(store, runId, { kind: "stop", body: {} });
90
+ await sendCommand(store, moment.id, { kind: "stop", body: {} });
89
91
  return true;
90
92
  }
91
93
  catch (error) {
@@ -158,9 +160,7 @@ export const resume = (store, moment) => pauseOrResume(store, moment, false);
158
160
  * which may skip it, in words. A runner applies every message, so while every runner here refused to claim, any message
159
161
  * (a person's or a trigger's) is refused in their words first, as a start is (prepareLaunch, runner/presence.ts). */
160
162
  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);
163
+ await refuseWhileNoRunner(store.runners);
164
164
  if (moment.importedSource !== undefined)
165
165
  throw importedRefusal(moment);
166
166
  const launchBody = await controlLaunchBody(store, moment.id);
@@ -511,7 +511,7 @@ export async function startInline(store, deps, inline, body, { origin, sealed }
511
511
  const entry = stored
512
512
  ? firstOfVersion ? { ...stored, agent: { ...stored.agent, name: inline.name, description: inline.description } } : stored
513
513
  : {
514
- agent: { id: uuidv7(), name: inline.name, description: inline.description, currentRevision: null, createdAt: Date.now(), archivedAt: null, externalRef: ref },
514
+ agent: { id: uuidv7(), name: inline.name, description: inline.description, currentRevision: null, createdAt: Date.now(), archivedAt: null, externalRef: ref, purgedAt: null },
515
515
  revision: null, version: 0, revisions: 0, sizes: new Map(),
516
516
  };
517
517
  // A store revision is the revision the run path reads as a pi Revision (its body is the revision body), as pinnedOf hands
@@ -0,0 +1,31 @@
1
+ import type { Shown } from "../learning.js";
2
+ import type { RunLaunch } from "../run-launch.js";
3
+ import type { Store } from "../store/store.js";
4
+ import type { SdkInbox } from "./runs.js";
5
+ export type SdkWorkflowCheckEvent = {
6
+ type: "workflow_check";
7
+ id: string;
8
+ digest: string;
9
+ outcome: "answered" | "handed_back" | "failed" | "skipped_write";
10
+ answer?: string;
11
+ reason?: string;
12
+ skipped?: {
13
+ tool: string;
14
+ unmarked?: true;
15
+ };
16
+ /** Fresh read-only calls the shadow made where the native recording had no result (the client's shadowReadFallback). */
17
+ fresh_reads?: number;
18
+ };
19
+ /** Settles a connected agent's check at its run's end. The client reports execution, never its own verdict, and the
20
+ * immutable completion is the baseline. A shadow that answered or handed back on a valid native turn is one row of the
21
+ * check (decideCheck); any other turn is given back (releaseSdkCheck) and the check waits for the next turn; a turn the
22
+ * backend never completed before its inbox expired is one failed row (sdkCheckDeadline). Exact retries and reclaims
23
+ * compete on the reservation. */
24
+ export declare function settleSdkCheck(deps: {
25
+ store: Store;
26
+ agentId: string;
27
+ launch: RunLaunch;
28
+ inbox: SdkInbox;
29
+ shown: () => Promise<Shown>;
30
+ log: (line: string) => void;
31
+ }): Promise<import("../learn/promote.js").Recorded | undefined>;
@@ -0,0 +1,58 @@
1
+ import { decideCheck, releaseSdkCheck, sdkCheckDeadline, sdkInputText } from "../runner/promotion.js";
2
+ import { promotionOf, promotionsOf } from "../learn/promote.js";
3
+ /** Why a completed inbox's native turn cannot be its check's baseline, or undefined when it can: a completed turn with
4
+ * complete, unredacted evidence and no learned workflow or nested call in it, whose shadow answered or handed back. */
5
+ function notBaseline(inbox, reported) {
6
+ const result = inbox.completion;
7
+ if (result.status !== "completed")
8
+ return `its native turn ${result.status === "cancelled" ? "was cancelled" : "failed"}`;
9
+ if (result.evidence_complete === false)
10
+ return "the backend reported its native turn's evidence incomplete";
11
+ if (inbox.check_redacted)
12
+ return "its native evidence held a protected value, so two different answers could agree by their placeholder";
13
+ if (inbox.batches.some((batch) => batch.events.some((event) => event.type === "tool" && (event.name === "learned_workflow" || event.parent_tool_use_id !== undefined))))
14
+ return "its native turn ran a learned workflow, so its answer is not the agent's own";
15
+ if (!reported)
16
+ return "the connected agent reported no shadow check";
17
+ if (reported.outcome === "failed")
18
+ return `its shadow did not answer (${reported.reason ?? "no reason given"})`;
19
+ if (reported.outcome === "skipped_write")
20
+ return `its shadow stopped at a write the native turn did not make (${reported.skipped?.tool ?? "a tool"})`;
21
+ return undefined;
22
+ }
23
+ /** Settles a connected agent's check at its run's end. The client reports execution, never its own verdict, and the
24
+ * immutable completion is the baseline. A shadow that answered or handed back on a valid native turn is one row of the
25
+ * check (decideCheck); any other turn is given back (releaseSdkCheck) and the check waits for the next turn; a turn the
26
+ * backend never completed before its inbox expired is one failed row (sdkCheckDeadline). Exact retries and reclaims
27
+ * compete on the reservation. */
28
+ export async function settleSdkCheck(deps) {
29
+ const { inbox } = deps;
30
+ const check = inbox.learning_check;
31
+ if (!check)
32
+ return;
33
+ const record = promotionOf(await promotionsOf(deps.store.settings, deps.agentId), check.workflow.name, check.digest);
34
+ if (record?.decided !== "replaying" || record.via !== "sdk" || record.replay_id !== check.id || !record.check || record.commit !== check.revision || record.runs?.[0] !== inbox.run_id)
35
+ return;
36
+ const completion = inbox.completion;
37
+ if (!completion) {
38
+ if (inbox.closed === "expired")
39
+ return sdkCheckDeadline(deps, record);
40
+ if (inbox.closed)
41
+ return releaseSdkCheck(deps, record, inbox.closed === "cancelled" ? "its native turn was stopped before the backend completed it" : "its native turn ended before the backend completed it");
42
+ return;
43
+ }
44
+ const reported = inbox.batches.flatMap((batch) => batch.events)
45
+ .find((event) => event.type === "workflow_check" && event.id === check.id && event.digest === check.digest);
46
+ const cause = notBaseline({ ...inbox, completion }, reported);
47
+ if (cause !== undefined || !reported)
48
+ return releaseSdkCheck(deps, record, cause ?? "the connected agent reported no shadow check");
49
+ const outcomes = { answered: 0, handed_back: 0, failed: 0, skipped_write: 0 };
50
+ outcomes[reported.outcome]++;
51
+ return decideCheck(deps, check.workflow.name, check.digest, record.check, {
52
+ rows: [{ of: inbox.run_id, input: sdkInputText(deps.launch), agent: completion.answer, outcome: reported.outcome,
53
+ answer: reported.outcome === "answered" ? reported.answer ?? null : null,
54
+ ...(reported.outcome === "handed_back" ? { escalated: reported.reason ?? "The shadow workflow handed the task back." } : {}),
55
+ }], cost: null, outcomes, unstarted: 0, ...(reported.fresh_reads ? { fresh_reads: reported.fresh_reads } : {}),
56
+ exactMismatchReason: "its answer did not match the native answer exactly; connected SDK checks do not use a semantic grader, so name the fields that carry the decision (learning.agree_on) when whole-answer equality is not the intended check",
57
+ }, (was) => was?.decided === "replaying" && was.replay_id === check.id, { via: "sdk", runs: record.runs, replay_id: check.id, commit: check.revision });
58
+ }
@@ -2,6 +2,8 @@ import type { Claim, RunOrigin, Store } from "../store/store.js";
2
2
  import type { AgentEntry } from "../agents-store.js";
3
3
  import { type StartDeps } from "../runs-over-store.js";
4
4
  import { type LearnedWorkflow } from "../learning.js";
5
+ import type { SdkWorkflowCheckEvent } from "./check.js";
6
+ import { type SdkWorkflowCheck } from "../runner/promotion.js";
5
7
  export type SdkRuntime = "claude-agent-sdk" | "codex-sdk" | "eve";
6
8
  export type SdkUsage = {
7
9
  input_tokens: number | null;
@@ -10,7 +12,7 @@ export type SdkUsage = {
10
12
  cache_write_tokens: number | null;
11
13
  cost_usd: number | null;
12
14
  };
13
- export type SdkEvent = {
15
+ export type SdkEvent = SdkWorkflowCheckEvent | {
14
16
  type: "text";
15
17
  text: string;
16
18
  } | {
@@ -42,8 +44,12 @@ export type SdkInbox = {
42
44
  sequence: number;
43
45
  events: SdkEvent[];
44
46
  }[];
45
- /** Exact approved executable workflows delivered by the start receipt. */
47
+ /** Exact promoted executable workflows delivered by the start receipt. */
46
48
  learning_workflows?: LearnedWorkflow[];
49
+ /** A compiled draft reserved for a shadow check, never supplied to the native agent. */
50
+ learning_check?: SdkWorkflowCheck;
51
+ /** Server cleaning changed evidence: two different secret-bearing answers must never agree by their placeholder. */
52
+ check_redacted?: true;
47
53
  completion?: SdkCompletion;
48
54
  /** Internal terminal admission fence. No later evidence can be newly acknowledged after this CAS wins. */
49
55
  closed?: "expired" | "failed" | "cancelled";
@@ -81,6 +87,7 @@ export declare class SdkRuns {
81
87
  console_url: string;
82
88
  token: string;
83
89
  learning: {
90
+ check?: SdkWorkflowCheck | undefined;
84
91
  enabled: boolean;
85
92
  revision: string | null;
86
93
  context: string;
@@ -93,6 +100,7 @@ export declare class SdkRuns {
93
100
  console_url: string;
94
101
  token: string;
95
102
  learning: {
103
+ check?: SdkWorkflowCheck | undefined;
96
104
  enabled: boolean;
97
105
  revision: string | null;
98
106
  context: string;
package/dist/sdk/runs.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Backend SDK calls remain in their application. This inbox only records their evidence and immutable completion;
2
2
  // the ordinary fenced runner owns journals, reflection, checking and learning commits.
3
3
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
4
- import { inspectWorkflow } from "@parcha/agentrun-dsl";
4
+ import { inspectWorkflow, resolveSchemaForWorkflow } from "@parcha/agentrun-dsl";
5
5
  import { ApiError } from "../errors.js";
6
6
  import { canonical, isObject } from "../store/agent-body.js";
7
7
  import { uuidv7 } from "../agents-store.js";
@@ -9,10 +9,14 @@ import { launchBody } from "../run-launch.js";
9
9
  import { learningStartFor } from "../runs-over-store.js";
10
10
  import { chooseWorkflows, learningFolderOf, seedAt, secretsShown } from "../learning.js";
11
11
  import { INSTRUCTION_EVIDENCE_BYTES } from "../native/instructions.js";
12
+ import { refuseWhileNoRunner } from "../runner/presence.js";
12
13
  import { secretRedactor } from "../runner/redact.js";
13
14
  import { redactedOutput } from "../key-refusal.js";
14
15
  import { decodedStrings, draftProblems } from "../learn/workflow-draft.js";
15
16
  import { sdkWorkflowManifest, sdkDraftTools } from "./workflows.js";
17
+ import { promotionOf, promotionsOf } from "../learn/promote.js";
18
+ import { championTextOf, releaseSdkCheck, reserveSdkCheck } from "../runner/promotion.js";
19
+ import { fits, workflowDigest } from "../runner/workflow-first.js";
16
20
  const keyOf = (id) => `sdk-run:${id}`;
17
21
  /** The settings key an SDK run's record is kept under (the run's delete with its agent's: agent-delete.ts). */
18
22
  export const sdkRunKey = keyOf;
@@ -189,9 +193,7 @@ export class SdkRuns {
189
193
  throw new ApiError("agent_not_runnable", "AgentRun cannot enforce a spend cap on an external SDK. Configure the budget in the backend SDK and remove this managed run cap.");
190
194
  // A runner keeps an SDK run's evidence and ends it: while every runner here refused to claim, the start is refused in
191
195
  // their words, as any start is (prepareLaunch), before the caller holds a receipt it would run on.
192
- const refused = await deps.runnersRefused?.();
193
- if (refused !== undefined)
194
- throw new ApiError("runner_refused", refused);
196
+ await refuseWhileNoRunner(this.store.runners);
195
197
  const learning = await learningStartFor(deps, entry, pinned.revision, revisionBody, {
196
198
  noWorkflows: !workflow,
197
199
  ...(compile.model ? { model: compile.model } : {}),
@@ -205,9 +207,24 @@ export class SdkRuns {
205
207
  if (learning.seedFailed)
206
208
  throw new ApiError("unavailable", "The learning seed could not be read. Retry after restoring the agent learning folder.");
207
209
  }
208
- const workflows = learning && !learning.noWorkflows && workflow ? await this.selectedWorkflows(entry.agent.id, learning.seed, workflow) : [];
210
+ const selected = learning && !learning.noWorkflows && workflow ? await this.selectedWorkflows(entry.agent.id, learning.seed, workflow) : { workflows: [], candidates: [] };
209
211
  const cleaned = this.clean({ instructions, ...(model ? { model } : {}) });
210
212
  const runId = uuidv7();
213
+ const redacted = cleanedInput !== input || cleaned.instructions !== instructions;
214
+ let task;
215
+ try {
216
+ task = JSON.parse(input);
217
+ }
218
+ catch { /* A prose task: the client resolves the draft's input from the turn. */ }
219
+ // A turn is a check only when it can be one's baseline: no protected value in its task or policy, and an input the
220
+ // draft takes. A JSON object task is the input, so it must fit (the managed check's own rule); a prose task's input
221
+ // is resolved by the client from the turn's recorded tool inputs or the host's resolveCheckInput, and a turn it
222
+ // cannot resolve is given back (releaseSdkCheck), never counted.
223
+ const takes = (flow) => !redacted && (!isObject(task) || fits(flow, task, resolveSchemaForWorkflow));
224
+ const checkDeps = { store: this.store, agentId: entry.agent.id, log: () => { }, shown: async () => secretsShown(this.secrets(), { local: true }) };
225
+ const check = learning ? await reserveSdkCheck(checkDeps, { runId, revision: learning.seed, learning: revisionBody.learning, flows: selected.candidates, takes }) : undefined;
226
+ // A shadow check needs the original agent's own answer, not an answer produced by its existing champion.
227
+ const workflows = check ? [] : selected.workflows;
211
228
  const launch = {
212
229
  input: { content: cleanedInput },
213
230
  title: cleanedInput.trim().replace(/\s+/g, " ").slice(0, 80),
@@ -222,18 +239,27 @@ export class SdkRuns {
222
239
  ...(learning ? { learning: { ...learning, workflows: workflows.map((flow) => flow.name) } } : {}),
223
240
  };
224
241
  const now = Date.now();
225
- await this.store.settings.put(keyOf(runId), {
226
- run_id: runId,
227
- created_at: now,
228
- expires_at: now + 3_600_000,
229
- batches: [],
230
- learning_workflows: workflows,
231
- });
232
242
  try {
243
+ await this.store.settings.put(keyOf(runId), {
244
+ run_id: runId,
245
+ created_at: now,
246
+ expires_at: now + 3_600_000,
247
+ batches: [],
248
+ learning_workflows: workflows,
249
+ ...(check ? { learning_check: check } : {}),
250
+ ...(redacted ? { check_redacted: true } : {}),
251
+ });
233
252
  await this.store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: entry.revision.id, ...(origin ? { origin } : {}) }, { body: launchBody(launch) });
234
253
  }
235
254
  catch (error) {
236
255
  await this.store.settings.remove(keyOf(runId));
256
+ // The reservation comes first because the launch it is created with withholds the champion from a check's turn.
257
+ // No turn ran, so the check waits for the next one, the release uncounted: never a hold of a draft never compared.
258
+ if (check) {
259
+ const record = promotionOf(await promotionsOf(this.store.settings, entry.agent.id).catch(() => []), check.workflow.name, check.digest);
260
+ if (record?.decided === "replaying" && record.replay_id === check.id)
261
+ await releaseSdkCheck(checkDeps, record, "its start could not be admitted", false).catch(() => undefined);
262
+ }
237
263
  throw error;
238
264
  }
239
265
  return this.receipt(runId, consoleOrigin);
@@ -247,7 +273,7 @@ export class SdkRuns {
247
273
  const workflows = inbox.learning_workflows ?? [];
248
274
  const shown = secretsShown(this.secrets(), { local: true });
249
275
  if (shown.holds(launch.learning?.section ?? "") ||
250
- workflows.some((flow) => {
276
+ [...workflows, ...(inbox.learning_check ? [inbox.learning_check.workflow] : [])].some((flow) => {
251
277
  const decoded = decodedStrings(flow.workflow);
252
278
  return shown.holds(flow.name) || shown.holds(flow.description) || shown.holds(flow.workflow) || decoded === "too_deep" || decoded.some(shown.holds);
253
279
  }))
@@ -262,6 +288,7 @@ export class SdkRuns {
262
288
  revision: launch.learning?.seed ?? null,
263
289
  context: launch.learning?.section ?? "",
264
290
  workflows,
291
+ ...(inbox.learning_check ? { check: inbox.learning_check } : {}),
265
292
  },
266
293
  };
267
294
  }
@@ -272,14 +299,25 @@ export class SdkRuns {
272
299
  const { flows } = chooseWorkflows(seed, secretsShown(this.secrets(), { local: true }));
273
300
  const dsl = await import("@parcha/agentrun-dsl");
274
301
  const { tools, gated, deniedBy } = sdkDraftTools(binding.workflow_tools);
302
+ const records = await promotionsOf(this.store.settings, agentId);
275
303
  let room = 256 * 1024;
276
- return flows.filter((flow) => {
304
+ const compatible = (flow) => {
277
305
  const bytes = Buffer.byteLength(JSON.stringify(flow));
278
306
  if (bytes > room || draftProblems(dsl, flow.workflow, tools, gated, deniedBy, undefined, binding.workflow_adapters).length)
279
307
  return false;
280
308
  room -= bytes;
281
309
  return true;
282
- });
310
+ };
311
+ const workflows = [], candidates = [];
312
+ const atCommit = async (name, commit) => chooseWorkflows(await seedAt(folder.workspace, commit), secretsShown(this.secrets(), { local: true })).flows.find((one) => one.name === name);
313
+ for (const flow of flows) {
314
+ const { text: serving } = await championTextOf(records, flow, atCommit);
315
+ if (serving && compatible(serving))
316
+ workflows.push(serving);
317
+ if ((!serving || workflowDigest(serving) !== workflowDigest(flow)) && compatible(flow))
318
+ candidates.push(flow);
319
+ }
320
+ return { workflows, candidates };
283
321
  }
284
322
  finally {
285
323
  await folder.end();
@@ -324,6 +362,31 @@ export class SdkRuns {
324
362
  only(value, ["type", "session_id"]);
325
363
  return { type: "session", session_id: text(value.session_id, "session_id", 256) };
326
364
  }
365
+ if (value.type === "workflow_check") {
366
+ only(value, ["type", "id", "digest", "outcome", "answer", "reason", "skipped", "fresh_reads"]);
367
+ if (value.fresh_reads !== undefined && (!Number.isSafeInteger(value.fresh_reads) || value.fresh_reads < 1 || value.fresh_reads > 256))
368
+ refuse("fresh_reads must be an integer from 1 to 256 when supplied.");
369
+ if (!["answered", "handed_back", "failed", "skipped_write"].includes(String(value.outcome)))
370
+ refuse("Invalid workflow check outcome.");
371
+ if (value.outcome === "answered" && typeof value.answer !== "string")
372
+ refuse("An answered workflow check needs its answer.");
373
+ if (value.skipped !== undefined) {
374
+ if (!isObject(value.skipped))
375
+ refuse("A skipped workflow check names its tool.");
376
+ only(value.skipped, ["tool", "unmarked"]);
377
+ text(value.skipped.tool, "skipped.tool", 256);
378
+ if (value.skipped.unmarked !== undefined && value.skipped.unmarked !== true)
379
+ refuse("skipped.unmarked must be true when supplied.");
380
+ }
381
+ if (value.outcome === "skipped_write" && value.skipped === undefined)
382
+ refuse("A skipped write names its tool.");
383
+ return { type: "workflow_check", id: text(value.id, "id", 256), digest: text(value.digest, "digest", 256), outcome: value.outcome,
384
+ ...(value.answer !== undefined ? { answer: text(value.answer, "answer") } : {}),
385
+ ...(value.reason !== undefined ? { reason: text(value.reason, "reason", 8000) } : {}),
386
+ ...(value.skipped !== undefined ? { skipped: value.skipped } : {}),
387
+ ...(value.fresh_reads !== undefined ? { fresh_reads: value.fresh_reads } : {}),
388
+ };
389
+ }
327
390
  if (value.type === "tool") {
328
391
  only(value, ["type", "id", "name", "status", "input", "output", "parent_tool_use_id"]);
329
392
  if (!["started", "completed", "failed"].includes(String(value.status)))
@@ -341,6 +404,7 @@ export class SdkRuns {
341
404
  return refuse("Unsupported SDK event type.");
342
405
  });
343
406
  const batch = this.clean({ sequence: body.sequence, events }, runId);
407
+ const checkRedacted = canonical(events) !== canonical(batch.events);
344
408
  const known = (await sdkInbox(this.store, runId)).batches.find((item) => item.sequence === batch.sequence);
345
409
  if (known) {
346
410
  if (canonical(known) !== canonical(batch))
@@ -361,7 +425,13 @@ export class SdkRuns {
361
425
  if (batch.sequence !== row.batches.length + 1)
362
426
  throw new ApiError("idempotency_mismatch", "SDK event sequences must be contiguous.");
363
427
  checkToolParents(row, batch.events);
364
- return { ...row, batches: [...row.batches, batch] };
428
+ const checks = [...row.batches.flatMap(item => item.events), ...batch.events].filter((event) => event.type === "workflow_check");
429
+ if (checks.length > 1)
430
+ refuse("Only one workflow check may be delivered per SDK run.");
431
+ for (const check of checks)
432
+ if (!row.learning_check || check.id !== row.learning_check.id || check.digest !== row.learning_check.digest)
433
+ refuse("The workflow check must name this SDK run's reserved candidate.");
434
+ return { ...row, batches: [...row.batches, batch], ...(checkRedacted ? { check_redacted: true } : {}) };
365
435
  }, EVIDENCE_LIMIT);
366
436
  return { accepted: true };
367
437
  }
@@ -394,7 +464,7 @@ export class SdkRuns {
394
464
  return row;
395
465
  }
396
466
  writableInbox(row);
397
- return { ...row, completion };
467
+ return { ...row, completion, ...(completion.answer !== body.answer ? { check_redacted: true } : {}) };
398
468
  });
399
469
  return { accepted: true };
400
470
  }
@@ -25,6 +25,13 @@ const event = {
25
25
  oneOf: [
26
26
  object({ type: { const: "text" }, text: { ...text, maxLength: 128000 } }),
27
27
  object({ type: { const: "session" }, session_id: { ...text, maxLength: 256 } }),
28
+ object({
29
+ type: { const: "workflow_check" }, id: { ...text, maxLength: 256 }, digest: { ...text, maxLength: 256 },
30
+ outcome: { enum: ["answered", "handed_back", "failed", "skipped_write"] },
31
+ answer: { ...text, maxLength: 128000 }, reason: { ...text, maxLength: 8000 },
32
+ skipped: object({ tool: { ...text, maxLength: 256 }, unmarked: { const: true } }, ["tool"]),
33
+ fresh_reads: { type: "integer", minimum: 1, maximum: 256 },
34
+ }, ["type", "id", "digest", "outcome"]),
28
35
  object({
29
36
  type: { const: "tool" },
30
37
  id: { ...text, maxLength: 256 },
@@ -49,15 +56,16 @@ const learning = object({
49
56
  enabled: { type: "boolean" },
50
57
  revision: { type: ["string", "null"] },
51
58
  context: { ...text, description: "The agent's corrections.md as the run reads it under # Learned; empty when Off or nothing is learned yet." },
52
- workflows: { type: "array", items: object({ name: text, workflow: text, description: text }), description: "Active, capability-compatible learned workflows pinned to this run; empty without a backend workflow bridge or when learning is Off." },
53
- });
59
+ workflows: { type: "array", items: object({ name: text, workflow: text, description: text }), description: "Promoted, capability-compatible learned workflows pinned to this run; empty without a backend workflow bridge, during an independent shadow-check turn, or when learning is Off." },
60
+ check: { ...object({ id: text, revision: text, digest: text, workflow: object({ name: text, workflow: text, description: text }) }), description: "One compiled draft reserved for a shadow check against this run's native answer. Keep outside the model context; replay only recorded tool results after the native turn and submit workflow_check evidence." },
61
+ }, ["enabled", "revision", "context", "workflows"]);
54
62
  export const SDK_PATHS = {
55
63
  "/agents/{agent_id}/sdk-runs": {
56
64
  post: {
57
65
  ...mark,
58
66
  operationId: "startSdkRun",
59
67
  summary: "Register a task executed by an existing backend SDK",
60
- description: "Requires an SDK agent definition. Captures the actual original policy and input, pins approved learning, and returns a credential scoped to this run. The backend retains all model/tool/auth settings. Learning requires a configured server reflection/grading model; learning Off needs no server model key.",
68
+ description: "Requires an SDK agent definition. Captures the actual original policy and input, pins promoted workflows and any compiled shadow-check candidate separately, and returns a credential scoped to this run. The backend retains all model/tool/auth settings. Learning requires a configured server reflection/grading model; learning Off needs no server model key.",
61
69
  parameters: [id("agent_id"), { ...key, required: true }],
62
70
  requestBody: body(object({
63
71
  runtime: SDK_BINDING.properties.runtime,
package/dist/server.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type LearningModel } from "./learning-model.js";
1
2
  import { type Server } from "node:http";
2
3
  import { type ModelNeeds } from "./model.js";
3
4
  import { type HarnessCapability } from "./harness.js";
@@ -207,9 +208,9 @@ export type ServeOptions = {
207
208
  /** A test's seam: step 2 of DELETE /agents/{id} (agent-delete.ts) in place of the learning module's deleteLearning over
208
209
  * the agent's learning folder (learn/delete.ts), the server's own. */
209
210
  deleteLearning?: DeleteLearning;
210
- /** A test's seam: awaited at each step's point of DELETE /agents/{id} (agent-delete.ts AgentDeleteStep), so a throw
211
- * there stops the delete as a crash would. */
212
- agentDeleteAt?: (step: AgentDeleteStep, agentId: string) => void | Promise<void>;
211
+ /** A test's seam: awaited at each step's point of DELETE /agents/{id} and DELETE /runs/{id} (agent-delete.ts
212
+ * AgentDeleteStep), with the agent's id or the run's, so a throw there stops the delete as a crash would. */
213
+ agentDeleteAt?: (step: AgentDeleteStep, id: string) => void | Promise<void>;
213
214
  /** A test's seam: awaited with a request's path and answer once its work under an Idempotency-Key is done, before the
214
215
  * answer is kept, so a test can hold a request there while a DELETE /agents/{id} runs. */
215
216
  beforeKeep?: (path: string, answer: unknown) => void | Promise<void>;
@@ -384,6 +385,7 @@ export declare function readingOf(base: NodeJS.ProcessEnv, maxRuns: number, stor
384
385
  fast: string | null;
385
386
  strong: string | null;
386
387
  };
388
+ learning_model: LearningModel;
387
389
  /** `pending`: a workflow draft with a call no price covers is kept to wait for its owner's OK, served to no run;
388
390
  * `approve`: whether the caller can approve one, which takes the owner's password session (forCaller), and
389
391
  * `approve_needs` when not. */
@@ -704,6 +706,7 @@ export declare function capabilities(env?: NodeJS.ProcessEnv, maxRuns?: number,
704
706
  fast: string | null;
705
707
  strong: string | null;
706
708
  };
709
+ learning_model: LearningModel;
707
710
  /** `pending`: a workflow draft with a call no price covers is kept to wait for its owner's OK, served to no run;
708
711
  * `approve`: whether the caller can approve one, which takes the owner's password session (forCaller), and
709
712
  * `approve_needs` when not. */