opencode-model-router 2.10.0 → 2.11.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 +306 -0
- package/README.md +3 -2
- package/package.json +8 -1
- package/src/compat/background.ts +5 -0
- package/src/compat/session-lookup.ts +21 -0
- package/src/compat/v2-hooks.ts +256 -88
- package/src/compat/v2-observations.ts +1 -0
- package/src/compat/v2-vocabulary.ts +14 -0
- package/src/executor/create.ts +3 -0
- package/src/executor/git.ts +110 -26
- package/src/executor/integrate/checks.ts +29 -11
- package/src/executor/integrate/queue.ts +95 -13
- package/src/executor/ledger.ts +16 -12
- package/src/executor/lfs-restore.ts +492 -0
- package/src/executor/paths.ts +7 -2
- package/src/executor/recovery.ts +2 -1
- package/src/executor/runtime.ts +1010 -226
- package/src/executor/slots/pool.ts +120 -19
- package/src/executor/slots/provision.ts +111 -23
- package/src/executor/slots/root.ts +81 -0
- package/src/executor/types.ts +28 -2
- package/src/executor/unattended.ts +6 -1
- package/src/executor/verify-trees.ts +507 -0
- package/src/guard/enforce.ts +2 -1
- package/src/guard/fingerprint.ts +9 -0
- package/src/guard/guards.ts +7 -1
- package/src/index.ts +107 -27
- package/src/router/answer-dedup.ts +198 -0
- package/src/router/common-dir.ts +241 -0
- package/src/router/config.ts +71 -12
- package/src/router/diff-handles.ts +322 -0
- package/src/router/diff-summary.ts +318 -0
- package/src/router/git-metadata-guard.ts +144 -7
- package/src/router/git-tools.ts +930 -73
- package/src/router/role-agents.ts +100 -36
- package/src/router/run-summary.ts +253 -0
- package/src/router/run-tools.ts +145 -23
- package/src/router/sessions.ts +14 -1
- package/src/routing/classify/rules.ts +93 -14
- package/src/routing/wire/hint.ts +9 -2
- package/src/v2.ts +3 -1
- package/src/verify/exec.ts +454 -2
- package/src/verify/plan-task.ts +86 -26
- package/src/verify/runner.ts +14 -6
- package/src/verify/tree.ts +5 -1
- package/src/verify/types.ts +44 -0
- package/src/verify/wiring.ts +87 -10
package/src/router/run-tools.ts
CHANGED
|
@@ -59,17 +59,24 @@
|
|
|
59
59
|
* absolute, drive, UNC or URL path or a `..` segment, but a symlink or junction inside
|
|
60
60
|
* the work root, and the contents of an `@response` file, are repository content.
|
|
61
61
|
*/
|
|
62
|
-
import { lstatSync, realpathSync, statSync } from "node:fs";
|
|
62
|
+
import { lstatSync, realpathSync, statSync, unlinkSync } from "node:fs";
|
|
63
63
|
import { createRequire } from "node:module";
|
|
64
|
-
import { homedir } from "node:os";
|
|
64
|
+
import { homedir, tmpdir } from "node:os";
|
|
65
65
|
import { posix, win32 } from "node:path";
|
|
66
66
|
import { tool } from "@opencode-ai/plugin";
|
|
67
67
|
import { applySlotEnv, slotEnvFor, type SlotBin, type SlotEnv } from "../executor/slots/env";
|
|
68
68
|
import type { RunConfig } from "./roles";
|
|
69
|
+
import {
|
|
70
|
+
canonicalArgs, dedupeAnswer, forgetAnswer, forgetToolAnswers, FORCE_ARG_DESCRIPTION, RUN_UNCHANGED_NOTE, withoutRunDuration, type AnswerKey,
|
|
71
|
+
} from "./answer-dedup";
|
|
69
72
|
import {
|
|
70
73
|
checkWorkRootAnswer, dropPartialCredential, envLookup, errorMessage, firstOutside, isFullPath, readBoundedRegularFile as readBounded,
|
|
71
74
|
realFileOrUndefined, spawnBounded, stripUrlUserinfo, workRootGuards, type BoundedLabel, type BoundedResult, type WorkRootAnswer,
|
|
72
75
|
} from "./git-tools";
|
|
76
|
+
import {
|
|
77
|
+
newRunReportPath, parseVitestReport, renderFailureSummary, renderSummaryUnavailable, REPORTER_OPTION_RE, RUN_REPORT_MAX_BYTES, runReportPathAllowed,
|
|
78
|
+
vitestScriptRefusal,
|
|
79
|
+
} from "./run-summary";
|
|
73
80
|
|
|
74
81
|
export { isFullPath } from "./git-tools";
|
|
75
82
|
export type { WorkRootAnswer } from "./git-tools";
|
|
@@ -156,10 +163,26 @@ export interface RunToolDeps {
|
|
|
156
163
|
platform?: NodeJS.Platform;
|
|
157
164
|
/** Test seam: the environment the run inherits (hardened). Default: process.env at call time. */
|
|
158
165
|
env?: NodeJS.ProcessEnv;
|
|
166
|
+
/**
|
|
167
|
+
* #108 slice 4 (OpenCode v2, roles mode at start): declare `force`, and answer a run whose output (status line without its
|
|
168
|
+
* duration, then the output or summary) equals the previous identical run's with a stub (answer-dedup.ts). The run still
|
|
169
|
+
* executes and is recorded. Absent: schema and behaviour are unchanged.
|
|
170
|
+
*/
|
|
171
|
+
dedupe?: boolean;
|
|
159
172
|
}
|
|
160
173
|
|
|
161
174
|
export interface RunInput { script: string; args?: readonly string[]; cwd: string }
|
|
162
175
|
|
|
176
|
+
/** Options of {@link planRun} beyond the call itself. */
|
|
177
|
+
export interface RunPlanOptions {
|
|
178
|
+
/**
|
|
179
|
+
* #108 `summary: "failures"`: the vitest JSON report the run writes (absolute, router-named, in the OS temp directory). The
|
|
180
|
+
* entry must run a vitest npm script; `--reporter=json --outputFile=<path>` is appended to the script's arguments. Absent
|
|
181
|
+
* (every other caller, the plan executor's checks included): the plan is unchanged.
|
|
182
|
+
*/
|
|
183
|
+
failuresReport?: string;
|
|
184
|
+
}
|
|
185
|
+
|
|
163
186
|
/** A resolved, spawnable run. `executable` is absolute; argv never passes through a shell. */
|
|
164
187
|
export interface RunPlan {
|
|
165
188
|
kind: "script" | "command";
|
|
@@ -796,6 +819,24 @@ function checkNpmArgv(fixed: readonly string[], scripts: Record<string, unknown>
|
|
|
796
819
|
}
|
|
797
820
|
}
|
|
798
821
|
|
|
822
|
+
/**
|
|
823
|
+
* #108: the arguments `summary: "failures"` appends to an npm run of `script` (undefined: the entry runs npm start, stop or
|
|
824
|
+
* restart, which name no single script). The script must be a vitest command ({@link vitestScriptRefusal}), and neither the
|
|
825
|
+
* entry's fixed arguments after `--` nor the caller's (`passed`) may set the reporter or output file. A `--` is added first
|
|
826
|
+
* when the argv has none, so npm hands the options to the script.
|
|
827
|
+
*/
|
|
828
|
+
function failuresReportArgs(report: string, scripts: Record<string, unknown>, script: string | undefined, name: string,
|
|
829
|
+
passed: readonly string[], separated: boolean): string[] {
|
|
830
|
+
const needs = 'summary "failures" needs a vitest npm script';
|
|
831
|
+
if (script === undefined) throw refuse(`${needs}; "${name}" does not run one package.json script`);
|
|
832
|
+
const why = vitestScriptRefusal(String(scripts[script]));
|
|
833
|
+
if (why !== undefined) throw refuse(`${needs}: script "${script}" ${why}`);
|
|
834
|
+
const set = passed.find(arg => REPORTER_OPTION_RE.test(arg));
|
|
835
|
+
if (set !== undefined) throw refuse(`summary "failures" sets vitest's reporter and output file itself; ${set} is not accepted with it`);
|
|
836
|
+
if (passed.includes("--")) throw refuse('summary "failures" does not accept a "--" argument (vitest would read the appended options as file filters)');
|
|
837
|
+
return [...(separated ? [] : ["--"]), "--reporter=json", `--outputFile=${report}`];
|
|
838
|
+
}
|
|
839
|
+
|
|
799
840
|
/**
|
|
800
841
|
* Resolve a call into a spawnable plan. `root` must come from authorizeCwd. Commands
|
|
801
842
|
* win over scripts of the same name. Package.json scripts take no caller arguments
|
|
@@ -803,9 +844,10 @@ function checkNpmArgv(fixed: readonly string[], scripts: Record<string, unknown>
|
|
|
803
844
|
* declaring `args`, e.g. `{ "argv": ["npm", "run", "test", "--"], "args": ["test/*"] }`.
|
|
804
845
|
* Caller arguments never name a path outside the work root, and an option-like one
|
|
805
846
|
* (`-`, `@`, `+`) needs a pattern with the same lead; a `node` entry takes option-like
|
|
806
|
-
* caller arguments only when its fixed argv starts with the script (QA-P13-1-1).
|
|
847
|
+
* caller arguments only when its fixed argv starts with the script (QA-P13-1-1). `options.failuresReport` (#108): see
|
|
848
|
+
* {@link RunPlanOptions}; any other entry is refused.
|
|
807
849
|
*/
|
|
808
|
-
export function planRun(input: RunInput, root: string, config: RunConfig, host: RunHost): RunPlan {
|
|
850
|
+
export function planRun(input: RunInput, root: string, config: RunConfig, host: RunHost, options: RunPlanOptions = {}): RunPlan {
|
|
809
851
|
const name = input.script;
|
|
810
852
|
if (typeof name !== "string" || !RUN_NAME_RE.test(name)) throw refuse("invalid entry name");
|
|
811
853
|
const args = validateRunArgs(input.args ?? []);
|
|
@@ -830,6 +872,9 @@ export function planRun(input: RunInput, root: string, config: RunConfig, host:
|
|
|
830
872
|
});
|
|
831
873
|
const [program, ...fixed] = command.argv as string[];
|
|
832
874
|
const pinned = pinnedProgram(program!);
|
|
875
|
+
if (options.failuresReport !== undefined && pinned !== "npm") {
|
|
876
|
+
throw refuse(`summary "failures" needs a vitest npm script; "${name}" is not an npm entry`);
|
|
877
|
+
}
|
|
833
878
|
if (pinned === "node") {
|
|
834
879
|
if (args.some(arg => optionLead(arg) !== undefined) && (fixed.length === 0 || optionLead(fixed[0]!) !== undefined)) {
|
|
835
880
|
throw refuse(`option-like arguments to the node command "${name}" need a fixed script first in its argv`);
|
|
@@ -838,13 +883,18 @@ export function planRun(input: RunInput, root: string, config: RunConfig, host:
|
|
|
838
883
|
argv = [...fixed, ...args];
|
|
839
884
|
} else if (pinned === "npm") {
|
|
840
885
|
refuseUncForShell(root, host.platform);
|
|
841
|
-
|
|
886
|
+
const scripts = packageScripts(root, host.platform);
|
|
887
|
+
checkNpmArgv(fixed, scripts, name);
|
|
842
888
|
// Caller options before `--` would be npm flags and could undo the hardening flags.
|
|
843
889
|
if (!fixed.includes("--") && args.some(arg => arg.startsWith("-"))) throw refuse(`option-like arguments to the npm command "${name}" need a "--" in its argv`);
|
|
890
|
+
const separator = fixed.indexOf("--");
|
|
891
|
+
const report = options.failuresReport === undefined ? [] : failuresReportArgs(options.failuresReport, scripts,
|
|
892
|
+
fixed[0] === "run" || fixed[0] === "run-script" ? fixed[1] : fixed[0] === "test" ? "test" : undefined, name,
|
|
893
|
+
[...(separator === -1 ? [] : fixed.slice(separator + 1)), ...args], separator !== -1);
|
|
844
894
|
const launch = npmLaunch(root, host, guarded());
|
|
845
895
|
executable = launch.node;
|
|
846
896
|
shell = launch.shell;
|
|
847
|
-
argv = [launch.cli, ...launch.flags, ...fixed, ...args];
|
|
897
|
+
argv = [launch.cli, ...launch.flags, ...fixed, ...args, ...report];
|
|
848
898
|
} else {
|
|
849
899
|
executable = slotToolExecutable(program!, slotEnv, host, guarded) ?? resolveCommandExecutable(program!, host, guarded());
|
|
850
900
|
argv = [...fixed, ...args];
|
|
@@ -852,11 +902,13 @@ export function planRun(input: RunInput, root: string, config: RunConfig, host:
|
|
|
852
902
|
} else if (scriptAllowed(config.scripts ?? [], name)) {
|
|
853
903
|
if (args.length > 0) throw refuse(`package.json scripts take no caller arguments; ${scriptArgumentsHint(config, name)}`);
|
|
854
904
|
refuseUncForShell(root, host.platform);
|
|
855
|
-
|
|
905
|
+
const scripts = packageScripts(root, host.platform);
|
|
906
|
+
requireScript(scripts, name);
|
|
907
|
+
const report = options.failuresReport === undefined ? [] : failuresReportArgs(options.failuresReport, scripts, name, name, [], false);
|
|
856
908
|
const launch = npmLaunch(root, host, guarded());
|
|
857
909
|
executable = launch.node;
|
|
858
910
|
shell = launch.shell;
|
|
859
|
-
argv = [launch.cli, ...launch.flags, "run", name];
|
|
911
|
+
argv = [launch.cli, ...launch.flags, "run", name, ...report];
|
|
860
912
|
} else {
|
|
861
913
|
throw refuse(`"${name}" is not in routing.run.scripts or routing.run.commands`);
|
|
862
914
|
}
|
|
@@ -930,8 +982,11 @@ function statusLine(plan: RunPlan, result: BoundedResult, ms: number): string {
|
|
|
930
982
|
return `[router_run] ${what}: exit code: ${result.code ?? "none (killed by a signal)"}; duration ${duration}`;
|
|
931
983
|
}
|
|
932
984
|
|
|
933
|
-
/**
|
|
934
|
-
|
|
985
|
+
/**
|
|
986
|
+
* Spawn a plan (shell: false), bounded by time, abort and 64 KiB of output; never rejects on a timeout or abort. `text` is the
|
|
987
|
+
* tool's answer; `status` (its first line) and `output` (the bounded output) are its parts, for a summary (#108).
|
|
988
|
+
*/
|
|
989
|
+
export async function executeRunPlan(plan: RunPlan, signal?: AbortSignal): Promise<{ result: BoundedResult; text: string; ms: number; status: string; output: string }> {
|
|
935
990
|
const started = performance.now();
|
|
936
991
|
const result = await spawnBounded(plan.executable, plan.argv, plan.cwd, {
|
|
937
992
|
env: plan.env, timeoutMs: plan.timeoutMs, signal, maxBytes: RUN_HEAD_BYTES, tailBytes: RUN_TAIL_BYTES,
|
|
@@ -939,7 +994,34 @@ export async function executeRunPlan(plan: RunPlan, signal?: AbortSignal): Promi
|
|
|
939
994
|
});
|
|
940
995
|
const ms = performance.now() - started;
|
|
941
996
|
const output = renderRunOutput(result);
|
|
942
|
-
|
|
997
|
+
const status = statusLine(plan, result, ms);
|
|
998
|
+
return { result, ms, status, output, text: `${status}\n${output}${output.endsWith("\n") || output === "" ? "" : "\n"}` };
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/** #108: a `summary: "failures"` report: its path and the OS temp directory read once for it (`os.tmpdir()` at the call). */
|
|
1002
|
+
interface RunReport { readonly path: string; readonly tmp: string }
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* #108: the answer of a `summary: "failures"` run: the report (only when the guard admits its path; its size is checked before
|
|
1006
|
+
* it is read, at most {@link RUN_REPORT_MAX_BYTES}) summarized, or why it could not be, with the output's last lines. The caller
|
|
1007
|
+
* deletes the report.
|
|
1008
|
+
*/
|
|
1009
|
+
function failuresAnswer(report: RunReport, cwd: string, run: { result: BoundedResult; status: string; output: string }): string {
|
|
1010
|
+
let text: string | undefined;
|
|
1011
|
+
let reason = "vitest wrote no report (it did not start, was stopped, or failed before reporting)";
|
|
1012
|
+
if (!runReportPathAllowed(report.path, report.tmp)) reason = "the report path was rejected";
|
|
1013
|
+
else {
|
|
1014
|
+
try {
|
|
1015
|
+
const size = statSync(report.path, { throwIfNoEntry: false })?.size;
|
|
1016
|
+
if (size !== undefined && size > RUN_REPORT_MAX_BYTES) reason = `the vitest report is larger than ${RUN_REPORT_MAX_BYTES / (1024 * 1024)} MiB`;
|
|
1017
|
+
else if (size !== undefined) text = readBounded(report.path, Math.max(1, size), "the vitest report");
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
reason = errorMessage(error);
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
const parsed = text === undefined ? undefined : parseVitestReport(text, cwd);
|
|
1023
|
+
if (parsed !== undefined) return renderFailureSummary(run.status, parsed, run.result.failure === undefined ? run.result.code : null, run.output);
|
|
1024
|
+
return renderSummaryUnavailable(run.status, text === undefined ? reason : "the vitest report is not a vitest JSON report", run.output);
|
|
943
1025
|
}
|
|
944
1026
|
|
|
945
1027
|
/**
|
|
@@ -949,24 +1031,36 @@ export async function executeRunPlan(plan: RunPlan, signal?: AbortSignal): Promi
|
|
|
949
1031
|
* is a normal result.
|
|
950
1032
|
*/
|
|
951
1033
|
export function routerRunTool(deps: RunToolDeps) {
|
|
952
|
-
const
|
|
1034
|
+
const shape = {
|
|
953
1035
|
script: tool.schema.string().min(1).max(200),
|
|
954
1036
|
args: tool.schema.array(tool.schema.string().max(200)).max(RUN_MAX_ARGS).optional(),
|
|
955
1037
|
cwd: tool.schema.string().min(1).max(4096),
|
|
956
|
-
|
|
1038
|
+
summary: tool.schema.enum(["failures"]).optional(),
|
|
1039
|
+
};
|
|
1040
|
+
// #108 slice 4: `force` is accepted only where it is declared (answers deduplicated).
|
|
1041
|
+
const inputSchema = deps.dedupe === true
|
|
1042
|
+
? tool.schema.object({ ...shape, force: tool.schema.boolean().optional() }).strict()
|
|
1043
|
+
: tool.schema.object(shape).strict();
|
|
957
1044
|
return tool({
|
|
958
1045
|
description: "Run one allowlisted package.json script or configured command in this dispatch's work root and report its exit code. "
|
|
959
1046
|
+ "No shell is spawned by the tool; arguments are accepted only when the entry declares them, each 1-200 characters of [A-Za-z0-9_./:=@+-], never a path outside the work root. "
|
|
960
1047
|
+ "cwd must be the dispatch's work root. Output (stdout and stderr) is bounded to 64 KiB; URL credentials in it are redacted (best effort, not a secret scanner) "
|
|
961
1048
|
+ "and credential-like environment variables are not passed to the run; agents and credential stores (ssh-agent, git credential helpers, "
|
|
962
1049
|
+ "cloud CLI caches in the home directory) stay reachable to scripts. The run is time-limited."
|
|
1050
|
+
+ " With summary \"failures\" (vitest npm scripts only) the answer is the test counts and the failing tests grouped by file, within 4 KiB."
|
|
963
1051
|
+ argumentCommandsDescription(deps.config()),
|
|
964
1052
|
args: {
|
|
965
1053
|
script: tool.schema.string().describe("Entry name: a script listed in routing.run.scripts (e.g. test, typecheck) or a routing.run.commands entry"),
|
|
966
1054
|
args: tool.schema.array(tool.schema.string()).optional().describe("Arguments, only for command entries that declare them"),
|
|
967
1055
|
cwd: tool.schema.string().describe("Absolute path of the dispatch's work root"),
|
|
1056
|
+
summary: tool.schema.enum(["failures"]).optional()
|
|
1057
|
+
.describe("failures: for an entry running a vitest npm script, return the counts and each failing test (first error block) instead of the raw output"),
|
|
1058
|
+
...(deps.dedupe === true ? { force: tool.schema.boolean().optional().describe(FORCE_ARG_DESCRIPTION) } : {}),
|
|
968
1059
|
},
|
|
969
1060
|
async execute(input, context) {
|
|
1061
|
+
// #108 slice 4: the call's dedup key, once known; an error answer forgets it, a refusal before it is known forgets the
|
|
1062
|
+
// session's router_run entries.
|
|
1063
|
+
let dedupKey: AnswerKey | undefined;
|
|
970
1064
|
try {
|
|
971
1065
|
const platform = deps.platform ?? process.platform;
|
|
972
1066
|
// Authority first (P-10, I9, QA-P13-2-8): nothing else is looked at for an unbound session.
|
|
@@ -975,18 +1069,46 @@ export function routerRunTool(deps: RunToolDeps) {
|
|
|
975
1069
|
if (answer.root === null) throw refuse("this session has no bound work root (I9); router_run only runs in a dispatch's work root");
|
|
976
1070
|
const root = authorizeCwd(answer.root, (input as { cwd?: unknown } | undefined)?.cwd, platform);
|
|
977
1071
|
const parsed = inputSchema.parse(input);
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
1072
|
+
if (deps.dedupe === true) {
|
|
1073
|
+
// `cwd` names `root` (authorizeCwd), whose real path is in the key already; however it was spelled, it is the same call.
|
|
1074
|
+
dedupKey = { sessionID: context.sessionID, tool: RUN_TOOL_NAME, via: { kind: "workRoot" }, root, args: canonicalArgs(parsed, { args: [] }, ["cwd"]) };
|
|
1075
|
+
}
|
|
1076
|
+
// #108: opt-in; the report path is router-named in the OS temp directory (read once) and deleted once the run settles. A path
|
|
1077
|
+
// the guard would not admit (a relative TEMP/TMPDIR) is refused before planning, so no report can land in the work root.
|
|
1078
|
+
let report: RunReport | undefined;
|
|
1079
|
+
if (parsed.summary === "failures") {
|
|
1080
|
+
const tmp = tmpdir();
|
|
1081
|
+
report = { path: newRunReportPath(tmp), tmp };
|
|
1082
|
+
if (!runReportPathAllowed(report.path, tmp)) {
|
|
1083
|
+
throw refuse(`summary "failures" needs an absolute OS temp directory for its report (it is "${tmp}"; check TEMP, TMP or TMPDIR)`);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
try {
|
|
1087
|
+
const plan = planRun(parsed, root, deps.config(), {
|
|
1088
|
+
platform, env: deps.env ?? process.env,
|
|
1089
|
+
...(deps.nodeExecPath !== undefined ? { nodeExecPath: deps.nodeExecPath } : {}),
|
|
1090
|
+
}, report === undefined ? {} : { failuresReport: report.path });
|
|
1091
|
+
const at = Date.now();
|
|
1092
|
+
const run = await executeRunPlan(plan, context.abort);
|
|
1093
|
+
const exitCode = run.result.failure === undefined ? run.result.code : null;
|
|
1094
|
+
try { deps.recordRun?.({ sessionID: context.sessionID, script: plan.name, exitCode, at }); } catch (error) {
|
|
1095
|
+
console.warn(`[model-router] router_run: could not record the run (${errorMessage(error)})`);
|
|
1096
|
+
}
|
|
1097
|
+
const text = report === undefined ? run.text : failuresAnswer(report, plan.cwd, run);
|
|
1098
|
+
// #108 slice 4: compared without the status line's duration; the stub keeps this run's status line. An answer given after
|
|
1099
|
+
// the call was aborted may never reach the model: it is not stored.
|
|
1100
|
+
return dedupKey === undefined ? text : dedupeAnswer(dedupKey, text, {
|
|
1101
|
+
force: "force" in parsed && parsed.force === true, compared: withoutRunDuration(text), stub: () => `${run.status}\n${RUN_UNCHANGED_NOTE}\n`,
|
|
1102
|
+
aborted: context.abort?.aborted === true,
|
|
1103
|
+
});
|
|
1104
|
+
} finally {
|
|
1105
|
+
if (report !== undefined && runReportPathAllowed(report.path, report.tmp)) {
|
|
1106
|
+
try { unlinkSync(report.path); } catch { /* missing (no report written) or already gone */ }
|
|
1107
|
+
}
|
|
987
1108
|
}
|
|
988
|
-
return text;
|
|
989
1109
|
} catch (error) {
|
|
1110
|
+
if (dedupKey !== undefined) forgetAnswer(dedupKey);
|
|
1111
|
+
else if (deps.dedupe === true) forgetToolAnswers(context.sessionID, RUN_TOOL_NAME);
|
|
990
1112
|
const prefix = error instanceof RunRefused ? "refused: " : "";
|
|
991
1113
|
return `[router_run] error: ${prefix}${stripUrlUserinfo(errorMessage(error))}`;
|
|
992
1114
|
}
|
package/src/router/sessions.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash, randomBytes } from "node:crypto";
|
|
2
2
|
import type { RouterConfig } from "./config";
|
|
3
3
|
import { fingerprintToolCall } from "../guard/fingerprint";
|
|
4
|
+
import { isWellFormedExpansion } from "./diff-handles";
|
|
4
5
|
import { DEFAULT_IDLE_TTL_MS } from "./idle-sweep";
|
|
5
6
|
import type { DecisionFacts, LadderStepKind } from "../routing/outcomes/types";
|
|
6
7
|
import type { ChangedFile } from "../verify/dispatch";
|
|
@@ -159,6 +160,15 @@ export function buildCapBanner(
|
|
|
159
160
|
/** Tools that count against the read-only cap. Keep narrow — editing tools should never count. */
|
|
160
161
|
export const READ_ONLY_TOOLS = new Set(["grep", "read", "glob", "ls"]);
|
|
161
162
|
|
|
163
|
+
/**
|
|
164
|
+
* #108 slice 5: a `router_git_show` call that expands a `gd_` handle, with well-formed arguments (`isWellFormedExpansion`: a
|
|
165
|
+
* malformed handle, `lines` or `side` is refused before git runs, so it is not a read). For a role session it is a read
|
|
166
|
+
* (read-only cap, guard clauses 4 and 5, trajectory); every other router_git_* call, and any call outside a role session, is not.
|
|
167
|
+
*/
|
|
168
|
+
export function isHandleExpansion(tool: string, args: unknown): boolean {
|
|
169
|
+
return tool === "router_git_show" && typeof args === "object" && args !== null && isWellFormedExpansion(args as Record<string, unknown>);
|
|
170
|
+
}
|
|
171
|
+
|
|
162
172
|
// ---------------------------------------------------------------------------
|
|
163
173
|
// Trivial classifier
|
|
164
174
|
// ---------------------------------------------------------------------------
|
|
@@ -569,10 +579,13 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
|
569
579
|
* Called from the tool.execute.after hook. Appends a cap/redundancy banner
|
|
570
580
|
* to the tool output for tracked subagent sessions running read-only tools.
|
|
571
581
|
* Mutates outputRef.output in place (same as the inlined hook logic).
|
|
582
|
+
* `roleExpansionReads` (#108 slice 5, set by the caller for a role session only): a handle expansion
|
|
583
|
+
* ({@link isHandleExpansion}) counts as a read too.
|
|
572
584
|
*/
|
|
573
585
|
recordToolCall(
|
|
574
586
|
input: { sessionID: string; tool: string; args: unknown },
|
|
575
587
|
outputRef: Record<string, unknown>,
|
|
588
|
+
opts: { roleExpansionReads?: boolean } = {},
|
|
576
589
|
): void {
|
|
577
590
|
const state = subagentCapState.get(input.sessionID);
|
|
578
591
|
if (!state) return; // not a tracked subagent session
|
|
@@ -581,7 +594,7 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
|
581
594
|
// removed it. Tracked sessions still refresh here, because the read-only
|
|
582
595
|
// filter below runs later.
|
|
583
596
|
touch(input.sessionID);
|
|
584
|
-
if (!READ_ONLY_TOOLS.has(input.tool)) return;
|
|
597
|
+
if (!READ_ONLY_TOOLS.has(input.tool) && !(opts.roleExpansionReads === true && isHandleExpansion(input.tool, input.args))) return;
|
|
585
598
|
|
|
586
599
|
const fp = fingerprintToolCall(input.tool, input.args);
|
|
587
600
|
const previousCall = state.seen.get(fp);
|
|
@@ -102,22 +102,100 @@ const COMPILED_RULES: readonly CompiledRule[] = (() => {
|
|
|
102
102
|
});
|
|
103
103
|
})();
|
|
104
104
|
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
// Term labels (#194, #200): what a decision row may log for a vocabulary match
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* #194 (R2-6), #200: what a decision row may log for one vocabulary term, derived once from the term's source. The label
|
|
111
|
+
* tables of the high-risk terms ({@link highRiskTermOf}) and of the needs table (`trace.needTerms`) are both built with
|
|
112
|
+
* {@link termLabelOf}. Only a single-token term names a word: a closed one (`\bbilling\b`) its matched word, an open one
|
|
113
|
+
* (`\bdeploy\w*`, `\b(?:en|de)crypt\w*`) only one of its literal stems (`deploy`, `encrypt`), never the rest of the prompt's
|
|
114
|
+
* word. A term with a gap or a separator ({@link hasGap}) can span the prompt's own words, also joined by hyphens
|
|
115
|
+
* (`npm-acme-internal-publish`, `remote-acme-push`): it logs its table id.
|
|
116
|
+
*/
|
|
117
|
+
type TermLabel = { readonly kind: "id" } | { readonly kind: "word" } | { readonly kind: "stems"; readonly stems: readonly string[] };
|
|
118
|
+
/** `\b`, an optional `(?:a|b)` of lower-case literals, lower-case literals, `\w*`: nothing else. */
|
|
119
|
+
const OPEN_TERM_SHAPE = /^\\b(?:\(\?:([a-z]+(?:\|[a-z]+)*)\))?([a-z]+)\\w\*$/;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* True when a regex source has a gap or a separator, a part that can match the prompt's own text between or around its fixed
|
|
123
|
+
* words: `\s` (in or out of a class), any negated class (`[^\n]`), or, outside a class, a blank, an unescaped `.`, `*`, `+`
|
|
124
|
+
* or `{` (a `{m,n}` quantifier). Escapes other than `\s` and the rest of a class are single characters. A lookahead counts
|
|
125
|
+
* too: a gap anywhere in the source makes the whole term an id.
|
|
126
|
+
*/
|
|
127
|
+
function hasGap(source: string): boolean {
|
|
128
|
+
let inClass = false;
|
|
129
|
+
for (let i = 0; i < source.length; i++) {
|
|
130
|
+
const c = source[i];
|
|
131
|
+
if (c === "\\") {
|
|
132
|
+
if (source[i + 1] === "s") return true;
|
|
133
|
+
i++;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (inClass) {
|
|
137
|
+
if (c === "]") inClass = false;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (c === "[") {
|
|
141
|
+
if (source[i + 1] === "^") return true;
|
|
142
|
+
inClass = true;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (c === " " || c === "." || c === "*" || c === "+" || c === "{") return true;
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The {@link TermLabel} of one term source: an open term's stems first (its `\w*` is no gap), else id or word by {@link hasGap}. */
|
|
151
|
+
function termLabelOf(source: string): TermLabel {
|
|
152
|
+
const open = OPEN_TERM_SHAPE.exec(source);
|
|
153
|
+
if (open !== null) return { kind: "stems", stems: (open[1]?.split("|") ?? [""]).map((prefix) => prefix + (open[2] ?? "")) };
|
|
154
|
+
return hasGap(source) ? { kind: "id" } : { kind: "word" };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* How one match of term `index` is logged: the matched word (lower-cased) or the matched stem when its {@link TermLabel}
|
|
159
|
+
* allows one and `word` accepts it, else `term-<index>`.
|
|
160
|
+
*/
|
|
161
|
+
function matchLabel(label: TermLabel | undefined, text: string, index: number, word: RegExp): string {
|
|
162
|
+
const matched = text.toLowerCase();
|
|
163
|
+
const named = label === undefined || label.kind === "id" ? ""
|
|
164
|
+
: label.kind === "word" ? matched : label.stems.find((stem) => matched.startsWith(stem)) ?? "";
|
|
165
|
+
return word.test(named) ? named : `term-${index}`;
|
|
166
|
+
}
|
|
167
|
+
|
|
105
168
|
interface CompiledNeed {
|
|
106
169
|
readonly need: Need;
|
|
107
170
|
readonly implies: readonly Need[];
|
|
108
171
|
readonly res: readonly RegExp[];
|
|
172
|
+
/** #200, one per term: the load-time label table of this need ({@link termLabelOf}). */
|
|
173
|
+
readonly labels: readonly TermLabel[];
|
|
109
174
|
}
|
|
110
175
|
|
|
111
176
|
const COMPILED_NEEDS: readonly CompiledNeed[] = NEED_RULES.map((rule) => ({
|
|
112
177
|
need: rule.need,
|
|
113
178
|
implies: rule.implies ?? [],
|
|
114
179
|
res: rule.terms.map(globalCopy),
|
|
180
|
+
labels: rule.terms.map((re) => termLabelOf(re.source)),
|
|
115
181
|
}));
|
|
116
182
|
|
|
183
|
+
/**
|
|
184
|
+
* #200: the ids of the needs-table terms whose matches are logged as `term-<n>` whatever they matched (their source has a gap),
|
|
185
|
+
* as `<need>:term-<n>` in table order. For tests and docs; scanning reads {@link COMPILED_NEEDS}.
|
|
186
|
+
*/
|
|
187
|
+
export const GAPPED_NEED_TERMS: readonly string[] = COMPILED_NEEDS.flatMap((rule) =>
|
|
188
|
+
rule.labels.flatMap((label, index) => (label.kind === "id" ? [`${rule.need}:term-${index}`] : [])),
|
|
189
|
+
);
|
|
190
|
+
|
|
117
191
|
const HIGH_RISK_RES: readonly RegExp[] = [
|
|
118
192
|
...HIGH_RISK_TERMS.map(globalCopy),
|
|
119
193
|
...HIGH_RISK_CASE_SENSITIVE_TERMS.map((re) => new RegExp(re.source, "g")),
|
|
120
194
|
];
|
|
195
|
+
/** #194 (R2-6): what {@link highRiskTermOf} may log for each high-risk term ({@link termLabelOf}). */
|
|
196
|
+
const HIGH_RISK_LABELS: readonly TermLabel[] = HIGH_RISK_RES.map((re) => termLabelOf(re.source));
|
|
197
|
+
/** A logged high-risk word: lower-case letters and hyphens, at most 40 characters. */
|
|
198
|
+
const RISK_WORD = /^[a-z-]{1,40}$/;
|
|
121
199
|
const MEDIUM_RISK_RES: readonly RegExp[] = MEDIUM_RISK_TERMS.map(globalCopy);
|
|
122
200
|
const REPO_SCOPE_RES: readonly RegExp[] = REPO_SCOPE_TERMS.map(globalCopy);
|
|
123
201
|
const ABS_PATH_RES: readonly RegExp[] = [WINDOWS_ABS_PATH_RE, POSIX_ABS_PATH_RE].map(globalCopy);
|
|
@@ -444,23 +522,24 @@ function externalPath(needsText: string, cwd: string): string | null {
|
|
|
444
522
|
}
|
|
445
523
|
|
|
446
524
|
/**
|
|
447
|
-
* One need R9 found in a text, and why — never text of the prompt itself (D14, QA-G-B-2-2): the
|
|
448
|
-
*
|
|
449
|
-
* `
|
|
525
|
+
* One need R9 found in a text, and why — never text of the prompt itself (D14, QA-G-B-2-2): `url` for a URL; the term's id in
|
|
526
|
+
* the needs table (`term-<n>`) when the term's source has a gap (#200, the {@link termLabelOf} rule of the high-risk terms:
|
|
527
|
+
* `\s`, `[^\n]`, `.`, `*`, `+`, `{m,n}`; e.g. `run the tests`, `remote … push`), whatever it matched; else the matched
|
|
528
|
+
* vocabulary word (lower-cased, a single word, e.g. `update`), or `term-<n>` when the match is not one; `path` for an absolute
|
|
529
|
+
* path outside cwd; `implied-by-<need>`.
|
|
450
530
|
*/
|
|
451
531
|
export interface NeedMatch {
|
|
452
532
|
readonly need: Need;
|
|
453
533
|
readonly term: string;
|
|
454
534
|
}
|
|
455
535
|
|
|
456
|
-
/** A matched vocabulary word: letters
|
|
457
|
-
const VOCABULARY_WORD = /^[a-z][a-z
|
|
536
|
+
/** A matched vocabulary word: one word of letters and hyphens, short. Anything else (blanks, a URL, a path, a file name, `&&`) is not. */
|
|
537
|
+
const VOCABULARY_WORD = /^[a-z][a-z-]{0,39}$/;
|
|
458
538
|
|
|
459
|
-
/** QA-G-B-2-2: how a term match is named in a {@link NeedMatch} (see there). */
|
|
460
|
-
function termLabel(
|
|
461
|
-
if (need === "web" && /^https?:\/\//i.test(hit.text)) return "url";
|
|
462
|
-
|
|
463
|
-
return VOCABULARY_WORD.test(word) ? word : `term-${hit.index}`;
|
|
539
|
+
/** QA-G-B-2-2, #200: how a term match is named in a {@link NeedMatch} (see there). */
|
|
540
|
+
function termLabel(rule: CompiledNeed, hit: { readonly index: number; readonly text: string }): string {
|
|
541
|
+
if (rule.need === "web" && /^https?:\/\//i.test(hit.text)) return "url";
|
|
542
|
+
return matchLabel(rule.labels[hit.index], hit.text, hit.index, VOCABULARY_WORD);
|
|
464
543
|
}
|
|
465
544
|
|
|
466
545
|
/**
|
|
@@ -474,7 +553,7 @@ function scanNeeds(needsText: string, cwd: string | null, matches?: NeedMatch[])
|
|
|
474
553
|
const hit = firstHit(rule.res, rule.need === "external_dir" ? needsText : pathFreeText, true);
|
|
475
554
|
if (hit === null) continue;
|
|
476
555
|
needs.add(rule.need);
|
|
477
|
-
matches?.push({ need: rule.need, term: termLabel(rule
|
|
556
|
+
matches?.push({ need: rule.need, term: termLabel(rule, hit) });
|
|
478
557
|
for (const implied of rule.implies) {
|
|
479
558
|
needs.add(implied);
|
|
480
559
|
matches?.push({ need: implied, term: `implied-by-${rule.need}` });
|
|
@@ -672,7 +751,7 @@ export function highRiskTermOf(text: string): string | undefined {
|
|
|
672
751
|
const { riskText, prohibitionText } = splitSections(prepareBody(raw));
|
|
673
752
|
const hit = firstHit(HIGH_RISK_RES, riskText, false) ?? firstHit(HIGH_RISK_RES, prohibitionText, true);
|
|
674
753
|
if (hit === null) return undefined;
|
|
675
|
-
|
|
676
|
-
//
|
|
677
|
-
return
|
|
754
|
+
// Multiword/command regexes can span arbitrary arguments, and credential names can be private: log only a table id for
|
|
755
|
+
// those (#194: decided by the term's shape, HIGH_RISK_LABELS). An open term logs its stem, never the prompt's word.
|
|
756
|
+
return matchLabel(HIGH_RISK_LABELS[hit.index], hit.text, hit.index, RISK_WORD);
|
|
678
757
|
}
|
package/src/routing/wire/hint.ts
CHANGED
|
@@ -68,7 +68,14 @@ export function buildHint(decision: Decision, facts: Pick<TaskFacts, "class">, d
|
|
|
68
68
|
return `Route hint: for ${facts.class} work like this turn, prefer ${destination}.`;
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* A user-role text that is harness input, not the user's ask (#191): a child report (the host's `<subagent …>` on 2.0.x and the
|
|
73
|
+
* router's held placeholder; the host's `<background-result …>`, of any kind, on 2.3+) or the router's `<router-verdict …>`
|
|
74
|
+
* entry. On 2.3+ every dispatch reports back this way inside the same turn; read as the ask, it changed the turn's hint.
|
|
75
|
+
*/
|
|
76
|
+
const HARNESS_ENTRY = /^\s*<(?:subagent|background-result|router-verdict)[\s>]/;
|
|
77
|
+
|
|
78
|
+
/** Text of the latest user message that is the user's own (not a synthetic `Instructions from:` attachment nor harness input). */
|
|
72
79
|
export function latestUserText(messages: readonly unknown[] | undefined): string | null {
|
|
73
80
|
if (messages === undefined) return null;
|
|
74
81
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
@@ -80,7 +87,7 @@ export function latestUserText(messages: readonly unknown[] | undefined): string
|
|
|
80
87
|
.filter((part): part is { type: "text"; text: string } =>
|
|
81
88
|
typeof part === "object" && part !== null && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string")
|
|
82
89
|
.map((part) => part.text)
|
|
83
|
-
.filter((text) => !/^Instructions from:/m.test(text));
|
|
90
|
+
.filter((text) => !/^Instructions from:/m.test(text) && !HARNESS_ENTRY.test(text));
|
|
84
91
|
if (texts.length > 0) return texts.join("\n").slice(0, HINT_MAX_USER_CHARS);
|
|
85
92
|
}
|
|
86
93
|
return null;
|
package/src/v2.ts
CHANGED
|
@@ -9,7 +9,7 @@ import type { PlanTaskVerifier } from "./executor/runtime";
|
|
|
9
9
|
import type { ExecutorChildGuardPort } from "./executor/types";
|
|
10
10
|
import { createExecutor, createExecutorAccess, prepareExecutor, type CreateExecutorOptions, type PreparedExecutor } from "./executor/create";
|
|
11
11
|
import { EXECUTOR_PLATFORM_REASON, executorPlatformSupported } from "./executor/platform";
|
|
12
|
-
import { loadConfig, resolveRolesRouting, resolveRouting } from "./router/config";
|
|
12
|
+
import { loadConfig, resolveRolesRouting, resolveRouting, setConfigBuildHost } from "./router/config";
|
|
13
13
|
import { locationOutsideWorkRoots } from "./router/work-roots";
|
|
14
14
|
import { openV2Observations } from "./compat/v2-observations";
|
|
15
15
|
|
|
@@ -18,6 +18,8 @@ export default {
|
|
|
18
18
|
id: "opencode-model-router",
|
|
19
19
|
server: ModelRouterPlugin,
|
|
20
20
|
async setup(ctx: Plugin.Context) {
|
|
21
|
+
// #80: before the first loadConfig(): on v2 a `null` inside an override's `presets` removes the inherited key.
|
|
22
|
+
setConfigBuildHost("v2");
|
|
21
23
|
const observations = openV2Observations();
|
|
22
24
|
try {
|
|
23
25
|
const runtime = createV2Runtime(ctx);
|