opencode-model-router 2.3.0 → 2.4.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +56 -10
  3. package/package.json +1 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1322 -18
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/v2.ts +26 -1
  54. package/src/verify/checker.ts +249 -7
  55. package/src/verify/deterministic.ts +10 -1
  56. package/src/verify/dispatch.ts +63 -6
  57. package/src/verify/dod.ts +127 -10
  58. package/src/verify/gate.ts +75 -7
  59. package/src/verify/types.ts +12 -0
  60. package/src/verify/wiring.ts +55 -10
  61. package/tiers.json +13 -5
@@ -14,6 +14,23 @@ import { formatRouterLine } from "./build-info";
14
14
  import { parseJsonc } from "./jsonc";
15
15
  import type { DelegateInstructionsPolicy } from "./instructions";
16
16
  import type { PluginLogger } from "./logger";
17
+ import { sanitizePluginAgents, type PluginAgentConfig } from "./plugin-agents";
18
+ // Runtime cycle config <-> roles: both sides use the other only inside functions, never at module evaluation.
19
+ import { resolveRoleTable, type ExplorationConfig, type RunConfig } from "./roles";
20
+ import {
21
+ DEFAULT_RUN_COMMANDS,
22
+ DEFAULT_RUN_SCRIPTS,
23
+ DEFAULT_RUN_TIMEOUT_MS,
24
+ ROLES_V1_NOTICE,
25
+ collectRolesIssues,
26
+ sanitizeDelegation,
27
+ sanitizeExploration,
28
+ sanitizeRoleAgents,
29
+ sanitizeRun,
30
+ sanitizeWorkRoots,
31
+ type DelegationMode,
32
+ type RoleAgentCustomisation,
33
+ } from "./roles-config";
17
34
 
18
35
  /**
19
36
  * Filename of the optional user overrides file (global and project copies share
@@ -85,6 +102,8 @@ export const DEFAULT_STRONG_MODEL_PATTERNS = [
85
102
 
86
103
  export interface TierConfig {
87
104
  model: string;
105
+ /** Host-enforced read-only tools. Defaults to true for fast, false otherwise. */
106
+ readOnly?: boolean;
88
107
  variant?: string;
89
108
  /**
90
109
  * Provider-agnostic effort. Loses to an explicit `thinking` budget on
@@ -302,6 +321,14 @@ export interface RoutingConfig {
302
321
  outcomes?: OutcomesConfig;
303
322
  sessionReuse?: SessionReuseConfig;
304
323
  advisor?: AdvisorConfig;
324
+ /** `tiers` (default) or `roles`; global and project layers. Inert on v1. */
325
+ delegation?: DelegationMode;
326
+ /** Global only. `rate` 0..0.2, default 0; `requireDetection` is fixed. Inert on v1. */
327
+ exploration?: Partial<ExplorationConfig>;
328
+ /** Global only. `router_run` allow-list. Inert on v1. */
329
+ run?: Partial<RunConfig>;
330
+ /** Global only. Absolute globs with a static long-form prefix; default none. */
331
+ workRoots?: string[];
305
332
  }
306
333
 
307
334
  export interface RouterConfig {
@@ -376,6 +403,20 @@ export interface RouterConfig {
376
403
  * subagents; a primary agent is the orchestrator.
377
404
  */
378
405
  subagentTiers?: Record<string, string>;
406
+ /**
407
+ * Subagents defined by the router config instead of opencode.json (#81):
408
+ * name → tier, description, optional prompt/steps and a router-published
409
+ * permission policy (`readOnly` and/or `permission`, plus `allowTools`).
410
+ * Only tiers.json and the global override may set it (A18). Validated per
411
+ * entry after merge: a bad entry is dropped with a config notice, never the
412
+ * layer. Absent ⇒ nothing is registered.
413
+ */
414
+ agents?: Record<string, PluginAgentConfig>;
415
+ /**
416
+ * Narrowing-only customisation of the shipped role agents (agent name → partial spec).
417
+ * tiers.json and the global override only; validated per entry, never dropping the layer.
418
+ */
419
+ roleAgents?: Record<string, RoleAgentCustomisation>;
379
420
  /** Experimental, opt-in features. Off by default. */
380
421
  experimental?: { verifiedDelegateTool?: boolean };
381
422
  /** Cost-aware routing engine (#74). Absent = today's static routing, byte for byte. */
@@ -728,6 +769,9 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
728
769
  );
729
770
  }
