opencode-model-router 2.9.1 → 2.10.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 +176 -0
- package/README.md +2 -1
- package/package.json +5 -5
- package/src/compat/background.ts +51 -19
- package/src/compat/child-history.ts +134 -0
- package/src/compat/child-report.ts +185 -0
- package/src/compat/child-session.ts +10 -0
- package/src/compat/v2-client.ts +124 -6
- package/src/compat/v2-hooks.ts +301 -147
- package/src/executor/create.ts +44 -28
- package/src/executor/git.ts +121 -9
- package/src/executor/integrate/land.ts +32 -2
- package/src/executor/runtime.ts +52 -17
- package/src/index.ts +84 -4
- package/src/router/config.ts +157 -28
- package/src/router/git-metadata-guard.ts +180 -0
- package/src/router/git-tools.ts +238 -8
- package/src/router/read-only.ts +37 -13
- package/src/router/run-tools.ts +32 -2
- package/src/router/sessions.ts +9 -0
- package/src/router/tool-paths.ts +62 -4
- package/src/routing/roles/read-set.ts +10 -1
- package/src/routing/roles/work-root.ts +20 -3
- package/src/verify/head.ts +6 -1
- package/src/verify/pending.ts +14 -1
- package/src/verify/reference.ts +60 -7
- package/src/verify/tree.ts +30 -10
- package/src/verify/wiring.ts +47 -12
package/src/index.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode-ai/plugin";
|
|
2
2
|
import { completionIdentity, observeV2 } from "./compat/v2-observations";
|
|
3
3
|
import type { RouterPluginInput } from "./compat/child-session";
|
|
4
|
-
import { DEPTH_BANNER, ResumeRejectedError, TASK_VERIFICATION } from "./compat/child-session";
|
|
4
|
+
import { DEPTH_BANNER, ResumeRejectedError, SESSION_DIRECTORY, TASK_VERIFICATION } from "./compat/child-session";
|
|
5
5
|
|
|
6
6
|
// Imports for internal use within this module
|
|
7
7
|
import {
|
|
@@ -25,6 +25,7 @@ import {
|
|
|
25
25
|
import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
|
|
26
26
|
import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
|
|
27
27
|
import { gitTools, nearestCheckout, type GitRootResolver } from "./router/git-tools";
|
|
28
|
+
import { gitMetadataUnknownDirectoryRefusal, gitMetadataWriteRefusal } from "./router/git-metadata-guard";
|
|
28
29
|
import { isReadOnlyTier, legacyReadOnlyTools, mergePermissions, readOnlyPermissions } from "./router/read-only";
|
|
29
30
|
import { buildPluginAgentDefinition, mergeHostAgentEntry, pluginAgentMarker } from "./router/plugin-agents";
|
|
30
31
|
import { filterSensitiveGrep } from "./router/sensitive-paths";
|
|
@@ -2614,7 +2615,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2614
2615
|
try {
|
|
2615
2616
|
const target = parseRouterVerifyArgs(args);
|
|
2616
2617
|
if ("error" in target) return target.error;
|
|
2617
|
-
// R6: handles are scoped by the calling session; without one,
|
|
2618
|
+
// R6: handles are scoped by the calling session; without one, the call is answered "no session".
|
|
2618
2619
|
const sessionID = typeof toolCtx?.sessionID === "string" ? toolCtx.sessionID : "";
|
|
2619
2620
|
const report = await verifyHandles(sessionID, target, toolCtx?.abort !== undefined ? { signal: toolCtx.abort } : {});
|
|
2620
2621
|
// Phase 1.2 (v2 only): the late notices this report answers stop being retained for the turn-state tail.
|
|
@@ -2814,6 +2815,38 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2814
2815
|
sessionStore.markChildSession(input.sessionID);
|
|
2815
2816
|
applyPendingRoleCap(input.sessionID); // QA-P21-2-3
|
|
2816
2817
|
}
|
|
2818
|
+
// Security: a delegated agent never writes git metadata (router/git-metadata-guard.ts); on v2 a role agent was already refused
|
|
2819
|
+
// by its authority check. Always on: neither `/bypass` nor the enforcement mode turns it off. Only a session the router has
|
|
2820
|
+
// not proven to be the root is checked (`isProvenRootCaller`: a tracked child, a grader, a session with a parentID, an unknown
|
|
2821
|
+
// or unresolvable one): the orchestrator is the user's own agent, acting under the host's permissions. The paths are checked
|
|
2822
|
+
// first, so a call that writes no git metadata never costs a session lookup. Relative paths and the session's repository are
|
|
2823
|
+
// resolved against the session's own location on v2 (the bridge's SESSION_DIRECTORY), else the instance directory (v1, which
|
|
2824
|
+
// never sets it). #161: a `null` SESSION_DIRECTORY (v2: the session's directory is unknown) refuses every write-class call
|
|
2825
|
+
// (fail closed), with the path refusal's own text when the paths alone already refuse it; the root exemption below still
|
|
2826
|
+
// applies, so in that state every write-class call costs the root check (no host call for a session already proven root).
|
|
2827
|
+
if (typeof input?.tool === "string") {
|
|
2828
|
+
let gitRefusal: string | undefined;
|
|
2829
|
+
try {
|
|
2830
|
+
const sessionDirectory: unknown = input?.[SESSION_DIRECTORY];
|
|
2831
|
+
const base = typeof sessionDirectory === "string" && isAbsolute(sessionDirectory) ? sessionDirectory : projectDir ?? process.cwd();
|
|
2832
|
+
gitRefusal = sessionDirectory === null
|
|
2833
|
+
? gitMetadataUnknownDirectoryRefusal(input.tool, output?.args, base)
|
|
2834
|
+
: gitMetadataWriteRefusal(input.tool, output?.args, base);
|
|
2835
|
+
} catch {
|
|
2836
|
+
// Unreachable (the guard never throws); a delegated session is still refused (fail closed).
|
|
2837
|
+
gitRefusal = "[router] Refused: the router could not check this write for git metadata, which delegated agents may not write (fail closed).";
|
|
2838
|
+
}
|
|
2839
|
+
if (gitRefusal !== undefined && !(await isProvenRootCaller(input?.sessionID))) {
|
|
2840
|
+
try {
|
|
2841
|
+
if (typeof input.sessionID === "string") {
|
|
2842
|
+
trajectoryStore.recordToolEvent(input.sessionID, { tool: input.tool, readOnly: false, blocked: true });
|
|
2843
|
+
}
|
|
2844
|
+
} catch (error) {
|
|
2845
|
+
logger.warn("[router] git metadata guard: refusal not recorded", { error: describeError(error) });
|
|
2846
|
+
}
|
|
2847
|
+
throw new Error(gitRefusal);
|
|
2848
|
+
}
|
|
2849
|
+
}
|
|
2817
2850
|
if (bypassed) {
|
|
2818
2851
|
noteBypassedRoleCall(input?.sessionID); // QA-P21-1-7
|
|
2819
2852
|
return;
|
|
@@ -4231,6 +4264,16 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4231
4264
|
const heldTexts = new Map<string, { readonly sessionID: string; readonly text: string; readonly post?: HeldPost }>();
|
|
4232
4265
|
/** = MAX_HOLDS_GLOBAL (background.ts): there are never more live holds than this. */
|
|
4233
4266
|
const MAX_HELD_TEXTS = 10_000;
|
|
4267
|
+
// Live registrations only, never journal-restored entries. Keep bounded tombstones after pending-entry eviction so a late
|
|
4268
|
+
// duplicate cannot gate or post again merely because its entry was forgotten. Oldest handles leave at the same global bound.
|
|
4269
|
+
const registeredLiveHolds = new Set<string>();
|
|
4270
|
+
function rememberLiveHold(handle: string): void {
|
|
4271
|
+
registeredLiveHolds.add(handle);
|
|
4272
|
+
if (registeredLiveHolds.size > MAX_HELD_TEXTS) {
|
|
4273
|
+
const oldest = registeredLiveHolds.values().next();
|
|
4274
|
+
if (!oldest.done) registeredLiveHolds.delete(oldest.value);
|
|
4275
|
+
}
|
|
4276
|
+
}
|
|
4234
4277
|
function rememberHeldText(handle: string, sessionID: string, text: string, post?: HeldPost): void {
|
|
4235
4278
|
heldTexts.delete(handle);
|
|
4236
4279
|
heldTexts.set(handle, { sessionID, text, ...(post === undefined ? {} : { post }) });
|
|
@@ -4656,10 +4699,39 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4656
4699
|
forgetTaskArgs(fin.callID);
|
|
4657
4700
|
return { outputText: fin.outputText, suffix: "", verification: { kind: "none" }, metadata: {} };
|
|
4658
4701
|
}
|
|
4659
|
-
|
|
4702
|
+
const priorHold = fin.heldHandle === undefined ? undefined : pending.get(fin.parentSessionID, fin.heldHandle);
|
|
4703
|
+
// A journal-restored held entry can lack its optional dispatch. It is not a live registration of this instance and
|
|
4704
|
+
// must settle through recovery, rather than silently joining a gate that this process never started.
|
|
4705
|
+
const restoredWithoutDispatch = fin.heldHandle !== undefined && !registeredLiveHolds.has(fin.heldHandle)
|
|
4706
|
+
&& !taskArgsByCall.has(fin.callID) && priorHold?.kind === "found"
|
|
4707
|
+
&& priorHold.entry.dispatchID === fin.callID && priorHold.entry.producerSessionID === fin.childSessionID
|
|
4708
|
+
&& priorHold.entry.hold?.callID === fin.callID && priorHold.entry.hold.childSessionID === fin.childSessionID;
|
|
4709
|
+
if (fin.restored !== undefined || restoredWithoutDispatch) {
|
|
4660
4710
|
const restored = finishRestored(fin, args, scratch);
|
|
4661
4711
|
if (restored !== undefined) return restored;
|
|
4662
4712
|
}
|
|
4713
|
+
// A repeated live completion must not re-gate an already registered hold: its first gate owns the verdict, even while
|
|
4714
|
+
// running. In particular, that gate may already have consumed the call's arguments and change-set records.
|
|
4715
|
+
const existingLiveHold = (): FinishResult | undefined => {
|
|
4716
|
+
if (fin.restored !== undefined || fin.heldHandle === undefined || !registeredLiveHolds.has(fin.heldHandle)) return undefined;
|
|
4717
|
+
return { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle: fin.heldHandle }, metadata: {} };
|
|
4718
|
+
};
|
|
4719
|
+
const existing = existingLiveHold();
|
|
4720
|
+
if (existing !== undefined) return existing;
|
|
4721
|
+
// No dispatch inputs is not evidence of a read-only delegation. Never infer acceptance (or a pass) from the empty
|
|
4722
|
+
// fallback above when a live call's inputs were consumed or evicted. Restored calls retain their own fail-closed path.
|
|
4723
|
+
if (fin.restored === undefined && !taskArgsByCall.has(fin.callID) && verificationModeOfArgs(args) !== "none") {
|
|
4724
|
+
changedFileStore.clear(`task:${fin.parentSessionID}:${fin.callID}`);
|
|
4725
|
+
changedFileStore.clear(fin.childSessionID);
|
|
4726
|
+
const reason = "dispatch inputs were lost; acceptance and changes could not be evaluated";
|
|
4727
|
+
const suffix = `\n\n[router] UNVERIFIABLE — ${reason}`;
|
|
4728
|
+
if (fin.heldHandle !== undefined) {
|
|
4729
|
+
trackHeldGate(postHeldDirect(fin.heldHandle, "UNVERIFIABLE", fin.outputText + suffix, reason));
|
|
4730
|
+
pending.releaseHandle(fin.heldHandle);
|
|
4731
|
+
return { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle: fin.heldHandle }, metadata: {} };
|
|
4732
|
+
}
|
|
4733
|
+
return { outputText: fin.outputText + suffix, suffix, verification: { kind: "required", verdict: "UNVERIFIABLE" }, metadata: {} };
|
|
4734
|
+
}
|
|
4663
4735
|
if (fin.heldHandle !== undefined) {
|
|
4664
4736
|
const handle = fin.heldHandle;
|
|
4665
4737
|
const dod = buildDelegationDoD({
|
|
@@ -4673,6 +4745,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4673
4745
|
const headRead = changedFileStore.baselineHead(dispatchKey);
|
|
4674
4746
|
const startHead = headRead === undefined ? undefined
|
|
4675
4747
|
: await withTimeout(headRead, HELD_HEAD_READ_MS, "dispatch head").catch(() => undefined);
|
|
4748
|
+
// Another finish may have registered this hold while the head read yielded. Registration and gate launch below are
|
|
4749
|
+
// synchronous, so only the first finish after this check owns them.
|
|
4750
|
+
const registered = existingLiveHold();
|
|
4751
|
+
if (registered !== undefined) return registered;
|
|
4676
4752
|
// The head the gate compares the tree with (as prepareVerification: the head read, else the dispatch snapshot's head and
|
|
4677
4753
|
// branch) is journaled as plain data, so the gate re-run after a restart runs the same branch check. A head reader whose
|
|
4678
4754
|
// read gave nothing (the gate fails closed on it too) is journaled as the fact alone (`hadHead`, restored as headLost).
|
|
@@ -4705,7 +4781,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
4705
4781
|
...(heldHead ? { heldHead: true as const } : {}),
|
|
4706
4782
|
...(dispatchHead !== undefined ? { dispatchHead } : {}),
|
|
4707
4783
|
});
|
|
4708
|
-
if (!reg.ok)
|
|
4784
|
+
if (!reg.ok) {
|
|
4785
|
+
logger.warn("[router] held dispatch not registered", { code: reg.code, detail: reg.detail });
|
|
4786
|
+
// The gate below posts the verdict directly; a reservation left behind would make router_verify answer `held` for hours.
|
|
4787
|
+
pending.releaseHandle(handle);
|
|
4788
|
+
} else rememberLiveHold(handle);
|
|
4709
4789
|
runHeldGate(fin, handle, callInput, scratch, delta === undefined ? undefined : { delta }, undefined);
|
|
4710
4790
|
return { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle }, metadata: {} };
|
|
4711
4791
|
}
|
package/src/router/config.ts
CHANGED
|
@@ -3295,6 +3295,100 @@ function boundProjectClassifier(merged: Record<string, unknown>, lower: unknown,
|
|
|
3295
3295
|
return { ...merged, routing: { ...merged.routing, classifier: bounded } };
|
|
3296
3296
|
}
|
|
3297
3297
|
|
|
3298
|
+
/** A key path dropped from an override layer (#80), with the validation error that kept it out. */
|
|
3299
|
+
interface DroppedKeyPath {
|
|
3300
|
+
path: readonly string[];
|
|
3301
|
+
reason: string;
|
|
3302
|
+
}
|
|
3303
|
+
|
|
3304
|
+
/**
|
|
3305
|
+
* #80: the dropped key paths split further before giving up on them: `presets`, one preset, one
|
|
3306
|
+
* preset tier. Every other top-level key is kept or dropped as a whole.
|
|
3307
|
+
*/
|
|
3308
|
+
function refinableKeyPath(path: readonly string[], value: unknown): value is Record<string, unknown> {
|
|
3309
|
+
return path[0] === "presets" && path.length <= 3 && isPlainObject(value) && Object.keys(value).length > 0;
|
|
3310
|
+
}
|
|
3311
|
+
|
|
3312
|
+
/** The value at `path` in `obj` (own keys only), or `undefined`. */
|
|
3313
|
+
function valueAtKeyPath(obj: unknown, path: readonly string[]): unknown {
|
|
3314
|
+
let current = obj;
|
|
3315
|
+
for (const key of path) {
|
|
3316
|
+
if (!isPlainObject(current) || !Object.hasOwn(current, key)) return undefined;
|
|
3317
|
+
current = current[key];
|
|
3318
|
+
}
|
|
3319
|
+
return current;
|
|
3320
|
+
}
|
|
3321
|
+
|
|
3322
|
+
/**
|
|
3323
|
+
* `obj` without the key at `path`. An object the removal leaves empty goes too, so dropping every
|
|
3324
|
+
* key of a block is the same as dropping the block. Copies along `path` only; never mutates `obj`.
|
|
3325
|
+
*/
|
|
3326
|
+
function withoutKeyPath(obj: Record<string, unknown>, path: readonly string[]): Record<string, unknown> {
|
|
3327
|
+
const [head, ...rest] = path;
|
|
3328
|
+
if (head === undefined || !Object.hasOwn(obj, head)) return obj;
|
|
3329
|
+
let replacement: Record<string, unknown> | undefined; // undefined: the key goes
|
|
3330
|
+
if (rest.length > 0) {
|
|
3331
|
+
const value = obj[head];
|
|
3332
|
+
if (!isPlainObject(value)) return obj;
|
|
3333
|
+
const pruned = withoutKeyPath(value, rest);
|
|
3334
|
+
if (pruned === value) return obj;
|
|
3335
|
+
replacement = Object.keys(pruned).length > 0 ? pruned : undefined;
|
|
3336
|
+
}
|
|
3337
|
+
// Object.fromEntries defines each key, so an own `__proto__` key stays a key and reparents nothing.
|
|
3338
|
+
return Object.fromEntries(
|
|
3339
|
+
Object.entries(obj).flatMap(([key, value]): Array<[string, unknown]> => {
|
|
3340
|
+
if (key !== head) return [[key, value]];
|
|
3341
|
+
return replacement === undefined ? [] : [[key, replacement]];
|
|
3342
|
+
}),
|
|
3343
|
+
);
|
|
3344
|
+
}
|
|
3345
|
+
|
|
3346
|
+
/**
|
|
3347
|
+
* #80: the key paths of an override layer to drop so that the config validates, instead of the
|
|
3348
|
+
* whole layer. `errorWith(data)` validates the config with the layer's data replaced by `data` and
|
|
3349
|
+
* returns the error message, or `undefined` when it is valid; the caller has checked that the
|
|
3350
|
+
* layer's absence (`{}`) is valid. Deterministic, in file order: every top-level key starts out
|
|
3351
|
+
* dropped and comes back when the config still validates with it; a `presets` block that cannot
|
|
3352
|
+
* come back is split into its presets, a preset into its tiers, a tier into its keys, each restored
|
|
3353
|
+
* the same way; a last pass restores a key that only failed because of one dropped later (an
|
|
3354
|
+
* `activePreset` naming a preset whose bad tier key came out after it). One validation per key
|
|
3355
|
+
* tried, plus that pass.
|
|
3356
|
+
*/
|
|
3357
|
+
function isolateInvalidKeys(
|
|
3358
|
+
data: Record<string, unknown>,
|
|
3359
|
+
errorWith: (pruned: Record<string, unknown>) => string | undefined,
|
|
3360
|
+
): { data: Record<string, unknown>; dropped: DroppedKeyPath[] } {
|
|
3361
|
+
let dropped: DroppedKeyPath[] = Object.keys(data).map((key) => ({ path: [key], reason: "" }));
|
|
3362
|
+
const pruned = (entries: readonly DroppedKeyPath[]): Record<string, unknown> =>
|
|
3363
|
+
entries.reduce((acc, entry) => withoutKeyPath(acc, entry.path), data);
|
|
3364
|
+
/** Restore `entry` when the config validates with it; otherwise record why it stays dropped. */
|
|
3365
|
+
const tryRestore = (entry: DroppedKeyPath): boolean => {
|
|
3366
|
+
const rest = dropped.filter((other) => other !== entry);
|
|
3367
|
+
const error = errorWith(pruned(rest));
|
|
3368
|
+
if (error === undefined) {
|
|
3369
|
+
dropped = rest;
|
|
3370
|
+
return true;
|
|
3371
|
+
}
|
|
3372
|
+
entry.reason = error;
|
|
3373
|
+
return false;
|
|
3374
|
+
};
|
|
3375
|
+
for (const entry of [...dropped]) tryRestore(entry);
|
|
3376
|
+
for (let i = 0; i < dropped.length; i++) {
|
|
3377
|
+
const entry = dropped[i]!;
|
|
3378
|
+
const value = valueAtKeyPath(data, entry.path);
|
|
3379
|
+
if (!refinableKeyPath(entry.path, value)) continue;
|
|
3380
|
+
const children = Object.keys(value).map((key) => ({ path: [...entry.path, key], reason: entry.reason }));
|
|
3381
|
+
dropped.splice(i, 1, ...children);
|
|
3382
|
+
for (const child of children) tryRestore(child);
|
|
3383
|
+
i--; // position i now holds the first child still dropped, or the next entry: visit it
|
|
3384
|
+
}
|
|
3385
|
+
for (let restored = true; restored;) {
|
|
3386
|
+
restored = false;
|
|
3387
|
+
for (const entry of [...dropped]) if (tryRestore(entry)) restored = true;
|
|
3388
|
+
}
|
|
3389
|
+
return { data: pruned(dropped), dropped };
|
|
3390
|
+
}
|
|
3391
|
+
|
|
3298
3392
|
/**
|
|
3299
3393
|
* Build a fresh config from tiers.json + override layers + persisted state.
|
|
3300
3394
|
* Throws only when tiers.json itself is unreadable/invalid. Override and state
|
|
@@ -3329,14 +3423,17 @@ function buildConfig(
|
|
|
3329
3423
|
rawUsed = merged;
|
|
3330
3424
|
notices.push(...attemptNotices);
|
|
3331
3425
|
} catch (err) {
|
|
3332
|
-
// A bad override must never brick startup, and one
|
|
3333
|
-
//
|
|
3334
|
-
//
|
|
3335
|
-
// a project file cannot force a conflict with a value valid on its own
|
|
3336
|
-
// so drop the user's
|
|
3337
|
-
//
|
|
3426
|
+
// A bad override must never brick startup, and one bad value must not discard the
|
|
3427
|
+
// rest of its file, let alone a good file (#80). The layers are settled one at a
|
|
3428
|
+
// time, each on top of those already settled. QA-4.1-21: the global layer goes
|
|
3429
|
+
// first, so a project file cannot force a conflict with a value valid on its own
|
|
3430
|
+
// and so drop the user's global keys; a broken global file still lets a project
|
|
3431
|
+
// file apply. A layer that validates whole is kept whole. Otherwise only the key
|
|
3432
|
+
// paths that keep it from validating are dropped, each with a notice
|
|
3433
|
+
// (isolateInvalidKeys); when every top-level key of the layer has to go, the layer
|
|
3434
|
+
// is dropped as a whole, with the log lines it always had.
|
|
3338
3435
|
console.warn(
|
|
3339
|
-
`[model-router] combined overrides are invalid (${(err as Error).message}); dropping
|
|
3436
|
+
`[model-router] combined overrides are invalid (${(err as Error).message}); dropping the invalid keys or layer(s)`,
|
|
3340
3437
|
);
|
|
3341
3438
|
const layerPaths = layers.map((l) => l.path).join(" + ");
|
|
3342
3439
|
failures.push({
|
|
@@ -3347,31 +3444,63 @@ function buildConfig(
|
|
|
3347
3444
|
...layers.map((_, i) => i).filter((i) => !layers[i]!.project).reverse(),
|
|
3348
3445
|
...layers.map((_, i) => i).filter((i) => layers[i]!.project === true).reverse(),
|
|
3349
3446
|
];
|
|
3350
|
-
|
|
3447
|
+
/** The layers settled so far, in priority order, with layer `i` as `layer`. */
|
|
3448
|
+
const settledWith = (kept: ReadonlyArray<OverrideLayer | undefined>, i: number, layer: OverrideLayer): OverrideLayer[] =>
|
|
3449
|
+
kept.map((l, j) => (j === i ? layer : l)).filter((l): l is OverrideLayer => l !== undefined);
|
|
3450
|
+
const validationError = (raw: unknown): string | undefined => {
|
|
3351
3451
|
try {
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3452
|
+
validateConfig(raw);
|
|
3453
|
+
return undefined;
|
|
3454
|
+
} catch (validationErr) {
|
|
3455
|
+
return (validationErr as Error).message;
|
|
3456
|
+
}
|
|
3457
|
+
};
|
|
3458
|
+
// The merge notices (A18 clamps) of a trial merge are not reported: only the final merge's are.
|
|
3459
|
+
const errorWith = (kept: ReadonlyArray<OverrideLayer | undefined>, i: number, layer: OverrideLayer): string | undefined =>
|
|
3460
|
+
validationError(merge(settledWith(kept, i, layer), []));
|
|
3461
|
+
const kept: Array<OverrideLayer | undefined> = layers.map(() => undefined);
|
|
3462
|
+
const droppedWhole: number[] = [];
|
|
3463
|
+
for (const i of order) {
|
|
3464
|
+
const layer = layers[i]!;
|
|
3465
|
+
if (errorWith(kept, i, layer) === undefined) {
|
|
3466
|
+
kept[i] = layer;
|
|
3467
|
+
continue;
|
|
3468
|
+
}
|
|
3469
|
+
const isolated = isolateInvalidKeys(layer.data, (data) => errorWith(kept, i, { ...layer, data }));
|
|
3470
|
+
const keptSomeKey = Object.keys(layer.data).some(
|
|
3471
|
+
(key) => !isolated.dropped.some((d) => d.path.length === 1 && d.path[0] === key),
|
|
3472
|
+
);
|
|
3473
|
+
if (keptSomeKey && errorWith(kept, i, { ...layer, data: isolated.data }) === undefined) {
|
|
3474
|
+
kept[i] = { ...layer, data: isolated.data };
|
|
3475
|
+
for (const { path, reason } of isolated.dropped) {
|
|
3476
|
+
const keyPath = path.join(".");
|
|
3477
|
+
console.warn(`[model-router] ignoring ${keyPath} from ${layer.path}: ${reason}`);
|
|
3478
|
+
notices.push({
|
|
3479
|
+
source: layer.path,
|
|
3480
|
+
message: `ignoring ${keyPath} from ${layer.path}: ${reason}; the rest of the file applies`,
|
|
3481
|
+
});
|
|
3361
3482
|
}
|
|
3362
|
-
|
|
3363
|
-
}
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
});
|
|
3371
|
-
cfg = validateConfig(base);
|
|
3372
|
-
rawUsed = base;
|
|
3483
|
+
continue;
|
|
3484
|
+
}
|
|
3485
|
+
// Not isolated: the layer goes as a whole, as before #80.
|
|
3486
|
+
droppedWhole.push(i);
|
|
3487
|
+
const aloneError = validationError(merge([layer], []));
|
|
3488
|
+
if (aloneError !== undefined) {
|
|
3489
|
+
console.warn(`[model-router] ignoring ${layer.path}: ${aloneError}`);
|
|
3490
|
+
failures.push({ source: layer.path, message: `${layer.path}: ${aloneError}` });
|
|
3373
3491
|
}
|
|
3374
3492
|
}
|
|
3493
|
+
if (kept.some((l) => l !== undefined)) {
|
|
3494
|
+
for (const i of droppedWhole.sort((a, b) => a - b)) {
|
|
3495
|
+
console.warn(`[model-router] dropped override layer ${layers[i]!.path}`);
|
|
3496
|
+
}
|
|
3497
|
+
}
|
|
3498
|
+
const used = kept.filter((l): l is OverrideLayer => l !== undefined);
|
|
3499
|
+
const attemptNotices: ConfigNotice[] = [];
|
|
3500
|
+
const settled = used.length > 0 ? merge(used, attemptNotices) : base;
|
|
3501
|
+
cfg = validateConfig(settled);
|
|
3502
|
+
rawUsed = settled;
|
|
3503
|
+
notices.push(...attemptNotices);
|
|
3375
3504
|
}
|
|
3376
3505
|
}
|
|
3377
3506
|
|
|
@@ -0,0 +1,180 @@
|
|
|
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.
|
|
16
|
+
* Each file is resolved in two readings, and refused when either hits: as written (links resolved before any `..` after them, as
|
|
17
|
+
* the kernel does on POSIX) and as the host resolves it (`path.resolve`: `..` collapsed as text first). A patch whose targets
|
|
18
|
+
* cannot be read is refused too (fail closed). Never throws.
|
|
19
|
+
*/
|
|
20
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
21
|
+
import { posix, win32 } from "node:path";
|
|
22
|
+
import { gitPointers, nearestRepository } from "./git-tools";
|
|
23
|
+
import { WRITE_CLASS, writeTargetTexts } from "./tool-paths";
|
|
24
|
+
import { canonicalAuthorityPath, insideWorkRoot } from "../routing/roles/work-root";
|
|
25
|
+
import { displaySafe, namesGitMetadata } from "../routing/roles/read-set";
|
|
26
|
+
|
|
27
|
+
/** The git directories of the session directory's repository, and its checkout (both canonical). */
|
|
28
|
+
export interface SessionGitDirectories {
|
|
29
|
+
/** The git directory and the common directory. */
|
|
30
|
+
readonly directories: readonly string[];
|
|
31
|
+
/** The checkout (repository top) holding the session directory; undefined outside a repository. */
|
|
32
|
+
readonly checkout: string | undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Seams of {@link gitMetadataWriteRefusal} (tests). */
|
|
36
|
+
export interface GitMetadataGuardDeps {
|
|
37
|
+
/** Default `process.platform`: path syntax, NTFS stream suffixes and 8.3 names on win32. */
|
|
38
|
+
readonly platform?: NodeJS.Platform;
|
|
39
|
+
/** `realpathSync.native` and `lstatSync` (the filesystem the paths are resolved on). */
|
|
40
|
+
readonly realpath?: (path: string) => string;
|
|
41
|
+
readonly lstat?: (path: string) => unknown;
|
|
42
|
+
/** The git directories and checkout of the repository holding `directory`. Default: its `.git` pointers. */
|
|
43
|
+
readonly gitDirectories?: (directory: string) => SessionGitDirectories;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The refusal of a write that targets git metadata. */
|
|
47
|
+
export function gitMetadataWriteRefusalText(path: string): string {
|
|
48
|
+
return `[router] Refused: writing git metadata (${displaySafe(path)}) is not allowed for delegated agents.`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The refusal of a write whose target the router cannot resolve (fail closed). */
|
|
52
|
+
function unresolvedText(path: string): string {
|
|
53
|
+
return `[router] Refused: the router could not resolve ${displaySafe(path)} to check that it is not git metadata, which delegated `
|
|
54
|
+
+ "agents may not write (fail closed). Name the file by a plain path.";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The refusal of a patch whose targets cannot be read (fail closed). */
|
|
58
|
+
export const GIT_METADATA_PATCH_UNREADABLE = "[router] Refused: the router could not read which files this patch writes, so it "
|
|
59
|
+
+ "cannot check that none of them is git metadata, which delegated agents may not write (fail closed). Name each file in an "
|
|
60
|
+
+ "`*** Add File:`, `*** Update File:` or `*** Delete File:` header.";
|
|
61
|
+
|
|
62
|
+
/** #161 (OpenCode v2): the refusal of a write-class call whose session directory is unknown (fail closed). */
|
|
63
|
+
export const GIT_METADATA_DIRECTORY_UNKNOWN = "[router] Refused: the session's location could not be read, so this write cannot be "
|
|
64
|
+
+ "checked for git metadata, which delegated agents may not write (fail closed).";
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* win32: `path` with each segment's NTFS stream suffix cut (`name:stream`, `name::$DATA`, `name::$INDEX_ALLOCATION` all name the
|
|
68
|
+
* entry `name`), a leading drive's `X:` kept, so the entry is what gets resolved.
|
|
69
|
+
*/
|
|
70
|
+
function withoutStreams(path: string): string {
|
|
71
|
+
return path.split(/([\\/])/).map((part, index) => {
|
|
72
|
+
const drive = index === 0 && /^[A-Za-z]:/.test(part) ? part.slice(0, 2) : "";
|
|
73
|
+
const rest = part.slice(drive.length);
|
|
74
|
+
const colon = rest.indexOf(":");
|
|
75
|
+
return drive + (colon === -1 ? rest : rest.slice(0, colon));
|
|
76
|
+
}).join("");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const NO_GIT_DIRECTORIES: SessionGitDirectories = Object.freeze({ directories: [], checkout: undefined });
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The canonical git directory and common directory of the repository whose checkout holds `directory`, and that checkout, read
|
|
83
|
+
* from its `.git` pointers without running git ({@link gitPointers}: bounded, never followed onto a network or device path). No
|
|
84
|
+
* directories when there is no repository or a pointer is refused or unreadable: the `.git` segment checks still apply.
|
|
85
|
+
*/
|
|
86
|
+
function sessionGitDirectories(directory: string): SessionGitDirectories {
|
|
87
|
+
try {
|
|
88
|
+
const checkout = nearestRepository(directory);
|
|
89
|
+
if (checkout === undefined) return NO_GIT_DIRECTORIES;
|
|
90
|
+
const pointers = gitPointers(checkout);
|
|
91
|
+
if (pointers === undefined) return NO_GIT_DIRECTORIES;
|
|
92
|
+
const directories: string[] = [];
|
|
93
|
+
for (const dir of new Set([pointers.gitdir, pointers.common])) {
|
|
94
|
+
try {
|
|
95
|
+
directories.push(realpathSync.native(dir));
|
|
96
|
+
} catch {
|
|
97
|
+
// a git directory that does not resolve holds nothing to write
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return { directories, checkout: realpathSync.native(checkout) };
|
|
101
|
+
} catch {
|
|
102
|
+
return NO_GIT_DIRECTORIES;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* `target` (canonical) lies in one of the session repository's git directories. A git directory that holds the checkout itself
|
|
108
|
+
* (a bare repository with its worktree inside it, or a malformed pointer naming the checkout) exempts only the checkout's own
|
|
109
|
+
* files; a git directory inside the checkout exempts nothing.
|
|
110
|
+
*/
|
|
111
|
+
function insideGitDirectory(target: string, git: SessionGitDirectories): boolean {
|
|
112
|
+
const top = git.checkout;
|
|
113
|
+
return git.directories.some((dir) => {
|
|
114
|
+
if (!insideWorkRoot(target, dir)) return false;
|
|
115
|
+
return !(top !== undefined && insideWorkRoot(top, dir) && insideWorkRoot(target, top));
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The refusal of the write-class call `tool(args)` of a delegated session whose relative paths resolve against `base` (the
|
|
121
|
+
* session's directory), or undefined when it writes no git metadata (and for every other tool). The caller decides whether the
|
|
122
|
+
* session is delegated.
|
|
123
|
+
*/
|
|
124
|
+
export function gitMetadataWriteRefusal(tool: string, args: unknown, base: string, deps: GitMetadataGuardDeps = {}): string | undefined {
|
|
125
|
+
if (typeof tool !== "string" || !WRITE_CLASS.has(tool.toLowerCase())) return undefined;
|
|
126
|
+
const texts = writeTargetTexts(tool, args);
|
|
127
|
+
if (texts === undefined) return GIT_METADATA_PATCH_UNREADABLE;
|
|
128
|
+
const platform = deps.platform ?? process.platform;
|
|
129
|
+
const api = platform === "win32" ? win32 : posix;
|
|
130
|
+
const fs = {
|
|
131
|
+
realpath: deps.realpath ?? ((p: string) => realpathSync.native(p)),
|
|
132
|
+
lstat: deps.lstat ?? ((p: string) => lstatSync(p)),
|
|
133
|
+
};
|
|
134
|
+
// 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.
|
|
135
|
+
const canonical = (path: string): string | undefined => {
|
|
136
|
+
try {
|
|
137
|
+
return canonicalAuthorityPath(path, base, { platform, shortNames: "resolve", uncRoot: base, ...fs });
|
|
138
|
+
} catch {
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
let git: SessionGitDirectories | undefined;
|
|
143
|
+
const gitDirectories = (): SessionGitDirectories => {
|
|
144
|
+
if (git === undefined) {
|
|
145
|
+
try {
|
|
146
|
+
git = (deps.gitDirectories ?? sessionGitDirectories)(base);
|
|
147
|
+
} catch {
|
|
148
|
+
git = NO_GIT_DIRECTORIES; // the `.git` segment checks still apply
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return git;
|
|
152
|
+
};
|
|
153
|
+
for (const text of texts) {
|
|
154
|
+
if (namesGitMetadata(text)) return gitMetadataWriteRefusalText(text);
|
|
155
|
+
const written = platform === "win32" ? withoutStreams(text) : text;
|
|
156
|
+
// The kernel's reading (links before `..`) and the host's (`path.resolve`, `..` collapsed as text first): either may write.
|
|
157
|
+
let hostReading: string;
|
|
158
|
+
try {
|
|
159
|
+
hostReading = api.resolve(base, written);
|
|
160
|
+
} catch {
|
|
161
|
+
return unresolvedText(text);
|
|
162
|
+
}
|
|
163
|
+
for (const reading of new Set([written, hostReading])) {
|
|
164
|
+
const target = canonical(reading);
|
|
165
|
+
if (target === undefined) return unresolvedText(text);
|
|
166
|
+
if (namesGitMetadata(target) || insideGitDirectory(target, gitDirectories())) return gitMetadataWriteRefusalText(text);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* #161 (OpenCode v2): the refusal of the write-class call `tool(args)` of a delegated session whose own directory is unknown (the
|
|
174
|
+
* v2 bridge could not look it up and knows none): a path refusal against `fallback` (the plugin's directory) keeps its text, any
|
|
175
|
+
* other write-class call gets GIT_METADATA_DIRECTORY_UNKNOWN; undefined for every other tool. Never throws.
|
|
176
|
+
*/
|
|
177
|
+
export function gitMetadataUnknownDirectoryRefusal(tool: string, args: unknown, fallback: string, deps: GitMetadataGuardDeps = {}): string | undefined {
|
|
178
|
+
if (typeof tool !== "string" || !WRITE_CLASS.has(tool.toLowerCase())) return undefined;
|
|
179
|
+
return gitMetadataWriteRefusal(tool, args, fallback, deps) ?? GIT_METADATA_DIRECTORY_UNKNOWN;
|
|
180
|
+
}
|