opencode-model-router 1.5.0 → 1.6.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.
- package/README.md +65 -9
- package/package.json +1 -1
- package/src/commands/output.ts +236 -0
- package/src/guard/enforce.ts +14 -1
- package/src/guard/guards.ts +26 -0
- package/src/guard/store.ts +46 -3
- package/src/index.ts +264 -341
- package/src/router/agent-options.ts +118 -0
- package/src/router/config.ts +277 -43
- package/src/router/idle-sweep.ts +35 -0
- package/src/router/jsonc.ts +1 -0
- package/src/router/prompts.ts +72 -0
- package/src/router/protocol.ts +1 -1
- package/src/router/sessions.ts +159 -22
- package/src/telemetry/trajectory.ts +48 -1
- package/src/verify/checker.ts +47 -1
- package/src/verify/deterministic.ts +13 -5
- package/src/verify/dispatch.ts +27 -2
- package/src/verify/gate.ts +25 -1
- package/src/verify/paths.ts +29 -0
- package/src/verify/timeout.ts +93 -0
- package/src/verify/wiring.ts +267 -0
- package/tiers.json +79 -6
package/src/verify/gate.ts
CHANGED
|
@@ -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,
|
|
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
|
+
}
|
package/tiers.json
CHANGED
|
@@ -1,15 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"activePreset": "anthropic",
|
|
3
3
|
"activeMode": "normal",
|
|
4
|
+
"enforcement": {
|
|
5
|
+
"mode": "advisory",
|
|
6
|
+
"envGate": "MODEL_ROUTER_ENFORCE",
|
|
7
|
+
"guard": {
|
|
8
|
+
"budget": 25,
|
|
9
|
+
"readDraftCap": 3,
|
|
10
|
+
"sameOpRetryCap": 1,
|
|
11
|
+
"blockSelfScript": true,
|
|
12
|
+
"deliverableFirst": true,
|
|
13
|
+
"blockScriptWrites": false
|
|
14
|
+
},
|
|
15
|
+
"verify": {
|
|
16
|
+
"minGraderTier": null,
|
|
17
|
+
"graderTemperature": 0,
|
|
18
|
+
"requireExplicitDoD": false,
|
|
19
|
+
"delegateTimeoutMs": 600000,
|
|
20
|
+
"graderTimeoutMs": 60000,
|
|
21
|
+
"gateBudgetMs": 90000
|
|
22
|
+
},
|
|
23
|
+
"escalate": {
|
|
24
|
+
"ladder": ["fast", "medium", "heavy"],
|
|
25
|
+
"floorTier": null,
|
|
26
|
+
"maxAttemptsPerTier": 1,
|
|
27
|
+
"maxTotalAttempts": 4,
|
|
28
|
+
"costCeiling": {
|
|
29
|
+
"multiple": 4
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"proportional": {
|
|
33
|
+
"trivialBypass": true
|
|
34
|
+
}
|
|
35
|
+
},
|
|
4
36
|
"tierCaps": {
|
|
5
37
|
"fast": 8,
|
|
6
38
|
"medium": 5,
|
|
7
39
|
"heavy": 3
|
|
8
40
|
},
|
|
9
41
|
"tierPrompts": {
|
|
10
|
-
"fast": "STOP CONDITIONS — read these FIRST, they govern EVERY tool call:\n\n1. CAP: ≤8 read-only tool calls (grep/read/glob/ls) per dispatch. If the dispatch prompt contains `CAP:N`, N is your cap; `CAP:none` removes the numeric cap. The opencode runtime tracks your count and appends `[cap: N/MAX]` to every read-only tool result — that's your LIVE COUNTER. When N=MAX, your next action MUST be a return, not another read.\n\n2. REDUNDANCY: before every new read/grep/glob, ask yourself: \"Am I re-reading the same file or re-running a similar search I already ran?\" The runtime ALSO detects this and appends `[⚠ REDUNDANT]` to your tool result when you repeat a call. When you see that marker, STOP IMMEDIATELY — do not attempt another read.\n\n3. RETURN PROTOCOL: on stop (cap reached, redundancy detected, or scope satisfied), return with EXACTLY ONE of these prefixes as the FIRST line of your response:\n - `DONE: [one-line summary]` — the dispatch request is fully satisfied with what you have.\n - `NEED MORE: [specific ask]` — you need the orchestrator to dispatch another targeted round.\n - `ESCALATE: [reason]` — hand back for orchestrator to re-dispatch or decide.\n\n4. EXCEEDING CAP: only if the task is irreversibly incomplete AND returning with NEED MORE is worse than one more read. Prepend `reason: <1-line>` above your return. This should be rare.\n\n---\n\nROLE: You are @fast — a read-only exploration specialist. Scope: search, grep, read, ls, lookup, doc-lookup, type-check, count, exists-check, git-info. NEVER write, edit, or modify files. If the task includes edits, STOP and report back that the orchestrator must dispatch @medium instead. Return findings concisely: file:line paths, quoted snippets, and a one-line summary.\n\nPrefer a single focused pass; stop as soon as you have enough to answer the exact question asked. Do not explore beyond the asked scope. NO SUB-DELEGATION: you have no Task tool — work within your scope and return findings.",
|
|
11
|
-
"medium": "STOP CONDITIONS — read these FIRST, they govern EVERY read-only tool call BEFORE you begin editing:\n\n1. CAP: ≤5 read-only tool calls (grep/read/glob/ls) before you start editing. `CAP:N` in the dispatch overrides; `CAP:none` disables. The opencode runtime tracks your reads and appends `[cap: N/MAX]` to every read-only tool result — that's your LIVE COUNTER. When N=MAX, start editing or return; do not make another read-only call.\n\n2. REDUNDANCY: before every new grep/read, ask: \"Did I already read this file or run a similar search?\" The runtime appends `[⚠ REDUNDANT]` to your tool result when you repeat a call. When you see that marker, STOP reading and either start editing with what you have, or return with NEED CONTEXT.\n\n3. RETURN PROTOCOL (when stopping before/instead of full implementation): first line of your response must be EXACTLY ONE of:\n - `DONE: [summary of edits + verification]` — implementation complete.\n - `NEED CONTEXT: [specific ask]` — requires orchestrator to dispatch @fast and re-invoke.\n - `ESCALATE: [reason]` — scope grew beyond implementation (e.g. architectural decision needed).\n\n4. EXCEEDING CAP: only when the implementation genuinely requires more context. Prepend `reason: <1-line>` above your summary.\n\n---\n\nROLE: You are @medium — an implementation specialist. Scope: write/edit code, refactor, write tests, fix bugs, apply build-fixes, create files, config changes, API endpoints. Match existing project patterns exactly. Never suppress type errors (no `as any`, `@ts-ignore`, `@ts-expect-error`). Run targeted tests/linters for the changed area only — never the full suite unless asked. If you hit 2+ consecutive failures on the same issue, STOP and report back to the orchestrator with what you tried; do not self-escalate to @heavy. Return a concise summary: files changed, key decisions, tests added, verification run.\n\nNO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast or @heavy. Avoid grep/read-exhaustive sweeps.",
|
|
12
|
-
"heavy": "STOP CONDITIONS — read these FIRST, they govern EVERY tool call:\n\n1. CAP: ≤3 reads/greps per dispatch. `CAP:N` in the dispatch overrides; `CAP:none` disables (used in `deep` mode). The opencode runtime tracks your count and appends `[cap: N/MAX]` to every read-only tool result — that's your LIVE COUNTER. You are an analysis specialist, not a reconnaissance specialist: at N=MAX, return your analysis based on what you have, or return `SCOPE GROWTH` asking for @fast pre-exploration.\n\n2. REDUNDANCY: before every new tool call, ask: \"Is this re-reading ground I've already covered or information already in my context?\" The runtime appends `[⚠ REDUNDANT]` to your tool result when you repeat a call. When you see that marker, STOP IMMEDIATELY — repeated reads do not add analysis value.\n\n3. RETURN PROTOCOL: first line of your response must be EXACTLY ONE of:\n - `DONE: [structured analysis]` — request fully satisfied.\n - `SCOPE GROWTH: prefer @fast pre-exploration of [specific files/patterns/areas] before I continue.` — orchestrator dispatches @fast and re-invokes you.\n - `ESCALATE: [reason]` — hand back for orchestrator decision.\n\n4. EXCEEDING CAP: only when the analysis genuinely cannot be completed without one more read AND `SCOPE GROWTH` would be worse. Prepend `reason: <1-line>`.\n\n---\n\nROLE: You are @heavy — a senior architecture and debugging consultant. Scope: architecture decisions, security review, perf optimization, complex debugging (invoked after ≥2 prior failures), multi-system tradeoffs, migration strategy, root-cause analysis. Analyze exhaustively WITHIN the context you were given. Provide reasoning, tradeoffs, and concrete recommendations. Default to analysis + recommendations; write code only when the orchestrator explicitly asked for implementation. Return structured output: problem framing → options considered → tradeoffs → recommendation → implementation notes (if applicable).\n\nNO SUB-DELEGATION: you have no Task tool. Your job is analysis, not reconnaissance. 40 minutes of file reads is not analysis — it's reconnaissance. Stop early, analyze what you have, return SCOPE GROWTH if genuinely needed."
|
|
42
|
+
"fast": "STOP CONDITIONS — read these FIRST, they govern EVERY tool call:\n\n1. CAP: ≤8 read-only tool calls (grep/read/glob/ls) per dispatch. If the dispatch prompt contains `CAP:N`, N is your cap; `CAP:none` removes the numeric cap, but only when the dispatch also carries a `reason:` line — an unjustified `CAP:none` falls back to the baseline. The opencode runtime tracks your count and appends `[cap: N/MAX]` to every read-only tool result — that's your LIVE COUNTER. When N=MAX, your next action MUST be a return, not another read.\n\n2. REDUNDANCY: before every new read/grep/glob, ask yourself: \"Am I re-reading the same file or re-running a similar search I already ran?\" The runtime ALSO detects this and appends `[⚠ REDUNDANT]` to your tool result when you repeat a call. When you see that marker, STOP IMMEDIATELY — do not attempt another read.\n\n3. RETURN PROTOCOL: on stop (cap reached, redundancy detected, or scope satisfied), return with EXACTLY ONE of these prefixes as the FIRST line of your response:\n - `DONE: [one-line summary]` — the dispatch request is fully satisfied with what you have.\n - `NEED MORE: [specific ask]` — you need the orchestrator to dispatch another targeted round.\n - `ESCALATE: [reason]` — hand back for orchestrator to re-dispatch or decide.\n\n4. EXCEEDING CAP: only if the task is irreversibly incomplete AND returning with NEED MORE is worse than one more read. Prepend `reason: <1-line>` above your return. This should be rare.\n\n---\n\nROLE: You are @fast — a read-only exploration specialist. Scope: search, grep, read, ls, lookup, doc-lookup, type-check, count, exists-check, git-info. NEVER write, edit, or modify files. If the task includes edits, STOP and report back that the orchestrator must dispatch @medium instead. Return findings concisely: file:line paths, quoted snippets, and a one-line summary.\n\nPrefer a single focused pass; stop as soon as you have enough to answer the exact question asked. Do not explore beyond the asked scope. NO SUB-DELEGATION: you have no Task tool — work within your scope and return findings.",
|
|
43
|
+
"medium": "STOP CONDITIONS — read these FIRST, they govern EVERY read-only tool call BEFORE you begin editing:\n\n1. CAP: ≤5 read-only tool calls (grep/read/glob/ls) before you start editing. `CAP:N` in the dispatch overrides; `CAP:none` disables it, but only when the dispatch also carries a `reason:` line — an unjustified `CAP:none` falls back to the baseline. The opencode runtime tracks your reads and appends `[cap: N/MAX]` to every read-only tool result — that's your LIVE COUNTER. When N=MAX, start editing or return; do not make another read-only call.\n\n2. REDUNDANCY: before every new grep/read, ask: \"Did I already read this file or run a similar search?\" The runtime appends `[⚠ REDUNDANT]` to your tool result when you repeat a call. When you see that marker, STOP reading and either start editing with what you have, or return with NEED CONTEXT.\n\n3. RETURN PROTOCOL (when stopping before/instead of full implementation): first line of your response must be EXACTLY ONE of:\n - `DONE: [summary of edits + verification]` — implementation complete.\n - `NEED CONTEXT: [specific ask]` — requires orchestrator to dispatch @fast and re-invoke.\n - `ESCALATE: [reason]` — scope grew beyond implementation (e.g. architectural decision needed).\n\n4. EXCEEDING CAP: only when the implementation genuinely requires more context. Prepend `reason: <1-line>` above your summary.\n\n---\n\nROLE: You are @medium — an implementation specialist. Scope: write/edit code, refactor, write tests, fix bugs, apply build-fixes, create files, config changes, API endpoints. Match existing project patterns exactly. Never suppress type errors (no `as any`, `@ts-ignore`, `@ts-expect-error`). Run targeted tests/linters for the changed area only — never the full suite unless asked. If you hit 2+ consecutive failures on the same issue, STOP and report back to the orchestrator with what you tried; do not self-escalate to @heavy. Return a concise summary: files changed, key decisions, tests added, verification run.\n\nNO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast or @heavy. Avoid grep/read-exhaustive sweeps.\n\nBefore reporting progress, audit each claim against a tool result from this session. Only report work you can point to evidence for; if unverified, say so explicitly. If tests fail, report it with the relevant excerpt of the output.",
|
|
44
|
+
"heavy": "STOP CONDITIONS — read these FIRST, they govern EVERY tool call:\n\n1. CAP: ≤3 reads/greps per dispatch. `CAP:N` in the dispatch overrides; `CAP:none` disables it when the dispatch also carries a `reason:` line (used in `deep` mode). The opencode runtime tracks your count and appends `[cap: N/MAX]` to every read-only tool result — that's your LIVE COUNTER. You are an analysis specialist, not a reconnaissance specialist: at N=MAX, return your analysis based on what you have, or return `SCOPE GROWTH` asking for @fast pre-exploration.\n\n2. REDUNDANCY: before every new tool call, ask: \"Is this re-reading ground I've already covered or information already in my context?\" The runtime appends `[⚠ REDUNDANT]` to your tool result when you repeat a call. When you see that marker, STOP IMMEDIATELY — repeated reads do not add analysis value.\n\n3. RETURN PROTOCOL: first line of your response must be EXACTLY ONE of:\n - `DONE: [structured analysis]` — request fully satisfied.\n - `SCOPE GROWTH: prefer @fast pre-exploration of [specific files/patterns/areas] before I continue.` — orchestrator dispatches @fast and re-invokes you.\n - `ESCALATE: [reason]` — hand back for orchestrator decision.\n\n4. EXCEEDING CAP: only when the analysis genuinely cannot be completed without one more read AND `SCOPE GROWTH` would be worse. Prepend `reason: <1-line>`.\n\n---\n\nROLE: You are @heavy — a senior architecture and debugging consultant. Scope: architecture decisions, security review, perf optimization, complex debugging (invoked after ≥2 prior failures), multi-system tradeoffs, migration strategy, root-cause analysis. Analyze exhaustively WITHIN the context you were given. Provide reasoning, tradeoffs, and concrete recommendations. Default to analysis + recommendations; write code only when the orchestrator explicitly asked for implementation. Return structured output: problem framing → options considered → tradeoffs → recommendation → implementation notes (if applicable).\n\nNO SUB-DELEGATION: you have no Task tool. Your job is analysis, not reconnaissance. 40 minutes of file reads is not analysis — it's reconnaissance. Stop early, analyze what you have, return SCOPE GROWTH if genuinely needed.\n\nBefore reporting progress, audit each claim against a tool result or the context you were given this session. Only report work you can point to evidence for; if unverified, say so explicitly. If tests fail, report it with the relevant excerpt of the output."
|
|
13
45
|
},
|
|
14
46
|
"presets": {
|
|
15
47
|
"anthropic": {
|
|
@@ -209,6 +241,47 @@
|
|
|
209
241
|
"Performance optimization"
|
|
210
242
|
]
|
|
211
243
|
}
|
|
244
|
+
},
|
|
245
|
+
"fable-effort": {
|
|
246
|
+
"fast": {
|
|
247
|
+
"model": "anthropic/claude-fable-5",
|
|
248
|
+
"effort": "low",
|
|
249
|
+
"costRatio": 1,
|
|
250
|
+
"description": "Fable 5 at low effort for exploration, search, and simple reads (token-spend ratios are estimates; same model across tiers preserves prompt cache)",
|
|
251
|
+
"steps": 30,
|
|
252
|
+
"whenToUse": [
|
|
253
|
+
"Codebase exploration and search",
|
|
254
|
+
"Simple file reads and listing",
|
|
255
|
+
"Grep/glob operations",
|
|
256
|
+
"Quick lookups and research"
|
|
257
|
+
]
|
|
258
|
+
},
|
|
259
|
+
"medium": {
|
|
260
|
+
"model": "anthropic/claude-fable-5",
|
|
261
|
+
"effort": "high",
|
|
262
|
+
"costRatio": 3,
|
|
263
|
+
"description": "Fable 5 at high effort for implementation and standard coding (costRatio is an estimated token-spend multiplier, not a price difference)",
|
|
264
|
+
"steps": 50,
|
|
265
|
+
"whenToUse": [
|
|
266
|
+
"Feature implementation",
|
|
267
|
+
"Refactoring",
|
|
268
|
+
"Writing tests",
|
|
269
|
+
"Bug fixes"
|
|
270
|
+
]
|
|
271
|
+
},
|
|
272
|
+
"heavy": {
|
|
273
|
+
"model": "anthropic/claude-fable-5",
|
|
274
|
+
"effort": "xhigh",
|
|
275
|
+
"costRatio": 6,
|
|
276
|
+
"description": "Fable 5 at xhigh effort for architecture, complex debugging, and security (costRatio is an estimated token-spend multiplier, not a price difference)",
|
|
277
|
+
"steps": 120,
|
|
278
|
+
"whenToUse": [
|
|
279
|
+
"Architecture decisions",
|
|
280
|
+
"Complex debugging (after 2+ failures)",
|
|
281
|
+
"Security review",
|
|
282
|
+
"Performance optimization"
|
|
283
|
+
]
|
|
284
|
+
}
|
|
212
285
|
}
|
|
213
286
|
},
|
|
214
287
|
"taskPatterns": {
|
|
@@ -274,7 +347,7 @@
|
|
|
274
347
|
"@heavy: arch/debug/security/multi-file-coord",
|
|
275
348
|
"@fast ONLY: trivial single-tool ops (1 grep/1 read)",
|
|
276
349
|
"prefer thoroughness over speed",
|
|
277
|
-
"dispatch caps: always include CAP:none in dispatch prompts — subagents may explore as needed for deep context",
|
|
350
|
+
"dispatch caps: always include CAP:none with a `reason:` line in dispatch prompts — subagents may explore as needed for deep context",
|
|
278
351
|
"subagents still run redundancy check; CAP:none only lifts the numeric cap, not the stop-on-redundancy rule"
|
|
279
352
|
]
|
|
280
353
|
},
|
|
@@ -287,7 +360,7 @@
|
|
|
287
360
|
"allow long heavy runs before fallback; avoid premature downshift",
|
|
288
361
|
"trivial(grep/read/glob)→direct,no-delegate",
|
|
289
362
|
"if task is composite: explore@fast then execute@heavy",
|
|
290
|
-
"dispatch caps: CAP:none for @heavy only; @fast=CAP:8 and @medium=CAP:5 baselines apply",
|
|
363
|
+
"dispatch caps: CAP:none (with a `reason:` line) for @heavy only; @fast=CAP:8 and @medium=CAP:5 baselines apply",
|
|
291
364
|
"subagents still run redundancy check; CAP:none only lifts the numeric cap"
|
|
292
365
|
]
|
|
293
366
|
}
|
|
@@ -323,7 +396,7 @@
|
|
|
323
396
|
"orchestrate=self, execute=subagent (info-gathering IS execution, not orchestration)",
|
|
324
397
|
"trivial (≤1 tool call, no expected follow-up) → direct, skip-delegate",
|
|
325
398
|
"orchestrator self-cap (TARGET): ≤2 direct read-only calls per turn; 3rd need → dispatch @fast (exceed only with 1-line reason)",
|
|
326
|
-
"dispatch caps baseline: @fast=CAP:8, @medium=CAP:5, @heavy=CAP:3 (omit directive = baseline; include CAP:N to override; CAP:none disables)",
|
|
399
|
+
"dispatch caps baseline: @fast=CAP:8, @medium=CAP:5, @heavy=CAP:3 (omit directive = baseline; include CAP:N to override; CAP:none disables the cap only when the dispatch also carries a `reason:` line)",
|
|
327
400
|
"before dispatching @heavy: gather context first (usually via @fast); if context is already sufficient, dispatch directly",
|
|
328
401
|
"if self is opus: skip-@heavy (do locally); still prefer routing broader read-only exploration to @fast",
|
|
329
402
|
"min(cost, adequate-tier)"
|