730
771
  const t = tier as Record<string, unknown>;
772
+ if (t.readOnly !== undefined && typeof t.readOnly !== "boolean") {
773
+ throw new Error(`tiers.json: '${presetName}.${tierName}.readOnly' must be a boolean`);
774
+ }
731
775
  // `model` is the only required tier field — so an overrides file can define
732
776
  // a new preset/tier with just `{ "model": "..." }`. The rest are optional
733
777
  // and only type-checked when present.
@@ -1765,6 +1809,16 @@ function validateRouting(value: unknown): RoutingConfig | undefined {
1765
1809
  const roles = validateRoles(routing);
1766
1810
  if (roles !== undefined) out.roles = roles;
1767
1811
 
1812
+ // Roles keys (#84): tolerant per entry, never throw (see roles-config.ts).
1813
+ const delegation = sanitizeDelegation(routing.delegation).value;
1814
+ if (delegation !== undefined) out.delegation = delegation;
1815
+ const exploration = sanitizeExploration(routing.exploration).value;
1816
+ if (exploration !== undefined) out.exploration = exploration;
1817
+ const run = sanitizeRun(routing.run).value;
1818
+ if (run !== undefined) out.run = run;
1819
+ const workRoots = sanitizeWorkRoots(routing.workRoots).value;
1820
+ if (workRoots !== undefined) out.workRoots = workRoots;
1821
+
1768
1822
  const outcomes = readBlock(routing, "outcomes", "routing");
1769
1823
  if (outcomes !== undefined) {
1770
1824
  const o: OutcomesConfig = {};
@@ -2034,9 +2088,11 @@ export function validateConfig(raw: unknown): RouterConfig {
2034
2088
  validateTaskPromptRepair(obj);
2035
2089
  validateFalseRefusalDetection(obj);
2036
2090
  const routing = validateRouting(obj.routing);
2091
+ // Never throws: a bad entry is dropped, and buildConfig reports it as a notice.
2092
+ const roleAgents = sanitizeRoleAgents(obj.roleAgents).value;
2037
2093
 
2038
2094
  const cfg = raw as RouterConfig;
2039
- return withValidatedSnapshots(cfg, { enforcement, routing });
2095
+ return withValidatedSnapshots(cfg, { enforcement, routing, roleAgents });
2040
2096
  }
2041
2097
 
2042
2098
  /**
@@ -2151,6 +2207,28 @@ const GLOBAL_ONLY_ROUTING_KEYS: ReadonlyArray<readonly [block: string, key: stri
2151
2207
  ["outcomes", "path"],
2152
2208
  ];
2153
2209
 
2210
+ /** Roles keys (#84) a project layer must not carry; `routing.delegation` is allowed there. */
2211
+ const GLOBAL_ONLY_ROLES_ROUTING_KEYS = ["exploration", "run", "workRoots"] as const;
2212
+
2213
+ function stripGlobalOnlyRolesKeys(data: Record<string, unknown>): string[] {
2214
+ const dropped: string[] = [];
2215
+ if (Object.hasOwn(data, "roleAgents")) {
2216
+ delete data.roleAgents;
2217
+ dropped.push("roleAgents");
2218
+ }
2219
+ const routing = data.routing;
2220
+ if (isPlainObject(routing)) {
2221
+ for (const key of GLOBAL_ONLY_ROLES_ROUTING_KEYS) {
2222
+ if (Object.hasOwn(routing, key)) {
2223
+ delete routing[key];
2224
+ dropped.push(`routing.${key}`);
2225
+ }
2226
+ }
2227
+ if (dropped.length > 0 && Object.keys(routing).length === 0) delete data.routing;
2228
+ }
2229
+ return dropped;
2230
+ }
2231
+
2154
2232
  /** Remove the global-only `routing` keys from a project layer; returns what was dropped. */
2155
2233
  function stripGlobalOnlyRoutingKeys(data: Record<string, unknown>): string[] {
2156
2234
  const routing = data.routing;
@@ -2200,6 +2278,24 @@ function collectOverrideLayers(
2200
2278
  message: `ignoring ${dropped.join(", ")} from ${p}: only the global override may set it`,
2201
2279
  });
2202
2280
  }
2281
+ // #84: a repository may pick `routing.delegation`, but not customise role agents, grant
2282
+ // exploration, define `router_run` commands or widen the work roots.
2283
+ const rolesDropped = stripGlobalOnlyRolesKeys(data);
2284
+ if (rolesDropped.length > 0) {
2285
+ notices?.push({
2286
+ source: p,
2287
+ message: `ignoring ${rolesDropped.join(", ")} from ${p}: only tiers.json or the global override may set it`,
2288
+ });
2289
+ }
2290
+ // A18 (#81): a cloned repository must not register agents, let alone
2291
+ // ones with permissions. The rest of the project layer still applies.
2292
+ if (Object.hasOwn(data, "agents")) {
2293
+ delete data.agents;
2294
+ notices?.push({
2295
+ source: p,
2296
+ message: `ignoring agents from ${p}: only tiers.json or the global override may define agents (A18)`,
2297
+ });
2298
+ }
2203
2299
  }
