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
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `router_plan` (4.1.2): the orchestrator's tool for the plan executor. `createRouterPlanTool(runtime)` returns the tool
|
|
3
|
+
* definition; Phase 5.1 registers it (v2 only). Every failure is a text answer: `execute` never throws.
|
|
4
|
+
*/
|
|
5
|
+
import { posix, win32 } from "node:path";
|
|
6
|
+
import { tool } from "@opencode-ai/plugin";
|
|
7
|
+
import { ExecutorError, type CompileSummary, type ExecutorRuntime } from "./types.js";
|
|
8
|
+
|
|
9
|
+
/** The `action` values of `router_plan`. */
|
|
10
|
+
export const ROUTER_PLAN_ACTIONS = [
|
|
11
|
+
"compile", "residue", "approve", "status", "ready", "add-tasks", "answer", "done",
|
|
12
|
+
"pause", "resume", "abort", "land", "adopt", "gc", "export", "purge",
|
|
13
|
+
] as const;
|
|
14
|
+
|
|
15
|
+
export type RouterPlanAction = (typeof ROUTER_PLAN_ACTIONS)[number];
|
|
16
|
+
|
|
17
|
+
/** The arguments as the host schema describes them; `execute` still re-validates (strict) because it never trusts them. */
|
|
18
|
+
export interface RouterPlanArgs {
|
|
19
|
+
action: RouterPlanAction;
|
|
20
|
+
planId?: string;
|
|
21
|
+
path?: string;
|
|
22
|
+
phases?: string[];
|
|
23
|
+
doneBefore?: string;
|
|
24
|
+
text?: string;
|
|
25
|
+
inboxId?: string;
|
|
26
|
+
task?: string;
|
|
27
|
+
/** status: true renders only the inbox section of the board. */
|
|
28
|
+
inbox?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The part of the host tool context this tool reads. */
|
|
32
|
+
export interface RouterPlanContext {
|
|
33
|
+
sessionID?: string;
|
|
34
|
+
/** The project directory of the session; a relative compile `path` is resolved against it (else `worktree`). */
|
|
35
|
+
directory?: string;
|
|
36
|
+
worktree?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type ArgKey = Exclude<keyof RouterPlanArgs, "action">;
|
|
40
|
+
|
|
41
|
+
interface ActionSpec {
|
|
42
|
+
required: readonly ArgKey[];
|
|
43
|
+
optional: readonly ArgKey[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Which arguments each action takes; anything else is refused (strict schema, 4.1.2.b). */
|
|
47
|
+
const ACTION_SPECS: Readonly<Record<RouterPlanAction, ActionSpec>> = {
|
|
48
|
+
compile: { required: ["path"], optional: ["phases", "doneBefore"] },
|
|
49
|
+
residue: { required: ["planId", "text"], optional: [] },
|
|
50
|
+
approve: { required: ["planId"], optional: [] },
|
|
51
|
+
status: { required: [], optional: ["planId", "inbox"] },
|
|
52
|
+
ready: { required: ["planId"], optional: [] },
|
|
53
|
+
"add-tasks": { required: ["planId", "text"], optional: [] },
|
|
54
|
+
// Without planId: the running or paused plan of the calling session (`runtime.planLine`); `/plan answer <id> <text>`
|
|
55
|
+
// names no plan unless `--plan <id>` is given.
|
|
56
|
+
answer: { required: ["inboxId", "text"], optional: ["planId"] },
|
|
57
|
+
done: { required: ["planId", "task"], optional: [] },
|
|
58
|
+
pause: { required: ["planId"], optional: [] },
|
|
59
|
+
resume: { required: ["planId"], optional: [] },
|
|
60
|
+
abort: { required: ["planId"], optional: [] },
|
|
61
|
+
land: { required: ["planId"], optional: [] },
|
|
62
|
+
adopt: { required: ["planId"], optional: [] },
|
|
63
|
+
gc: { required: [], optional: [] },
|
|
64
|
+
export: { required: ["planId"], optional: [] },
|
|
65
|
+
purge: { required: ["planId"], optional: [] },
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const KNOWN_KEYS: ReadonlySet<string> = new Set(["action", "planId", "path", "phases", "doneBefore", "text", "inboxId", "task", "inbox"]);
|
|
69
|
+
|
|
70
|
+
const MAX_ID = 200;
|
|
71
|
+
const MAX_PATH = 4096;
|
|
72
|
+
const MAX_TEXT = 2_000_000;
|
|
73
|
+
const MAX_PHASES = 200;
|
|
74
|
+
const MAX_LIST = 12;
|
|
75
|
+
const MAX_STATUS = 40_000;
|
|
76
|
+
const MAX_ERROR = 600;
|
|
77
|
+
|
|
78
|
+
const PREFIX = "[router_plan]";
|
|
79
|
+
|
|
80
|
+
function isString(v: unknown): v is string {
|
|
81
|
+
return typeof v === "string";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function typeName(v: unknown): string {
|
|
85
|
+
if (v === null) return "null";
|
|
86
|
+
if (Array.isArray(v)) return "array";
|
|
87
|
+
return typeof v;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function oneLine(s: string, max: number): string {
|
|
91
|
+
const flat = s.replace(/\s+/g, " ").trim();
|
|
92
|
+
return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** A plan id names a ledger directory and the `omr/<planId>/` ref namespace: no separators, wildcards or whitespace. */
|
|
96
|
+
function validId(v: string): boolean {
|
|
97
|
+
if (v.length === 0 || v.length > MAX_ID) return false;
|
|
98
|
+
for (const ch of v) {
|
|
99
|
+
const c = ch.codePointAt(0) ?? 0;
|
|
100
|
+
if (c <= 0x20 || c === 0x7f) return false;
|
|
101
|
+
if (ch === "/" || ch === "\\" || ch === "*" || ch === "?") return false;
|
|
102
|
+
}
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
type Parsed =
|
|
107
|
+
| { ok: true; action: RouterPlanAction; a: RouterPlanArgs }
|
|
108
|
+
| { ok: false; error: string };
|
|
109
|
+
|
|
110
|
+
function refuse(error: string): { ok: false; error: string } {
|
|
111
|
+
return { ok: false, error: `${PREFIX} ${error}` };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Strict validation: known keys only, the action's required fields present, every field of the right type and size. */
|
|
115
|
+
function parseArgs(raw: unknown): Parsed {
|
|
116
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
117
|
+
return refuse(`arguments must be an object with an "action" (${ROUTER_PLAN_ACTIONS.join(", ")}); got ${typeName(raw)}.`);
|
|
118
|
+
}
|
|
119
|
+
const rec = raw as Record<string, unknown>;
|
|
120
|
+
const action = rec.action;
|
|
121
|
+
if (!isString(action)) {
|
|
122
|
+
return refuse(`"action" is required and must be a string: one of ${ROUTER_PLAN_ACTIONS.join(", ")}.`);
|
|
123
|
+
}
|
|
124
|
+
if (!(ROUTER_PLAN_ACTIONS as readonly string[]).includes(action)) {
|
|
125
|
+
return refuse(`unknown action "${oneLine(action, 40)}". Use one of: ${ROUTER_PLAN_ACTIONS.join(", ")}.`);
|
|
126
|
+
}
|
|
127
|
+
const act = action as RouterPlanAction;
|
|
128
|
+
const spec = ACTION_SPECS[act];
|
|
129
|
+
const allowed = new Set<string>(["action", ...spec.required, ...spec.optional]);
|
|
130
|
+
const unknownKeys = Object.keys(rec).filter(k => rec[k] !== undefined && !allowed.has(k));
|
|
131
|
+
if (unknownKeys.length > 0) {
|
|
132
|
+
const kind = unknownKeys.every(k => KNOWN_KEYS.has(k)) ? "not used by" : "unknown for";
|
|
133
|
+
const takes = [...spec.required, ...spec.optional];
|
|
134
|
+
return refuse(
|
|
135
|
+
`${unknownKeys.map(k => oneLine(k, 40)).join(", ")} ${kind} action=${act}` +
|
|
136
|
+
`${takes.length > 0 ? ` (it takes: ${takes.join(", ")})` : " (it takes no arguments)"}.`,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
const missing = spec.required.filter(k => rec[k] === undefined || rec[k] === null);
|
|
140
|
+
if (missing.length > 0) {
|
|
141
|
+
return refuse(`action=${act} needs ${missing.join(", ")}.`);
|
|
142
|
+
}
|
|
143
|
+
const a: RouterPlanArgs = { action: act };
|
|
144
|
+
const fields: ArgKey[] = [...spec.required, ...spec.optional];
|
|
145
|
+
for (const k of fields) {
|
|
146
|
+
const v = rec[k];
|
|
147
|
+
if (v === undefined || v === null) continue;
|
|
148
|
+
if (k === "phases") {
|
|
149
|
+
if (!Array.isArray(v) || !v.every(isString)) return refuse(`phases must be an array of phase id strings; got ${typeName(v)}.`);
|
|
150
|
+
const ids = v.map(s => s.trim());
|
|
151
|
+
if (ids.length === 0 || ids.length > MAX_PHASES || ids.some(s => !validId(s))) {
|
|
152
|
+
return refuse(`phases must hold 1-${MAX_PHASES} phase ids without whitespace or path separators.`);
|
|
153
|
+
}
|
|
154
|
+
a.phases = ids;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (k === "inbox") {
|
|
158
|
+
if (typeof v !== "boolean") return refuse(`inbox must be a boolean; got ${typeName(v)}.`);
|
|
159
|
+
a.inbox = v;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (!isString(v)) return refuse(`${k} must be a string; got ${typeName(v)}.`);
|
|
163
|
+
if (k === "text") {
|
|
164
|
+
if (v.trim().length === 0) return refuse("text must not be empty.");
|
|
165
|
+
if (v.length > MAX_TEXT) return refuse(`text is too long (${v.length} chars, max ${MAX_TEXT}).`);
|
|
166
|
+
a.text = v;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const s = v.trim();
|
|
170
|
+
if (s.length === 0) return refuse(`${k} must not be empty.`);
|
|
171
|
+
if (k === "path") {
|
|
172
|
+
if (s.length > MAX_PATH) return refuse(`path is too long (max ${MAX_PATH}).`);
|
|
173
|
+
a.path = s;
|
|
174
|
+
} else if (!validId(s)) {
|
|
175
|
+
return refuse(`${k} must be 1-${MAX_ID} characters without whitespace, path separators or wildcards.`);
|
|
176
|
+
} else {
|
|
177
|
+
a[k] = s;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return { ok: true, action: act, a };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// The board (runtime.ts renderBoard) starts with `Plan <planId> [<status>] <path>`; open inbox items follow an `Inbox:`
|
|
184
|
+
// line, each starting with two spaces; only `Metrics:` comes after them. Only these shapes are read here.
|
|
185
|
+
const BOARD_HEAD = /^Plan (\S+) \[[^\]]*\]/;
|
|
186
|
+
|
|
187
|
+
/** The plan id of a board's first line, or null when the board does not start with one. */
|
|
188
|
+
export function boardPlanId(board: string): string | null {
|
|
189
|
+
const id = BOARD_HEAD.exec(board.split("\n", 1)[0] ?? "")?.[1];
|
|
190
|
+
return id !== undefined && validId(id) ? id : null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// `runtime.planLine` (runtime.ts) is `plan <planId>: <done>/<total> done, ...` for the session's running or paused plan, and
|
|
194
|
+
// null when it has none. It is the one runtime view that skips completed and aborted plans (QA-4.1-5).
|
|
195
|
+
const PLAN_LINE_HEAD = /^plan (\S+): \d+\/\d+ done, /;
|
|
196
|
+
|
|
197
|
+
/** The plan id of a `planLine`, or null when there is none (no running or paused plan in the session). */
|
|
198
|
+
export function planLinePlanId(line: string | null): string | null {
|
|
199
|
+
if (line === null) return null;
|
|
200
|
+
const id = PLAN_LINE_HEAD.exec(line)?.[1];
|
|
201
|
+
return id !== undefined && validId(id) ? id : null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The plan this session runs now (running or paused), or null. Never the oldest plan of the session (QA-4.1-5). */
|
|
205
|
+
function sessionPlanId(runtime: ExecutorRuntime, sessionID: string): string | null {
|
|
206
|
+
return planLinePlanId(runtime.planLine(sessionID));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The board's first line plus its inbox section, with how to answer an item. `--plan` appears in the `/plan answer` hint
|
|
211
|
+
* unless the board is the session's running plan, the one `/plan answer` without `--plan` picks.
|
|
212
|
+
*/
|
|
213
|
+
function inboxSection(board: string, sessionPlan: string | null): string {
|
|
214
|
+
const lines = board.split("\n");
|
|
215
|
+
const head = lines[0] ?? "";
|
|
216
|
+
const start = lines.indexOf("Inbox:");
|
|
217
|
+
if (start === -1) return `${head}\nInbox: no open items.`;
|
|
218
|
+
// Up to `Metrics:` so an item text with a line break stays whole; the count is of item lines (two-space indent).
|
|
219
|
+
const end = lines.findIndex((l, i) => i > start && l.startsWith("Metrics: "));
|
|
220
|
+
const section = lines.slice(start + 1, end === -1 ? lines.length : end);
|
|
221
|
+
const count = section.filter(l => l.startsWith(" ")).length;
|
|
222
|
+
const planId = boardPlanId(board);
|
|
223
|
+
const flag = planId !== null && planId !== sessionPlan ? `--plan ${planId} ` : "";
|
|
224
|
+
return [
|
|
225
|
+
head,
|
|
226
|
+
`Inbox (${count}):`,
|
|
227
|
+
...section,
|
|
228
|
+
`Answer: /plan answer ${flag}<id> <text>` +
|
|
229
|
+
` (tool: router_plan action=answer${planId === null ? "" : ` planId=${planId}`} inboxId=<id> text=<answer>).`,
|
|
230
|
+
].join("\n");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function listIds(ids: readonly string[]): string {
|
|
234
|
+
if (ids.length === 0) return "none";
|
|
235
|
+
const head = ids.slice(0, MAX_LIST).join(", ");
|
|
236
|
+
return ids.length > MAX_LIST ? `${head} (+${ids.length - MAX_LIST} more)` : head;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function fmtDuration(ms: number): string {
|
|
240
|
+
if (!Number.isFinite(ms) || ms <= 0) return "0m";
|
|
241
|
+
const totalMin = Math.round(ms / 60_000);
|
|
242
|
+
if (totalMin < 1) return `${Math.max(1, Math.round(ms / 1000))}s`;
|
|
243
|
+
const h = Math.floor(totalMin / 60);
|
|
244
|
+
const m = totalMin % 60;
|
|
245
|
+
return h > 0 ? `${h}h${String(m).padStart(2, "0")}m` : `${m}m`;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function fmtSummary(planId: string, s: CompileSummary): string {
|
|
249
|
+
const lines = [
|
|
250
|
+
`plan ${planId}: ${s.tasks} tasks, ${s.phases} phases, ${s.edges} edges; work ${fmtDuration(s.workMs)}, ` +
|
|
251
|
+
`critical path ${fmtDuration(s.criticalPathMs)}, width ${s.width}, expected makespan ${fmtDuration(s.expectedMakespanMs)}.`,
|
|
252
|
+
];
|
|
253
|
+
if (s.manual.length > 0) lines.push(`manual tasks (${s.manual.length}): ${listIds(s.manual)} - you run these and report each with action=done.`);
|
|
254
|
+
if (s.warnings.length > 0) {
|
|
255
|
+
lines.push(`warnings (${s.warnings.length}):`);
|
|
256
|
+
for (const w of s.warnings.slice(0, 5)) lines.push(`- ${oneLine(w, 200)}`);
|
|
257
|
+
if (s.warnings.length > 5) lines.push(`- (+${s.warnings.length - 5} more)`);
|
|
258
|
+
}
|
|
259
|
+
return lines.join("\n");
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** What to do next after a refusal, by error code. */
|
|
263
|
+
function hint(code: string): string {
|
|
264
|
+
switch (code) {
|
|
265
|
+
// QA-4.1-16 (round 3): adopt is no way around the user's approval.
|
|
266
|
+
case "E_NOT_OWNER": return "That plan belongs to another session; do not act on it. Adoption is only for a running or paused plan " +
|
|
267
|
+
"whose owning session is gone: then action=adopt planId=<id> takes it over. A plan awaiting approval is never adopted: " +
|
|
268
|
+
"the user approves it in its own session, or it is compiled again.";
|
|
269
|
+
case "E_PLAN_STATE": return "The plan is not in a state that allows this; action=status shows its status.";
|
|
270
|
+
case "E_LEDGER_NOT_FOUND": return "No such plan; action=status (without planId) shows the plan of this session.";
|
|
271
|
+
case "E_INVALID_INPUT": return "Fix the input and call again.";
|
|
272
|
+
case "E_COMPILE": return "Fix the plan file at the line named and call action=compile again.";
|
|
273
|
+
case "E_CYCLE": return "Remove one dependency from the cycle.";
|
|
274
|
+
case "E_RESIDUE": return "Re-dispatch the residue prompt, or fix the JSON, and call action=residue again.";
|
|
275
|
+
case "E_LOCK_HELD": return "Another process holds this plan's lock; retry later or, once it is gone, use action=adopt for a running or paused plan (a plan awaiting approval is never adopted).";
|
|
276
|
+
default: return "";
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function describeError(action: string, error: unknown): string {
|
|
281
|
+
if (error instanceof ExecutorError || (error instanceof Error && error.name === "ExecutorError")) {
|
|
282
|
+
const code = (error as { code?: unknown }).code;
|
|
283
|
+
const c = isString(code) ? code : "E_UNKNOWN";
|
|
284
|
+
const h = hint(c);
|
|
285
|
+
return `${PREFIX} ${action} refused (${c}): ${oneLine(error.message, MAX_ERROR)}${h ? ` ${h}` : ""}`;
|
|
286
|
+
}
|
|
287
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
288
|
+
return `${PREFIX} ${action} failed: ${oneLine(msg, MAX_ERROR)}`;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Options of the factory. `approve` reads the effective `executor.approve` setting (config can change; default "ask"); it is
|
|
293
|
+
* read only by compile and residue, the two actions that can finish a draft, so a failing getter breaks nothing else.
|
|
294
|
+
*/
|
|
295
|
+
export interface RouterPlanToolOptions {
|
|
296
|
+
approve?: () => "ask" | "auto";
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** The `ask` answer once a draft is complete: approval is the user's decision, never the model's (QA-4.1-1). */
|
|
300
|
+
export function askApprovalText(planId: string): string {
|
|
301
|
+
// QA-4.1-16: the user's "run this plan" is already in the conversation, so it must not read as approval.
|
|
302
|
+
return "status: awaiting-approval. Stop here. This plan is not approved. A request to compile or run it is not approval. " +
|
|
303
|
+
`Call action=approve only when the user approves plan ${planId} after seeing this summary, or types /plan approve ${planId}.`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** After a draft is complete: `approve: auto` approves it at once (no stop), otherwise the user is asked to approve it. */
|
|
307
|
+
async function approveStep(runtime: ExecutorRuntime, planId: string, sessionID: string, auto: boolean): Promise<string> {
|
|
308
|
+
if (!auto) return askApprovalText(planId);
|
|
309
|
+
try {
|
|
310
|
+
await runtime.approve(planId, sessionID);
|
|
311
|
+
} catch (error) {
|
|
312
|
+
return `status: awaiting-approval. ${describeError("auto-approve", error)} Call router_plan action=approve planId=${planId} when fixed.`;
|
|
313
|
+
}
|
|
314
|
+
return `status: approved and running (approve: auto). Next: router_plan action=status planId=${planId}; run manual tasks as they appear.`;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* The plan path as the compiler needs it (absolute): a relative `path` is resolved against the project directory of the
|
|
319
|
+
* calling session (QA-4.1-6). Null when it is relative and no project directory is known, and for a drive-relative path
|
|
320
|
+
* (`C:foo`), which Windows resolves against drive C's current directory, outside the project (QA-4.1-20).
|
|
321
|
+
*/
|
|
322
|
+
export function resolvePlanPath(p: string, baseDir: string | null): string | null {
|
|
323
|
+
if (isAbsolutePlanPath(p)) return p;
|
|
324
|
+
if (baseDir === null || DRIVE_RELATIVE.test(p)) return null;
|
|
325
|
+
// The form of the base decides the path flavour, so the result does not depend on the platform the tests run on.
|
|
326
|
+
return WINDOWS_ABSOLUTE.test(baseDir) ? win32.resolve(baseDir, p) : posix.resolve(baseDir, p);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// What the compiler takes as absolute (compile/index.ts isAbsolutePlanPath): a drive path, a UNC path or a POSIX path.
|
|
330
|
+
const WINDOWS_ABSOLUTE = /^(?:[A-Za-z]:[\\/]|\\\\[^\\]+\\[^\\]+)/;
|
|
331
|
+
|
|
332
|
+
/** A drive letter without a separator after it: `C:foo`, `C:` (QA-4.1-20). Never resolved against the project. */
|
|
333
|
+
const DRIVE_RELATIVE = /^[A-Za-z]:(?![\\/])/;
|
|
334
|
+
|
|
335
|
+
function isAbsolutePlanPath(p: string): boolean {
|
|
336
|
+
return WINDOWS_ABSOLUTE.test(p) || p.startsWith("/");
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** The project directory of the tool context: `directory`, else `worktree`; only an absolute one counts. */
|
|
340
|
+
function projectDir(ctx: RouterPlanContext | undefined): string | null {
|
|
341
|
+
for (const v of [ctx?.directory, ctx?.worktree]) if (isString(v) && isAbsolutePlanPath(v)) return v;
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
interface RunContext {
|
|
346
|
+
sessionID: string;
|
|
347
|
+
baseDir: string | null;
|
|
348
|
+
/**
|
|
349
|
+
* Reads `executor.approve`; called only where a draft can complete (compile, residue) and, through `approvalGuard`,
|
|
350
|
+
* when status or ready shows a plan awaiting approval.
|
|
351
|
+
*/
|
|
352
|
+
auto: () => boolean;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const AWAITING_APPROVAL_HEAD = /^Plan (\S+) \[awaiting-approval\]/;
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* QA-4.1-16 (round 3): a model that comes back to a plan awaiting approval through status or ready (after a resume, a
|
|
359
|
+
* compaction or an adopt) gets the same stop text as after compile. Empty unless the board head says
|
|
360
|
+
* `[awaiting-approval]`; empty with `approve: auto`. A throwing getter counts as "ask": it never breaks status.
|
|
361
|
+
*/
|
|
362
|
+
function approvalGuard(board: string, rc: RunContext): string {
|
|
363
|
+
const id = AWAITING_APPROVAL_HEAD.exec(board.split("\n", 1)[0] ?? "")?.[1];
|
|
364
|
+
if (id === undefined || !validId(id)) return "";
|
|
365
|
+
let auto = false;
|
|
366
|
+
try {
|
|
367
|
+
auto = rc.auto();
|
|
368
|
+
} catch {
|
|
369
|
+
auto = false;
|
|
370
|
+
}
|
|
371
|
+
return auto ? "" : `\n${askApprovalText(id)}`;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** The board of `planId`, or "" when it cannot be read (ready then shows no guard, as before). */
|
|
375
|
+
async function boardOrEmpty(runtime: ExecutorRuntime, planId: string, sessionID: string): Promise<string> {
|
|
376
|
+
try {
|
|
377
|
+
return await runtime.status(planId, sessionID);
|
|
378
|
+
} catch {
|
|
379
|
+
return "";
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async function run(runtime: ExecutorRuntime, a: RouterPlanArgs, rc: RunContext): Promise<string> {
|
|
384
|
+
// `planId` is present for every action that requires it (parseArgs); the empty fallbacks only satisfy the types.
|
|
385
|
+
const planId = a.planId ?? "";
|
|
386
|
+
const text = a.text ?? "";
|
|
387
|
+
const sessionID = rc.sessionID;
|
|
388
|
+
switch (a.action) {
|
|
389
|
+
case "compile": {
|
|
390
|
+
const path = resolvePlanPath(a.path ?? "", rc.baseDir);
|
|
391
|
+
if (path === null) {
|
|
392
|
+
const why = DRIVE_RELATIVE.test(a.path ?? "")
|
|
393
|
+
? "is relative to a drive's current directory, not to the project"
|
|
394
|
+
: "is relative and the project directory is unknown";
|
|
395
|
+
return `${PREFIX} action=compile refused: path "${oneLine(a.path ?? "", 200)}" ${why}; pass an absolute path.`;
|
|
396
|
+
}
|
|
397
|
+
const auto = rc.auto();
|
|
398
|
+
const r = await runtime.compile({
|
|
399
|
+
path,
|
|
400
|
+
...(a.phases !== undefined ? { phases: a.phases } : {}),
|
|
401
|
+
...(a.doneBefore !== undefined ? { doneBefore: a.doneBefore } : {}),
|
|
402
|
+
sessionID,
|
|
403
|
+
});
|
|
404
|
+
if (r.residuePrompt !== null) {
|
|
405
|
+
return [
|
|
406
|
+
`${fmtSummary(r.planId, r.summary)}`,
|
|
407
|
+
`status: awaiting-residue. Dispatch the prompt below to a subagent (architect role, or heavy tier), then call ` +
|
|
408
|
+
`router_plan action=residue planId=${r.planId} text=<its complete JSON reply>.`,
|
|
409
|
+
"--- residue prompt ---",
|
|
410
|
+
r.residuePrompt,
|
|
411
|
+
].join("\n");
|
|
412
|
+
}
|
|
413
|
+
return `${fmtSummary(r.planId, r.summary)}\n${await approveStep(runtime, r.planId, sessionID, auto)}`;
|
|
414
|
+
}
|
|
415
|
+
case "residue": {
|
|
416
|
+
const auto = rc.auto();
|
|
417
|
+
const s = await runtime.residue(planId, text, sessionID);
|
|
418
|
+
return `${fmtSummary(planId, s)}\nresidue merged. ${await approveStep(runtime, planId, sessionID, auto)}`;
|
|
419
|
+
}
|
|
420
|
+
case "approve":
|
|
421
|
+
await runtime.approve(planId, sessionID);
|
|
422
|
+
return `plan ${planId} approved and running. Next: router_plan action=status planId=${planId}; run manual tasks as they appear.`;
|
|
423
|
+
case "status": {
|
|
424
|
+
// Without planId: the session's running or paused plan; with none, the runtime's pick (a finished plan of the session).
|
|
425
|
+
const current = sessionPlanId(runtime, sessionID);
|
|
426
|
+
const board = await runtime.status(a.planId ?? current, sessionID);
|
|
427
|
+
const out = a.inbox === true ? inboxSection(board, current) : board;
|
|
428
|
+
// The stop text goes after any truncation, so it is never cut off.
|
|
429
|
+
const shown = out.length > MAX_STATUS ? `${out.slice(0, MAX_STATUS)}\n... (status truncated at ${MAX_STATUS} chars)` : out;
|
|
430
|
+
return `${shown}${approvalGuard(board, rc)}`;
|
|
431
|
+
}
|
|
432
|
+
case "ready": {
|
|
433
|
+
const r = await runtime.ready(planId);
|
|
434
|
+
const lines = [`plan ${planId} ready: launchable ${r.launchable.length} (${listIds(r.launchable)}); manual ${r.manual.length} (${listIds(r.manual)}).`];
|
|
435
|
+
// `ready` does not carry the plan status; the board head does (a read-only call). Its failure only drops the guard.
|
|
436
|
+
const guard = approvalGuard(await boardOrEmpty(runtime, planId, sessionID), rc);
|
|
437
|
+
if (r.manual.length > 0 && guard === "") lines.push(`Run each manual task yourself, then report it: router_plan action=done planId=${planId} task=<id>.`);
|
|
438
|
+
return `${lines.join("\n")}${guard}`;
|
|
439
|
+
}
|
|
440
|
+
case "add-tasks": {
|
|
441
|
+
const r = await runtime.addTasks(planId, text, sessionID);
|
|
442
|
+
const parts = [`plan ${planId}: added ${r.added.length} (${listIds(r.added)})`];
|
|
443
|
+
if (r.reopened.length > 0) parts.push(`returned to pending ${r.reopened.length} (${listIds(r.reopened)})`);
|
|
444
|
+
return `${parts.join("; ")}.`;
|
|
445
|
+
}
|
|
446
|
+
case "answer": {
|
|
447
|
+
const target = a.planId ?? sessionPlanId(runtime, sessionID);
|
|
448
|
+
if (target === null) {
|
|
449
|
+
return `${PREFIX} action=answer refused: this session runs no plan now; pass planId (the user: /plan answer --plan <planId> <id> <text>).`;
|
|
450
|
+
}
|
|
451
|
+
await runtime.answer(target, a.inboxId ?? "", text, sessionID);
|
|
452
|
+
return `plan ${target}: inbox ${a.inboxId ?? ""} answered.`;
|
|
453
|
+
}
|
|
454
|
+
case "done":
|
|
455
|
+
await runtime.done(planId, a.task ?? "", sessionID);
|
|
456
|
+
return `plan ${planId}: task ${a.task ?? ""} marked done.`;
|
|
457
|
+
case "pause":
|
|
458
|
+
await runtime.pause(planId, sessionID);
|
|
459
|
+
return `plan ${planId} paused. No new task starts; running ones finish. Resume: router_plan action=resume planId=${planId}.`;
|
|
460
|
+
case "resume":
|
|
461
|
+
await runtime.resume(planId, sessionID);
|
|
462
|
+
return `plan ${planId} resumed.`;
|
|
463
|
+
case "abort":
|
|
464
|
+
await runtime.abort(planId, sessionID);
|
|
465
|
+
return `plan ${planId} aborted. Integrated work stays. Clean up: router_plan action=gc, or action=purge planId=${planId}.`;
|
|
466
|
+
case "land":
|
|
467
|
+
await runtime.land(planId, sessionID);
|
|
468
|
+
return `plan ${planId}: landing requested. Check router_plan action=status planId=${planId}.`;
|
|
469
|
+
case "adopt":
|
|
470
|
+
await runtime.adopt(planId, sessionID);
|
|
471
|
+
return `plan ${planId} adopted by this session; it resumes after your next router call. Check router_plan action=status planId=${planId}.`;
|
|
472
|
+
case "gc": {
|
|
473
|
+
const r = await runtime.gc();
|
|
474
|
+
return `gc: removed ${r.removed.length} (${listIds(r.removed)}); reported ${r.reported.length} (${listIds(r.reported)}).` +
|
|
475
|
+
`${r.reported.length > 0 ? " Reported slots were not removed; inspect them by hand." : ""}`;
|
|
476
|
+
}
|
|
477
|
+
case "export":
|
|
478
|
+
return runtime.exportPlan(planId);
|
|
479
|
+
case "purge":
|
|
480
|
+
await runtime.purge(planId, sessionID);
|
|
481
|
+
return `plan ${planId} purged: slots, omr/${planId}/ refs and ledger removed.`;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Validates `rawArgs`, calls the runtime and renders a compact answer. Never throws: validation failures and
|
|
487
|
+
* `ExecutorError`s come back as text that names what to do next.
|
|
488
|
+
*/
|
|
489
|
+
export async function executeRouterPlan(
|
|
490
|
+
runtime: ExecutorRuntime,
|
|
491
|
+
rawArgs: unknown,
|
|
492
|
+
ctx?: RouterPlanContext,
|
|
493
|
+
opts?: RouterPlanToolOptions,
|
|
494
|
+
): Promise<string> {
|
|
495
|
+
let action = "router_plan";
|
|
496
|
+
try {
|
|
497
|
+
const parsed = parseArgs(rawArgs);
|
|
498
|
+
if (!parsed.ok) return parsed.error;
|
|
499
|
+
action = `action=${parsed.action}`;
|
|
500
|
+
const sessionID = isString(ctx?.sessionID) ? ctx.sessionID : "";
|
|
501
|
+
if (sessionID.length === 0) return `${PREFIX} ${action} refused: no calling session; plans are owned by the session that runs them.`;
|
|
502
|
+
// QA-4.1-10: the approve getter is read lazily, inside compile and residue only.
|
|
503
|
+
const auto = (): boolean => opts?.approve?.() === "auto";
|
|
504
|
+
return await run(runtime, parsed.a, { sessionID, baseDir: projectDir(ctx), auto });
|
|
505
|
+
} catch (error) {
|
|
506
|
+
return describeError(action, error);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
export function createRouterPlanTool(runtime: ExecutorRuntime, options?: RouterPlanToolOptions): ReturnType<typeof tool> {
|
|
511
|
+
return tool({
|
|
512
|
+
description:
|
|
513
|
+
"Drive the plan executor. Actions: compile (path, phases?, doneBefore?) -> summary or a residue prompt to dispatch; " +
|
|
514
|
+
"residue (planId, text = architect JSON); approve (planId; only after the user approves it after seeing its summary (a request to run it is not approval); " +
|
|
515
|
+
"with approve: auto, compile and residue approve by itself); " +
|
|
516
|
+
"status (planId?, inbox?); ready (planId); add-tasks (planId, text); " +
|
|
517
|
+
"answer (planId?, inboxId, text; without planId: this session's running plan); done (planId, task; manual/preflight tasks only); pause|resume|abort|land|adopt (planId); " +
|
|
518
|
+
"gc; export (planId); purge (planId; completed or aborted only). A plan owned by another session is refused.",
|
|
519
|
+
args: {
|
|
520
|
+
action: tool.schema.enum(ROUTER_PLAN_ACTIONS).describe("What to do."),
|
|
521
|
+
planId: tool.schema.string().optional().describe("The plan id (printed by compile)."),
|
|
522
|
+
path: tool.schema.string().optional().describe("compile: path of the plan file, absolute or relative to the project directory."),
|
|
523
|
+
phases: tool.schema.array(tool.schema.string()).optional().describe("compile: only these phase ids."),
|
|
524
|
+
doneBefore: tool.schema.string().optional().describe("compile: treat every phase before this id as done."),
|
|
525
|
+
text: tool.schema.string().optional().describe("residue / add-tasks / answer: the JSON or answer text."),
|
|
526
|
+
inboxId: tool.schema.string().optional().describe("answer: the inbox item id."),
|
|
527
|
+
task: tool.schema.string().optional().describe("done: the task id."),
|
|
528
|
+
inbox: tool.schema.boolean().optional().describe("status: true shows only the open inbox items."),
|
|
529
|
+
},
|
|
530
|
+
async execute(args: RouterPlanArgs, toolCtx?: RouterPlanContext): Promise<string> {
|
|
531
|
+
return executeRouterPlan(runtime, args, toolCtx, options);
|
|
532
|
+
},
|
|
533
|
+
});
|
|
534
|
+
}
|