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
3,981 changes: 482 additions & 3,499 deletions .opencode/opencode.jsonc

Large diffs are not rendered by default.

45 changes: 44 additions & 1 deletion bin/opencode-route-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@
// ~/.local/share/opencode/opencode.jsonc,
// else ../.opencode/opencode.jsonc
// relative to this file)
// OPENCODE_ROUTE_PROXY_RUNTIME_CONFIG
// runtime overlay jsonc whose provider
// catalogs are deep-merged over the
// config's (default:
// ~/.local/state/opencode/opencode-runtime.jsonc;
// absent = no overlay) (#4544)
// 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
Expand All @@ -59,6 +65,9 @@ const CONFIG_PATH =
process.env.OPENCODE_ROUTE_PROXY_CONFIG ||
join(homedir(), ".local/share/opencode/opencode.jsonc");
const CONFIG_FALLBACK = join(HERE, "..", ".opencode", "opencode.jsonc");
const RUNTIME_CONFIG_PATH =
process.env.OPENCODE_ROUTE_PROXY_RUNTIME_CONFIG ||
join(homedir(), ".local/state/opencode/opencode-runtime.jsonc");
const DB_PATH =
process.env.OPENCODE_ROUTE_PROXY_DB ||
join(homedir(), ".local/share/opencode/opencode.db");
Expand Down Expand Up @@ -152,6 +161,18 @@ const parseJsonc = (text) => {
}
};

const isPlainObj = (v) =>
v !== null && typeof v === "object" && !Array.isArray(v);
// Deep-merge plain objects (overlay wins on scalars): mirrors the fork
// server's config layering for the runtime overlay (#4544), so the proxy
// resolves the same effective provider catalog the server does.
const deepMergePlain = (base, over) => {
if (!isPlainObj(base) || !isPlainObj(over)) return over;
const out = { ...base };
for (const k of Object.keys(over)) out[k] = deepMergePlain(base[k], over[k]);
return out;
};