2204
2300
  layers.push({ path: p, data, project });
2205
2301
  }
@@ -2412,6 +2508,10 @@ const ROUTING_KNOWN_KEYS: Readonly<Record<string, readonly string[]>> = {
2412
2508
  "outcomes",
2413
2509
  "sessionReuse",
2414
2510
  "advisor",
2511
+ "delegation",
2512
+ "exploration",
2513
+ "run",
2514
+ "workRoots",
2415
2515
  ],
2416
2516
  detection: ["deterministic", "grader", "none"],
2417
2517
  classifier: ["backend", "model", "baseUrl", "apiKeyEnv", "timeoutMs", "samples", "maxStateChars", "presets"],
@@ -2648,10 +2748,76 @@ function buildConfig(
2648
2748
  applyTierDefaults(cfg);
2649
2749
  const rawRouting = isPlainObject(rawUsed) ? rawUsed.routing : undefined;
2650
2750
  for (const message of collectRoutingNotices(rawRouting, cfg)) notices.push({ message });
2751
+ const rawRoleAgents = isPlainObject(rawUsed) ? rawUsed.roleAgents : undefined;
2752
+ for (const issue of collectRolesIssues(rawRouting, rawRoleAgents)) notices.push({ message: issue.message });
2651
2753
  dropIgnoredCandidates(cfg);
2754
+ applyPluginAgents(cfg, layers, notices);
2755
+ applyRoleNotices(cfg, notices);
2652
2756
  return cfg;
2653
2757
  }
2654
2758
 
