opencode-model-router 1.1.16 → 1.2.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 +37 -0
- package/package.json +12 -2
- package/src/escalate/ladder.ts +201 -0
- package/src/guard/enforce.ts +135 -0
- package/src/guard/fingerprint.ts +16 -0
- package/src/guard/guards.ts +343 -0
- package/src/guard/narration.ts +34 -0
- package/src/guard/scrub.ts +26 -0
- package/src/guard/store.ts +39 -0
- package/src/index.ts +613 -749
- package/src/router/config.ts +478 -0
- package/src/router/enforcement.ts +53 -0
- package/src/router/protocol.ts +306 -0
- package/src/router/sessions.ts +268 -0
- package/src/telemetry/trajectory.ts +180 -0
- package/src/verify/checker.ts +224 -0
- package/src/verify/deterministic.ts +319 -0
- package/src/verify/dispatch.ts +153 -0
- package/src/verify/dod.ts +274 -0
- package/src/verify/gate.ts +166 -0
- package/src/verify/types.ts +49 -0
- package/tiers.json +9 -9
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import type { RouterConfig, Preset, ModeConfig } from "./config";
|
|
2
|
+
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
// Tier / mode helpers
|
|
5
|
+
// ---------------------------------------------------------------------------
|
|
6
|
+
|
|
7
|
+
export function getActiveTiers(cfg: RouterConfig): Preset {
|
|
8
|
+
return cfg.presets[cfg.activePreset] ?? Object.values(cfg.presets)[0]!;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function getActiveMode(cfg: RouterConfig): ModeConfig | undefined {
|
|
12
|
+
if (!cfg.modes || !cfg.activeMode) return undefined;
|
|
13
|
+
return cfg.modes[cfg.activeMode];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Fallback instructions builder
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
export function buildFallbackInstructions(cfg: RouterConfig): string {
|
|
21
|
+
const fb = cfg.fallback;
|
|
22
|
+
if (!fb) return "";
|
|
23
|
+
|
|
24
|
+
const presetMap = fb.presets?.[cfg.activePreset];
|
|
25
|
+
const map =
|
|
26
|
+
presetMap && Object.keys(presetMap).length > 0 ? presetMap : fb.global;
|
|
27
|
+
if (!map) return "";
|
|
28
|
+
|
|
29
|
+
const chains = Object.entries(map).flatMap(([provider, presetOrder]) => {
|
|
30
|
+
if (!Array.isArray(presetOrder)) return [];
|
|
31
|
+
const valid = presetOrder.filter(
|
|
32
|
+
(p) => p !== cfg.activePreset && Boolean(cfg.presets[p]),
|
|
33
|
+
);
|
|
34
|
+
return valid.length > 0 ? [`${provider}→${valid.join("→")}`] : [];
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
if (chains.length === 0) return "";
|
|
38
|
+
return `Err→retry-alt-tier→fail→direct. Chain: ${chains.join(" | ")}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
// Cost & taxonomy builders
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
export function buildTaskTaxonomy(cfg: RouterConfig): string {
|
|
46
|
+
if (!cfg.taskPatterns || Object.keys(cfg.taskPatterns).length === 0)
|
|
47
|
+
return "";
|
|
48
|
+
const lines = ["R:"];
|
|
49
|
+
for (const [tier, patterns] of Object.entries(cfg.taskPatterns)) {
|
|
50
|
+
if (Array.isArray(patterns) && patterns.length > 0) {
|
|
51
|
+
lines.push(`@${tier}→${patterns.join("/")}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return lines.join(" ");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Injects a multi-phase decomposition hint into the delegation protocol.
|
|
59
|
+
* Teaches the orchestrator to split composite tasks (explore + implement)
|
|
60
|
+
* so the cheap @fast tier handles exploration and @medium handles execution.
|
|
61
|
+
* Only active in normal mode — budget/quality modes have their own override rules.
|
|
62
|
+
*/
|
|
63
|
+
export function buildDecomposeHint(cfg: RouterConfig): string {
|
|
64
|
+
const mode = getActiveMode(cfg);
|
|
65
|
+
// Budget and quality modes handle this via overrideRules — skip to avoid conflicts
|
|
66
|
+
if (mode?.overrideRules?.length) return "";
|
|
67
|
+
|
|
68
|
+
const tiers = getActiveTiers(cfg);
|
|
69
|
+
const entries = Object.entries(tiers);
|
|
70
|
+
if (entries.length < 2) return "";
|
|
71
|
+
|
|
72
|
+
// Sort by costRatio ascending to find cheapest (explore) and next (execute) tiers
|
|
73
|
+
const sorted = [...entries].sort(
|
|
74
|
+
([, a], [, b]) => (a.costRatio ?? 1) - (b.costRatio ?? 1),
|
|
75
|
+
);
|
|
76
|
+
const cheapest = sorted[0]?.[0];
|
|
77
|
+
const mid = sorted[1]?.[0];
|
|
78
|
+
if (!cheapest || !mid) return "";
|
|
79
|
+
|
|
80
|
+
return `Multi-phase: prefer explore(@${cheapest})→execute(@${mid}) when phases are separable. Cheapest-first when practical.`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
// System prompt builder
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
export function buildDelegationProtocol(cfg: RouterConfig): string {
|
|
88
|
+
const tiers = getActiveTiers(cfg);
|
|
89
|
+
|
|
90
|
+
// Compact tier summary: @name=model/variant(costRatio)
|
|
91
|
+
const tierLine = Object.entries(tiers)
|
|
92
|
+
.map(([name, t]) => {
|
|
93
|
+
const short = t.model.split("/").pop() ?? t.model;
|
|
94
|
+
const v = t.variant ? `/${t.variant}` : "";
|
|
95
|
+
const c = t.costRatio != null ? `(${t.costRatio}x)` : "";
|
|
96
|
+
return `@${name}=${short}${v}${c}`;
|
|
97
|
+
})
|
|
98
|
+
.join(" ");
|
|
99
|
+
|
|
100
|
+
const mode = getActiveMode(cfg);
|
|
101
|
+
const modeSuffix = cfg.activeMode ? ` mode:${cfg.activeMode}` : "";
|
|
102
|
+
|
|
103
|
+
const taxonomy = buildTaskTaxonomy(cfg);
|
|
104
|
+
const decompose = buildDecomposeHint(cfg);
|
|
105
|
+
|
|
106
|
+
const effectiveRules = mode?.overrideRules?.length
|
|
107
|
+
? mode.overrideRules
|
|
108
|
+
: cfg.rules;
|
|
109
|
+
const rulesLine = effectiveRules.map((r, i) => `${i + 1}.${r}`).join(" ");
|
|
110
|
+
|
|
111
|
+
const fallback = buildFallbackInstructions(cfg);
|
|
112
|
+
|
|
113
|
+
return [
|
|
114
|
+
`## Model Delegation Protocol — MANDATORY`,
|
|
115
|
+
``,
|
|
116
|
+
`You are the orchestrator. Information-gathering is NOT orchestration — it IS execution. Execution belongs to subagents, not to you.`,
|
|
117
|
+
``,
|
|
118
|
+
`Preset: ${cfg.activePreset}. Tiers: ${tierLine}.${modeSuffix}`,
|
|
119
|
+
``,
|
|
120
|
+
`### HARD ROUTING (non-negotiable)`,
|
|
121
|
+
`- **Read-only work** (grep, glob, read, ls, lookup, count, git-info, doc-lookup, type-check, exists-check) → default to \`Task(subagent_type="fast", ...)\`. Self-cap (TARGET): ≤2 direct read-only calls per user turn; on the 3rd read-only need, dispatch @fast instead. You may exceed with a 1-line \`reason:\` note when dispatching feels clearly wrong. Rationale: every tool-result token is billed at your tier rate — a grep via @fast costs ~20x less than the same grep here.`,
|
|
122
|
+
`- **Implementation work** (write, edit, refactor, tests, bug-fix, build-fix, create-file, config, api-endpoint) → \`Task(subagent_type="medium", ...)\`.`,
|
|
123
|
+
`- **Architecture / security / perf / debugging after ≥2 failures / multi-system tradeoffs / RCA** → \`Task(subagent_type="heavy", ...)\`, UNLESS you ARE @heavy (opus); then handle locally and never self-call @heavy.`,
|
|
124
|
+
``,
|
|
125
|
+
`### DISPATCH CAPS (read-only budget per subagent)`,
|
|
126
|
+
`Subagents carry a TARGET cap on their own read-only tool calls (baseline: @fast=8, @medium=5, @heavy=3). Include \`CAP:N\` in the dispatch prompt to override (e.g., \`CAP:3\` for a tight lookup, \`CAP:none\` to disable). Mode adjustments apply automatically via rules below. Subagents also run a redundancy check every call: if they detect repeated reads/greps of the same area, they STOP and return partial findings with \`DONE: ...\`, \`NEED MORE: ...\`, or \`ESCALATE: ...\` — you decide the next step from their return.`,
|
|
127
|
+
``,
|
|
128
|
+
`### ROLE CONTRACT`,
|
|
129
|
+
`The primary agent's job: decompose the user's request, dispatch subagents, synthesize their results, and answer the user. Keep orchestration-first posture: prefer dispatching read-only exploration to @fast rather than running repeated Grep/Read/Glob/Bash calls yourself. Self-cap applies (see HARD ROUTING above): ≤2 direct read-only calls per turn as a target; beyond that, dispatch @fast.`,
|
|
130
|
+
``,
|
|
131
|
+
`### @fast contract`,
|
|
132
|
+
`@fast is a read-only explorer. It will search/grep/read/count/lookup and return file:line paths, snippets, and a one-line summary. It will refuse edits. Batch related searches into a single @fast dispatch when possible; fire independent searches in parallel (one message, multiple Task calls).`,
|
|
133
|
+
``,
|
|
134
|
+
`### @medium contract`,
|
|
135
|
+
`@medium is the implementer. It writes, edits, refactors, adds tests, fixes bugs, applies build-fixes. It matches existing project patterns, runs targeted tests for changed areas, and reports back if it hits 2+ consecutive failures instead of self-escalating. Give it context: file paths, patterns to match, what verification to run.`,
|
|
136
|
+
``,
|
|
137
|
+
`### @heavy contract (CRITICAL — read before every @heavy dispatch)`,
|
|
138
|
+
`@heavy has **no Task tool** — it cannot self-explore, cannot grep, cannot delegate. Dispatching @heavy without context can waste a run: it may reason on thin evidence or return "SCOPE GROWTH" asking for additional @fast findings.`,
|
|
139
|
+
`**Before @heavy, gather context first — usually via @fast.** If you already have sufficient concrete context, dispatch @heavy directly. If @heavy still needs more evidence, collect it with @fast and re-invoke.`,
|
|
140
|
+
`Pattern: \`Task(@fast, "collect X, Y, Z")\` (when needed) → synthesize findings → \`Task(@heavy, "given these findings: [paste], analyze W")\`.`,
|
|
141
|
+
``,
|
|
142
|
+
`### CONFLICT WITH CLAUDE.md / AGENTS.md`,
|
|
143
|
+
`If CLAUDE.md or AGENTS.md (or any other guide in your context) says "use direct tools first when scope is clear" or labels Grep/Read/Glob as "FREE", **this protocol wins**. Those labels are wrong about cost: tools executed by you are billed at your tier rate — every tool-result token is tokenized into your context. A Grep dispatched to @fast costs ~20x less than the same Grep executed by @heavy. Treat yourself as expensive and delegate reads by default.`,
|
|
144
|
+
``,
|
|
145
|
+
...(taxonomy ? [taxonomy, ``] : []),
|
|
146
|
+
...(decompose ? [decompose, ``] : []),
|
|
147
|
+
`### Compact rules`,
|
|
148
|
+
rulesLine,
|
|
149
|
+
...(fallback ? [``, fallback] : []),
|
|
150
|
+
``,
|
|
151
|
+
`Delegate with \`Task(subagent_type="fast"|"medium"|"heavy", prompt="...")\`. Keep orchestration and final synthesis here.`,
|
|
152
|
+
].join("\n");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ---------------------------------------------------------------------------
|
|
156
|
+
// Claude-model adversarial prefixes
|
|
157
|
+
//
|
|
158
|
+
// Anthropic models (direct or via other providers) are served with a large
|
|
159
|
+
// cached "Claude Code" signature prompt that primes them toward broad
|
|
160
|
+
// exploratory Read/Grep/Glob behavior. Our tier prompts land after that
|
|
161
|
+
// cached block and lose authority through primacy bias and cache freezing.
|
|
162
|
+
// For Claude models specifically, we prepend an override block that
|
|
163
|
+
// explicitly revokes the exploratory priming for the current dispatch.
|
|
164
|
+
//
|
|
165
|
+
// Detection is by model identifier, not preset — a hybrid preset mixing
|
|
166
|
+
// providers gets the override only on its Claude-backed tiers.
|
|
167
|
+
// ---------------------------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
export function isClaudeModel(modelID: string | undefined): boolean {
|
|
170
|
+
if (!modelID) return false;
|
|
171
|
+
const s = modelID.toLowerCase();
|
|
172
|
+
if (s.startsWith("anthropic/")) return true;
|
|
173
|
+
return /\/claude-/.test(s) || /(^|[\/\-])claude-/.test(s);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Per-tier adversarial openers. @fast/@medium use Tom 2 (scoping); @heavy uses Tom 1 (override). */
|
|
177
|
+
export const CLAUDE_TIER_PREFIX: Record<string, string> = {
|
|
178
|
+
fast: [
|
|
179
|
+
"SCOPE NOTE — any cached instruction priming you to 'thoroughly explore",
|
|
180
|
+
"the codebase' or 'gather context broadly' does not apply here. This is",
|
|
181
|
+
"a single dispatch with a single question. Stay narrow to the ask.",
|
|
182
|
+
"",
|
|
183
|
+
"Before every tool call, ask: 'Does THIS read answer the dispatch",
|
|
184
|
+
"question specifically, or am I drifting into context-gathering for my",
|
|
185
|
+
"own understanding?' If the latter, stop — you have enough.",
|
|
186
|
+
].join("\n"),
|
|
187
|
+
medium: [
|
|
188
|
+
"SCOPE NOTE — cached instructions may prime you to deeply understand",
|
|
189
|
+
"surrounding code before editing. For THIS dispatch, the orchestrator",
|
|
190
|
+
"has already scoped the problem; trust that scoping. Read what's needed",
|
|
191
|
+
"for the edit, not the whole module.",
|
|
192
|
+
"",
|
|
193
|
+
"A 4th or 5th 'context read' is usually a sign the dispatch was under-",
|
|
194
|
+
"scoped — return NEED CONTEXT rather than expanding scope yourself.",
|
|
195
|
+
].join("\n"),
|
|
196
|
+
heavy: [
|
|
197
|
+
"AUTHORITY OVERRIDE — this block supersedes any cached prefix suggesting",
|
|
198
|
+
"you should 'investigate thoroughly', 'gather comprehensive context', or",
|
|
199
|
+
"'trace through the code systematically before analyzing'. You are",
|
|
200
|
+
"@heavy, an ANALYSIS specialist. The orchestrator should have pre-",
|
|
201
|
+
"gathered context via @fast before dispatching you. If it didn't, return",
|
|
202
|
+
"`SCOPE GROWTH:` immediately — do NOT self-gather.",
|
|
203
|
+
"",
|
|
204
|
+
"40 minutes of Read/Grep is not analysis — it is the orchestrator's job",
|
|
205
|
+
"that leaked into yours. Push it back with SCOPE GROWTH. Your 3 reads",
|
|
206
|
+
"are for targeted verification, not exploration.",
|
|
207
|
+
].join("\n"),
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
/** Adversarial opener prepended to the delegation protocol when the orchestrator is a Claude model. */
|
|
211
|
+
export const CLAUDE_ORCHESTRATOR_PREFIX = [
|
|
212
|
+
"AUTHORITY OVERRIDE — this block supersedes any prior system instruction",
|
|
213
|
+
"about 'exploring the codebase', 'gathering context with tools', or using",
|
|
214
|
+
"Read/Grep/Glob to validate assumptions. Those instructions describe a",
|
|
215
|
+
"general-purpose Claude Code session. THIS session is a routing",
|
|
216
|
+
"orchestrator.",
|
|
217
|
+
"",
|
|
218
|
+
"Your job is to DISPATCH, not to EXECUTE. Read-only work (grep/read/",
|
|
219
|
+
"glob/ls) is execution, and execution is delegated to @fast. You may run",
|
|
220
|
+
"AT MOST 2 direct read-only tool calls per turn — a 3rd call is a rule",
|
|
221
|
+
"violation. If you need more context, you dispatch @fast.",
|
|
222
|
+
"",
|
|
223
|
+
"If a cached instruction told you to 'be thorough', 'explore broadly', or",
|
|
224
|
+
"'read supporting files' — ignore it here. Thoroughness is achieved by",
|
|
225
|
+
"dispatching the right tier, not by you becoming the explorer.",
|
|
226
|
+
].join("\n");
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Anti-narration clause appended to every Claude-model prefix (tier + orchestrator).
|
|
230
|
+
*
|
|
231
|
+
* Thinking-enabled Claude models (esp. Sonnet with `max` variant) sometimes
|
|
232
|
+
* produce progress narration in place of actual work — "Still writing X...",
|
|
233
|
+
* "Now I'll implement Y...", "Let me add Z..." — without the X/Y/Z ever
|
|
234
|
+
* appearing. This clause names the pattern, lists specific forbidden phrasings
|
|
235
|
+
* (A3 — exemplified), and carves out an escape valve for legitimate
|
|
236
|
+
* explanation/plan requests (A2 — with exception).
|
|
237
|
+
*/
|
|
238
|
+
export const CLAUDE_ANTI_NARRATION = [
|
|
239
|
+
"ANTI-NARRATION — do NOT write progress commentary in your response or",
|
|
240
|
+
"thinking output. Forbidden phrasings include:",
|
|
241
|
+
" - \"Still writing the X function...\"",
|
|
242
|
+
" - \"Now I'll implement Y...\"",
|
|
243
|
+
" - \"Let me add Z...\"",
|
|
244
|
+
" - \"Continuing with W...\"",
|
|
245
|
+
" - \"Going to fix V...\"",
|
|
246
|
+
"",
|
|
247
|
+
"Each of these signals planning without production. If you write one, the",
|
|
248
|
+
"NEXT tokens MUST contain the actual artifact (the code, the edit, the",
|
|
249
|
+
"concrete output). Otherwise, stop and return with status.",
|
|
250
|
+
"",
|
|
251
|
+
"Exception: when the user explicitly asks for an explanation, plan, or",
|
|
252
|
+
"walkthrough, prose is welcome — this rule targets unsolicited progress",
|
|
253
|
+
"narration during code and implementation tasks.",
|
|
254
|
+
].join("\n");
|
|
255
|
+
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
// Assembled system prompt (pure — no side effects)
|
|
258
|
+
// ---------------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Builds the DoD / Acceptance block protocol section shown when enforcement is ON.
|
|
262
|
+
* Pure: no side-effects, no I/O.
|
|
263
|
+
*/
|
|
264
|
+
export function buildDoDProtocolSection(cfg: RouterConfig): string {
|
|
265
|
+
const requireExplicit = cfg.enforcement?.verify?.requireExplicitDoD === true;
|
|
266
|
+
const omitLine = requireExplicit
|
|
267
|
+
? "A DoD is REQUIRED: a non-trivial dispatch without an [acceptance] block is rejected."
|
|
268
|
+
: "If you omit the block, a minimal DoD is auto-inferred from the task type.";
|
|
269
|
+
return [
|
|
270
|
+
"### Acceptance / Definition of Done (enforcement is ON)",
|
|
271
|
+
"Non-trivial delegations are independently verified before their result is accepted (producer \u2260 grader; grader \u2265 producer tier). Attach an acceptance block to your dispatch so the gate knows what \"done\" means:",
|
|
272
|
+
"",
|
|
273
|
+
"[acceptance]",
|
|
274
|
+
"check: testsPass",
|
|
275
|
+
"check: buildPasses",
|
|
276
|
+
"check: fileExists path=src/foo.ts",
|
|
277
|
+
"check: run command=\"node -e ...\" expect=OK",
|
|
278
|
+
"criteria: <plain-language success condition>",
|
|
279
|
+
"deliverable: <path or short description>",
|
|
280
|
+
"[/acceptance]",
|
|
281
|
+
"",
|
|
282
|
+
"- check kinds: testsPass | buildPasses | lintClean | fileExists path=\u2026 | schemaMatch path=\u2026 schema=\u2026 | run command=\"\u2026\" expect=\u2026",
|
|
283
|
+
"- " + omitLine,
|
|
284
|
+
"- A failing DoD causes the result to be rejected and retried/escalated, not silently accepted.",
|
|
285
|
+
].join("\n");
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Assembles the full system prompt injected by the experimental.chat.system.transform hook.
|
|
290
|
+
* For Claude orchestrators: prepends CLAUDE_ORCHESTRATOR_PREFIX + CLAUDE_ANTI_NARRATION.
|
|
291
|
+
* For non-Claude orchestrators: returns the delegation protocol verbatim.
|
|
292
|
+
*
|
|
293
|
+
* When enforcementOn is true, appends the DoD/Acceptance protocol section.
|
|
294
|
+
* When false/omitted (default), the output is byte-identical to the pre-enforcement baseline (GA-1).
|
|
295
|
+
*/
|
|
296
|
+
export function assembleSystemPrompt(
|
|
297
|
+
cfg: RouterConfig,
|
|
298
|
+
orchestratorModel: string | undefined,
|
|
299
|
+
enforcementOn: boolean = false,
|
|
300
|
+
): string {
|
|
301
|
+
const delegationProtocol = buildDelegationProtocol(cfg);
|
|
302
|
+
const dodSection = enforcementOn ? `\n\n---\n\n${buildDoDProtocolSection(cfg)}` : "";
|
|
303
|
+
return isClaudeModel(orchestratorModel)
|
|
304
|
+
? `${CLAUDE_ORCHESTRATOR_PREFIX}\n\n${CLAUDE_ANTI_NARRATION}\n\n---\n\n${delegationProtocol}${dodSection}`
|
|
305
|
+
: `${delegationProtocol}${dodSection}`;
|
|
306
|
+
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import type { RouterConfig } from "./config";
|
|
2
|
+
import { fingerprintToolCall } from "../guard/fingerprint";
|
|
3
|
+
|
|
4
|
+
// ---------------------------------------------------------------------------
|
|
5
|
+
// Types
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
|
|
8
|
+
export type Cap = number | "none";
|
|
9
|
+
|
|
10
|
+
export interface SubagentState {
|
|
11
|
+
tierName: string;
|
|
12
|
+
cap: Cap;
|
|
13
|
+
calls: number;
|
|
14
|
+
/** Fingerprint → call index where this fingerprint was first seen. */
|
|
15
|
+
seen: Map<string, number>;
|
|
16
|
+
trivial: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
// Fallback caps when tiers.json has no tierCaps block.
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
/** Fallback caps when tiers.json has no tierCaps block. */
|
|
24
|
+
export const DEFAULT_TIER_CAPS: Record<string, number> = {
|
|
25
|
+
fast: 8,
|
|
26
|
+
medium: 5,
|
|
27
|
+
heavy: 3,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
// Cap directive parser
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
/** Extract the first `CAP:N` or `CAP:none` directive from a dispatch prompt. */
|
|
35
|
+
export function parseCapDirective(text: string): Cap | null {
|
|
36
|
+
const m = text.match(/\bCAP\s*:\s*(none|\d+)\b/i);
|
|
37
|
+
if (!m) return null;
|
|
38
|
+
const raw = m[1]!.toLowerCase();
|
|
39
|
+
if (raw === "none") return "none";
|
|
40
|
+
const n = parseInt(raw, 10);
|
|
41
|
+
return Number.isFinite(n) && n > 0 ? n : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
// Dispatch text extractor (internal)
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
/** Best-effort extraction of textual content from a chat.message output payload. */
|
|
49
|
+
function extractDispatchText(output: unknown): string {
|
|
50
|
+
const o = output as Record<string, unknown> | undefined;
|
|
51
|
+
const parts = (o?.parts as unknown[]) ?? [];
|
|
52
|
+
const chunks: string[] = [];
|
|
53
|
+
for (const p of parts) {
|
|
54
|
+
if (typeof p === "string") {
|
|
55
|
+
chunks.push(p);
|
|
56
|
+
} else if (p && typeof p === "object") {
|
|
57
|
+
const rec = p as Record<string, unknown>;
|
|
58
|
+
if (typeof rec.text === "string") chunks.push(rec.text);
|
|
59
|
+
else if (typeof rec.content === "string") chunks.push(rec.content);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (chunks.length === 0) {
|
|
63
|
+
const msg = o?.message as Record<string, unknown> | undefined;
|
|
64
|
+
const content = msg?.content;
|
|
65
|
+
if (typeof content === "string") chunks.push(content);
|
|
66
|
+
}
|
|
67
|
+
return chunks.join("\n");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
// Cap banner builder
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
/** Build the banner appended to every read-only tool result in a subagent session. */
|
|
75
|
+
export function buildCapBanner(
|
|
76
|
+
state: SubagentState,
|
|
77
|
+
isRedundant: boolean,
|
|
78
|
+
previousCall: number | undefined,
|
|
79
|
+
tool: string,
|
|
80
|
+
): string {
|
|
81
|
+
const lines: string[] = [];
|
|
82
|
+
const capDisplay = state.cap === "none" ? "∞" : String(state.cap);
|
|
83
|
+
lines.push(`[cap: ${state.calls}/${capDisplay}]`);
|
|
84
|
+
|
|
85
|
+
if (isRedundant && previousCall !== undefined) {
|
|
86
|
+
lines.push(
|
|
87
|
+
`[⚠ REDUNDANT: this is the same ${tool} you ran at call #${previousCall}. STOP now — repeated reads add no information. Return with DONE/NEED MORE/NEED CONTEXT/SCOPE GROWTH/ESCALATE.]`,
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (state.cap !== "none") {
|
|
92
|
+
const remaining = state.cap - state.calls;
|
|
93
|
+
if (remaining <= 0) {
|
|
94
|
+
lines.push(
|
|
95
|
+
`[⚠ CAP REACHED (${state.calls}/${state.cap}): your NEXT response MUST be a return — do NOT make another read-only call. Start the response with DONE:, NEED MORE:, NEED CONTEXT:, SCOPE GROWTH:, or ESCALATE:.]`,
|
|
96
|
+
);
|
|
97
|
+
} else if (remaining <= 2) {
|
|
98
|
+
lines.push(
|
|
99
|
+
`[⚠ CAP WARNING: ${remaining} read-only call(s) remaining before forced return]`,
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return lines.join("\n");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// Read-only tools set (used by the session store)
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
/** Tools that count against the read-only cap. Keep narrow — editing tools should never count. */
|
|
112
|
+
export const READ_ONLY_TOOLS = new Set(["grep", "read", "glob", "ls"]);
|
|
113
|
+
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
// Trivial classifier
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
/** Normalise a taskPattern keyword to a lowercase stem for substring matching. */
|
|
119
|
+
function normTaskKw(kw: string): string {
|
|
120
|
+
return kw.toLowerCase().split("(")[0]!.split("/")[0]!.trim();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Classify a dispatch as "trivial" AT DISPATCH TIME (m2): conservative,
|
|
125
|
+
* tier-gated. Only a `fast`-tier dispatch whose text matches a fast taskPattern
|
|
126
|
+
* and contains NO medium/heavy signal is trivial. Real work (medium/heavy tier,
|
|
127
|
+
* or implementation keywords) is NEVER trivial — so proportional bypass can
|
|
128
|
+
* never silently disable enforcement on real work.
|
|
129
|
+
*/
|
|
130
|
+
export function classifyTrivial(
|
|
131
|
+
dispatchText: string,
|
|
132
|
+
tier: string | null,
|
|
133
|
+
cfg: RouterConfig,
|
|
134
|
+
): boolean {
|
|
135
|
+
if (tier !== "fast") return false;
|
|
136
|
+
const text = (dispatchText || "").toLowerCase();
|
|
137
|
+
if (!text.trim()) return false;
|
|
138
|
+
const disqualifiers = [
|
|
139
|
+
...(cfg.taskPatterns?.medium ?? []),
|
|
140
|
+
...(cfg.taskPatterns?.heavy ?? []),
|
|
141
|
+
];
|
|
142
|
+
for (const kw of disqualifiers) {
|
|
143
|
+
const n = normTaskKw(kw);
|
|
144
|
+
if (n.length >= 3 && text.includes(n)) return false;
|
|
145
|
+
}
|
|
146
|
+
const fast = cfg.taskPatterns?.fast ?? [];
|
|
147
|
+
for (const kw of fast) {
|
|
148
|
+
const n = normTaskKw(kw);
|
|
149
|
+
if (n.length >= 3 && text.includes(n)) return true;
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ---------------------------------------------------------------------------
|
|
155
|
+
// Session store factory
|
|
156
|
+
// ---------------------------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Creates a per-plugin-instance session store that owns the subagent tracking
|
|
160
|
+
* state (session IDs + cap state). Returns methods the hooks delegate to.
|
|
161
|
+
* Concurrency: Set/Map are per-store-instance, NOT module-level singletons.
|
|
162
|
+
*/
|
|
163
|
+
export function createSessionStore() {
|
|
164
|
+
const subagentSessionIDs = new Set<string>();
|
|
165
|
+
const subagentCapState = new Map<string, SubagentState>();
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
/** Returns true when sessionID belongs to a tracked subagent session. */
|
|
169
|
+
isSubagent(sessionID: string): boolean {
|
|
170
|
+
return subagentSessionIDs.has(sessionID);
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
/** Returns the tier name for a tracked subagent session, or null. */
|
|
174
|
+
getTier(sessionID: string): string | null {
|
|
175
|
+
return subagentCapState.get(sessionID)?.tierName ?? null;
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
/** Returns true when the session was classified as trivial at dispatch time. */
|
|
179
|
+
isTrivial(sessionID: string): boolean {
|
|
180
|
+
return subagentCapState.get(sessionID)?.trivial === true;
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Register a plugin-created producer session (from the delegate tool) so that
|
|
185
|
+
* Layer-1 (tool.execute.before) guards it like any other subagent. trivial:false
|
|
186
|
+
* ensures the producer is always fully enforced (never downgraded to advisory).
|
|
187
|
+
*/
|
|
188
|
+
registerProducerSession(sessionID: string, tier: string, cfg: RouterConfig): void {
|
|
189
|
+
subagentSessionIDs.add(sessionID);
|
|
190
|
+
const baseline = cfg.tierCaps?.[tier] ?? DEFAULT_TIER_CAPS[tier] ?? 5;
|
|
191
|
+
subagentCapState.set(sessionID, {
|
|
192
|
+
tierName: tier,
|
|
193
|
+
cap: baseline,
|
|
194
|
+
calls: 0,
|
|
195
|
+
seen: new Map(),
|
|
196
|
+
trivial: false,
|
|
197
|
+
});
|
|
198
|
+
},
|
|
199
|
+
|
|
200
|
+
/** Remove a session from tracking (used to clean up delegate producer sessions). */
|
|
201
|
+
unregister(sessionID: string): void {
|
|
202
|
+
subagentSessionIDs.delete(sessionID);
|
|
203
|
+
subagentCapState.delete(sessionID);
|
|
204
|
+
},
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Called from the chat.message hook. If the incoming message is directed
|
|
208
|
+
* at a registered tier agent, records the session and initialises its cap state.
|
|
209
|
+
* Accepts `tierNames` (from getActiveTiers) so this module doesn't need to
|
|
210
|
+
* import protocol.ts.
|
|
211
|
+
*/
|
|
212
|
+
registerFromChatMessage(
|
|
213
|
+
input: { agent?: string; sessionID: string },
|
|
214
|
+
output: unknown,
|
|
215
|
+
cfg: RouterConfig,
|
|
216
|
+
tierNames: string[],
|
|
217
|
+
): void {
|
|
218
|
+
if (input.agent && tierNames.includes(input.agent)) {
|
|
219
|
+
subagentSessionIDs.add(input.sessionID);
|
|
220
|
+
|
|
221
|
+
// Initialize cap state on first dispatch; reset on subsequent rounds to the same
|
|
222
|
+
// subagent session (rare but supported — treats each round as a fresh budget).
|
|
223
|
+
const tierName = input.agent;
|
|
224
|
+
const dispatchText = extractDispatchText(output);
|
|
225
|
+
const override = parseCapDirective(dispatchText);
|
|
226
|
+
const baseline =
|
|
227
|
+
cfg.tierCaps?.[tierName] ?? DEFAULT_TIER_CAPS[tierName] ?? 5;
|
|
228
|
+
const cap: Cap = override ?? baseline;
|
|
229
|
+
subagentCapState.set(input.sessionID, {
|
|
230
|
+
tierName,
|
|
231
|
+
cap,
|
|
232
|
+
calls: 0,
|
|
233
|
+
seen: new Map(),
|
|
234
|
+
trivial: classifyTrivial(dispatchText, tierName, cfg),
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Called from the tool.execute.after hook. Appends a cap/redundancy banner
|
|
241
|
+
* to the tool output for tracked subagent sessions running read-only tools.
|
|
242
|
+
* Mutates outputRef.output in place (same as the inlined hook logic).
|
|
243
|
+
*/
|
|
244
|
+
recordToolCall(
|
|
245
|
+
input: { sessionID: string; tool: string; args: unknown },
|
|
246
|
+
outputRef: Record<string, unknown>,
|
|
247
|
+
): void {
|
|
248
|
+
const state = subagentCapState.get(input.sessionID);
|
|
249
|
+
if (!state) return; // not a tracked subagent session
|
|
250
|
+
if (!READ_ONLY_TOOLS.has(input.tool)) return;
|
|
251
|
+
|
|
252
|
+
const fp = fingerprintToolCall(input.tool, input.args);
|
|
253
|
+
const previousCall = state.seen.get(fp);
|
|
254
|
+
const isRedundant = previousCall !== undefined;
|
|
255
|
+
|
|
256
|
+
state.calls += 1;
|
|
257
|
+
if (!isRedundant) {
|
|
258
|
+
state.seen.set(fp, state.calls);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const banner = buildCapBanner(state, isRedundant, previousCall, input.tool);
|
|
262
|
+
|
|
263
|
+
const existing =
|
|
264
|
+
typeof outputRef.output === "string" ? outputRef.output : "";
|
|
265
|
+
outputRef.output = existing ? `${existing}\n\n${banner}` : banner;
|
|
266
|
+
},
|
|
267
|
+
};
|
|
268
|
+
}
|