opencode-model-router 2.9.1 → 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.
Files changed (59) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/README.md +4 -2
  3. package/package.json +12 -5
  4. package/src/compat/background.ts +56 -19
  5. package/src/compat/child-history.ts +134 -0
  6. package/src/compat/child-report.ts +185 -0
  7. package/src/compat/child-session.ts +10 -0
  8. package/src/compat/session-lookup.ts +21 -0
  9. package/src/compat/v2-client.ts +124 -6
  10. package/src/compat/v2-hooks.ts +525 -203
  11. package/src/compat/v2-observations.ts +1 -0
  12. package/src/compat/v2-vocabulary.ts +14 -0
  13. package/src/executor/create.ts +47 -28
  14. package/src/executor/git.ts +226 -30
  15. package/src/executor/integrate/checks.ts +29 -11
  16. package/src/executor/integrate/land.ts +32 -2
  17. package/src/executor/integrate/queue.ts +95 -13
  18. package/src/executor/ledger.ts +16 -12
  19. package/src/executor/lfs-restore.ts +492 -0
  20. package/src/executor/paths.ts +7 -2
  21. package/src/executor/recovery.ts +2 -1
  22. package/src/executor/runtime.ts +1062 -243
  23. package/src/executor/slots/pool.ts +120 -19
  24. package/src/executor/slots/provision.ts +111 -23
  25. package/src/executor/slots/root.ts +81 -0
  26. package/src/executor/types.ts +28 -2
  27. package/src/executor/unattended.ts +6 -1
  28. package/src/executor/verify-trees.ts +507 -0
  29. package/src/guard/enforce.ts +2 -1
  30. package/src/guard/fingerprint.ts +9 -0
  31. package/src/guard/guards.ts +7 -1
  32. package/src/index.ts +191 -31
  33. package/src/router/answer-dedup.ts +198 -0
  34. package/src/router/common-dir.ts +241 -0
  35. package/src/router/config.ts +228 -40
  36. package/src/router/diff-handles.ts +322 -0
  37. package/src/router/diff-summary.ts +318 -0
  38. package/src/router/git-metadata-guard.ts +317 -0
  39. package/src/router/git-tools.ts +1136 -49
  40. package/src/router/read-only.ts +37 -13
  41. package/src/router/role-agents.ts +100 -36
  42. package/src/router/run-summary.ts +253 -0
  43. package/src/router/run-tools.ts +177 -25
  44. package/src/router/sessions.ts +23 -1
  45. package/src/router/tool-paths.ts +62 -4
  46. package/src/routing/classify/rules.ts +93 -14
  47. package/src/routing/roles/read-set.ts +10 -1
  48. package/src/routing/roles/work-root.ts +20 -3
  49. package/src/routing/wire/hint.ts +9 -2
  50. package/src/v2.ts +3 -1
  51. package/src/verify/exec.ts +454 -2
  52. package/src/verify/head.ts +6 -1
  53. package/src/verify/pending.ts +14 -1
  54. package/src/verify/plan-task.ts +86 -26
  55. package/src/verify/reference.ts +60 -7
  56. package/src/verify/runner.ts +14 -6
  57. package/src/verify/tree.ts +34 -10
  58. package/src/verify/types.ts +44 -0
  59. package/src/verify/wiring.ts +134 -22
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Security: a delegated agent never writes repository git metadata (`.git` and everything below it: config, hooks, a linked
3
+ * worktree's pointer and admin directory). Role agents are refused by their authority check (compat/v2-hooks.ts
4
+ * `roleAuthorityDecision`, `editsGitMetadata`); this is the same rule for every other delegated session — tier agents, plugin
5
+ * agents (#81), producer sessions — on OpenCode v1 and v2, enforced in the shared `tool.execute.before` (index.ts). Hook-based:
6
+ * the published permission maps are unchanged. The file tools only: a shell command is not covered.
7
+ *
8
+ * A write-class call ({@link WRITE_CLASS}) is refused when any file it names ({@link writeTargetTexts}):
9
+ * - has a segment naming `.git` as written ({@link namesGitMetadata}: case-insensitive, trailing dots and spaces, NTFS `:stream`);
10
+ * - has no canonical form ({@link canonicalAuthorityPath}: padding whitespace, wildcard, NUL, UNC/device path outside the session
11
+ * directory's own UNC root, drive-relative or drive-less rooted path, dangling or looping link, `..` in a missing tail, an
12
+ * unresolvable entry) — fail closed;
13
+ * - resolves (links and junctions followed, case and 8.3 short names as on disk) to a path with a `.git` segment, or into the git
14
+ * directory or common directory of the session directory's repository (also when it is not named `.git`: a bare repository's
15
+ * linked worktree, `--separate-git-dir`), the checkout's own files excepted when such a directory holds the checkout; or (#161)
16
+ * into the bare repository the session directory itself is in, the files of its linked worktrees inside it excepted.
17
+ * Each file is resolved in two readings, and refused when either hits: as written (links resolved before any `..` after them, as
18
+ * the kernel does on POSIX) and as the host resolves it (`path.resolve`: `..` collapsed as text first). A patch whose targets
19
+ * cannot be read is refused too (fail closed). Never throws.
20
+ */
21
+ import { existsSync, lstatSync, readdirSync, readlinkSync, realpathSync, statSync } from "node:fs";
22
+ import { dirname, join, posix, resolve, win32 } from "node:path";
23
+ import { gitPointers, isNetworkOrDevicePath, nearestRepository, readBoundedRegularFile } from "./git-tools";
24
+ import { WRITE_CLASS, writeTargetTexts } from "./tool-paths";
25
+ import { canonicalAuthorityPath, insideWorkRoot } from "../routing/roles/work-root";
26
+ import { displaySafe, namesGitMetadata } from "../routing/roles/read-set";
27
+
28
+ /** The git directories of the session directory's repository, and its checkout (both canonical). */
29
+ export interface SessionGitDirectories {
30
+ /** The git directory and the common directory. */
31
+ readonly directories: readonly string[];
32
+ /** The checkout (repository top) holding the session directory; undefined outside a repository. */
33
+ readonly checkout: string | undefined;
34
+ /**
35
+ * #161: the linked worktrees inside a bare repository among `directories` (the session directory's own, when it is in one); each
36
+ * exempts its own files as `checkout` does. Called only once a target lands in a git directory the checkout does not exempt it
37
+ * from. Absent when there is no such repository.
38
+ */
39
+ readonly worktrees?: () => readonly string[];
40
+ }
41
+
42
+ /** Seams of {@link gitMetadataWriteRefusal} (tests). */
43
+ export interface GitMetadataGuardDeps {
44
+ /** Default `process.platform`: path syntax, NTFS stream suffixes and 8.3 names on win32. */
45
+ readonly platform?: NodeJS.Platform;
46
+ /** `realpathSync.native` and `lstatSync` (the filesystem the paths are resolved on). */
47
+ readonly realpath?: (path: string) => string;
48
+ readonly lstat?: (path: string) => unknown;
49
+ /** The git directories and checkout of the repository holding `directory`. Default: its `.git` pointers. */
50
+ readonly gitDirectories?: (directory: string) => SessionGitDirectories;
51
+ }
52
+
53
+ /** The refusal of a write that targets git metadata. */
54
+ export function gitMetadataWriteRefusalText(path: string): string {
55
+ return `[router] Refused: writing git metadata (${displaySafe(path)}) is not allowed for delegated agents.`;
56
+ }
57
+
58
+ /** The refusal of a write whose target the router cannot resolve (fail closed). */
59
+ function unresolvedText(path: string): string {
60
+ return `[router] Refused: the router could not resolve ${displaySafe(path)} to check that it is not git metadata, which delegated `
61
+ + "agents may not write (fail closed). Name the file by a plain path.";
62
+ }
63
+
64
+ /** The refusal of a patch whose targets cannot be read (fail closed). */
65
+ export const GIT_METADATA_PATCH_UNREADABLE = "[router] Refused: the router could not read which files this patch writes, so it "
66
+ + "cannot check that none of them is git metadata, which delegated agents may not write (fail closed). Name each file in an "
67
+ + "`*** Add File:`, `*** Update File:` or `*** Delete File:` header.";
68
+
69
+ /** #161 (OpenCode v2): the refusal of a write-class call whose session directory is unknown (fail closed). */
70
+ export const GIT_METADATA_DIRECTORY_UNKNOWN = "[router] Refused: the session's location could not be read, so this write cannot be "
71
+ + "checked for git metadata, which delegated agents may not write (fail closed).";
72
+
73
+ /**
74
+ * win32: `path` with each segment's NTFS stream suffix cut (`name:stream`, `name::$DATA`, `name::$INDEX_ALLOCATION` all name the
75
+ * entry `name`), a leading drive's `X:` kept, so the entry is what gets resolved.
76
+ */
77
+ function withoutStreams(path: string): string {
78
+ return path.split(/([\\/])/).map((part, index) => {
79
+ const drive = index === 0 && /^[A-Za-z]:/.test(part) ? part.slice(0, 2) : "";
80
+ const rest = part.slice(drive.length);
81
+ const colon = rest.indexOf(":");
82
+ return drive + (colon === -1 ? rest : rest.slice(0, colon));
83
+ }).join("");
84
+ }
85
+
86
+ const NO_GIT_DIRECTORIES: SessionGitDirectories = Object.freeze({ directories: [], checkout: undefined });
87
+
88
+ /**
89
+ * The canonical git directory and common directory of the repository whose checkout holds `directory`, and that checkout, read
90
+ * from its `.git` pointers without running git ({@link gitPointers}: bounded, never followed onto a network or device path). No
91
+ * directories when there is no repository or a pointer is refused or unreadable: the `.git` segment checks still apply.
92
+ */
93
+ function checkoutGitDirectories(directory: string): SessionGitDirectories {
94
+ try {
95
+ const checkout = nearestRepository(directory);
96
+ if (checkout === undefined) return NO_GIT_DIRECTORIES;
97
+ const pointers = gitPointers(checkout);
98
+ if (pointers === undefined) return NO_GIT_DIRECTORIES;
99
+ const directories: string[] = [];
100
+ for (const dir of new Set([pointers.gitdir, pointers.common])) {
101
+ try {
102
+ directories.push(realpathSync.native(dir));
103
+ } catch {
104
+ // a git directory that does not resolve holds nothing to write
105
+ }
106
+ }
107
+ return { directories, checkout: realpathSync.native(checkout) };
108
+ } catch {
109
+ return NO_GIT_DIRECTORIES;
110
+ }
111
+ }
112
+
113
+ /** Bound of the `gitdir` file of a linked worktree's admin directory (as git-tools bounds `.git` and `commondir`). */
114
+ const GITDIR_FILE_BYTES = 4 * 1024;
115
+ /** #161: at most this many entries of a bare repository's `worktrees/` are read; the files of any other worktree stay refused. */
116
+ const MAX_BARE_WORKTREES = 256;
117
+ /** #161: git's own directories in a git directory: a worktree in one of them is never exempt. */
118
+ const GIT_OWN_DIRECTORIES = [
119
+ "hooks", "info", "logs", "objects", "refs", "worktrees", "modules", "lfs", "rr-cache", "remotes", "branches", "reftable",
120
+ ] as const;
121
+
122
+ /** Two canonical paths name the same directory (win32 case folding). */
123
+ function sameDirectory(a: string, b: string): boolean {
124
+ return insideWorkRoot(a, b) && insideWorkRoot(b, a);
125
+ }
126
+
127
+ /** What `path` itself is, never following a link: a plain file or directory, a link (symlink or junction), or undefined. */
128
+ function entryKind(path: string): "file" | "directory" | "link" | undefined {
129
+ try {
130
+ const stats = lstatSync(path);
131
+ return stats.isSymbolicLink() ? "link" : stats.isFile() ? "file" : stats.isDirectory() ? "directory" : undefined;
132
+ } catch {
133
+ return undefined;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * #161: `path` is a directory, or a link to a local one (git accepts a bare repository whose `objects` or `refs` is a link): the
139
+ * link's text is never followed when it names a network or device path, nor is a target that resolves to one.
140
+ */
141
+ function directoryOrLocalLink(path: string): boolean {
142
+ const kind = entryKind(path);
143
+ if (kind !== "link") return kind === "directory";
144
+ try {
145
+ if (isNetworkOrDevicePath(readlinkSync(path))) return false;
146
+ const target = realpathSync.native(path);
147
+ return !isNetworkOrDevicePath(target) && statSync(target).isDirectory();
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * #161: `dir` has git's bare repository shape, as git's own discovery checks it: a `HEAD` regular file, and `objects` and `refs`
155
+ * directories, each also a link to a local directory ({@link directoryOrLocalLink}). Also used by the on-disk common-directory
156
+ * lookup of role agent registration (router/common-dir.ts, #192).
157
+ */
158
+ export function bareShaped(dir: string): boolean {
159
+ return entryKind(join(dir, "HEAD")) === "file" && directoryOrLocalLink(join(dir, "objects")) && directoryOrLocalLink(join(dir, "refs"));
160
+ }
161
+
162
+ /** `text` as the first `gitdir:` line of a `.git` file names it, or undefined. */
163
+ function gitdirLine(text: string | undefined): string | undefined {
164
+ return /^gitdir:\s*(.+?)\s*$/m.exec(text ?? "")?.[1];
165
+ }
166
+
167
+ /**
168
+ * #161: the linked worktrees of the bare repository `bare` (canonical) that lie inside it, each confirmed both ways: the `gitdir`
169
+ * file of its admin directory `worktrees/<name>` names `<worktree>/.git`, that `.git` file names the same admin directory back,
170
+ * and the admin directory's `commondir` names `bare`. `worktrees`, each `worktrees/<name>` and every file read must be a plain
171
+ * directory or regular file (no link is followed, so none reaches a network path); each file is read bounded (4 KiB) and a pointer
172
+ * naming a network or device path is never followed. A worktree that is `bare` itself, holds its admin directory or lies in one of
173
+ * git's own directories is never one. Canonical; an entry that cannot be read is skipped (its files stay refused). Never throws.
174
+ */
175
+ function worktreesInside(bare: string): string[] {
176
+ const read = (path: string): string | undefined =>
177
+ (entryKind(path) === "file" ? readBoundedRegularFile(path, GITDIR_FILE_BYTES, "worktree pointer")?.trim() : undefined);
178
+ let names: string[];
179
+ try {
180
+ if (entryKind(join(bare, "worktrees")) !== "directory") return [];
181
+ names = readdirSync(join(bare, "worktrees"));
182
+ } catch {
183
+ return [];
184
+ }
185
+ const found: string[] = [];
186
+ for (const name of names.slice(0, MAX_BARE_WORKTREES)) {
187
+ try {
188
+ const admin = join(bare, "worktrees", name);
189
+ if (entryKind(admin) !== "directory") continue;
190
+ const named = read(join(admin, "gitdir"));
191
+ if (named === undefined || named === "" || isNetworkOrDevicePath(named)) continue;
192
+ const candidate = dirname(resolve(admin, named));
193
+ if (!insideWorkRoot(candidate, bare)) continue; // nothing outside the repository is touched
194
+ const worktree = realpathSync.native(candidate);
195
+ if (!insideWorkRoot(worktree, bare) || insideWorkRoot(bare, worktree) || insideWorkRoot(admin, worktree)) continue;
196
+ if (GIT_OWN_DIRECTORIES.some((own) => insideWorkRoot(worktree, join(bare, own)))) continue;
197
+ const back = gitdirLine(read(join(worktree, ".git")));
198
+ if (back === undefined || isNetworkOrDevicePath(back) || !sameDirectory(resolve(worktree, back), admin)) continue;
199
+ const common = read(join(admin, "commondir"));
200
+ if (common === undefined || common === "" || isNetworkOrDevicePath(common) || !sameDirectory(resolve(admin, common), bare)) continue;
201
+ found.push(worktree);
202
+ } catch {
203
+ // unreadable: not exempt
204
+ }
205
+ }
206
+ return found;
207
+ }
208
+
209
+ /**
210
+ * #161: the bare repository the session directory is in — `directory` itself or its nearest ancestor with git's bare shape
211
+ * ({@link bareShaped}) when no checkout (a directory holding `.git`) comes first, as git's own discovery finds the repository —
212
+ * canonical. Undefined otherwise, and when it cannot be read (the checkout's directories and the `.git` segment checks still
213
+ * apply). Spawns nothing; never throws.
214
+ */
215
+ function bareRepositoryOf(directory: string): string | undefined {
216
+ try {
217
+ for (let current = directory; ; current = dirname(current)) {
218
+ if (existsSync(join(current, ".git"))) return undefined; // a checkout: its git directories come from its pointers
219
+ if (bareShaped(current)) return realpathSync.native(current);
220
+ if (dirname(current) === current) return undefined;
221
+ }
222
+ } catch {
223
+ return undefined;
224
+ }
225
+ }
226
+
227
+ /**
228
+ * The git directories of the session directory's repository ({@link checkoutGitDirectories}) and (#161) the bare repository the
229
+ * session directory itself is in ({@link bareRepositoryOf}: OpenCode opened at `proj.git`, which holds its worktrees), which no
230
+ * `.git` pointer names; its linked worktrees ({@link worktreesInside}) are read only once a target lands in it. Never throws.
231
+ */
232
+ function sessionGitDirectories(directory: string): SessionGitDirectories {
233
+ const found = checkoutGitDirectories(directory);
234
+ const bare = bareRepositoryOf(directory);
235
+ if (bare === undefined) return found;
236
+ const directories = found.directories.some((dir) => sameDirectory(dir, bare)) ? found.directories : [...found.directories, bare];
237
+ let worktrees: readonly string[] | undefined;
238
+ return { directories, checkout: found.checkout, worktrees: () => (worktrees ??= worktreesInside(bare)) };
239
+ }
240
+
241
+ /**
242
+ * `target` (canonical) lies in one of the session repository's git directories. A git directory that holds the checkout itself
243
+ * (a bare repository with its worktree inside it, or a malformed pointer naming the checkout) exempts only the checkout's own
244
+ * files; a git directory inside the checkout exempts nothing. #161: so does a linked worktree a bare repository holds (read only
245
+ * when the checkout does not exempt the target).
246
+ */
247
+ function insideGitDirectory(target: string, git: SessionGitDirectories): boolean {
248
+ const top = git.checkout;
249
+ return git.directories.some((dir) => {
250
+ if (!insideWorkRoot(target, dir)) return false;
251
+ if (top !== undefined && insideWorkRoot(top, dir) && insideWorkRoot(target, top)) return false;
252
+ return !(git.worktrees?.() ?? []).some((worktree) => insideWorkRoot(worktree, dir) && insideWorkRoot(target, worktree));
253
+ });
254
+ }
255
+
256
+ /**
257
+ * The refusal of the write-class call `tool(args)` of a delegated session whose relative paths resolve against `base` (the
258
+ * session's directory), or undefined when it writes no git metadata (and for every other tool). The caller decides whether the
259
+ * session is delegated.
260
+ */
261
+ export function gitMetadataWriteRefusal(tool: string, args: unknown, base: string, deps: GitMetadataGuardDeps = {}): string | undefined {
262
+ if (typeof tool !== "string" || !WRITE_CLASS.has(tool.toLowerCase())) return undefined;
263
+ const texts = writeTargetTexts(tool, args);
264
+ if (texts === undefined) return GIT_METADATA_PATCH_UNREADABLE;
265
+ const platform = deps.platform ?? process.platform;
266
+ const api = platform === "win32" ? win32 : posix;
267
+ const fs = {
268
+ realpath: deps.realpath ?? ((p: string) => realpathSync.native(p)),
269
+ lstat: deps.lstat ?? ((p: string) => lstatSync(p)),
270
+ };
271
+ // 8.3 names expanded on disk; a project on a share (`base` a UNC path) may resolve its own paths, never another UNC or device one.
272
+ const canonical = (path: string): string | undefined => {
273
+ try {
274
+ return canonicalAuthorityPath(path, base, { platform, shortNames: "resolve", uncRoot: base, ...fs });
275
+ } catch {
276
+ return undefined;
277
+ }
278
+ };
279
+ let git: SessionGitDirectories | undefined;
280
+ const gitDirectories = (): SessionGitDirectories => {
281
+ if (git === undefined) {
282
+ try {
283
+ git = (deps.gitDirectories ?? sessionGitDirectories)(base);
284
+ } catch {
285
+ git = NO_GIT_DIRECTORIES; // the `.git` segment checks still apply
286
+ }
287
+ }
288
+ return git;
289
+ };
290
+ for (const text of texts) {
291
+ if (namesGitMetadata(text)) return gitMetadataWriteRefusalText(text);
292
+ const written = platform === "win32" ? withoutStreams(text) : text;
293
+ // The kernel's reading (links before `..`) and the host's (`path.resolve`, `..` collapsed as text first): either may write.
294
+ let hostReading: string;
295
+ try {
296
+ hostReading = api.resolve(base, written);
297
+ } catch {
298
+ return unresolvedText(text);
299
+ }
300
+ for (const reading of new Set([written, hostReading])) {
301
+ const target = canonical(reading);
302
+ if (target === undefined) return unresolvedText(text);
303
+ if (namesGitMetadata(target) || insideGitDirectory(target, gitDirectories())) return gitMetadataWriteRefusalText(text);
304
+ }
305
+ }
306
+ return undefined;
307
+ }
308
+
309
+ /**
310
+ * #161 (OpenCode v2): the refusal of the write-class call `tool(args)` of a delegated session whose own directory is unknown (the
311
+ * v2 bridge could not look it up and knows none): a path refusal against `fallback` (the plugin's directory) keeps its text, any
312
+ * other write-class call gets GIT_METADATA_DIRECTORY_UNKNOWN; undefined for every other tool. Never throws.
313
+ */
314
+ export function gitMetadataUnknownDirectoryRefusal(tool: string, args: unknown, fallback: string, deps: GitMetadataGuardDeps = {}): string | undefined {
315
+ if (typeof tool !== "string" || !WRITE_CLASS.has(tool.toLowerCase())) return undefined;
316
+ return gitMetadataWriteRefusal(tool, args, fallback, deps) ?? GIT_METADATA_DIRECTORY_UNKNOWN;
317
+ }