opencode-model-router 1.5.0 → 1.7.0

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.
@@ -22,6 +22,12 @@ export interface GraderRequest {
22
22
  tier: string;
23
23
  system: string;
24
24
  prompt: string;
25
+ /**
26
+ * Producer working directory. When present, the grader session MUST be scoped
27
+ * to this directory so any file-existence / command claims the grader verifies
28
+ * are checked against the producer's cwd, not the grader's own session cwd.
29
+ */
30
+ cwd?: string;
25
31
  }
26
32
 
27
33
  export interface GraderResult {
@@ -45,6 +51,8 @@ export interface CheckerInput {
45
51
  artefact: ArtefactView;
46
52
  producerTier: string;
47
53
  producerSessionID: string;
54
+ /** Effective producer working directory; scopes the grader + informs its prompt. */
55
+ workingDir?: string;
48
56
  }
49
57
 
50
58
  // ---------------------------------------------------------------------------
@@ -76,9 +84,42 @@ export function atLeastProducerTier(
76
84
  const GRADER_SYSTEM =
77
85
  'You are an independent, skeptical verification grader. You did NOT produce this work and have no stake in it. Evaluate ONLY whether the artefact satisfies EACH acceptance criterion below. For every criterion, cite concrete evidence from the artefact. If the evidence is missing, ambiguous, partial, or you are uncertain for ANY reason, you MUST fail that criterion. Default to FAIL. Do not give the benefit of the doubt. Output ONLY a single JSON object on one line: {"pass": boolean, "reasons": string[]}. Set pass=true ONLY if every criterion is satisfied with cited evidence; otherwise pass=false with a reason per failed criterion.';
78
86
 
87
+ /** Upper bound on the working-directory string interpolated into the prompt. */
88
+ const MAX_WORKING_DIR_CHARS = 512;
89
+
90
+ /**
91
+ * Make an attacker-influenced value safe to interpolate into a single prompt
92
+ * line. The working directory reaches us from a delegate tool argument, i.e.
93
+ * from model output, so it is untrusted text: scrubText strips secrets, and
94
+ * collapsing newlines and control characters stops a crafted path from ending
95
+ * the line and forging further instructions to the grader.
96
+ */
97
+ function sanitizeOneLine(value: string): string {
98
+ const cleaned = scrubText(value)
99
+ // C0 controls, DEL, the C1 block, and the Unicode LINE/PARAGRAPH
100
+ // SEPARATORS. U+2028 and U+2029 matter as much as \n here: plenty of
101
+ // renderers and tokenizers treat them as line breaks, so leaving them in
102
+ // would reopen the forged-instruction hole that stripping \n closes.
103
+ // eslint-disable-next-line no-control-regex
104
+ .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ")
105
+ .trim();
106
+ // A path has no legitimate reason to be long, and an unbounded one lets a
107
+ // caller push the real criteria out of the grader's attention.
108
+ return cleaned.length > MAX_WORKING_DIR_CHARS
109
+ ? cleaned.slice(0, MAX_WORKING_DIR_CHARS) + "…(truncated)"
110
+ : cleaned;
111
+ }
112
+
79
113
  export function buildGradingPrompt(input: CheckerInput): { system: string; prompt: string } {
80
114
  const lines: string[] = [];
81
115
 
116
+ if (input.workingDir) {
117
+ lines.push(
118
+ `Producer working directory: ${sanitizeOneLine(input.workingDir)}. Any file-existence or command claims MUST be verified against THIS directory, not your own session directory.`,
119
+ );
120
+ lines.push("");
121
+ }
122
+
82
123
  lines.push("## Acceptance criteria (ALL must be satisfied)");
83
124
  for (let i = 0; i < input.criteria.length; i++) {
84
125
  lines.push(`${i + 1}. ${input.criteria[i]}`);
@@ -181,7 +222,12 @@ export async function runChecker(input: CheckerInput, deps: CheckerDeps): Promis
181
222
  // 4. Dispatch grader
182
223
  let res: GraderResult;
183
224
  try {
184
- res = await deps.dispatchGrader({ tier: graderTier, system, prompt });
225
+ res = await deps.dispatchGrader({
226
+ tier: graderTier,
227
+ system,
228
+ prompt,
229
+ ...(input.workingDir ? { cwd: input.workingDir } : {}),
230
+ });
185
231
  } catch (err) {
186
232
  return {
187
233
  pass: false,
@@ -1,10 +1,13 @@
1
1
  // src/verify/deterministic.ts
2
2
  // Deterministic verifier: runs DoD checks using injected seams (no real fs/exec imports).
3
- // PURE: no Node built-ins; all I/O goes through DeterministicDeps seams.
3
+ // PURE: no I/O-capable Node built-ins; all I/O goes through DeterministicDeps
4
+ // seams. ./paths is pure path math (node:path only) and keeps that contract.
4
5
 
5
6
  import type { Check, DoD } from "./dod";
6
7
  import type { Verdict, DeterministicDeps, MutexRegistry, ExecResult } from "./types";
7
8
  import { scrubText } from "../guard/scrub";
9
+ import { resolveAgainst } from "./paths";
10
+ import { isAbsolute } from "node:path";
8
11
 
9
12
  // ---------------------------------------------------------------------------
10
13
  // MutexRegistry — per-key serialization via promise-chaining
@@ -113,9 +116,14 @@ interface CheckResult {
113
116
  async function runFileExists(check: Check, deps: DeterministicDeps): Promise<CheckResult> {
114
117
  try {
115
118
  if (!check.path) return { ok: false, reason: "fileExists check missing 'path'" };
116
- const ok = await deps.fs.fileExists(check.path);
119
+ const resolved = resolveAgainst(deps.cwd, check.path);
120
+ const ok = await deps.fs.fileExists(resolved);
117
121
  if (ok) return { ok: true, evidence: `exists: ${check.path}` };
118
- return { ok: false, reason: `file not found: ${check.path}` };
122
+ // An absolute check path ignores deps.cwd entirely, so claiming the file
123
+ // was missing "in <cwd>" would name a directory the check never looked in.
124
+ return isAbsolute(check.path)
125
+ ? { ok: false, reason: `file not found: ${resolved}` }
126
+ : { ok: false, reason: `file not found in ${deps.cwd}: ${check.path}` };
119
127
  } catch (err) {
120
128
  return { ok: false, reason: `fileExists check errored: ${scrubText(String(err))}` };
121
129
  }
@@ -214,7 +222,7 @@ async function runSchemaMatch(check: Check, deps: DeterministicDeps): Promise<Ch
214
222
  return { ok: false, reason: "schemaMatch requires 'path' and 'schema'" };
215
223
  }
216
224
 
217
- const targetRaw = await deps.fs.readFile(check.path);
225
+ const targetRaw = await deps.fs.readFile(resolveAgainst(deps.cwd, check.path));
218
226
  let targetVal: unknown;
219
227
  try {
220
228
  targetVal = JSON.parse(targetRaw);
@@ -230,7 +238,7 @@ async function runSchemaMatch(check: Check, deps: DeterministicDeps): Promise<Ch
230
238
  return { ok: false, reason: "schema is not valid JSON" };
231
239
  }
232
240
  } else {
233
- const schemaRaw = await deps.fs.readFile(check.schema);
241
+ const schemaRaw = await deps.fs.readFile(resolveAgainst(deps.cwd, check.schema));
234
242
  try {
235
243
  schemaVal = JSON.parse(schemaRaw);
236
244
  } catch {
@@ -8,6 +8,12 @@ import type { RouterConfig } from "../router/config";
8
8
  import { getActiveTiers } from "../router/protocol";
9
9
  import { parseDoDFromDispatch, inferDoD } from "./dod";
10
10
  import type { DoD, InferHints } from "./dod";
11
+ import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
12
+
13
+ export interface ChangedFileStoreOptions {
14
+ /** Injectable clock (tests). Defaults to Date.now. */
15
+ now?: () => number;
16
+ }
11
17
 
12
18
  /** Tools that mutate the workspace (mirrors the guard taxonomy). */
13
19
  const WRITE_TOOLS = new Set(["write", "edit", "patch", "multiedit"]);
@@ -39,10 +45,23 @@ export function extractChangedFile(tool: string, args: unknown): ChangedFile | n
39
45
  * by observing that session's own edit/write tool calls (ADR 0002 D3 — NOT a
40
46
  * global git diff), which is concurrency-safe under interleaved subagents.
41
47
  */
42
- export function createChangedFileStore() {
48
+ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
49
+ const now = options.now ?? Date.now;
43
50
  const bySession = new Map<string, Map<string, string>>();
51
+ const lastTouch = new Map<string, number>();
52
+
53
+ function touch(sessionID: string): void {
54
+ lastTouch.set(sessionID, now());
55
+ }
56
+
57
+ function evict(sessionID: string): void {
58
+ bySession.delete(sessionID);
59
+ lastTouch.delete(sessionID);
60
+ }
61
+
44
62
  return {
45
63
  record(sessionID: string, tool: string, args: unknown): void {
64
+ touch(sessionID);
46
65
  const cf = extractChangedFile(tool, args);
47
66
  if (!cf) return;
48
67
  let m = bySession.get(sessionID);
@@ -60,7 +79,13 @@ export function createChangedFileStore() {
60
79
  return [...m.entries()].map(([path, status]) => ({ path, status }));
61
80
  },
62
81
  clear(sessionID: string): void {
63
- bySession.delete(sessionID);
82
+ evict(sessionID);
83
+ },
84
+ /** Evict every session idle for >= ttlMs. Future stamps are never evicted. */
85
+ sweep(nowMs: number = now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): void {
86
+ for (const [sessionID, stamp] of [...lastTouch.entries()]) {
87
+ if (nowMs - stamp >= ttlMs) evict(sessionID);
88
+ }
64
89
  },
65
90
  };
66
91
  }
@@ -23,6 +23,7 @@ import { isCheckable } from "./dod";
23
23
  import { runDeterministic } from "./deterministic";
24
24
  import { runChecker } from "./checker";
25
25
  import type { ArtefactView, CheckerDeps } from "./checker";
26
+ import { resolveBaseDir } from "./paths";
26
27
 
27
28
  /** The concrete, inspectable result of a delegation (artefact contract §3.3). */
28
29
  export interface Artefact {
@@ -40,6 +41,13 @@ export interface Delegation {
40
41
  trivial?: boolean;
41
42
  /** Mode A (on-the-fly) vs Mode B (plan annotation) — drives the no-DoD message. */
42
43
  mode?: "modeA" | "modeB";
44
+ /**
45
+ * Working directory the producer was told to work in. When present it becomes
46
+ * the base directory for verification: relative deterministic-check paths
47
+ * resolve against it, and the grader is scoped to it. Absent means "the
48
+ * router's own directory", which is the pre-existing behaviour exactly.
49
+ */
50
+ cwd?: string;
43
51
  }
44
52
 
45
53
  export interface GateDeps {
@@ -146,9 +154,21 @@ export async function accept(
146
154
  // The two wirings (Option i verify-dispatch / Option ii delegate tool) still
147
155
  // wrap accept() defensively so that any unexpected throw surfaces as a
148
156
  // visible failure (forcing note / honest status), never a silent accept.
157
+ // A delegation that declared a working directory must be verified against
158
+ // THAT directory, not the router's. Both verifiers get the same effective
159
+ // base dir so a deterministic check and a grader can never disagree about
160
+ // where the work was supposed to land.
161
+ const effectiveBaseDir = resolveBaseDir(
162
+ delegation.cwd,
163
+ deps.deterministic.cwd,
164
+ );
165
+
149
166
  let verdict: Verdict;
150
167
  if (dod.kind === "deterministic") {
151
- verdict = await runDeterministic(dod, deps.deterministic);
168
+ verdict = await runDeterministic(dod, {
169
+ ...deps.deterministic,
170
+ cwd: effectiveBaseDir,
171
+ });
152
172
  } else {
153
173
  // "checker" is the only remaining checkable kind.
154
174
  verdict = await runChecker(
@@ -157,6 +177,10 @@ export async function accept(
157
177
  artefact: view(artefact),
158
178
  producerTier: artefact.producerTier,
159
179
  producerSessionID: artefact.producerSessionID,
180
+ // Only when the delegation actually declared one. Passing the router's
181
+ // own directory here would scope every existing grader and add a
182
+ // working-directory line to every existing prompt for no reason.
183
+ ...(delegation.cwd ? { workingDir: effectiveBaseDir } : {}),
160
184
  },
161
185
  deps.checker,
162
186
  );
@@ -0,0 +1,29 @@
1
+ // src/verify/paths.ts
2
+ // Pure path helpers for scoping verification to a producer subagent's working
3
+ // directory. Path math only (no fs/exec/network I/O), so this stays inside the
4
+ // verifier's purity contract while letting deterministic checks and the grader
5
+ // resolve relative paths against an effective base dir instead of the router's
6
+ // own cwd.
7
+
8
+ import { isAbsolute, join } from "node:path";
9
+
10
+ /**
11
+ * Resolve the effective base directory for a delegation's verification.
12
+ * - no cwd -> the router's own directory (byte-identical default)
13
+ * - absolute cwd -> that cwd
14
+ * - relative cwd -> joined onto the router directory
15
+ */
16
+ export function resolveBaseDir(cwd: string | undefined, routerDir: string): string {
17
+ if (!cwd) return routerDir;
18
+ if (isAbsolute(cwd)) return cwd;
19
+ return join(routerDir, cwd);
20
+ }
21
+
22
+ /**
23
+ * Resolve a (possibly relative) path against a base directory. Absolute paths
24
+ * are returned unchanged so downstream fs seams that special-case absolute
25
+ * paths bypass their own (router-scoped) join.
26
+ */
27
+ export function resolveAgainst(baseDir: string, p: string): string {
28
+ return isAbsolute(p) ? p : join(baseDir, p);
29
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * src/verify/timeout.ts — shared time-box primitives for delegation.
3
+ *
4
+ * Lives in its own module so both the plugin factory (src/index.ts, producer
5
+ * prompt + verification gate) and the impure verification wiring
6
+ * (src/verify/wiring.ts, grader prompt) can import it without either importing
7
+ * the other. An index -> wiring -> index cycle would be the alternative, and
8
+ * this also keeps the index.ts diff to the call sites themselves.
9
+ *
10
+ * Why a ceiling at all: `session.prompt` has no client-side bound. A model or
11
+ * transport that never answers leaves the delegate waiting forever with no
12
+ * status, no disposal and no way for the ladder to advance. The ceiling turns
13
+ * "never returns" into an honest failed attempt.
14
+ *
15
+ * The timeout is a real cancellation, not merely an abandoned wait: every call
16
+ * site pairs the rejection with `session.abort` (directly, or via
17
+ * disposeChildSession, which aborts before it deletes), and the SDK's abort is
18
+ * a genuine server-side POST /session/{id}/abort.
19
+ *
20
+ * This module owns the ONLY setTimeout in src/. Everything else that needs a
21
+ * clock takes `now` as an argument.
22
+ */
23
+
24
+ /** Ceiling for one producer `session.prompt` turn (10 minutes). */
25
+ export const DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS = 600_000;
26
+ /** Ceiling for one grader `session.prompt` turn (1 minute). */
27
+ export const DEFAULT_GRADER_PROMPT_TIMEOUT_MS = 60_000;
28
+ /** Ceiling for the whole acceptance gate, grader ladder included (90 s). */
29
+ export const DEFAULT_GATE_BUDGET_MS = 90_000;
30
+
31
+ /**
32
+ * Thrown by `withTimeout` when the budget elapses first. A distinct class so
33
+ * call sites can tell "the operation timed out" apart from "the operation
34
+ * failed", and report each honestly instead of collapsing both into one
35
+ * message.
36
+ */
37
+ export class RouterTimeoutError extends Error {
38
+ readonly operation: string;
39
+ readonly timeoutMs: number;
40
+
41
+ constructor(operation: string, timeoutMs: number) {
42
+ super(`${operation} timed out after ${timeoutMs}ms`);
43
+ this.name = "RouterTimeoutError";
44
+ this.operation = operation;
45
+ this.timeoutMs = timeoutMs;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Coerce a configured budget to a usable one, falling back on anything that is
51
+ * not a finite positive number.
52
+ *
53
+ * validateEnforcement already rejects `0`, negatives and non-integers in
54
+ * tiers.json, so this is defence in depth for config that reaches the runtime
55
+ * without passing through validation (override layers, tests, a hand-built
56
+ * RouterConfig). Note the fallback direction: an unusable value becomes the
57
+ * DEFAULT ceiling, never "no ceiling".
58
+ */
59
+ export function timeoutMs(value: unknown, fallback: number): number {
60
+ return typeof value === "number" && Number.isFinite(value) && value > 0
61
+ ? value
62
+ : fallback;
63
+ }
64
+
65
+ /**
66
+ * Race `promise` against `budgetMs`, rejecting with a RouterTimeoutError if the
67
+ * budget wins. The timer is always cleared in a finally, so a promise that
68
+ * settles first does not leave the event loop pinned for the rest of the
69
+ * budget.
70
+ *
71
+ * Losing the race does not stop the underlying work by itself — cancellation is
72
+ * the caller's job (see the module header).
73
+ */
74
+ export async function withTimeout<T>(
75
+ promise: Promise<T>,
76
+ budgetMs: number,
77
+ operation: string,
78
+ ): Promise<T> {
79
+ let timer: ReturnType<typeof setTimeout> | undefined;
80
+ try {
81
+ return await Promise.race([
82
+ promise,
83
+ new Promise<never>((_, reject) => {
84
+ timer = setTimeout(
85
+ () => reject(new RouterTimeoutError(operation, budgetMs)),
86
+ budgetMs,
87
+ );
88
+ }),
89
+ ]);
90
+ } finally {
91
+ if (timer) clearTimeout(timer);
92
+ }
93
+ }
@@ -0,0 +1,267 @@
1
+ /**
2
+ * The impure corner of Layer 2.
3
+ *
4
+ * Everything else under src/verify/ is pure: the gate, the DoD schema, the
5
+ * deterministic checks and the grader protocol all take their side effects as
6
+ * injected deps. This module is where those deps are actually built out of a
7
+ * child_process, a filesystem and an opencode client, so the impurity lives in
8
+ * one named place instead of spread through the plugin factory.
9
+ *
10
+ * Config is read through a getter rather than captured. `cfg` in index.ts is a
11
+ * `let` that is reassigned whenever a command reloads it, so a snapshot taken
12
+ * at construction would leave the grader pinned to the models and enforcement
13
+ * settings that were active when the plugin loaded, and `/preset` would
14
+ * silently stop applying to graded work.
15
+ */
16
+ import { exec as nodeExec } from "node:child_process";
17
+ import { access, readFile as fsReadFile } from "node:fs/promises";
18
+ import { isAbsolute, join } from "node:path";
19
+ import { createMutexRegistry } from "./deterministic";
20
+ import { tierModel } from "./dispatch";
21
+ import {
22
+ DEFAULT_GRADER_PROMPT_TIMEOUT_MS,
23
+ timeoutMs,
24
+ withTimeout,
25
+ } from "./timeout";
26
+ import type { RouterConfig } from "../router/config";
27
+ import type { GateDeps } from "./gate";
28
+ // The grader request shape is owned by checker.ts, which builds it. Re-exported
29
+ // here because this module is where it is consumed, and because keeping a
30
+ // second local copy is exactly how `cwd` got dropped: the checker set it, the
31
+ // wiring's narrower structural type silently discarded it, and the grader ran
32
+ // against the router's directory while claiming to check the producer's.
33
+ import type { GraderRequest } from "./checker";
34
+ export type { GraderRequest };
35
+
36
+ /**
37
+ * Upper bound on the disposal memo. Far above the number of child sessions any
38
+ * one delegation can have in flight, and small enough that the memo can never
39
+ * become a meaningful retention for a long-lived plugin instance.
40
+ */
41
+ export const DISPOSED_MEMO_MAX = 512;
42
+
43
+ export interface ExecResult {
44
+ code: number;
45
+ stdout: string;
46
+ stderr: string;
47
+ timedOut: boolean;
48
+ }
49
+
50
+ /**
51
+ * Join the text parts of an opencode prompt response. Tolerant of a missing or
52
+ * malformed body by design: every call site is fail-closed, and an empty string
53
+ * reads downstream as "the grader said nothing", which is not a pass.
54
+ */
55
+ export function extractAssistantText(res: any): string {
56
+ const parts: any[] = res?.data?.parts ?? [];
57
+ return parts
58
+ .filter((p) => p?.type === "text" && typeof p.text === "string")
59
+ .map((p) => p.text)
60
+ .join("\n");
61
+ }
62
+
63
+ export interface VerificationWiring {
64
+ /** Session ids currently running a grader prompt, so hooks can skip them. */
65
+ graderSessions: Set<string>;
66
+ /** Abort then delete a plugin-created child session. Never throws. */
67
+ disposeChildSession(sid: string): Promise<void>;
68
+ /** Run one grader turn, parented to the caller's session when given. */
69
+ dispatchGrader(
70
+ req: GraderRequest,
71
+ parentSessionID?: string,
72
+ inFlight?: Set<string>,
73
+ ): Promise<{ sessionID: string; text: string }>;
74
+ /**
75
+ * Deps for the acceptance gate; graders are parented to parentSessionID.
76
+ *
77
+ * `inFlight`, when supplied, receives the id of every grader session this
78
+ * gate invocation currently has open, and loses it again the moment that
79
+ * grader finishes. A caller enforcing a gate budget aborts THAT set — never
80
+ * the wiring-global one, which belongs to every concurrent delegation at
81
+ * once.
82
+ */
83
+ buildGateDeps(parentSessionID?: string, inFlight?: Set<string>): GateDeps;
84
+ }
85
+
86
+ export function createVerificationWiring(deps: {
87
+ client: any;
88
+ /** Project root; relative paths in checks resolve against it. */
89
+ directory: string;
90
+ getConfig: () => RouterConfig;
91
+ }): VerificationWiring {
92
+ const { client, directory, getConfig } = deps;
93
+ const graderSessions = new Set<string>();
94
+ /** Child sessions already torn down; see disposeChildSession. */
95
+ const disposed = new Set<string>();
96
+ const mutex = createMutexRegistry();
97
+
98
+ const execSeam = (
99
+ command: string,
100
+ opts?: { cwd?: string; timeoutMs?: number },
101
+ ): Promise<ExecResult> =>
102
+ new Promise((resolve) => {
103
+ try {
104
+ nodeExec(
105
+ command,
106
+ {
107
+ cwd: opts?.cwd ?? directory,
108
+ timeout: opts?.timeoutMs ?? 120000,
109
+ maxBuffer: 10 * 1024 * 1024,
110
+ windowsHide: true,
111
+ },
112
+ (err: any, stdout: any, stderr: any) => {
113
+ const timedOut = !!(err && err.killed && err.signal === "SIGTERM");
114
+ const code =
115
+ err && typeof err.code === "number" ? err.code : err ? 1 : 0;
116
+ resolve({
117
+ code,
118
+ stdout: String(stdout ?? ""),
119
+ stderr: String(stderr ?? ""),
120
+ timedOut,
121
+ });
122
+ },
123
+ );
124
+ } catch {
125
+ resolve({ code: 1, stdout: "", stderr: "exec failed", timedOut: false });
126
+ }
127
+ });
128
+
129
+ const fsSeam = {
130
+ async fileExists(p: string): Promise<boolean> {
131
+ try {
132
+ await access(isAbsolute(p) ? p : join(directory, p));
133
+ return true;
134
+ } catch {
135
+ return false;
136
+ }
137
+ },
138
+ async readFile(p: string): Promise<string> {
139
+ return await fsReadFile(isAbsolute(p) ? p : join(directory, p), "utf-8");
140
+ },
141
+ };
142
+
143
+ // Best-effort disposal of a plugin-created child session: abort any in-flight
144
+ // work, then delete it so it does not linger forever as a top-level session in
145
+ // the TUI. Fail-soft by contract — never throws, so it is safe to call from a
146
+ // finally without masking the original error.
147
+ const disposeChildSession = async (sid: string): Promise<void> => {
148
+ // Idempotent, not merely fail-soft. Several paths legitimately dispose the
149
+ // same session — the per-attempt teardown in the delegate ladder and the
150
+ // end-of-execute safety net both do, and a timeout racing a late completion
151
+ // can too. Re-issuing abort+delete was harmless but not free, and it made
152
+ // "disposed exactly once" unassertable, which is precisely the property the
153
+ // time-box work has to be able to prove.
154
+ if (disposed.has(sid)) return;
155
+ // Bounded: the memo only has to outlive the handful of callers that can
156
+ // race over one session (per-attempt teardown, the end-of-execute safety
157
+ // net, a timeout beaten by a late completion), all of which happen within a
158
+ // single delegate call. A plugin instance lives for the whole editor
159
+ // session, so an unbounded Set would be a slow leak. Insertion order is
160
+ // specified for Set, so dropping from the front evicts the oldest ids.
161
+ if (disposed.size >= DISPOSED_MEMO_MAX) {
162
+ let toDrop = disposed.size - DISPOSED_MEMO_MAX + 1;
163
+ for (const old of disposed) {
164
+ disposed.delete(old);
165
+ if (--toDrop <= 0) break;
166
+ }
167
+ }
168
+ disposed.add(sid);
169
+ try {
170
+ await client.session.abort({ path: { id: sid } });
171
+ } catch {
172
+ // best-effort: the session may already have completed or been removed
173
+ }
174
+ try {
175
+ await client.session.delete({ path: { id: sid } });
176
+ } catch {
177
+ // best-effort: cleanup must never break the run
178
+ }
179
+ };
180
+
181
+ const dispatchGrader = async (
182
+ req: GraderRequest,
183
+ parentSessionID?: string,
184
+ inFlight?: Set<string>,
185
+ ): Promise<{ sessionID: string; text: string }> => {
186
+ // Scope the grader session to the producer's working directory when one was
187
+ // declared. Naming the directory in the prompt is not enough: the grader
188
+ // has real tools, and an unscoped session resolves every read and command
189
+ // against the router's own cwd, so it would happily report "file not found"
190
+ // for work that exists exactly where it was asked for.
191
+ const created: any = await client.session.create({
192
+ body: { ...(parentSessionID ? { parentID: parentSessionID } : {}) },
193
+ ...(req.cwd ? { query: { directory: req.cwd } } : {}),
194
+ });
195
+ const sid: string | undefined = created?.data?.id;
196
+ if (!sid) return { sessionID: "", text: "" };
197
+ graderSessions.add(sid);
198
+ inFlight?.add(sid);
199
+ try {
200
+ const cfg = getConfig();
201
+ const model = tierModel(cfg, req.tier) ?? undefined;
202
+ // Time-boxed for the same reason as the producer prompt, but with a
203
+ // sharper edge: a grader that never answers must not be able to hold the
204
+ // gate open. The RouterTimeoutError is deliberately allowed to propagate
205
+ // to runChecker, whose fail-closed catch turns it into a non-passing
206
+ // verdict naming the timeout. Explicitly NOT modelled as "inconclusive",
207
+ // because an inconclusive grader that releases the gate is a fabricated
208
+ // pass wearing a hedge.
209
+ //
210
+ // No abort is issued here: the finally below already calls
211
+ // disposeChildSession, which aborts before it deletes, so a second abort
212
+ // on this path would be a redundant round trip that cancels nothing extra.
213
+ // (The gate-budget path in index.ts does issue a raw abort, deliberately:
214
+ // it fires while this call is still suspended, before the finally has had
215
+ // a chance to run at all.)
216
+ const res: any = await withTimeout(
217
+ client.session.prompt({
218
+ path: { id: sid },
219
+ body: {
220
+ ...(model ? { model } : {}),
221
+ system: req.system,
222
+ parts: [{ type: "text", text: req.prompt }],
223
+ },
224
+ }),
225
+ timeoutMs(
226
+ cfg.enforcement?.verify?.graderTimeoutMs,
227
+ DEFAULT_GRADER_PROMPT_TIMEOUT_MS,
228
+ ),
229
+ "grader prompt",
230
+ );
231
+ return { sessionID: sid, text: extractAssistantText(res) };
232
+ } finally {
233
+ graderSessions.delete(sid);
234
+ inFlight?.delete(sid);
235
+ await disposeChildSession(sid);
236
+ }
237
+ };
238
+
239
+ const buildGateDeps = (
240
+ parentSessionID?: string,
241
+ inFlight?: Set<string>,
242
+ ): GateDeps => {
243
+ const cfg = getConfig();
244
+ return {
245
+ deterministic: {
246
+ exec: execSeam,
247
+ fs: fsSeam,
248
+ cwd: directory,
249
+ mutex,
250
+ },
251
+ checker: {
252
+ dispatchGrader: (req: GraderRequest) =>
253
+ dispatchGrader(req, parentSessionID, inFlight),
254
+ ladder: ["fast", "medium", "heavy"],
255
+ minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
256
+ },
257
+ require: cfg.enforcement?.verify?.require,
258
+ };
259
+ };
260
+
261
+ return {
262
+ graderSessions,
263
+ disposeChildSession,
264
+ dispatchGrader,
265
+ buildGateDeps,
266
+ };
267
+ }