Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 78 additions & 2 deletions bin/opencode-route-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@
// relative to this file)
// OPENCODE_ROUTE_PROXY_DB opencode.db path (default:
// ~/.local/share/opencode/opencode.db)
// OPENCODE_ROUTE_PROXY_NOW_MS pin the clock (epoch ms) used for
// route window gates — tests and
// incident replay; unset = wall clock
import { createServer } from "node:http";
import { readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
Expand Down Expand Up @@ -146,6 +149,7 @@ const loadConfig = () => {
mtimeMs: st.mtimeMs,
providers: raw.provider || {},
routes: raw.experimental?.model_routes || raw.model_routes || {},
windows: raw.experimental?.model_route_windows || raw.model_route_windows || {},
disabled: new Set(raw.disabled_providers || []),
};
return cfgCache;
Expand Down Expand Up @@ -312,13 +316,83 @@ const parseTargetRef = (ref) => {
return { providerId: ref.slice(0, s), modelKey: ref.slice(s + 1), variant };
};

// Route target window gates (#3225): a target may carry
// `window: "<name>"` or `window: { name, invert: true }`, naming a
// window in experimental.model_route_windows
// ({ daysOfWeek: ["mon", ...], start: "HH:MM", end: "HH:MM",
// timezone }). The gate survives normalization — dropping it here was
// the bug — and resolveRoute expands a gated target only while its
// window is active (or, with invert, only while it is NOT). A gate
// naming an unknown window never matches: fail closed, so a config
// typo surfaces as a loud no-members route instead of silently
// ungating the target.
const normalizeWindowGate = (w) => {
if (typeof w === "string" && w) return { name: w, invert: false };
if (w && typeof w.name === "string" && w.name)
return { name: w.name, invert: w.invert === true };
return null;
};

const normalizeTarget = (t) => {
if (typeof t === "string") return { ...parseTargetRef(t), variantMap: null };
if (typeof t === "string")
return { ...parseTargetRef(t), variantMap: null, windowGate: null };
if (t && typeof t.model === "string")
return { ...parseTargetRef(t.model), variantMap: t.variants || null };
return {
...parseTargetRef(t.model),
variantMap: t.variants || null,
windowGate: normalizeWindowGate(t.window),
};
return null;
};

// Clock for window evaluation. OPENCODE_ROUTE_PROXY_NOW_MS pins
// "now" (epoch ms) for tests and incident replay; unset = wall clock.
const nowMs = () => {
const pinned = Number(process.env.OPENCODE_ROUTE_PROXY_NOW_MS);
return Number.isFinite(pinned) && pinned > 0 ? pinned : Date.now();
};

const parseHHMM = (s) => {
const m = /^([0-9]{1,2}):([0-9]{2})$/.exec(typeof s === "string" ? s.trim() : "");
return m ? Number(m[1]) * 60 + Number(m[2]) : null;
};

// Is window `win` active at `now` (epoch ms)? Day and wall time are
// read in the window's own timezone; start inclusive, end exclusive;
// an end at or before start wraps past midnight.
const windowActive = (win, now) => {
if (!win || typeof win !== "object") return false;
const start = parseHHMM(win.start);
const end = parseHHMM(win.end);
if (start === null || end === null) return false;
let parts;
try {
parts = new Intl.DateTimeFormat("en-US", {
timeZone: win.timezone || "UTC",
weekday: "short",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
}).formatToParts(new Date(now));
} catch {
return false;
}
const get = (type) => parts.find((part) => part.type === type)?.value;
const day = String(get("weekday") || "").slice(0, 3).toLowerCase();
if (Array.isArray(win.daysOfWeek) && win.daysOfWeek.length) {
const days = win.daysOfWeek.map((d) => String(d).slice(0, 3).toLowerCase());
if (!days.includes(day)) return false;
}
const mins = Number(get("hour")) * 60 + Number(get("minute"));
return start <= end ? mins >= start && mins < end : mins >= start || mins < end;
};

const targetEligible = (cfg, t, now) => {
if (!t.windowGate) return true;
const active = windowActive(cfg.windows?.[t.windowGate.name], now);
return t.windowGate.invert ? !active : active;
};

const rotation = new Map(); // routeId -> counter
const rotate = (arr, routeId) => {
if (arr.length < 2) return arr;
Expand Down Expand Up @@ -352,6 +426,7 @@ const weightedOrder = (targets, weights) => {
// [{ providerId, modelKey, variant }]. Nested routes recurse; disabled
// providers are skipped; cycles are cut.
const resolveRoute = (cfg, routeId, variantIn = null) => {
const now = nowMs();
const out = [];
const expand = (rid, vIn, seen) => {
if (seen.has(rid)) return;
Expand All @@ -361,6 +436,7 @@ const resolveRoute = (cfg, routeId, variantIn = null) => {
let targets = (route.targets || [])
.map(normalizeTarget)
.filter(Boolean)
.filter((t) => targetEligible(cfg, t, now))
.map((t) => ({ ...t, refBase: `${t.providerId}/${t.modelKey}` }));
if (route.selection === "round-robin") targets = rotate(targets, rid);
else if (route.selection === "weighted")
Expand Down
86 changes: 85 additions & 1 deletion bin/opencode-route-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ const ROUTE_ATTEMPT_SCHEMA = `CREATE TABLE route_attempt (
quota text, tokens_estimated integer, error_body text, hedged integer,
cost_usd real)`;

const startProxy = async () => {
const startProxy = async ({ nowMs: pinnedNow } = {}) => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "route-proxy-test-"));
const leafA = await makeLeaf("LEAF-A", "key-a");
const leafB = await makeLeaf("LEAF-B", "key-b");
Expand Down Expand Up @@ -165,11 +165,17 @@ const startProxy = async () => {
},
},
"experimental": {
"model_route_windows": {
"peak": { "daysOfWeek": ["mon", "tue", "wed", "thu", "fri"], "start": "01:00", "end": "04:00", "timezone": "UTC" },
},
"model_routes": {
"t-ordered": { "selection": "ordered", "targets": ["leafA/m-a", "leafB/m-b"] },
"t-variant": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "variants": { "medium": "high" } } ] },
"t-nested": { "selection": "ordered", "targets": ["opencode-route/t-ordered"] },
"t-disabled": { "selection": "ordered", "targets": ["leafOff/m-b", "leafB/m-b"] },
"t-window": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "window": "peak" }, "leafB/m-b" ] },
"t-window-inv": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "window": { "name": "peak", "invert": true } }, "leafB/m-b" ] },
"t-window-unknown": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "window": "no-such-window" }, "leafB/m-b" ] },
},
},
}`,
Expand All @@ -183,6 +189,9 @@ const startProxy = async () => {
OPENCODE_ROUTE_PROXY_CONFIG: configPath,
OPENCODE_ROUTE_PROXY_DB: dbPath,
OPENCODE_ROUTE_PROXY_TIMEOUT_MS: "15000",
...(pinnedNow
? { OPENCODE_ROUTE_PROXY_NOW_MS: String(pinnedNow) }
: {}),
};
const child = spawn(
process.execPath,
Expand Down Expand Up @@ -360,3 +369,78 @@ test("unknown route and malformed bodies are rejected", async () => {
await p.cleanup();
}
});

// Window gates (#3225): the fixture "peak" window is Mon-Fri
// 01:00-04:00 UTC. 2026-11-04 is a Wednesday.
const IN_PEAK = Date.UTC(2026, 10, 4, 2, 30);
const OUT_PEAK = Date.UTC(2026, 10, 4, 12, 0);

test("window-gated target is expanded inside its window", async () => {
const p = await startProxy({ nowMs: IN_PEAK });
try {
const res = await p.post({ model: "opencode-route/t-window", messages: MSGS });
assert.equal(res.status, 200);
assert.equal((await res.json()).choices[0].message.content, "LEAF-A");
const rows = p.attempts();
assert.equal(rows.length, 1);
assert.equal(rows[0].provider_id, "leafA");
} finally {
await p.cleanup();
}
});

test("window-gated target is excluded outside its window", async () => {
const p = await startProxy({ nowMs: OUT_PEAK });
try {
const res = await p.post({ model: "opencode-route/t-window", messages: MSGS });
assert.equal(res.status, 200);
assert.equal((await res.json()).choices[0].message.content, "LEAF-B");
const rows = p.attempts();
assert.equal(rows.length, 1);
assert.equal(rows[0].provider_id, "leafB");
} finally {
await p.cleanup();
}
});

test("inverted window gate is eligible only outside the window", async () => {
const inP = await startProxy({ nowMs: IN_PEAK });
try {
const res = await inP.post({
model: "opencode-route/t-window-inv",
messages: MSGS,
});
assert.equal(res.status, 200);
assert.equal((await res.json()).choices[0].message.content, "LEAF-B");
} finally {
await inP.cleanup();
}
const outP = await startProxy({ nowMs: OUT_PEAK });
try {
const res = await outP.post({
model: "opencode-route/t-window-inv",
messages: MSGS,
});
assert.equal(res.status, 200);
assert.equal((await res.json()).choices[0].message.content, "LEAF-A");
} finally {
await outP.cleanup();
}
});

test("a gate naming an unknown window fails closed", async () => {
const p = await startProxy({ nowMs: IN_PEAK });
try {
const res = await p.post({
model: "opencode-route/t-window-unknown",
messages: MSGS,
});
assert.equal(res.status, 200);
assert.equal((await res.json()).choices[0].message.content, "LEAF-B");
const rows = p.attempts();
assert.equal(rows.length, 1);
assert.equal(rows[0].provider_id, "leafB");
} finally {
await p.cleanup();
}
});