let cfgCache = null;
const loadConfig = () => {
let path = CONFIG_PATH;
Expand All @@ -162,15 +183,37 @@ const loadConfig = () => {
path = CONFIG_FALLBACK;
st = statSync(path);
}
if (cfgCache && cfgCache.path === path && cfgCache.mtimeMs === st.mtimeMs)
let rtSt = null;
try {
rtSt = statSync(RUNTIME_CONFIG_PATH);
} catch {
rtSt = null;
}
const rtMtimeMs = rtSt ? rtSt.mtimeMs : null;
if (
cfgCache &&
cfgCache.path === path &&
cfgCache.mtimeMs === st.mtimeMs &&
cfgCache.rtMtimeMs === rtMtimeMs
)
return cfgCache;
const raw = parseJsonc(readFileSync(path, "utf8"));
if (rtSt) {
try {
const rt = parseJsonc(readFileSync(RUNTIME_CONFIG_PATH, "utf8"));
if (rt && typeof rt === "object" && rt.provider)
raw.provider = deepMergePlain(raw.provider || {}, rt.provider);
} catch {
// Overlay unreadable: serve the tracked default alone rather than fail.
}
}
const windows =
raw.experimental?.model_route_windows || raw.model_route_windows || {};
warnInvalidWindows(windows);
cfgCache = {
path,
mtimeMs: st.mtimeMs,
rtMtimeMs,
providers: raw.provider || {},
providerRoutes:
raw.experimental?.provider_routes || raw.provider_routes || {},
Expand Down
82 changes: 76 additions & 6 deletions bin/provider-catalog-sync.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@
// route membership, never in the catalog — so this tool only ever ADDS,
// through a reviewable PR.
//
// #4544 split: the tracked configured default no longer carries the model
// catalogs sync-models owns (antigravity-direct, openai-codex, google,
// openai, cloudflare-gateway) — those live in the runtime overlay
// (~/.local/state/opencode/opencode-runtime.jsonc). This tool diffs the
// merged effective config (default + overlay; --runtime-config) and skips
// the sync-owned providers on --apply; sync-models owns their writes.
//
// Sources: laptop proxies are enumerated over HTTP on 127.0.0.1 (run this on
// the laptop, or pass --source-dir with <port>.json snapshots for an offline
// reproducible run). models.dev is a cross-check for every provider and the
Expand Down Expand Up @@ -498,9 +505,45 @@ async function loadModelsDev(spec) {
// ---------------------------------------------------------------------------
// Run
// ---------------------------------------------------------------------------
export async function runSync({ configPath, modelsDevSpec, sourceDir }) {
// Providers whose model catalogs bin/sync-models.mjs owns in the runtime
// overlay (#4544). Catalog-sync diffs them (via the merged effective config)
// but never writes them into the tracked configured default on --apply.
export const SYNC_OWNED_PROVIDERS = new Set([
'antigravity-direct',
'openai-codex',
'google',
'openai',
'cloudflare-gateway',
]);

// Deep-merge plain objects (overlay wins on scalars) — the same layering
// the OpenCode server applies to OPENCODE_CONFIG.
export function deepMergeProviders(base, over) {
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
if (!isObj(base) || !isObj(over)) return over;
const out = { ...base };
for (const k of Object.keys(over)) out[k] = deepMergeProviders(base[k], over[k]);
return out;
}

export async function runSync({ configPath, modelsDevSpec, sourceDir, runtimeConfigPath }) {
const configText = fs.readFileSync(configPath, 'utf8');
const config = parseJsonc(configText);
// #4544: diff against the merged effective config (tracked default +
// runtime overlay) so the sync-owned providers still enumerate and their
// vanishings still surface exactly as before the split.
let runtimeOverlay = null;
if (runtimeConfigPath && fs.existsSync(runtimeConfigPath)) {
try {
const overlay = parseJsonc(fs.readFileSync(runtimeConfigPath, 'utf8'));
if (overlay && typeof overlay === 'object' && overlay.provider) {
config.provider = deepMergeProviders(config.provider ?? {}, overlay.provider);
runtimeOverlay = runtimeConfigPath;
}
} catch {
runtimeOverlay = null;
}
}
const providers = config.provider ?? {};
let modelsDev = null;
let modelsDevError = null;
Expand All @@ -512,6 +555,7 @@ export async function runSync({ configPath, modelsDevSpec, sourceDir }) {
const report = {
generated_at: new Date().toISOString(),
config: configPath,
runtime_overlay: runtimeOverlay,
models_dev: modelsDev ? 'loaded' : `unavailable (${modelsDevError})`,
providers: {},
totals: { additions_validated: 0, additions_unverified: 0, vanishings: 0, unverifiable: 0 },
Expand Down Expand Up @@ -735,11 +779,11 @@ export function openPrCommands({ branch, branchExists, date, bodyFile }) {
// hard-error code, matching the sibling usage-error pattern from
// #3419/#3295) that names the offending flag.
// ---------------------------------------------------------------------------
export const VALUE_OPTIONS = ['--config', '--models-dev', '--source-dir', '--repo'];
export const VALUE_OPTIONS = ['--config', '--models-dev', '--source-dir', '--repo', '--runtime-config'];
export const FLAG_OPTIONS = ['--apply', '--open-pr', '--json', '--help'];
export const USAGE =
'usage: provider-catalog-sync [--config <path>] [--models-dev <url|path>] ' +
'[--source-dir <dir>] [--repo <dir>] [--apply] [--open-pr] [--json]';
'[--source-dir <dir>] [--repo <dir>] [--runtime-config <path>] [--apply] [--open-pr] [--json]';

export class UsageError extends Error {}

Expand Down Expand Up @@ -783,12 +827,25 @@ async function main(argv) {
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..');
const configPath =
process.env.OPENCODE_CONFIG_PATH || opt('--config', path.join(root, '.opencode', 'opencode.jsonc'));
const runtimeConfigPath = opt(
'--runtime-config',
process.env.OPENCODE_RUNTIME_CONFIG ||
path.join(
process.env.HOME || '/home/user',
'.local/state/opencode/opencode-runtime.jsonc',
),
);
const modelsDevSpec = opt('--models-dev', 'https://models.dev/api.json');
const sourceDir = opt('--source-dir', null);
const apply = flags.has('--apply');
const openPr = flags.has('--open-pr');

const { report, configText, config } = await runSync({ configPath, modelsDevSpec, sourceDir });
const { report, configText, config } = await runSync({
configPath,
modelsDevSpec,
sourceDir,
runtimeConfigPath,
});

if (!apply) {
if (flags.has('--json')) console.log(JSON.stringify(report, null, 2));
Expand All @@ -804,10 +861,23 @@ async function main(argv) {
try {
modelsDev = await loadModelsDev(modelsDevSpec);
} catch {}
const { text, added } = applyAdditions(configText, config, report, modelsDev);
// #4544: never write sync-models-owned catalogs into the tracked default;
// sync-models lands them in the runtime overlay instead.
const applyReport = { ...report, providers: {} };
for (const [pid, entry] of Object.entries(report.providers)) {
if (SYNC_OWNED_PROVIDERS.has(pid) && (entry.additions_validated ?? []).length > 0) {
console.log(
`[catalog-sync] skipping ${pid}: ${entry.additions_validated.length} validated addition(s) owned by sync-models (runtime overlay)`,
);
applyReport.providers[pid] = { ...entry, additions_validated: [] };
} else {
applyReport.providers[pid] = entry;
}
}
const { text, added } = applyAdditions(configText, config, applyReport, modelsDev);
assertCatalogOnly(configText, text, added);
fs.writeFileSync(configPath, text);
const body = renderPrBody(report, added);
const body = renderPrBody(applyReport, added);
console.log(body);
if (openPr) {
const repoDir = opt('--repo', path.dirname(path.dirname(configPath)));
Expand Down
56 changes: 56 additions & 0 deletions bin/provider-catalog-sync.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ import {
catalogSyncBranch,
assertNotDefaultBranch,
openPrCommands,
runSync,
deepMergeProviders,
SYNC_OWNED_PROVIDERS,
} from './provider-catalog-sync.mjs';

const FIXTURE = `{
Expand Down Expand Up @@ -335,3 +338,56 @@ test('CLI control: dry run exits 3 without writing; --apply exits 0 and writes',
assert.equal(applied.status, 0, `apply: ${applied.stdout} ${applied.stderr}`);
assert.ok(fs.readFileSync(configPath, 'utf8').includes('acme-2'));
});

// ---------------------------------------------------------------------------
// #4544: runtime overlay (sync-models-owned catalogs outside the tracked
// configured default)
// ---------------------------------------------------------------------------

test('SYNC_OWNED_PROVIDERS names exactly the five sync-models-owned providers (#4544)', () => {
assert.deepEqual(
[...SYNC_OWNED_PROVIDERS].sort(),
['antigravity-direct', 'cloudflare-gateway', 'google', 'openai', 'openai-codex'],
);
});

test('deepMergeProviders merges catalogs per model, overlay wins on conflict (#4544)', () => {
const base = { google: { models: { a: { name: 'A' }, b: { name: 'B', limit: { context: 1 } } } }, x: { models: { m: {} } } };
const over = { google: { models: { b: { name: 'B2' }, c: { name: 'C' } } } };
const merged = deepMergeProviders(base, over);
assert.deepEqual(Object.keys(merged.google.models).sort(), ['a', 'b', 'c']);
assert.equal(merged.google.models.b.name, 'B2');
assert.equal(merged.google.models.a.name, 'A');
assert.deepEqual(Object.keys(merged.x.models), ['m']);
});

test('runSync diffs the merged effective config when a runtime overlay exists (#4544)', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'catalog-sync-overlay-'));
const configPath = path.join(dir, 'opencode.jsonc');
// Tracked default post-split: no google block at all (it was models-only).
fs.writeFileSync(configPath, '{ "provider": { "deepseek": { "models": { "ds-1": {} } } } }');
const overlayPath = path.join(dir, 'opencode-runtime.jsonc');
fs.writeFileSync(
overlayPath,
JSON.stringify({ provider: { google: { models: { 'gem-a': {}, 'gem-b': {} } } } }),
);
const modelsDev = path.join(dir, 'models-dev.json');
fs.writeFileSync(modelsDev, '{}');
const { report } = await runSync({
configPath,
modelsDevSpec: modelsDev,
sourceDir: null,
runtimeConfigPath: overlayPath,
});
assert.equal(report.runtime_overlay, overlayPath);
assert.equal(report.providers.google.config_count, 2);
// Without the overlay the same tracked file has no google provider at all.
const bare = await runSync({
configPath,
modelsDevSpec: modelsDev,
sourceDir: null,
runtimeConfigPath: path.join(dir, 'absent.jsonc'),
});
assert.equal(bare.report.runtime_overlay, null);
assert.equal(bare.report.providers.google, undefined);
});
27 changes: 20 additions & 7 deletions bin/sync-models.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,30 @@ const VERBOSE = process.argv.includes('--verbose') || process.argv.includes('-v'

const ROOT_DIR = path.resolve(import.meta.dirname, '..');
const HOME_DIR = process.env.HOME || '/home/user';
// Config resolution (#591): in a repo checkout, sync the repo's own
// .opencode/opencode.jsonc. When home-manager installs this script it lands
// alone in the Nix store, so ROOT_DIR resolves to /nix and the repo-relative
// path never exists — fall back to the deployed user config, which is the
// file the sync-models service actually maintains. $OPENCODE_CONFIG_PATH
// overrides both.
// Config resolution (#591, #4544): the model catalogs this script maintains
// live in the runtime overlay (~/.local/state/opencode/opencode-runtime.jsonc),
// which the OpenCode server layers over the tracked configured default via
// OPENCODE_CONFIG. The tracked file carries deliberate configuration only,
// so these automatic rewrites never dirty the repo tree. $OPENCODE_CONFIG_PATH
// overrides everything. When no runtime overlay exists yet (pre-split
// installs), fall back to the historical chain: in a repo checkout, sync the
// repo's own .opencode/opencode.jsonc; when home-manager installs this script
// it lands alone in the Nix store, so ROOT_DIR resolves to /nix and the
// repo-relative path never exists — fall back to the deployed user config,
// which is the file the sync-models service actually maintains.
const RUNTIME_CONFIG_PATH = path.join(
HOME_DIR,
'.local/state/opencode/opencode-runtime.jsonc',
);
const REPO_CONFIG_PATH = path.join(ROOT_DIR, '.opencode/opencode.jsonc');
const USER_CONFIG_PATH = path.join(HOME_DIR, '.config/opencode/opencode.jsonc');
const OPENCODE_CONFIG_PATH =
process.env.OPENCODE_CONFIG_PATH ||
(fs.existsSync(REPO_CONFIG_PATH) ? REPO_CONFIG_PATH : USER_CONFIG_PATH);
(fs.existsSync(RUNTIME_CONFIG_PATH)
? RUNTIME_CONFIG_PATH
: fs.existsSync(REPO_CONFIG_PATH)
? REPO_CONFIG_PATH
: USER_CONFIG_PATH);
const POLICY_PATH = path.join(import.meta.dirname, 'sync-models.policy.json');
const CODEX_CACHE_PATH = path.join(HOME_DIR, '.codex/models_cache.json');
const GEMINI_CACHE_PATH = path.join(HOME_DIR, '.gemini/antigravity_models_cache.json');
Expand Down
12 changes: 12 additions & 0 deletions home/common/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,11 @@ in
};
Service = {
Type = "oneshot";
# #4544: sync-models maintains the runtime overlay, never the tracked
# configured default — its rewrites must not dirty the repo tree.
Environment = [
"OPENCODE_CONFIG_PATH=%h/.local/state/opencode/opencode-runtime.jsonc"
];
ExecStart = toString (
pkgs.writeShellScript "sync-models-run" ''
export PATH="/run/current-system/sw/bin:$HOME/.gemini/bin:$HOME/.local/bin:$PATH"
Expand Down Expand Up @@ -1596,6 +1601,13 @@ in
# reads OPENCODE_DISABLE_FILEWATCHER; the EXPERIMENTAL_ name was
# read nowhere, so the watcher was silently still on.)
OPENCODE_DISABLE_FILEWATCHER = "1";
# Config split (#4544): the runtime overlay — the provider catalogs
# sync-models maintains, plus the server's own runtime config patches
# — layers over the tracked configured default
# (.opencode/opencode.jsonc). OPENCODE_CONFIG is the server's explicit
# config layer; OPENCODE_CONFIG_PATH points sync-models at the file.
OPENCODE_CONFIG = "$HOME/.local/state/opencode/opencode-runtime.jsonc";
OPENCODE_CONFIG_PATH = "$HOME/.local/state/opencode/opencode-runtime.jsonc";
# XDG_CACHE_HOME = "$HOME/.cache";
# XDG_CONFIG_DIRS = "/etc/xdg";
# XDG_CONFIG_HOME = "$HOME/.config";
Expand Down
12 changes: 11 additions & 1 deletion pm-stack/aggregator/scripts/collect-fleet-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ const snapshotOutboxPath = process.env.USAGE_SNAPSHOT_OUTBOX_PATH ?? join(HIDDEN
const chargeCandidatesPath = process.env.CHARGE_CANDIDATES_PATH ?? join(HIDDEN, "charges-candidates.json");
const chargesSurfacedStatePath = process.env.CHARGES_SURFACED_STATE_PATH ?? join(HIDDEN, "charges-surfaced-state.json");
const opencodeConfigPath = process.env.AA_OPENCODE_CONFIG_PATH ?? join(PKG, "..", "..", ".opencode", "opencode.jsonc");
const opencodeRuntimeConfigPath =
process.env.AA_OPENCODE_RUNTIME_CONFIG_PATH ?? join(HOME, ".local", "state", "opencode", "opencode-runtime.jsonc");
const serverUrl = process.env.OPENCODE_SERVER_URL ?? process.env.SANDBOX_OPENCODE_URL ?? "http://127.0.0.1:4096";
/** Session source label for the scraped server: the collector's home host
* decides — the laptop collector labels its local server
Expand Down Expand Up @@ -505,7 +507,15 @@ async function collectAaSection(generatedAt: string): Promise<AaFeedSection> {
} catch {
console.error("collector: opencode.jsonc unreadable; AA coverage omitted this run");
}
const section = aaSectionFromSupabase(raw, configText, generatedAt);
// #4544: the sync-models-owned provider catalogs live in the runtime
// overlay; read it when present so AA coverage sees the effective config.
let runtimeText: string | null = null;
try {
runtimeText = await readFile(opencodeRuntimeConfigPath, "utf8");
} catch {
runtimeText = null;
}
const section = aaSectionFromSupabase(raw, configText, generatedAt, runtimeText);
if (!section) return degrade("Supabase payload failed its structural check");
await writeAaLastGood({ batch: section.batch, configFingerprint: fingerprint, section });
return section;
Expand Down
Loading
Loading