opencode-model-router 2.7.0 → 2.9.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/CHANGELOG.md +583 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/approvals.ts +354 -0
- package/src/commands/output.ts +34 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2853 -109
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1789 -288
- package/src/router/config.ts +823 -26
- package/src/router/dispatch-header.ts +95 -2
- package/src/router/git-tools.ts +266 -19
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +44 -10
- package/src/router/role-agents.ts +334 -20
- package/src/router/roles-config.ts +93 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/sessions.ts +11 -0
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/route-line.ts +96 -5
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/classify/types.ts +26 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/signals.ts +17 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/admission.ts +1028 -0
- package/src/routing/roles/approvals.ts +957 -0
- package/src/routing/roles/binding.ts +116 -13
- package/src/routing/roles/check-placement.ts +112 -0
- package/src/routing/roles/git-root.ts +500 -0
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +30 -3
- package/src/routing/roles/read-set.ts +325 -0
- package/src/routing/roles/work-root.ts +12 -2
- package/src/routing/wire/dispatch.ts +697 -30
- package/src/routing/wire/hint.ts +56 -8
- package/src/routing/wire/working-set.ts +58 -0
- package/src/util/linear-trim.ts +32 -0
- package/src/v2.ts +94 -49
- package/src/verify/batch.ts +7 -2
- package/src/verify/branch.ts +141 -0
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +268 -17
- package/src/verify/dispatch.ts +348 -37
- package/src/verify/dod.ts +46 -0
- package/src/verify/edges.ts +817 -0
- package/src/verify/exec.ts +52 -9
- package/src/verify/gate.ts +349 -16
- package/src/verify/git-top.ts +43 -0
- package/src/verify/head.ts +107 -0
- package/src/verify/pending.ts +1846 -18
- package/src/verify/perimeter.ts +1186 -0
- package/src/verify/pin.ts +109 -0
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +297 -8
- package/src/verify/risk.ts +16 -3
- package/src/verify/runner.ts +706 -32
- package/src/verify/tree.ts +372 -16
- package/src/verify/types.ts +66 -2
- package/src/verify/wiring.ts +1594 -46
package/README.md
CHANGED
|
@@ -1232,6 +1232,26 @@ With `routing.delegation: "roles"` the orchestrator stops picking tiers: it disp
|
|
|
1232
1232
|
|
|
1233
1233
|
Put `{ "routing": { "delegation": "roles" } }` in the global override file and **restart OpenCode** (roles mode is decided at plugin start); restore the previous file and restart to go back. OpenCode v1 keeps the tier model. Guide: [`docs/ROLES.md`](docs/ROLES.md); decision record: [`docs/adr/0006-role-tier-assurance-delegation.md`](docs/adr/0006-role-tier-assurance-delegation.md).
|
|
1234
1234
|
|
|
1235
|
+
## Executing plans
|
|
1236
|
+
|
|
1237
|
+
On **OpenCode v2 in roles mode selected at start**, `/plan run <path>` asks the orchestrator to compile a Markdown plan into a durable task ledger and
|
|
1238
|
+
dependency graph through `router_plan`. It shows the task count, critical path, expected makespan and manual tasks.
|
|
1239
|
+
With the default `routing.executor.approve: "ask"`, compilation **does not start work**: review the summary, then use
|
|
1240
|
+
`/plan approve <planId>` or explicitly approve that plan after seeing its summary. A request to run it is not approval;
|
|
1241
|
+
the model never approves on its own. Global `approve: "auto"` is an explicit opt-in.
|
|
1242
|
+
|
|
1243
|
+
Ready tasks run in parallel in isolated git worktree slots, are verified there, then integrate serially through checks.
|
|
1244
|
+
`/plan status [planId]` shows progress, inbox and metrics; `/plan inbox` lists decisions and `/plan answer <id> <text>`
|
|
1245
|
+
answers one. Use `/plan pause <planId>` to stop new launches, `/plan resume <planId>` to continue, and `/plan land <planId>`
|
|
1246
|
+
to request fast-forward landing into a clean checkout. The ledger survives a restart; it is not conversation state.
|
|
1247
|
+
|
|
1248
|
+
The executor requires roles mode selected at start, enforced leases, a git repository and an available plan-task
|
|
1249
|
+
verifier (`enforcement.verify.require` must not be `"never"`). OpenCode v1 registers no executor tool or command.
|
|
1250
|
+
`router_plan` and `/plan` are registered only in roles mode at start, like `router_run`; tiers mode registers neither.
|
|
1251
|
+
See [the executor guide](docs/EXECUTOR.md) for setup, every command/action/config key, the safety model, Windows notes,
|
|
1252
|
+
recovery, troubleshooting, metrics and the owner checklist; [ADR 0007](docs/adr/0007-critical-path-execution.md) records
|
|
1253
|
+
the decisions. `/annotate-plan` below only annotates a plan; it does not execute it.
|
|
1254
|
+
|
|
1235
1255
|
## TUI status (OpenCode v2)
|
|
1236
1256
|
|
|
1237
1257
|
On OpenCode v2 (2.0.24 or later) the package also ships a TUI entry, `tui.ts`, that shows which model and effort the router's sessions run with:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-model-router",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.9.0",
|
|
4
4
|
"description": "OpenCode plugin that routes tasks to tiered subagents (fast/medium/heavy) based on complexity",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
|
@@ -15,7 +15,11 @@
|
|
|
15
15
|
"smoke:routing": "cross-env RUN_OC_SMOKE_ROUTING=1 vitest run --config vitest.smoke.config.ts test/smoke/routing-engine.smoke.test.ts",
|
|
16
16
|
"smoke:v2:e2e": "cross-env RUN_OC_SMOKE_V2_E2E=1 vitest run --config vitest.smoke.config.ts test/smoke/v2-provider-e2e.smoke.test.ts",
|
|
17
17
|
"smoke:tui": "cross-env RUN_OC_SMOKE_TUI=1 vitest run --config vitest.smoke.config.ts test/smoke/tui-status.smoke.test.ts",
|
|
18
|
+
"smoke:cpx": "cross-env RUN_OC_SMOKE_CPX=1 vitest run --config vitest.smoke.config.ts test/smoke/helpers/cpx-scripted-provider test/smoke/helpers/routing-host test/smoke/cpx-host-contract test/smoke/cpx-cache-prefix test/smoke/cpx-background",
|
|
19
|
+
"smoke:cpx:provision": "cross-env RUN_OC_SMOKE_CPX=1 vitest run --config vitest.smoke.config.ts test/smoke/cpx-provision",
|
|
20
|
+
"smoke:cpx:e2e": "cross-env RUN_OC_SMOKE_CPX=1 vitest run --config vitest.smoke.config.ts test/smoke/cpx-e2e",
|
|
18
21
|
"routing:stats": "node scripts/routing-stats.ts",
|
|
22
|
+
"soak:analyze": "node scripts/soak-analyze.mjs",
|
|
19
23
|
"typecheck": "tsc --noEmit"
|
|
20
24
|
},
|
|
21
25
|
"license": "GPL-3.0-only",
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-repo Phase 4 (P4.7): `/router approve <path>`, `/router repos` and `/router revoke <path>`
|
|
3
|
+
* (`docs/design/cross-repo-phase4-plan.md`, SD-P4-10..13, S1/S2).
|
|
4
|
+
*
|
|
5
|
+
* Only these commands write the approvals store (S1). What the human sees and what gets stored come from git at approve time
|
|
6
|
+
* (`inspectCandidate`), never from the dispatch text or the refusal note (S2). `repos` reads the store only (no git). Every
|
|
7
|
+
* repository-derived string passes through `displaySafe`. Whether the commands are available at all (v2 host, roles mode,
|
|
8
|
+
* `routing.repoParents` non-empty, a top-level human session: SD-P4-10) is decided by the `/router` handler, not here.
|
|
9
|
+
*/
|
|
10
|
+
import * as fs from "node:fs";
|
|
11
|
+
import * as path from "node:path";
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
applyApproval,
|
|
15
|
+
expiresAt,
|
|
16
|
+
inspectCandidate,
|
|
17
|
+
isApprovalValid,
|
|
18
|
+
readApprovals,
|
|
19
|
+
type ApprovalsEnv,
|
|
20
|
+
type IdentityDeps,
|
|
21
|
+
type InspectDeps,
|
|
22
|
+
type RepoApproval,
|
|
23
|
+
} from "../routing/roles/approvals";
|
|
24
|
+
import { displaySafe } from "../routing/roles/read-set";
|
|
25
|
+
import { permissionMatches } from "../router/read-only";
|
|
26
|
+
import { REPO_APPROVAL_CAP_DAYS } from "../router/roles-config";
|
|
27
|
+
import { dropFromWorkingSets } from "../routing/wire/working-set";
|
|
28
|
+
|
|
29
|
+
/** The `/router` subcommands of this module, in help order. */
|
|
30
|
+
export const ROUTER_APPROVAL_SUBCOMMANDS = ["approve", "repos", "revoke"] as const;
|
|
31
|
+
export type RouterApprovalSubcommand = (typeof ROUTER_APPROVAL_SUBCOMMANDS)[number];
|
|
32
|
+
|
|
33
|
+
/** Whether `sub` (lower-cased first word of the `/router` arguments) is one of {@link ROUTER_APPROVAL_SUBCOMMANDS}. */
|
|
34
|
+
export function isRouterApprovalSubcommand(sub: string): sub is RouterApprovalSubcommand {
|
|
35
|
+
return (ROUTER_APPROVAL_SUBCOMMANDS as readonly string[]).includes(sub);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What an `approve` or `revoke` changed in the store; carried by the command output for the v2 adapter (SD-P4-11). */
|
|
39
|
+
export interface ApprovalsChange {
|
|
40
|
+
readonly kind: "approve" | "revoke";
|
|
41
|
+
/** The canonical path of the approved or revoked repository. */
|
|
42
|
+
readonly path: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Non-enumerable key on the `/router` command output (its `parts` array) after an `approve` or `revoke` that wrote the store
|
|
47
|
+
* (SD-P4-11). The v2 command adapter then reloads the role agents before it sends the text on.
|
|
48
|
+
*/
|
|
49
|
+
export const APPROVALS_CHANGED: unique symbol = Symbol.for("opencode-model-router.approvals-changed");
|
|
50
|
+
|
|
51
|
+
/** Mark `target` (the command output's `parts`) with `change`, non-enumerable, so serialisation and copies never carry it. */
|
|
52
|
+
export function markApprovalsChanged(target: object, change: ApprovalsChange): void {
|
|
53
|
+
Object.defineProperty(target, APPROVALS_CHANGED, { value: Object.freeze({ ...change }), enumerable: false, configurable: true, writable: false });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The change marked on `target` by {@link markApprovalsChanged}, or undefined. */
|
|
57
|
+
export function approvalsChangedOf(target: unknown): ApprovalsChange | undefined {
|
|
58
|
+
if (typeof target !== "object" || target === null) return undefined;
|
|
59
|
+
const value: unknown = Reflect.get(target, APPROVALS_CHANGED);
|
|
60
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
61
|
+
const kind: unknown = Reflect.get(value, "kind");
|
|
62
|
+
const where: unknown = Reflect.get(value, "path");
|
|
63
|
+
if ((kind !== "approve" && kind !== "revoke") || typeof where !== "string") return undefined;
|
|
64
|
+
return { kind, path: where };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The line the v2 command adapter appends after it reloaded the role agents for `change` (SD-P4-11). `applies` is
|
|
69
|
+
* `APPROVAL_RELOAD_APPLIES` (spike T6: a reload makes the host allow the approved directory); `reloadError` is set when the
|
|
70
|
+
* reload failed, which gives the restart line too.
|
|
71
|
+
*/
|
|
72
|
+
export function approvalReloadLine(change: ApprovalsChange, applies: boolean, reloadError?: string): string {
|
|
73
|
+
const repo = displaySafe(change.path);
|
|
74
|
+
const failed = reloadError === undefined ? "" : `The role agents could not be reloaded (${displaySafe(reloadError)}). `;
|
|
75
|
+
if (change.kind === "approve") {
|
|
76
|
+
return reloadError === undefined && applies
|
|
77
|
+
? `Role agents reloaded; dispatch again with root=${repo}.`
|
|
78
|
+
: `${failed}Restart OpenCode to use it.`;
|
|
79
|
+
}
|
|
80
|
+
return reloadError === undefined && applies
|
|
81
|
+
? `Role agents reloaded; root=${repo} is no longer allowed.`
|
|
82
|
+
: `${failed}The router refuses root=${repo} now; restart OpenCode to remove its directory permission from the role agents.`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Configuration and injectable I/O of {@link runRouterApprovals}. */
|
|
86
|
+
export interface RouterApprovalsOptions {
|
|
87
|
+
/** `routing.repoParents` (resolved). */
|
|
88
|
+
readonly parents: readonly string[];
|
|
89
|
+
/** `routing.repoExclude` (resolved). */
|
|
90
|
+
readonly exclude: readonly string[];
|
|
91
|
+
/** `routing.repoApprovalDays` (resolved). */
|
|
92
|
+
readonly days: number;
|
|
93
|
+
/**
|
|
94
|
+
* `routing.repoDepth` (resolved): a candidate below a parent but deeper than this is reported as one no approval applies to.
|
|
95
|
+
* Undefined: no depth check (every candidate inside a parent needs no approval).
|
|
96
|
+
*/
|
|
97
|
+
readonly repoDepth?: number;
|
|
98
|
+
/** Store environment (tests: the store directory and the clock). */
|
|
99
|
+
readonly env?: ApprovalsEnv;
|
|
100
|
+
/** Git and filesystem of the candidate inspection (tests). */
|
|
101
|
+
readonly identity?: IdentityDeps;
|
|
102
|
+
/** Default `process.platform`. */
|
|
103
|
+
readonly platform?: NodeJS.Platform;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface RouterApprovalsResult {
|
|
107
|
+
readonly text: string;
|
|
108
|
+
/** Set when the store was written (approve, revoke). */
|
|
109
|
+
readonly change?: ApprovalsChange;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const DAY_MS = 86_400_000;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The path argument: the rest of the `/router` arguments, trimmed, with one pair of surrounding double or single quotes
|
|
116
|
+
* removed (so a path with spaces can be quoted, or typed as is). Undefined when empty.
|
|
117
|
+
*/
|
|
118
|
+
export function parseApprovalPath(rest: string): string | undefined {
|
|
119
|
+
let text = rest.trim();
|
|
120
|
+
const q = text[0];
|
|
121
|
+
if (text.length >= 2 && (q === "\"" || q === "'") && text.endsWith(q)) text = text.slice(1, -1).trim();
|
|
122
|
+
return text === "" ? undefined : text;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function keyOf(p: string, platform: NodeJS.Platform): string {
|
|
126
|
+
return platform === "win32" ? p.toLowerCase() : p;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Normalized comparison form: resolved, no trailing separator except at a root, case-folded on win32. */
|
|
130
|
+
function cmpForm(p: string, platform: NodeJS.Platform): string {
|
|
131
|
+
let r = path.resolve(p);
|
|
132
|
+
const root = path.parse(r).root;
|
|
133
|
+
while (r.length > root.length && (r.endsWith(path.sep) || r.endsWith("/"))) r = r.slice(0, -1);
|
|
134
|
+
return keyOf(r, platform);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function realOrUndefined(p: string, realpath: (p: string) => string): string | undefined {
|
|
138
|
+
try {
|
|
139
|
+
const real = realpath(p);
|
|
140
|
+
return typeof real === "string" && real !== "" ? real : undefined;
|
|
141
|
+
} catch {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function realpathOf(opts: RouterApprovalsOptions): (p: string) => string {
|
|
147
|
+
return opts.identity?.realpath ?? ((p: string) => fs.realpathSync.native(p));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** `form` with one trailing separator (comparison forms keep one only at a filesystem root). */
|
|
151
|
+
function withSep(form: string): string {
|
|
152
|
+
return form.endsWith(path.sep) || form.endsWith("/") ? form : `${form}${path.sep}`;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Whether comparison form `child` is strictly inside comparison form `parent`. */
|
|
156
|
+
function strictlyInside(child: string, parent: string): boolean {
|
|
157
|
+
return child !== parent && child.startsWith(withSep(parent));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** How a candidate relates to `routing.repoParents`: it is a parent, contains one, or is `depth` levels below one. */
|
|
161
|
+
type ParentRelation =
|
|
162
|
+
| { readonly kind: "is" | "contains"; readonly parent: string }
|
|
163
|
+
| { readonly kind: "inside"; readonly parent: string; readonly depth: number };
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* How `canonical` relates to the `routing.repoParents` entries (each in its text and canonical form, case-insensitive on
|
|
167
|
+
* win32), or undefined when it is outside all of them. Being or containing a parent wins over being inside another one;
|
|
168
|
+
* among the parents holding it, the nearest (smallest depth) is reported. No git.
|
|
169
|
+
*/
|
|
170
|
+
function parentRelation(canonical: string, opts: RouterApprovalsOptions, platform: NodeJS.Platform): ParentRelation | undefined {
|
|
171
|
+
const candidate = cmpForm(canonical, platform);
|
|
172
|
+
const realpath = realpathOf(opts);
|
|
173
|
+
let nearest: { parent: string; depth: number } | undefined;
|
|
174
|
+
let holder: ParentRelation | undefined;
|
|
175
|
+
for (const parent of opts.parents) {
|
|
176
|
+
if (parent.trim() === "" || !path.isAbsolute(parent)) continue;
|
|
177
|
+
const forms = new Set([cmpForm(parent, platform)]);
|
|
178
|
+
const real = realOrUndefined(parent, realpath);
|
|
179
|
+
if (real !== undefined) forms.add(cmpForm(real, platform));
|
|
180
|
+
for (const form of forms) {
|
|
181
|
+
if (candidate === form) return { kind: "is", parent };
|
|
182
|
+
if (strictlyInside(form, candidate)) holder ??= { kind: "contains", parent };
|
|
183
|
+
else if (strictlyInside(candidate, form)) {
|
|
184
|
+
const depth = candidate.slice(withSep(form).length).split(/[\\/]/).filter((part) => part !== "").length;
|
|
185
|
+
if (nearest === undefined || depth < nearest.depth) nearest = { parent, depth };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (holder !== undefined) return holder;
|
|
190
|
+
return nearest === undefined ? undefined : { kind: "inside", ...nearest };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** A time for the human: `YYYY-MM-DD HH:MM UTC`. */
|
|
194
|
+
function when(ms: number): string {
|
|
195
|
+
const d = new Date(ms);
|
|
196
|
+
return Number.isNaN(d.getTime()) ? "unknown" : `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** A date for the human: `YYYY-MM-DD` (UTC). */
|
|
200
|
+
function day(ms: number): string {
|
|
201
|
+
const d = new Date(ms);
|
|
202
|
+
return Number.isNaN(d.getTime()) ? "unknown" : d.toISOString().slice(0, 10);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function usage(sub: "approve" | "revoke"): string {
|
|
206
|
+
return `Usage: /router ${sub} <path> (quote a path with spaces: /router ${sub} "D:\\my repo")`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function approve(rest: string, opts: RouterApprovalsOptions, platform: NodeJS.Platform): Promise<RouterApprovalsResult> {
|
|
210
|
+
const typed = parseApprovalPath(rest);
|
|
211
|
+
if (typed === undefined) return { text: usage("approve") };
|
|
212
|
+
const shown = displaySafe(typed);
|
|
213
|
+
const deps: InspectDeps = {
|
|
214
|
+
...(opts.identity ?? {}),
|
|
215
|
+
exclude: opts.exclude,
|
|
216
|
+
platform,
|
|
217
|
+
...(opts.env === undefined ? {} : { env: opts.env }),
|
|
218
|
+
// S2: what is shown and stored comes from git now, never from a cached inspection.
|
|
219
|
+
fresh: true,
|
|
220
|
+
};
|
|
221
|
+
const found = await inspectCandidate(typed, deps);
|
|
222
|
+
if (typeof found === "string") return { text: `Not approved: ${shown} ${displaySafe(found)}.\nNothing was stored.` };
|
|
223
|
+
|
|
224
|
+
const repo = displaySafe(found.path);
|
|
225
|
+
const relation = parentRelation(found.path, opts, platform);
|
|
226
|
+
if (relation !== undefined) {
|
|
227
|
+
const parent = displaySafe(relation.parent);
|
|
228
|
+
if (relation.kind !== "inside") {
|
|
229
|
+
// The router refuses a root that is or contains a parent, and its approval would be registered wider than the parents.
|
|
230
|
+
return {
|
|
231
|
+
text: `Not approved: ${repo} ${relation.kind === "is" ? "is" : "contains"} routing.repoParents entry ${parent}; `
|
|
232
|
+
+ `a repository that is or contains a parent cannot be approved.\nNothing was stored.`,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
const depth = opts.repoDepth;
|
|
236
|
+
if (depth !== undefined && relation.depth > depth) {
|
|
237
|
+
return {
|
|
238
|
+
text: `No approval applies: ${repo} is below ${parent} but deeper than routing.repoDepth (${String(depth)}); `
|
|
239
|
+
+ `the router refuses it with or without an approval.\nNothing was stored.`,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
text: `No approval needed: ${repo} is inside routing.repoParents (${parent}); dispatch with root=${repo}.\nNothing was stored.`,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const outcome = await applyApproval(
|
|
248
|
+
{ kind: "put", approval: { path: found.path, commonDir: found.commonDir, roots: found.roots, origin: found.origin }, days: opts.days },
|
|
249
|
+
opts.env,
|
|
250
|
+
);
|
|
251
|
+
if (outcome.status !== "written" || outcome.entry === undefined) {
|
|
252
|
+
const why = outcome.status === "refused"
|
|
253
|
+
? outcome.message
|
|
254
|
+
: `the store was not changed (${outcome.status === "unchanged" ? outcome.reason : "no entry read back"})`;
|
|
255
|
+
return { text: `Not approved: ${repo}: ${displaySafe(why)}.` };
|
|
256
|
+
}
|
|
257
|
+
const entry = outcome.entry;
|
|
258
|
+
const roots = entry.roots.length;
|
|
259
|
+
const cap = entry.approvedAt + REPO_APPROVAL_CAP_DAYS * DAY_MS;
|
|
260
|
+
const lines = [
|
|
261
|
+
`Approved repository ${displaySafe(entry.path)}`,
|
|
262
|
+
` origin: ${displaySafe(entry.origin)}`,
|
|
263
|
+
` branch: ${displaySafe(found.branch)} @ ${displaySafe(found.head.slice(0, 12))}`,
|
|
264
|
+
` roots: ${String(roots)} root commit${roots === 1 ? "" : "s"}`,
|
|
265
|
+
` expires: ${day(expiresAt(entry, opts.days))} (${String(opts.days)} days after its last use; at the latest ${day(cap)})`,
|
|
266
|
+
`Stored in ${displaySafe(outcome.file)}.`,
|
|
267
|
+
];
|
|
268
|
+
return { text: lines.join("\n"), change: { kind: "approve", path: entry.path } };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The `routing.repoExclude` pattern matching the stored path text (as on registration: text only, no filesystem), or undefined. */
|
|
272
|
+
function excludedByText(p: string, exclude: readonly string[], platform: NodeJS.Platform, matches: (input: string, pattern: string) => boolean): string | undefined {
|
|
273
|
+
const win = platform === "win32";
|
|
274
|
+
const forms = win && p.includes("/") ? [p, p.replace(/\//g, "\\")] : [p];
|
|
275
|
+
for (const form of forms) {
|
|
276
|
+
const input = win ? form.toLowerCase() : form;
|
|
277
|
+
const hit = exclude.find((pattern) => pattern.trim() !== "" && matches(input, win ? pattern.toLowerCase() : pattern));
|
|
278
|
+
if (hit !== undefined) return hit;
|
|
279
|
+
}
|
|
280
|
+
return undefined;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function repos(opts: RouterApprovalsOptions, platform: NodeJS.Platform): Promise<RouterApprovalsResult> {
|
|
284
|
+
const read = readApprovals(opts.env);
|
|
285
|
+
const file = displaySafe(read.file);
|
|
286
|
+
if (read.invalid !== undefined) {
|
|
287
|
+
return { text: `The approvals file ${file} is invalid (${displaySafe(read.invalid)}); no approvals apply until it is fixed or removed.` };
|
|
288
|
+
}
|
|
289
|
+
const now = (opts.env?.now ?? Date.now)();
|
|
290
|
+
const lines: string[] = [];
|
|
291
|
+
if (read.approvals.length === 0) lines.push(`No approved repositories (${file}).`);
|
|
292
|
+
else lines.push(`Approved repositories (${file}):`);
|
|
293
|
+
for (const entry of read.approvals) {
|
|
294
|
+
const marks: string[] = [];
|
|
295
|
+
if (!isApprovalValid(entry, opts.days, now)) marks.push("expired");
|
|
296
|
+
const excluded = excludedByText(entry.path, opts.exclude, platform, permissionMatches);
|
|
297
|
+
if (excluded !== undefined) marks.push(`excluded by routing.repoExclude (${displaySafe(excluded)})`);
|
|
298
|
+
lines.push(`- ${displaySafe(entry.path)}${marks.length === 0 ? "" : ` [${marks.join("; ")}]`}`);
|
|
299
|
+
lines.push(` origin: ${displaySafe(entry.origin)}`);
|
|
300
|
+
lines.push(` approved: ${when(entry.approvedAt)}; last used: ${when(entry.lastUsedAt)}; expires: ${when(expiresAt(entry, opts.days))}`);
|
|
301
|
+
}
|
|
302
|
+
if (read.dropped.length > 0) lines.push(`${String(read.dropped.length)} invalid entr${read.dropped.length === 1 ? "y was" : "ies were"} ignored.`);
|
|
303
|
+
return { text: lines.join("\n") };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** The stored approval that `typed` names: by text first (comparison form), then by its realpath. No git. */
|
|
307
|
+
function approvalNamed(approvals: readonly RepoApproval[], typed: string, opts: RouterApprovalsOptions, platform: NodeJS.Platform): RepoApproval | undefined {
|
|
308
|
+
if (!path.isAbsolute(typed)) return undefined;
|
|
309
|
+
const byText = cmpForm(typed, platform);
|
|
310
|
+
const hit = approvals.find((a) => cmpForm(a.path, platform) === byText);
|
|
311
|
+
if (hit !== undefined) return hit;
|
|
312
|
+
const real = realOrUndefined(typed, realpathOf(opts));
|
|
313
|
+
if (real === undefined) return undefined;
|
|
314
|
+
const byReal = cmpForm(real, platform);
|
|
315
|
+
return approvals.find((a) => cmpForm(a.path, platform) === byReal);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function revoke(rest: string, opts: RouterApprovalsOptions, platform: NodeJS.Platform): Promise<RouterApprovalsResult> {
|
|
319
|
+
const typed = parseApprovalPath(rest);
|
|
320
|
+
if (typed === undefined) return { text: usage("revoke") };
|
|
321
|
+
const shown = displaySafe(typed);
|
|
322
|
+
const read = readApprovals(opts.env);
|
|
323
|
+
if (read.invalid !== undefined) {
|
|
324
|
+
return { text: `Not revoked: the approvals file ${displaySafe(read.file)} is invalid (${displaySafe(read.invalid)}); fix or remove it first.` };
|
|
325
|
+
}
|
|
326
|
+
const entry = approvalNamed(read.approvals, typed, opts, platform);
|
|
327
|
+
if (entry === undefined) return { text: `No approval for ${shown}; nothing was changed. /router repos lists the approved repositories.` };
|
|
328
|
+
const outcome = await applyApproval({ kind: "delete", path: entry.path }, opts.env);
|
|
329
|
+
if (outcome.status === "refused") return { text: `Not revoked: ${displaySafe(outcome.message)}.` };
|
|
330
|
+
if (outcome.status === "unchanged") return { text: `No approval for ${shown}; nothing was changed. /router repos lists the approved repositories.` };
|
|
331
|
+
const removed = dropFromWorkingSets(entry.path, platform);
|
|
332
|
+
const repo = displaySafe(entry.path);
|
|
333
|
+
const lines = [
|
|
334
|
+
`Revoked the approval of ${repo}.`,
|
|
335
|
+
removed === 0 ? "It was not in any working set." : `Removed from the working sets (${String(removed)} binding${removed === 1 ? "" : "s"}).`,
|
|
336
|
+
`A new dispatch with root=${repo} is refused.`,
|
|
337
|
+
];
|
|
338
|
+
return { text: lines.join("\n"), change: { kind: "revoke", path: entry.path } };
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Run `/router approve <path>`, `/router repos` or `/router revoke <path>`; `rest` is the argument text after the subcommand.
|
|
343
|
+
* Never throws: an unexpected error is reported and nothing is stored.
|
|
344
|
+
*/
|
|
345
|
+
export async function runRouterApprovals(sub: RouterApprovalSubcommand, rest: string, opts: RouterApprovalsOptions): Promise<RouterApprovalsResult> {
|
|
346
|
+
const platform = opts.platform ?? process.platform;
|
|
347
|
+
try {
|
|
348
|
+
if (sub === "approve") return await approve(rest, opts, platform);
|
|
349
|
+
if (sub === "revoke") return await revoke(rest, opts, platform);
|
|
350
|
+
return await repos(opts, platform);
|
|
351
|
+
} catch (e) {
|
|
352
|
+
return { text: `/router ${sub} failed: ${displaySafe(e instanceof Error ? e.message : String(e))}` };
|
|
353
|
+
}
|
|
354
|
+
}
|
package/src/commands/output.ts
CHANGED
|
@@ -228,8 +228,21 @@ export function buildRoleLines(roles: Iterable<RoleSpec>): string[] {
|
|
|
228
228
|
return lines.length === 0 ? [] : ["Roles:", ...lines];
|
|
229
229
|
}
|
|
230
230
|
|
|
231
|
+
/**
|
|
232
|
+
* Cross-repo P4.7 (SD-P4-10): the help lines of `/router approve|repos|revoke`, listed only where they run (OpenCode v2, roles
|
|
233
|
+
* mode, `routing.repoParents` non-empty).
|
|
234
|
+
*/
|
|
235
|
+
export const ROUTER_APPROVAL_HELP_LINES: readonly string[] = Object.freeze([
|
|
236
|
+
"- `/router approve <path>` — approve a repository outside `routing.repoParents` for role dispatches with `root=<path>` (identity from git; quote a path with spaces)",
|
|
237
|
+
"- `/router repos` — list the approved repositories, their last use and expiry",
|
|
238
|
+
"- `/router revoke <path>` — remove an approval and drop the repository from every working set",
|
|
239
|
+
]);
|
|
240
|
+
|
|
231
241
|
/** Bare `/router`. */
|
|
232
|
-
export function buildRouterHelp(
|
|
242
|
+
export function buildRouterHelp(
|
|
243
|
+
current: string,
|
|
244
|
+
options: { stats?: boolean; roles?: Iterable<RoleSpec>; approvals?: boolean; plan?: boolean } = {},
|
|
245
|
+
): string {
|
|
233
246
|
const roleLines = options.roles === undefined ? [] : buildRoleLines(options.roles);
|
|
234
247
|
return [
|
|
235
248
|
`# Model Router`,
|
|
@@ -242,11 +255,31 @@ export function buildRouterHelp(current: string, options: { stats?: boolean; rol
|
|
|
242
255
|
...(options.stats === true
|
|
243
256
|
? ["- `/router stats [--since <ISO>]` — routing statistics from the decision log and outcome store (same table as `npm run routing:stats` (in a clone))"]
|
|
244
257
|
: []),
|
|
258
|
+
...(options.approvals === true ? ROUTER_APPROVAL_HELP_LINES : []),
|
|
245
259
|
"- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
|
|
260
|
+
...(options.plan === true ? ["", ...PLAN_HELP_LINES] : []),
|
|
246
261
|
...(roleLines.length > 0 ? ["", ...roleLines] : []),
|
|
247
262
|
].join("\n");
|
|
248
263
|
}
|
|
249
264
|
|
|
265
|
+
/** `/plan` usage lines (v2 only): appended to `/router` help when `plan` is set and printed for an unknown `/plan` subcommand. */
|
|
266
|
+
export const PLAN_HELP_LINES: readonly string[] = [
|
|
267
|
+
"Plan executor (`/plan`):",
|
|
268
|
+
"- `/plan run <path> [--phases <id,id,...>] [--done-before <id>]` — compile a plan file (path absolute, or relative to the project directory) and show its summary; it does not start until approved",
|
|
269
|
+
"- `/plan approve <planId>` — approve a compiled plan and start it (not needed with `executor.approve: \"auto\"`)",
|
|
270
|
+
"- `/plan status [planId]` — show plan progress",
|
|
271
|
+
"- `/plan inbox [--plan <planId>]` — show the questions waiting for an answer",
|
|
272
|
+
"- `/plan answer [--plan <planId>] <id> <text>` — answer an inbox question (without `--plan`: this session's running plan)",
|
|
273
|
+
"- `/plan pause|resume|abort <planId>` — pause, resume or abort a plan",
|
|
274
|
+
"- `/plan land <planId>` — land a finished plan",
|
|
275
|
+
"- `/plan adopt <planId>` — adopt a plan whose owning session is gone",
|
|
276
|
+
];
|
|
277
|
+
|
|
278
|
+
/** `/plan` with no or an unknown subcommand. */
|
|
279
|
+
export function buildPlanHelp(): string {
|
|
280
|
+
return ["# Plan executor", "", ...PLAN_HELP_LINES].join("\n");
|
|
281
|
+
}
|
|
282
|
+
|
|
250
283
|
/**
|
|
251
284
|
* `/router models [provider]`. Takes the catalog the caller fetched, so a
|
|
252
285
|
* failed or unavailable fetch is a null here rather than an exception path.
|