2759
+ /** Prefix of every role-table notice: they describe roles mode, which only OpenCode v2 runs (QA-P11-2-1). */
2760
+ export const ROLE_NOTICE_PREFIX = "roles mode (OpenCode v2 only): ";
2761
+
2762
+ /** The role-table resolver used for notices; replaceable in tests only. */
2763
+ let roleTableResolver: typeof resolveRoleTable = resolveRoleTable;
2764
+
2765
+ /** Test-only: replace the resolver {@link applyRoleNotices} calls; no argument restores it. */
2766
+ export function setRoleTableResolverForTest(resolver?: typeof resolveRoleTable): void {
2767
+ roleTableResolver = resolver ?? resolveRoleTable;
2768
+ }
2769
+
2770
+ /**
2771
+ * Roles mode (#84): the notices of resolving the role table — unknown `roleAgents` names,
2772
+ * clamped budgets and ranges, disabled roles, #81 `agents` that replace or are dropped for a
2773
+ * role — so they reach `/router` with the other config notices. Pure; the host is not known
2774
+ * here, so the table is resolved as on v2 and every notice says it is about roles mode (on v1
2775
+ * the roles keys stay inert). It never throws: a failure is one notice, and the config loads
2776
+ * (QA-P11-2-2).
2777
+ */
2778
+ function applyRoleNotices(cfg: RouterConfig, notices: ConfigNotice[]): void {
2779
+ if (cfg.routing?.delegation !== "roles") return;
2780
+ try {
2781
+ for (const issue of roleTableResolver(cfg, "v2").issues) notices.push({ message: `${ROLE_NOTICE_PREFIX}${issue.message}` });
2782
+ } catch (err) {
2783
+ const reason = err instanceof Error ? err.message : String(err);
2784
+ notices.push({ message: `roles: the role table could not be resolved (${reason}); no role agent will be registered` });
2785
+ }
2786
+ }
2787
+
2788
+ /**
2789
+ * Validate the merged `agents` block per entry against the active preset (#81).
2790
+ * Runs after the persisted preset is applied, so a `/preset` rebuild re-checks
2791
+ * every `tier`. A bad entry is removed with a notice naming its key path and
2792
+ * file; the other entries, the layer and `routing` are kept (#80).
2793
+ */
2794
+ /**
2795
+ * The one preset resolver for plugin agents: validation, registration and the status lines all use it,
2796
+ * so they cannot disagree (QA-81-9). Case-insensitive like /preset; falls back to the first preset.
2797
+ */
2798
+ export function resolveActiveTiers(cfg: RouterConfig): Preset {
2799
+ const name = resolvePresetName(cfg, cfg.activePreset);
2800
+ return (name !== undefined ? cfg.presets[name] : undefined) ?? Object.values(cfg.presets)[0] ?? {};
2801
+ }
2802
+
2803
+ function applyPluginAgents(cfg: RouterConfig, layers: readonly OverrideLayer[], notices: ConfigNotice[]): void {
2804
+ if (!Object.hasOwn(cfg, "agents")) return;
2805
+ const tiers = resolveActiveTiers(cfg);
2806
+ const { agents, issues } = sanitizePluginAgents(cfg.agents, { activePreset: cfg.activePreset, tiers });
2807
+ // Project layers never carry `agents` (stripped while collecting), so the
2808
+ // source is the global override when it names the entry, else tiers.json.
2809
+ const globalAgents = layers.find((layer) => !layer.project)?.data.agents;
2810
+ for (const issue of issues) {
2811
+ const name = issue.name;
2812
+ const source = isPlainObject(globalAgents) && (name === undefined || Object.hasOwn(globalAgents, name))
2813
+ ? layers.find((layer) => !layer.project)!.path
2814
+ : configPath();
2815
+ notices.push({ source, message: `${issue.path}: ${issue.message} (${source})` });
2816
+ }
2817
+ if (agents === undefined) delete cfg.agents;
2818
+ else cfg.agents = agents;
2819
+ }
2820
+
2655
2821
  /**
2656
2822
  * Remove, from the built config, every `candidates` list that loading reports as
2657
2823
  * ignored ({@link candidatesProblem}), after the notice has been recorded
@@ -3006,6 +3172,63 @@ export function resolveRouting(
3006
3172
  });
3007
3173
  }
3008
3174
 
3175
+ /** The roles keys with their defaults applied, for one host (#84). Never mutates `cfg`. */
3176
+ export interface ResolvedRolesRouting {
3177
+ readonly delegation: DelegationMode;
3178
+ readonly exploration: Readonly<ExplorationConfig>;
3179
+ readonly run: Readonly<RunConfig>;
3180
+ readonly workRoots: readonly string[];
3181
+ /** True on v1 when roles keys were set: they are validated but have no effect. */
3182
+ readonly inert: boolean;
3183
+ }
3184
+
3185
+ let warnedRolesInertOnV1 = false;
3186
+
3187
+ /** Test-only: re-arm the once-per-process "roles delegation requires v2" notice. */
3188
+ export function resetRolesWarnings(): void {
3189
+ warnedRolesInertOnV1 = false;
3190
+ }
3191
+
3192
+ /**
3193
+ * Defaults for `routing.delegation`, `exploration`, `run` and `workRoots`. On v1 (`routerHost`
3194
+ * `v1`) delegation is always `tiers`, and one notice says so when any of delegation `roles`,
3195
+ * `roleAgents`, `exploration`, `run` or `workRoots` was set. Exploration is off (rate 0) unless
3196
+ * the effective delegation is `roles`. Switching `delegation` is only a config value here;
3197
+ * registration follows a hot reload elsewhere. The plugin logs the v1 notice at start-up by
3198
+ * calling this with its logger next to `resolveRouting` (wired with the roles runtime, #84 P2.1).
3199
+ */
3200
+ export function resolveRolesRouting(
3201
+ cfg: RouterConfig | undefined,
3202
+ host: RouterHost,
3203
+ logger?: Pick<PluginLogger, "warn">,
3204
+ ): ResolvedRolesRouting {
3205
+ const r: RoutingConfig = cfg?.routing ?? {};
3206
+ const requested = r.delegation ?? "tiers";
3207
+ const touched = requested === "roles" || cfg?.roleAgents !== undefined || r.exploration !== undefined
3208
+ || r.run !== undefined || r.workRoots !== undefined;
3209
+ const inert = host === "v1" && touched;
3210
+ if (inert && !warnedRolesInertOnV1) {
3211
+ warnedRolesInertOnV1 = true;
3212
+ if (logger) logger.warn(ROLES_V1_NOTICE);
3213
+ else console.warn(`[model-router] ${ROLES_V1_NOTICE}`);
3214
+ }
3215
+ const delegation: DelegationMode = host === "v1" ? "tiers" : requested;
3216
+ return Object.freeze({
3217
+ delegation,
3218
+ exploration: Object.freeze({
3219
+ rate: delegation === "roles" ? (r.exploration?.rate ?? 0) : 0,
3220
+ requireDetection: "deterministic" as const,
3221
+ }),
3222
+ run: Object.freeze({
3223
+ scripts: Object.freeze([...(r.run?.scripts ?? DEFAULT_RUN_SCRIPTS)]),
3224
+ commands: Object.freeze({ ...(r.run?.commands ?? DEFAULT_RUN_COMMANDS) }),
3225
+ timeoutMs: r.run?.timeoutMs ?? DEFAULT_RUN_TIMEOUT_MS,
3226
+ }),
3227
+ workRoots: Object.freeze([...(r.workRoots ?? [])]),
3228
+ inert,
3229
+ });
3230
+ }
3231
+
3009
3232
  /**
3010
3233
  * The key of `presets` that names `presetName`: an exact match, else a
3011
3234
  * case-insensitive, trimmed one, like {@link resolvePresetName} (what `/preset`
@@ -3111,6 +3334,29 @@ export function routerStatusLines(
3111
3334
  ): string[] {
3112
3335
  return [
3113
3336
  formatRouterLine(resolveRouting(cfg, host, logger).engine),
3337
+ ...pluginAgentLines(cfg),
3114
3338
  ...getConfigNotices(dir).map((notice) => `router: config notice: ${notice.message}`),
3115
3339
  ];
3116
3340
  }
3341
+
3342
+ /**
3343
+ * The `/router` "Plugin agents" listing (#81): one line per agent of the
3344
+ * `agents` block. Empty without the block, so `/router` output is unchanged.
3345
+ */
3346
+ export function pluginAgentLines(cfg: RouterConfig): string[] {
3347
+ const agents = cfg.agents;
3348
+ if (agents === undefined) return [];
3349
+ const names = Object.keys(agents);
3350
+ if (names.length === 0) return [];
3351
+ const preset = resolveActiveTiers(cfg);
3352
+ return [
3353
+ "router: Plugin agents:",
3354
+ ...names.map((name) => {
3355
+ const agent = agents[name];
3356
+ const tier = preset !== undefined && Object.hasOwn(preset, agent.tier) ? preset[agent.tier] : undefined;
3357
+ const policy = agent.readOnly === true ? "read-only" : "custom permission";
3358
+ const model = tier === undefined ? "?" : `${tier.model}${tier.variant ? `#${tier.variant}` : ""}`;
3359
+ return `router: ${name} → ${agent.tier} (${model}), ${policy}`;
3360
+ }),
3361
+ ];
3362
+ }
@@ -1,3 +1,14 @@
1
+ import { parseRouteLine } from "../routing/classify/route-line";
2
+
3
+ /** First characters of every router dispatch header (index.ts never adds a second one). */
4
+ export const DISPATCH_HEADER_PREFIX = "[router] You are @";
5
+
6
+ /** What index.ts puts between the header and the orchestrator's prompt. */
7
+ export const DISPATCH_HEADER_SEPARATOR = "\n\n---\n\n";
8
+
9
+ /** The header's last paragraph: the end of a header whose separator is missing. */
10
+ const FALSE_REFUSAL_PARAGRAPH = "A hand-back with zero tool calls is recorded as a false refusal.";
11
+
1
12
  /**
2
13
  * Mechanical dispatch guidance, independent of provider tool vocabulary.
3
14
  * Tier identity prevents delegates routing their assignment back to another tier.
@@ -10,17 +21,23 @@
10
21
  * The budget paragraph makes the cap explicit and prevents halting when the
11
22
  * redundancy detector flags a legitimate non-overlapping second read of a file.
12
23
  * The final notice calls out the zero-tool-call false refusals directly.
24
+ *
25
+ * `root` (plan §2.2, T1.5.3a): the dispatch's work root — the route line's `root=`
26
+ * (`routeLineRoot`) — named by the working-directory paragraph instead of the
27
+ * project directory. Absent or empty: the header is byte-identical to before.
13
28
  */
