opencode-model-router 2.6.1 → 2.8.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 +239 -0
- package/README.md +3 -1
- package/package.json +2 -2
- package/src/commands/approvals.ts +354 -0
- package/src/commands/output.ts +12 -1
- package/src/compat/v2-hooks.ts +255 -53
- package/src/index.ts +328 -37
- package/src/router/config.ts +48 -2
- package/src/router/dispatch-header.ts +95 -2
- package/src/router/git-tools.ts +165 -9
- package/src/router/protocol.ts +5 -1
- package/src/router/role-agents.ts +110 -3
- package/src/router/roles-config.ts +83 -0
- package/src/router/roles.ts +1 -1
- package/src/router/sessions.ts +11 -0
- package/src/routing/classify/route-line.ts +96 -5
- package/src/routing/classify/types.ts +26 -0
- package/src/routing/outcomes/signals.ts +17 -0
- package/src/routing/roles/admission.ts +1028 -0
- package/src/routing/roles/approvals.ts +876 -0
- package/src/routing/roles/binding.ts +17 -4
- package/src/routing/roles/check-placement.ts +112 -0
- package/src/routing/roles/git-root.ts +500 -0
- package/src/routing/roles/policy.ts +9 -0
- package/src/routing/roles/read-set.ts +325 -0
- package/src/routing/roles/work-root.ts +9 -1
- package/src/routing/wire/dispatch.ts +611 -18
- package/src/routing/wire/working-set.ts +58 -0
- package/src/util/linear-trim.ts +32 -0
- package/src/verify/batch.ts +7 -2
- package/src/verify/branch.ts +135 -0
- package/src/verify/deterministic.ts +232 -10
- package/src/verify/dispatch.ts +284 -9
- package/src/verify/dod.ts +46 -0
- package/src/verify/edges.ts +817 -0
- 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 +155 -8
- package/src/verify/perimeter.ts +1180 -0
- package/src/verify/pin.ts +109 -0
- package/src/verify/reference.ts +174 -30
- package/src/verify/risk.ts +16 -3
- package/src/verify/runner.ts +706 -32
- package/src/verify/tree.ts +347 -8
- package/src/verify/types.ts +57 -0
- package/src/verify/wiring.ts +1324 -35
package/src/router/config.ts
CHANGED
|
@@ -20,11 +20,17 @@ import { resolveRoleTable, type ExplorationConfig, type RunConfig } from "./role
|
|
|
20
20
|
import {
|
|
21
21
|
DEFAULT_RUN_COMMANDS,
|
|
22
22
|
DEFAULT_RUN_SCRIPTS,
|
|
23
|
+
DEFAULT_REPO_APPROVAL_DAYS,
|
|
24
|
+
DEFAULT_REPO_DEPTH,
|
|
23
25
|
DEFAULT_RUN_TIMEOUT_MS,
|
|
24
26
|
ROLES_V1_NOTICE,
|
|
25
27
|
collectRolesIssues,
|
|
26
28
|
sanitizeDelegation,
|
|
27
29
|
sanitizeExploration,
|
|
30
|
+
sanitizeRepoApprovalDays,
|
|
31
|
+
sanitizeRepoDepth,
|
|
32
|
+
sanitizeRepoExclude,
|
|
33
|
+
sanitizeRepoParents,
|
|
28
34
|
sanitizeRoleAgents,
|
|
29
35
|
sanitizeRun,
|
|
30
36
|
sanitizeWorkRoots,
|
|
@@ -329,6 +335,14 @@ export interface RoutingConfig {
|
|
|
329
335
|
run?: Partial<RunConfig>;
|
|
330
336
|
/** Global only. Absolute globs with a static long-form prefix; default none. */
|
|
331
337
|
workRoots?: string[];
|
|
338
|
+
/** Global only. Literal absolute directories below which a git top level is an admissible work root (cross-repo, Phase 1). Inert on v1. */
|
|
339
|
+
repoParents?: string[];
|
|
340
|
+
/** Global only. Levels below a parent, 1–4; default 2. */
|
|
341
|
+
repoDepth?: number;
|
|
342
|
+
/** Global only. Absolute globs never admitted below a parent. */
|
|
343
|
+
repoExclude?: string[];
|
|
344
|
+
/** Global only. Days an approved repository outside the parents stays approved after its last use, 1–90; default 14. Inert on v1. */
|
|
345
|
+
repoApprovalDays?: number;
|
|
332
346
|
}
|
|
333
347
|
|
|
334
348
|
export interface RouterConfig {
|
|
@@ -1818,6 +1832,14 @@ function validateRouting(value: unknown): RoutingConfig | undefined {
|
|
|
1818
1832
|
if (run !== undefined) out.run = run;
|
|
1819
1833
|
const workRoots = sanitizeWorkRoots(routing.workRoots).value;
|
|
1820
1834
|
if (workRoots !== undefined) out.workRoots = workRoots;
|
|
1835
|
+
const repoParents = sanitizeRepoParents(routing.repoParents).value;
|
|
1836
|
+
if (repoParents !== undefined) out.repoParents = repoParents;
|
|
1837
|
+
const repoDepth = sanitizeRepoDepth(routing.repoDepth).value;
|
|
1838
|
+
if (repoDepth !== undefined) out.repoDepth = repoDepth;
|
|
1839
|
+
const repoExclude = sanitizeRepoExclude(routing.repoExclude).value;
|
|
1840
|
+
if (repoExclude !== undefined) out.repoExclude = repoExclude;
|
|
1841
|
+
const repoApprovalDays = sanitizeRepoApprovalDays(routing.repoApprovalDays).value;
|
|
1842
|
+
if (repoApprovalDays !== undefined) out.repoApprovalDays = repoApprovalDays;
|
|
1821
1843
|
|
|
1822
1844
|
const outcomes = readBlock(routing, "outcomes", "routing");
|
|
1823
1845
|
if (outcomes !== undefined) {
|
|
@@ -2208,7 +2230,15 @@ const GLOBAL_ONLY_ROUTING_KEYS: ReadonlyArray<readonly [block: string, key: stri
|
|
|
2208
2230
|
];
|
|
2209
2231
|
|
|
2210
2232
|
/** Roles keys (#84) a project layer must not carry; `routing.delegation` is allowed there. */
|
|
2211
|
-
const GLOBAL_ONLY_ROLES_ROUTING_KEYS = [
|
|
2233
|
+
const GLOBAL_ONLY_ROLES_ROUTING_KEYS = [
|
|
2234
|
+
"exploration",
|
|
2235
|
+
"run",
|
|
2236
|
+
"workRoots",
|
|
2237
|
+
"repoParents",
|
|
2238
|
+
"repoDepth",
|
|
2239
|
+
"repoExclude",
|
|
2240
|
+
"repoApprovalDays",
|
|
2241
|
+
] as const;
|
|
2212
2242
|
|
|
2213
2243
|
function stripGlobalOnlyRolesKeys(data: Record<string, unknown>): string[] {
|
|
2214
2244
|
const dropped: string[] = [];
|
|
@@ -2512,6 +2542,10 @@ const ROUTING_KNOWN_KEYS: Readonly<Record<string, readonly string[]>> = {
|
|
|
2512
2542
|
"exploration",
|
|
2513
2543
|
"run",
|
|
2514
2544
|
"workRoots",
|
|
2545
|
+
"repoParents",
|
|
2546
|
+
"repoDepth",
|
|
2547
|
+
"repoExclude",
|
|
2548
|
+
"repoApprovalDays",
|
|
2515
2549
|
],
|
|
2516
2550
|
detection: ["deterministic", "grader", "none"],
|
|
2517
2551
|
classifier: ["backend", "model", "baseUrl", "apiKeyEnv", "timeoutMs", "samples", "maxStateChars", "presets"],
|
|
@@ -3186,6 +3220,12 @@ export interface ResolvedRolesRouting {
|
|
|
3186
3220
|
readonly exploration: Readonly<ExplorationConfig>;
|
|
3187
3221
|
readonly run: Readonly<RunConfig>;
|
|
3188
3222
|
readonly workRoots: readonly string[];
|
|
3223
|
+
/** Cross-repo (Phase 1): admissible repositories lie 1..repoDepth levels below these directories. */
|
|
3224
|
+
readonly repoParents: readonly string[];
|
|
3225
|
+
readonly repoDepth: number;
|
|
3226
|
+
readonly repoExclude: readonly string[];
|
|
3227
|
+
/** Cross-repo (Phase 4): days an approval outside the parents lasts after its last use (1–90, default 14). */
|
|
3228
|
+
readonly repoApprovalDays: number;
|
|
3189
3229
|
/** True on v1 when roles keys were set: they are validated but have no effect. */
|
|
3190
3230
|
readonly inert: boolean;
|
|
3191
3231
|
}
|
|
@@ -3213,7 +3253,9 @@ export function resolveRolesRouting(
|
|
|
3213
3253
|
const r: RoutingConfig = cfg?.routing ?? {};
|
|
3214
3254
|
const requested = r.delegation ?? "tiers";
|
|
3215
3255
|
const touched = requested === "roles" || cfg?.roleAgents !== undefined || r.exploration !== undefined
|
|
3216
|
-
|| r.run !== undefined || r.workRoots !== undefined
|
|
3256
|
+
|| r.run !== undefined || r.workRoots !== undefined
|
|
3257
|
+
|| r.repoParents !== undefined || r.repoDepth !== undefined || r.repoExclude !== undefined
|
|
3258
|
+
|| r.repoApprovalDays !== undefined;
|
|
3217
3259
|
const inert = host === "v1" && touched;
|
|
3218
3260
|
if (inert && !warnedRolesInertOnV1) {
|
|
3219
3261
|
warnedRolesInertOnV1 = true;
|
|
@@ -3233,6 +3275,10 @@ export function resolveRolesRouting(
|
|
|
3233
3275
|
timeoutMs: r.run?.timeoutMs ?? DEFAULT_RUN_TIMEOUT_MS,
|
|
3234
3276
|
}),
|
|
3235
3277
|
workRoots: Object.freeze([...(r.workRoots ?? [])]),
|
|
3278
|
+
repoParents: Object.freeze([...(r.repoParents ?? [])]),
|
|
3279
|
+
repoDepth: r.repoDepth ?? DEFAULT_REPO_DEPTH,
|
|
3280
|
+
repoExclude: Object.freeze([...(r.repoExclude ?? [])]),
|
|
3281
|
+
repoApprovalDays: r.repoApprovalDays ?? DEFAULT_REPO_APPROVAL_DAYS,
|
|
3236
3282
|
inert,
|
|
3237
3283
|
});
|
|
3238
3284
|
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { parseRouteLine } from "../routing/classify/route-line";
|
|
2
|
+
import { displaySafe } from "../routing/roles/read-set";
|
|
2
3
|
|
|
3
4
|
/** First characters of every router dispatch header (index.ts never adds a second one). */
|
|
4
5
|
export const DISPATCH_HEADER_PREFIX = "[router] You are @";
|
|
5
6
|
|
|
6
|
-
/** What index.ts
|
|
7
|
+
/** What index.ts (tiers) and the role dispatch path put between a header and the orchestrator's prompt. */
|
|
7
8
|
export const DISPATCH_HEADER_SEPARATOR = "\n\n---\n\n";
|
|
8
9
|
|
|
9
10
|
/** The header's last paragraph: the end of a header whose separator is missing. */
|
|
@@ -25,19 +26,31 @@ const FALSE_REFUSAL_PARAGRAPH = "A hand-back with zero tool calls is recorded as
|
|
|
25
26
|
* `root` (plan §2.2, T1.5.3a): the dispatch's work root — the route line's `root=`
|
|
26
27
|
* (`routeLineRoot`) — named by the working-directory paragraph instead of the
|
|
27
28
|
* project directory. Absent or empty: the header is byte-identical to before.
|
|
29
|
+
*
|
|
30
|
+
* Cross-repo (`docs/design/cross-repo.md` §5, P1.7), all optional and inert when absent or empty:
|
|
31
|
+
* `location` names the working directory's repository, branch and head; `workingSet` and `readParents` add one paragraph
|
|
32
|
+
* listing the session's repositories and where a role may read.
|
|
28
33
|
*/
|
|
29
34
|
export function buildDispatchHeader(input: {
|
|
30
35
|
tier: string;
|
|
31
36
|
cap: number | "none";
|
|
32
37
|
projectDirectory: string | undefined;
|
|
33
38
|
root?: string | null;
|
|
39
|
+
location?: { readonly name: string; readonly branch: string | null; readonly head: string | null };
|
|
40
|
+
workingSet?: readonly { readonly name: string; readonly branch: string | null }[];
|
|
41
|
+
readParents?: readonly string[];
|
|
34
42
|
}): string {
|
|
35
43
|
const paragraphs = [
|
|
36
44
|
`${DISPATCH_HEADER_PREFIX}${input.tier}. Execute this dispatch yourself; do not route it to another tier, and do not ask to be re-dispatched.`,
|
|
37
45
|
];
|
|
38
46
|
const directory = input.root || input.projectDirectory;
|
|
39
47
|
if (directory) {
|
|
40
|
-
paragraphs.push(
|
|
48
|
+
paragraphs.push(...locationParagraphs(directory, {
|
|
49
|
+
location: input.location,
|
|
50
|
+
workingSet: input.workingSet,
|
|
51
|
+
readParents: input.readParents,
|
|
52
|
+
verb: "read or write",
|
|
53
|
+
}));
|
|
41
54
|
}
|
|
42
55
|
paragraphs.push(
|
|
43
56
|
'Tool names mentioned in this dispatch are descriptive and vary by provider; your own tool schema is the authority on what you can do. Never refuse or hand back work because a named tool looks unfamiliar or missing — attempt it, and if you cannot finish, name the specific step that failed.',
|
|
@@ -52,6 +65,86 @@ export function buildDispatchHeader(input: {
|
|
|
52
65
|
return paragraphs.join("\n\n");
|
|
53
66
|
}
|
|
54
67
|
|
|
68
|
+
type HeaderLocation = { readonly name: string; readonly branch: string | null; readonly head: string | null };
|
|
69
|
+
type HeaderRepository = { readonly name: string; readonly branch: string | null };
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The working-directory paragraph and, with a working set or read parents, the repositories paragraph. Shared by the tier
|
|
73
|
+
* header and the role header; `verb` completes "do not ask permission to <verb> inside it". Callers escape what they pass.
|
|
74
|
+
*/
|
|
75
|
+
function locationParagraphs(
|
|
76
|
+
directory: string,
|
|
77
|
+
input: {
|
|
78
|
+
location?: HeaderLocation;
|
|
79
|
+
workingSet?: readonly HeaderRepository[];
|
|
80
|
+
readParents?: readonly string[];
|
|
81
|
+
verb: string;
|
|
82
|
+
/** A read-only role: the repositories paragraph carries no edit clause. Absent: the tier wording, byte-identical. */
|
|
83
|
+
readOnly?: boolean;
|
|
84
|
+
},
|
|
85
|
+
): string[] {
|
|
86
|
+
const where = input.location === undefined
|
|
87
|
+
? ""
|
|
88
|
+
: ` (repository ${input.location.name}, branch ${input.location.branch ?? "detached"}${input.location.head ? ` at ${input.location.head.slice(0, 7)}` : ""})`;
|
|
89
|
+
const paragraphs = [`Working directory: ${directory}${where}. You are already there — do not ask permission to ${input.verb} inside it.`];
|
|
90
|
+
const set = input.workingSet ?? [];
|
|
91
|
+
const parents = input.readParents ?? [];
|
|
92
|
+
if (set.length > 0 || parents.length > 0) {
|
|
93
|
+
const listed = set.length > 0
|
|
94
|
+
? `Repositories in this session: ${set.map((entry) => `${entry.name} (${entry.branch ?? "detached"})`).join(", ")}. `
|
|
95
|
+
: "";
|
|
96
|
+
const rest = input.readOnly === true
|
|
97
|
+
? (parents.length > 0
|
|
98
|
+
? `You may read any repository below ${parents.join(", ")}.`
|
|
99
|
+
: "You read only in your working directory.")
|
|
100
|
+
: parents.length > 0
|
|
101
|
+
? `You may read any repository below ${parents.join(", ")}; you edit and run only in your working directory.`
|
|
102
|
+
: "You edit and run only in your working directory.";
|
|
103
|
+
paragraphs.push(`${listed}${rest}`.trimEnd());
|
|
104
|
+
}
|
|
105
|
+
return paragraphs;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The header of a role dispatch (OD6: a role delegate is told its work root). Ends with DISPATCH_HEADER_SEPARATOR so
|
|
110
|
+
* stripDispatchHeader removes it before DoD inference (E8). No cap, verify directive, route line or nonce: those belong to
|
|
111
|
+
* the tier header and the protocol. Every name, branch and path goes through displaySafe, so a newline, a bracket or a
|
|
112
|
+
* `\n\n---\n\n` in a directory, repository or branch name can neither end the header early nor forge a line.
|
|
113
|
+
* `edits` false (a read-only role): "do not ask permission to read inside it". `exactResume`: the head may be stale, so the
|
|
114
|
+
* head clause is left out (as for a null head). A read-only role's repositories paragraph carries no edit clause ("You may
|
|
115
|
+
* read any repository below <parents>."): it cannot edit or run anywhere, so telling it where it may is noise. A caller that
|
|
116
|
+
* wants only the work root (`dispatchHeader: false` with a `root=`/`repo=` work root) passes no `workingSet` / `readParents`.
|
|
117
|
+
*/
|
|
118
|
+
export function buildRoleDispatchHeader(input: {
|
|
119
|
+
agent: string;
|
|
120
|
+
workRoot: string;
|
|
121
|
+
edits: boolean;
|
|
122
|
+
location?: HeaderLocation;
|
|
123
|
+
workingSet?: readonly HeaderRepository[];
|
|
124
|
+
readParents?: readonly string[];
|
|
125
|
+
exactResume?: boolean;
|
|
126
|
+
}): string {
|
|
127
|
+
const safeBranch = (branch: string | null): string | null => (branch === null ? null : displaySafe(branch));
|
|
128
|
+
const location = input.location === undefined
|
|
129
|
+
? undefined
|
|
130
|
+
: {
|
|
131
|
+
name: displaySafe(input.location.name),
|
|
132
|
+
branch: safeBranch(input.location.branch),
|
|
133
|
+
head: input.exactResume || input.location.head === null ? null : displaySafe(input.location.head),
|
|
134
|
+
};
|
|
135
|
+
const paragraphs = [
|
|
136
|
+
`${DISPATCH_HEADER_PREFIX}${displaySafe(input.agent)}. Execute this dispatch yourself.`,
|
|
137
|
+
...locationParagraphs(displaySafe(input.workRoot), {
|
|
138
|
+
location,
|
|
139
|
+
workingSet: input.workingSet?.map((entry) => ({ name: displaySafe(entry.name), branch: safeBranch(entry.branch) })),
|
|
140
|
+
readParents: input.readParents?.map((parent) => displaySafe(parent)),
|
|
141
|
+
verb: input.edits ? "read or write" : "read",
|
|
142
|
+
...(input.edits ? {} : { readOnly: true }),
|
|
143
|
+
}),
|
|
144
|
+
];
|
|
145
|
+
return `${paragraphs.join("\n\n")}${DISPATCH_HEADER_SEPARATOR}`;
|
|
146
|
+
}
|
|
147
|
+
|
|
55
148
|
/**
|
|
56
149
|
* The work root a dispatch prompt names on its first-line route line (`root=`,
|
|
57
150
|
* an absolute path validated by the parser), or undefined. The caller passes it
|
package/src/router/git-tools.ts
CHANGED
|
@@ -20,6 +20,8 @@ export interface GitInspectOptions {
|
|
|
20
20
|
* dispatch) the common directory must be that repository's. QA-G-A2-4: paths and output are limited to the work root.
|
|
21
21
|
*/
|
|
22
22
|
role?: { dispatchRepository?: string };
|
|
23
|
+
/** Absolute `Date.now()` deadline shared with the caller (a `root` resolution, SD-3b-8); without it a fresh 15 s budget starts. */
|
|
24
|
+
deadlineAt?: number;
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
const MAX_BYTES = 64 * 1024;
|
|
@@ -149,9 +151,18 @@ export function gitEnvironment(extra: Record<string, string> = {}): NodeJS.Proce
|
|
|
149
151
|
GIT_TERMINAL_PROMPT: "0", GIT_PAGER: "cat", PAGER: "cat", GIT_NO_LAZY_FETCH: "1", ...extra };
|
|
150
152
|
}
|
|
151
153
|
|
|
154
|
+
/**
|
|
155
|
+
* Every transport refused on the command line. A repository's `protocol.<name>.allow=always` beats a
|
|
156
|
+
* generic `protocol.allow=never`, and GIT_NO_LAZY_FETCH is honoured only from git 2.44, so a partial
|
|
157
|
+
* clone's promisor (an `ext::` command, say) could otherwise run on a lazy fetch. Command-line `-c`
|
|
158
|
+
* overrides repository config; no router git call needs a transport.
|
|
159
|
+
*/
|
|
160
|
+
export const PROTOCOL_HARDENING: readonly string[] = Object.freeze(["ext", "file", "ssh", "git", "http", "https"]
|
|
161
|
+
.flatMap(name => ["-c", `protocol.${name}.allow=never`]).concat(["-c", "protocol.allow=never"]));
|
|
162
|
+
|
|
152
163
|
export function hardeningArgs(): string[] {
|
|
153
164
|
return ["--no-optional-locks", "--no-pager", "-c", "core.pager=cat", "-c", "core.fsmonitor=false", "-c", "diff.external=",
|
|
154
|
-
"-c", `core.hooksPath=${NULL_DEVICE}`,
|
|
165
|
+
"-c", `core.hooksPath=${NULL_DEVICE}`, ...PROTOCOL_HARDENING,
|
|
155
166
|
"-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "color.ui=false",
|
|
156
167
|
// G2: signature display would run gpg.program; blank every signing program too.
|
|
157
168
|
"-c", "log.showSignature=false", "-c", "gpg.program=", "-c", "gpg.ssh.program=", "-c", "gpg.x509.program=",
|
|
@@ -799,6 +810,31 @@ export async function inheritedSafeDirectoryArgs(executable: string, timeoutMs:
|
|
|
799
810
|
}
|
|
800
811
|
}
|
|
801
812
|
|
|
813
|
+
/**
|
|
814
|
+
* Cross-repo QA round 2: the user's inherited non-executing settings (`core.autocrlf`, `core.eol`, `core.safecrlf`,
|
|
815
|
+
* `core.longpaths`, `core.quotepath`; not `safe.directory`, see {@link inheritedSafeDirectoryArgs}) as `-c key=value` pairs for a
|
|
816
|
+
* hardened git run in `root`, whose environment hides the system and global config (`gitEnvironment()`). Without them a CRLF
|
|
817
|
+
* checkout made under `core.autocrlf=true` reads as modified. Exactly what `inspectGit` passes: a key the repository's own
|
|
818
|
+
* configuration sets is left out (a `-c` value would override it). `base` is the hardening (and trusted `safe.directory`)
|
|
819
|
+
* prefix the repository query runs with. Any failure yields no pairs (the previous behaviour, never a wider setting).
|
|
820
|
+
*/
|
|
821
|
+
export async function inheritedConfigArgs(executable: string, root: string, base: readonly string[], timeoutMs: number = DEADLINE_MS): Promise<string[]> {
|
|
822
|
+
const deadline = performance.now() + timeoutMs;
|
|
823
|
+
const budget: Budget = { timeoutMs: () => {
|
|
824
|
+
const remaining = deadline - performance.now();
|
|
825
|
+
if (remaining <= 0) throw new Error("Git configuration query timed out");
|
|
826
|
+
return remaining;
|
|
827
|
+
} };
|
|
828
|
+
try {
|
|
829
|
+
const pairs = (await inheritedConfig(executable, budget)).filter(pair => !pair.startsWith("safe.directory="));
|
|
830
|
+
if (pairs.length === 0) return [];
|
|
831
|
+
const repository = await repositoryConfig(executable, root, gitEnvironment(), [...base], budget);
|
|
832
|
+
return pairs.filter(pair => !repository.overridden.has(pair.slice(0, pair.indexOf("=")))).flatMap(pair => ["-c", pair]);
|
|
833
|
+
} catch {
|
|
834
|
+
return [];
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
|
|
802
838
|
/**
|
|
803
839
|
* Repository-level (local, worktree, included) driver programs and line-ending
|
|
804
840
|
* settings. Every configured filter/diff program is blanked with `-c key=` (G1);
|
|
@@ -990,8 +1026,8 @@ async function verifyRoleRepository(executable: string, base: string[], session:
|
|
|
990
1026
|
}
|
|
991
1027
|
|
|
992
1028
|
export async function inspectGit(operation: GitOperation, input: GitInput, directory: string, signal?: AbortSignal, options: GitInspectOptions = {}): Promise<string> {
|
|
993
|
-
// Discovery and inspection share one tool-call deadline, not two 15 s waits.
|
|
994
|
-
const deadline = performance.now() + DEADLINE_MS;
|
|
1029
|
+
// Discovery and inspection share one tool-call deadline, not two 15 s waits (SD-3b-8: with a `root`, resolution shares it too).
|
|
1030
|
+
const deadline = performance.now() + (options.deadlineAt === undefined ? DEADLINE_MS : options.deadlineAt - Date.now());
|
|
995
1031
|
const budget: Budget = { signal, timeoutMs: () => {
|
|
996
1032
|
const remaining = deadline - performance.now();
|
|
997
1033
|
if (remaining <= 0) throw new Error("Git inspection timed out");
|
|
@@ -1082,7 +1118,7 @@ export async function inspectGit(operation: GitOperation, input: GitInput, direc
|
|
|
1082
1118
|
* checkout rather than a sibling worktree (S11, P-10).
|
|
1083
1119
|
* Any other answer, or a throwing resolver, is reported as a tool error; nothing is spawned.
|
|
1084
1120
|
*/
|
|
1085
|
-
export type WorkRootAnswer = { role: false } | { role: true; root: string | null };
|
|
1121
|
+
export type WorkRootAnswer = { role: false } | { role: true; root: string | null; repository?: string };
|
|
1086
1122
|
/**
|
|
1087
1123
|
* P1.3 injects, P2.1 wires it to the dispatch binding. Shared by router_git_* and
|
|
1088
1124
|
* router_run (QA-P13-2-8); router_run refuses `{ role: false }` (it exists for role
|
|
@@ -1096,6 +1132,55 @@ export interface GitToolsOptions {
|
|
|
1096
1132
|
* bound work root's common git directory must be that repository's. Absent: only the work root's own pointers are checked.
|
|
1097
1133
|
*/
|
|
1098
1134
|
dispatchRepository?: string;
|
|
1135
|
+
/**
|
|
1136
|
+
* Cross-repo (3b.3, OpenCode v2 roles mode only): resolves a `root` argument against the session's read set and admission.
|
|
1137
|
+
* Only when set do the tools declare `root` and the longer description (SD-3b-1); absent, schema and behaviour are unchanged.
|
|
1138
|
+
*/
|
|
1139
|
+
resolveRoot?: GitRootResolver;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
/**
|
|
1143
|
+
* A `root` resolver's answer (structurally `GitRootResolution` of `routing/roles/git-root.ts`, not imported: no cycle):
|
|
1144
|
+
* - `{ ok: false, reason }`: refused; the tool reports `refused: <reason>` and spawns nothing.
|
|
1145
|
+
* - `{ ok: true, inWorkRoot: true }`: `root` names the work root; the tool behaves exactly as without `root` (SD-3b-4).
|
|
1146
|
+
* - `{ ok: true, inWorkRoot: false, … }`: an admitted repository; the tool inspects `root` (the git cwd only) with the role
|
|
1147
|
+
* hardening against `repository`, guards for `root` and `workRoot`, and `provenance` as its first line (SD-3b-6, SD-3b-7).
|
|
1148
|
+
*/
|
|
1149
|
+
export type GitRootAnswer =
|
|
1150
|
+
| { readonly ok: false; readonly reason: string }
|
|
1151
|
+
| { readonly ok: true; readonly inWorkRoot: true }
|
|
1152
|
+
| {
|
|
1153
|
+
readonly ok: true;
|
|
1154
|
+
readonly inWorkRoot: false;
|
|
1155
|
+
readonly root: string;
|
|
1156
|
+
readonly repository: string;
|
|
1157
|
+
readonly name: string;
|
|
1158
|
+
readonly branch: string | null;
|
|
1159
|
+
readonly workRoot: string;
|
|
1160
|
+
readonly provenance: string;
|
|
1161
|
+
};
|
|
1162
|
+
/** Resolves `root` for one call; `deadlineAt` (a `Date.now()` value) is the call's single 15 s deadline (SD-3b-8). */
|
|
1163
|
+
export type GitRootResolver = (value: string, ctx: { sessionID: string; signal?: AbortSignal; deadlineAt: number }) => Promise<GitRootAnswer>;
|
|
1164
|
+
|
|
1165
|
+
/** The refusal for a resolver answer that is not a {@link GitRootAnswer} (fail closed, SD-3b-11). */
|
|
1166
|
+
const INVALID_ROOT_ANSWER = "the root resolver returned an invalid answer; nothing ran";
|
|
1167
|
+
|
|
1168
|
+
/** Validate a `root` resolver answer; anything malformed becomes a refusal (never an inspection). */
|
|
1169
|
+
export function checkGitRootAnswer(answer: unknown): GitRootAnswer {
|
|
1170
|
+
const refused: GitRootAnswer = { ok: false, reason: INVALID_ROOT_ANSWER };
|
|
1171
|
+
if (typeof answer !== "object" || answer === null) return refused;
|
|
1172
|
+
const a = answer as Record<string, unknown>;
|
|
1173
|
+
if (a.ok === false) return typeof a.reason === "string" && a.reason.trim() !== "" ? { ok: false, reason: a.reason } : refused;
|
|
1174
|
+
if (a.ok !== true) return refused;
|
|
1175
|
+
if (a.inWorkRoot === true) return { ok: true, inWorkRoot: true };
|
|
1176
|
+
if (a.inWorkRoot !== false) return refused;
|
|
1177
|
+
const { root, repository, name, branch, workRoot, provenance } = a;
|
|
1178
|
+
const fullPath = (value: unknown): value is string => typeof value === "string" && isFullPath(value) && !isNetworkOrDevicePath(value);
|
|
1179
|
+
if (!fullPath(root) || !fullPath(repository) || !fullPath(workRoot)) return refused;
|
|
1180
|
+
if (typeof name !== "string" || name === "" || (branch !== null && typeof branch !== "string")) return refused;
|
|
1181
|
+
// The provenance is the output's first line: one non-empty line.
|
|
1182
|
+
if (typeof provenance !== "string" || provenance.trim() === "" || /[\r\n]/.test(provenance)) return refused;
|
|
1183
|
+
return { ok: true, inWorkRoot: false, root, repository, name, branch, workRoot, provenance };
|
|
1099
1184
|
}
|
|
1100
1185
|
|
|
1101
1186
|
/** Validate a resolver answer; throws for anything that is not a WorkRootAnswer. */
|
|
@@ -1106,43 +1191,114 @@ export function checkWorkRootAnswer(answer: unknown): WorkRootAnswer {
|
|
|
1106
1191
|
if (role === true && "root" in answer) {
|
|
1107
1192
|
const { root } = answer as { root: unknown };
|
|
1108
1193
|
if (root === null) return { role: true, root: null };
|
|
1109
|
-
if (typeof root === "string" && isFullPath(root))
|
|
1194
|
+
if (typeof root === "string" && isFullPath(root)) {
|
|
1195
|
+
// Cross-repo (P1.5): the binding's repository, when the dispatch recorded one, replaces the session directory's.
|
|
1196
|
+
const { repository } = answer as { repository?: unknown };
|
|
1197
|
+
if (repository === undefined) return { role: true, root };
|
|
1198
|
+
if (typeof repository === "string" && isFullPath(repository)) return { role: true, root, repository };
|
|
1199
|
+
throw new Error("Bound repository is not an absolute path");
|
|
1200
|
+
}
|
|
1110
1201
|
throw new Error("Bound work root is not an absolute path");
|
|
1111
1202
|
}
|
|
1112
1203
|
}
|
|
1113
1204
|
throw new Error("Invalid work-root answer: expected { role: false } or { role: true, root }");
|
|
1114
1205
|
}
|
|
1115
1206
|
|
|
1207
|
+
/** SD-3b-1: appended to every router_git_* description only when a `root` resolver is configured. */
|
|
1208
|
+
const GIT_ROOT_DESCRIPTION_SUFFIX = " Role agents may set root to inspect another repository they may read (its absolute top-level path, or its name below routing.repoParents).";
|
|
1209
|
+
const GIT_ROOT_ARG_DESCRIPTION = "Another repository to inspect, read-only: its absolute top-level path, or its name below routing.repoParents; path is then relative to it";
|
|
1210
|
+
const UNSAFE_DISPLAY = /[\p{Cc}\p{Cf}\p{Cn}\p{Co}\p{Cs}\u2028\u2029[\]]/u;
|
|
1211
|
+
|
|
1212
|
+
/** A `root` value as echoed into an error: `displaySafe` of `routing/roles/read-set.ts` (not imported: read-set imports this module). */
|
|
1213
|
+
function displayRoot(text: string): string {
|
|
1214
|
+
if (!UNSAFE_DISPLAY.test(text)) return text;
|
|
1215
|
+
const quoted = quoteGitPath(text, true);
|
|
1216
|
+
return (quoted.startsWith('"') ? quoted : `"${quoted}"`).replaceAll("[", "\\133").replaceAll("]", "\\135");
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
/**
|
|
1220
|
+
* 3b.3: one call with `root` (SD-3b-4, SD-3b-6 to SD-3b-8). Undefined: `root` names the work root, inspect as without it.
|
|
1221
|
+
* `root` is only the git cwd, never a git argument; a refusal or a malformed answer spawns nothing.
|
|
1222
|
+
*/
|
|
1223
|
+
async function inspectRoot(operation: GitOperation, input: GitInput, value: unknown, resolveRoot: GitRootResolver,
|
|
1224
|
+
executables: readonly string[], sessionID: string, signal: AbortSignal, deadlineAt: number): Promise<string | undefined> {
|
|
1225
|
+
if (typeof value !== "string") return "[router_git] error: refused: root must be a string; nothing ran";
|
|
1226
|
+
try {
|
|
1227
|
+
const answer = checkGitRootAnswer(await resolveRoot(value, { sessionID, signal, deadlineAt }));
|
|
1228
|
+
if (!answer.ok) return `[router_git] error: refused: ${stripUrlUserinfo(answer.reason)}`;
|
|
1229
|
+
if (answer.inWorkRoot) return undefined;
|
|
1230
|
+
// F2, before anything is spawned: `root` is still the real path the resolver answered (no junction or link swapped in since
|
|
1231
|
+
// resolution), and a main worktree's `.git` is its own git directory (no gitdir file, link or junction naming another
|
|
1232
|
+
// repository): for a main worktree the dispatch check below compares `root` with itself.
|
|
1233
|
+
let real: string | undefined;
|
|
1234
|
+
try { real = realpath(answer.root); } catch { real = undefined; }
|
|
1235
|
+
if (real === undefined || foldCase(real) !== foldCase(answer.root)) {
|
|
1236
|
+
return `[router_git] error: refused: root=${displayRoot(value)}: ${displayRoot(answer.root)} changed since it was resolved; nothing ran`;
|
|
1237
|
+
}
|
|
1238
|
+
if (sameOnDisk(answer.repository, answer.root)) {
|
|
1239
|
+
const dotGit = join(answer.root, ".git");
|
|
1240
|
+
let own = false;
|
|
1241
|
+
try { const stats = lstatSync(dotGit); own = stats.isDirectory() && !stats.isSymbolicLink(); } catch { own = false; }
|
|
1242
|
+
if (!own) return `[router_git] error: refused: root=${displayRoot(value)}: ${displayRoot(dotGit)} is not the repository's own git directory; nothing ran`;
|
|
1243
|
+
}
|
|
1244
|
+
const output = await inspectGit(operation, input, answer.root, signal, {
|
|
1245
|
+
executables, guards: [...workRootGuards(answer.root), ...workRootGuards(answer.workRoot)],
|
|
1246
|
+
role: { dispatchRepository: answer.repository }, deadlineAt,
|
|
1247
|
+
});
|
|
1248
|
+
return `${answer.provenance}\n${output}`;
|
|
1249
|
+
} catch (error) {
|
|
1250
|
+
return `[router_git] error: root=${displayRoot(value)}: ${stripUrlUserinfo(errorMessage(error))}`;
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1116
1254
|
export function gitTools(opts: GitToolsOptions = {}) {
|
|
1117
1255
|
// G4: resolve the git executable once, at plugin load.
|
|
1118
1256
|
const executables = defaultCandidates();
|
|
1257
|
+
const resolveRoot = opts.resolveRoot;
|
|
1119
1258
|
const inputSchema = tool.schema.object({
|
|
1120
1259
|
path: tool.schema.string().optional(), ref: tool.schema.string().optional(),
|
|
1121
1260
|
limit: tool.schema.number().int().min(1).max(50).optional(),
|
|
1122
1261
|
mode: tool.schema.enum(["patch", "stat", "name-only", "cached"]).optional(),
|
|
1123
1262
|
}).strict();
|
|
1124
1263
|
return Object.fromEntries(GIT_OPERATIONS.map(operation => [`router_git_${operation}`, tool({
|
|
1125
|
-
description: `Read-only git ${operation.replaceAll("_", "-")} in the session repository. No shell, helpers, arbitrary options or writes. Output is bounded to 64 KiB and 15 seconds. Paths are literal and repository-relative
|
|
1264
|
+
description: `Read-only git ${operation.replaceAll("_", "-")} in the session repository. No shell, helpers, arbitrary options or writes. Output is bounded to 64 KiB and 15 seconds. Paths are literal and repository-relative.${resolveRoot === undefined ? "" : GIT_ROOT_DESCRIPTION_SUFFIX}`,
|
|
1126
1265
|
args: {
|
|
1127
1266
|
path: tool.schema.string().optional().describe("Literal repository-relative path; required for blame"),
|
|
1128
1267
|
...(operation === "log" || operation === "diff" || operation === "show" || operation === "blame"
|
|
1129
1268
|
? { ref: tool.schema.string().optional().describe(operation === "show" ? "One commit or annotated tag pointing to a commit; ranges require log or diff" : "Ref or diff range, at most 200 characters; never an option") } : {}),
|
|
1130
1269
|
...(operation === "log" ? { limit: tool.schema.number().int().min(1).max(50).optional() } : {}),
|
|
1131
1270
|
...(operation === "diff" ? { mode: tool.schema.enum(["patch", "stat", "name-only", "cached"]).optional() } : {}),
|
|
1271
|
+
...(resolveRoot === undefined ? {} : { root: tool.schema.string().optional().describe(GIT_ROOT_ARG_DESCRIPTION) }),
|
|
1132
1272
|
},
|
|
1133
1273
|
async execute(input, context) {
|
|
1134
1274
|
try {
|
|
1275
|
+
// 3b.3: `root` is stripped before the strict parse; without a resolver the input is parsed as given (unchanged, I9).
|
|
1276
|
+
let args: unknown = input;
|
|
1277
|
+
let deadline: { deadlineAt?: number } = {};
|
|
1278
|
+
if (resolveRoot !== undefined && typeof input === "object" && input !== null && "root" in input) {
|
|
1279
|
+
const { root, ...rest } = input as GitInput & { root?: unknown };
|
|
1280
|
+
args = rest;
|
|
1281
|
+
if (root !== undefined) {
|
|
1282
|
+
// SD-3b-8: one 15 s deadline covers resolution and inspection.
|
|
1283
|
+
const deadlineAt = Date.now() + DEADLINE_MS;
|
|
1284
|
+
deadline = { deadlineAt };
|
|
1285
|
+
const other = await inspectRoot(operation, inputSchema.parse(rest), root, resolveRoot, executables, context.sessionID, context.abort, deadlineAt);
|
|
1286
|
+
if (other !== undefined) return other;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1135
1289
|
if (opts.resolveWorkRoot) {
|
|
1136
1290
|
const answer = checkWorkRootAnswer(opts.resolveWorkRoot(context.sessionID));
|
|
1137
1291
|
if (answer.role) {
|
|
1138
1292
|
if (answer.root === null) return "[router_git] error: refused: this role session has no bound work root (I9)";
|
|
1139
|
-
|
|
1293
|
+
// Cross-repo (P1.5): a binding's repository is the expected one; without it, the plugin's directory.
|
|
1294
|
+
const expected = answer.repository ?? opts.dispatchRepository;
|
|
1295
|
+
return await inspectGit(operation, inputSchema.parse(args), answer.root, context.abort, {
|
|
1140
1296
|
executables, guards: workRootGuards(answer.root),
|
|
1141
|
-
role:
|
|
1297
|
+
role: expected ? { dispatchRepository: expected } : {}, ...deadline,
|
|
1142
1298
|
});
|
|
1143
1299
|
}
|
|
1144
1300
|
}
|
|
1145
|
-
return await inspectGit(operation, inputSchema.parse(
|
|
1301
|
+
return await inspectGit(operation, inputSchema.parse(args), context.directory, context.abort, { worktree: context.worktree, executables, ...deadline });
|
|
1146
1302
|
} catch (error) {
|
|
1147
1303
|
// G12: report, never throw into the session; messages are credential-redacted.
|
|
1148
1304
|
return `[router_git] error: ${stripUrlUserinfo(errorMessage(error))}`;
|
package/src/router/protocol.ts
CHANGED
|
@@ -63,6 +63,10 @@ export function buildRolesProtocol(cfg: RouterConfig, roles: ReadonlyMap<string,
|
|
|
63
63
|
const rawShell = enabled.some((spec) => spec.authority.allow.includes("router_run"))
|
|
64
64
|
? `Only when \`router_run\` refuses a command that is not on its allowlist, ask the user or dispatch a tier agent explicitly.`
|
|
65
65
|
: `For a command, ask the user or dispatch a tier agent explicitly.`;
|
|
66
|
+
// Cross-repo (P1.7): one sentence, only when `routing.repoParents` is configured; otherwise the text is unchanged.
|
|
67
|
+
const crossRepo = (cfg.routing?.repoParents?.length ?? 0) > 0
|
|
68
|
+
? ` Cross-repo: name another repository with repo=<name> (and branch=<ref> when it has several worktrees) instead of root=; each dispatch edits one repository, and a role may read the others below routing.repoParents. A check may run in another repository of the read set with cwd= and must then use scope=full, e.g. \`check: testsPass cwd="<repo>" scope=full\`.`
|
|
69
|
+
: "";
|
|
66
70
|
return [
|
|
67
71
|
ROLES_PROTOCOL_HEADING,
|
|
68
72
|
``,
|
|
@@ -77,7 +81,7 @@ export function buildRolesProtocol(cfg: RouterConfig, roles: ReadonlyMap<string,
|
|
|
77
81
|
// QA-P22-1-1: `tier`/`pin` are not in the template; only a plan's `[tier:X]` tag is transcribed.
|
|
78
82
|
`Route line: when present it must be the FIRST line of the prompt (the router removes it; a malformed one is refused for a role): \`[route class=<c> risk=<r> scope=<s> needs=<n,..> d=<d> budget=<n> root=<path>]\`, every key optional. class=search|recon|mechanical|implement|debug|design|review|other; risk=low|medium|high; scope=single|multi|repo; needs=shell|web|edit|network|external_dir (\`edit\` unlocks editing, \`shell\` router_run, where the role allows); d=deterministic|grader|none (counts only when the prompt's \`[acceptance]\` block backs it); budget=tool calls (up to twice the role's); root=the absolute work root. Only when the plan step carries \`[tier:X]\`, add \`tier=X pin\`; never otherwise.`,
|
|
79
83
|
``,
|
|
80
|
-
`Work root: a role works only in the session directory or one git worktree of this repo; for a worktree put \`root=<absolute path>\` on the route line (quote a path with spaces) and in ENVIRONMENT
|
|
84
|
+
`Work root: a role works only in the session directory or one git worktree of this repo; for a worktree put \`root=<absolute path>\` on the route line (quote a path with spaces) and in ENVIRONMENT.${crossRepo}`,
|
|
81
85
|
``,
|
|
82
86
|
`No role holds the web together with read, run or edit authority.${compose} Raw shell is outside roles mode. ${rawShell}`,
|
|
83
87
|
``,
|