14
29
  export function buildDispatchHeader(input: {
15
30
  tier: string;
16
31
  cap: number | "none";
17
32
  projectDirectory: string | undefined;
33
+ root?: string | null;
18
34
  }): string {
19
35
  const paragraphs = [
20
- `[router] You are @${input.tier}. Execute this dispatch yourself; do not route it to another tier, and do not ask to be re-dispatched.`,
36
+ `${DISPATCH_HEADER_PREFIX}${input.tier}. Execute this dispatch yourself; do not route it to another tier, and do not ask to be re-dispatched.`,
21
37
  ];
22
- if (input.projectDirectory) {
23
- paragraphs.push(`Working directory: ${input.projectDirectory}. You are already there — do not ask permission to read or write inside it.`);
38
+ const directory = input.root || input.projectDirectory;
39
+ if (directory) {
40
+ paragraphs.push(`Working directory: ${directory}. You are already there — do not ask permission to read or write inside it.`);
24
41
  }
25
42
  paragraphs.push(
26
43
  'Tool names mentioned in this dispatch are descriptive and vary by provider; your own tool schema is the authority on what you can do. Never refuse or hand back work because a named tool looks unfamiliar or missing — attempt it, and if you cannot finish, name the specific step that failed.',
@@ -30,7 +47,32 @@ export function buildDispatchHeader(input: {
30
47
  // instructional CAP:none example, which must not override the real dispatch.
31
48
  `CAP:${input.cap}`,
32
49
  'To change the budget, put CAP:N or CAP:none accompanied by a reason: line in the dispatch.',
33
- 'A hand-back with zero tool calls is recorded as a false refusal.',
50
+ FALSE_REFUSAL_PARAGRAPH,
34
51
  );
35
52
  return paragraphs.join("\n\n");
36
53
  }
54
+
55
+ /**
56
+ * The work root a dispatch prompt names on its first-line route line (`root=`,
57
+ * an absolute path validated by the parser), or undefined. The caller passes it
58
+ * to buildDispatchHeader as `root`.
59
+ */
60
+ export function routeLineRoot(prompt: string): string | undefined {
61
+ return parseRouteLine(prompt, { positions: "first" }).line?.root;
62
+ }
63
+
64
+ /**
65
+ * The orchestrator's prompt without the router dispatch header (R6/P-15): when
66
+ * the text starts with DISPATCH_HEADER_PREFIX, everything up to and including the
67
+ * first DISPATCH_HEADER_SEPARATOR is dropped. The prefix and the separator carry
68
+ * no v1 tool vocabulary, so the v2-translated header (v2Instructions) strips the
69
+ * same way. Without a separator, the header ends at its last paragraph; a text
70
+ * with neither is returned unchanged.
71
+ */
72
+ export function stripDispatchHeader(prompt: string): string {
73
+ if (!prompt.startsWith(DISPATCH_HEADER_PREFIX)) return prompt;
74
+ const separator = prompt.indexOf(DISPATCH_HEADER_SEPARATOR);
75
+ if (separator !== -1) return prompt.slice(separator + DISPATCH_HEADER_SEPARATOR.length);
76
+ const last = prompt.indexOf(FALSE_REFUSAL_PARAGRAPH);
77
+ return last === -1 ? prompt : prompt.slice(last + FALSE_REFUSAL_PARAGRAPH.length).replace(/^\s+/, "");
78
+ }