diff --git a/README.md b/README.md index d371aee..31f16e2 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,7 @@ Create `~/.config/opencode/opencode-synced.jsonc`: "includeModelFavorites": true, "includeOpencodeSkills": true, "includeAgentsDir": true, + "modelRemap": {}, "extraSecretPaths": [], "extraConfigPaths": [], } @@ -155,6 +156,27 @@ Create `~/.config/opencode/opencode-synced.jsonc`: Review it before syncing, keep the sync repository private when needed, or set `"includeAgentsDir": false` to opt out. +### Model remap + +Agent and command files often pin a `model:` that only exists on some machines. Set `modelRemap` +in `opencode-synced.jsonc` to translate those values per machine: + +```jsonc +{ + "modelRemap": { + "some-provider/some-model": "other-provider/other-model" + } +} +``` + +- On pull, the `model:` frontmatter key of markdown files in `agent/`, `agents/`, `command/`, + `commands/`, `mode/` and `modes/`, and the `model` and `small_model` values in + `opencode.json(c)`, are rewritten to the local value. +- On push, the mapping is reversed, so the repository keeps the canonical value. If two canonical + values map to the same local value, that local value is left as is on push. +- A `#variant` suffix is preserved when only the base model is mapped. +- Only exact model strings are replaced. Prompt bodies and other keys are never touched. + Disable default directory sync by setting: - `"includeOpencodeSkills": false` to skip `~/.config/opencode/skills/` - `"includeAgentsDir": false` to skip `~/.agents/` diff --git a/src/sync/apply.test.ts b/src/sync/apply.test.ts index 1d881c1..c2bad8f 100644 --- a/src/sync/apply.test.ts +++ b/src/sync/apply.test.ts @@ -902,3 +902,86 @@ describe('MCP secret scrub round trip', () => { }); }); }); + +describe('model remap on pull and push', () => { + const REMAP = { 'claude-agent/opus': 'vercel/anthropic/claude-opus-5.5' }; + + async function seed(root: string): Promise<{ + plan: SyncPlan; + repoAgent: string; + localAgent: string; + repoConfig: string; + localConfig: string; + }> { + const repoRoot = path.join(root, 'repo'); + const homeDir = path.join(root, 'home'); + const configRoot = path.join(homeDir, '.config', 'opencode'); + const repoAgent = path.join(repoRoot, 'config', 'agents', 'lead.md'); + const localAgent = path.join(configRoot, 'agents', 'lead.md'); + const repoConfig = path.join(repoRoot, 'config', 'opencode.json'); + const localConfig = path.join(configRoot, 'opencode.json'); + await fs.mkdir(path.dirname(repoAgent), { recursive: true }); + await fs.writeFile( + repoAgent, + '---\nmodel: claude-agent/opus\nmode: primary\n---\nPrompt\n', + 'utf8' + ); + await fs.writeFile(repoConfig, '{"agent":{"lead":{"model":"claude-agent/opus"}}}\n', 'utf8'); + const plan = createPlan(repoRoot, homeDir, [ + { + localPath: localConfig, + repoPath: repoConfig, + type: 'file', + isSecret: false, + isConfigFile: true, + }, + { + localPath: path.dirname(localAgent), + repoPath: path.dirname(repoAgent), + type: 'dir', + isSecret: false, + isConfigFile: false, + }, + ]); + return { plan, repoAgent, localAgent, repoConfig, localConfig }; + } + + it('applies the remap to agent files and opencode.json on pull', async () => { + await withTempDir(async (root) => { + const { plan, localAgent, localConfig } = await seed(root); + + await syncRepoToLocal(plan, null, { modelRemap: REMAP }); + + expect(await fs.readFile(localAgent, 'utf8')).toContain( + 'model: vercel/anthropic/claude-opus-5.5' + ); + expect(await fs.readFile(localConfig, 'utf8')).toContain('vercel/anthropic/claude-opus-5.5'); + }); + }); + + it('writes canonical models back to the repo on push, leaving no diff after a pull', async () => { + await withTempDir(async (root) => { + const { plan, repoAgent, repoConfig } = await seed(root); + const repoAgentBefore = await fs.readFile(repoAgent, 'utf8'); + const repoConfigBefore = await fs.readFile(repoConfig, 'utf8'); + + await syncRepoToLocal(plan, null, { modelRemap: REMAP }); + await syncLocalToRepo(plan, null, { modelRemap: REMAP }); + + expect(await fs.readFile(repoAgent, 'utf8')).toBe(repoAgentBefore); + expect(parseJsonc(await fs.readFile(repoConfig, 'utf8'))).toEqual( + parseJsonc(repoConfigBefore) + ); + }); + }); + + it('does nothing when no remap is configured', async () => { + await withTempDir(async (root) => { + const { plan, localAgent } = await seed(root); + + await syncRepoToLocal(plan, null); + + expect(await fs.readFile(localAgent, 'utf8')).toContain('model: claude-agent/opus'); + }); + }); +}); diff --git a/src/sync/apply.ts b/src/sync/apply.ts index 0e0e9f7..2be6ff0 100644 --- a/src/sync/apply.ts +++ b/src/sync/apply.ts @@ -22,6 +22,14 @@ import { mergeOverrides, stripOverrideKeys, } from './mcp-secrets.js'; +import { + invertModelRemap, + isEmptyRemap, + MODEL_REMAP_DIR_NAMES, + type ModelRemap, + remapConfigModels, + remapMarkdownDirectory, +} from './model-remap.js'; import type { ExtraPathPlan, SyncItem, SyncPlan } from './paths.js'; import { fromPortablePath, normalizePath, toPortablePath } from './paths.js'; @@ -51,7 +59,7 @@ interface ExtraPathManifest { export async function syncRepoToLocal( plan: SyncPlan, overrides: Record | null, - options: { chunkOptions?: ChunkOptions } = {} + options: { chunkOptions?: ChunkOptions; modelRemap?: ModelRemap } = {} ): Promise { for (const item of plan.items) { if (item.chunkLargeFiles) { @@ -64,6 +72,10 @@ export async function syncRepoToLocal( await applyExtraPaths(plan, plan.extraConfigs); await applyExtraPaths(plan, plan.extraSecrets); + if (!isEmptyRemap(options.modelRemap)) { + await applyModelRemapToLocal(plan, options.modelRemap as ModelRemap); + } + if (overrides && Object.keys(overrides).length > 0) { await applyOverridesToLocalConfig(plan, overrides); } @@ -93,8 +105,11 @@ export async function syncLocalToRepo( overridesPath?: string; allowMcpSecrets?: boolean; chunkOptions?: ChunkOptions; + modelRemap?: ModelRemap; } = {} ): Promise { + const inverseRemap = invertModelRemap(options.modelRemap); + const hasInverseRemap = !isEmptyRemap(inverseRemap); const configItems = plan.items.filter((item) => item.isConfigFile); const sanitizedConfigs = new Map>(); let secretOverrides: Record = {}; @@ -104,10 +119,12 @@ export async function syncLocalToRepo( if (!(await pathExists(item.localPath))) continue; const content = await fs.readFile(item.localPath, 'utf8'); - const parsed = parseJsonc>(content); + const parsed = remapConfigModels(parseJsonc>(content), inverseRemap); const { sanitizedConfig, secretOverrides: extracted } = extractMcpSecrets(parsed); if (!allowMcpSecrets) { sanitizedConfigs.set(item.localPath, sanitizedConfig); + } else if (hasInverseRemap) { + sanitizedConfigs.set(item.localPath, parsed); } if (hasOverrides(extracted)) { secretOverrides = mergeOverrides(secretOverrides, extracted); @@ -144,6 +161,9 @@ export async function syncLocalToRepo( } await copyItem(item.localPath, item.repoPath, item.type, !item.preserveWhenMissing); + if (hasInverseRemap && isModelRemapDirectory(item)) { + await remapMarkdownDirectory(item.repoPath, inverseRemap); + } } await writeExtraPathManifest(plan, plan.extraConfigs); @@ -500,6 +520,30 @@ async function readRepoConfig( return parseJsonc>(content); } +function isModelRemapDirectory(item: SyncItem): boolean { + if (item.type !== 'dir' || item.isSecret) return false; + return MODEL_REMAP_DIR_NAMES.has(path.basename(item.localPath)); +} + +async function applyModelRemapToLocal(plan: SyncPlan, remap: ModelRemap): Promise { + for (const item of plan.items) { + if (isModelRemapDirectory(item)) { + await remapMarkdownDirectory(item.localPath, remap); + continue; + } + if (!item.isConfigFile || !(await pathExists(item.localPath))) continue; + + const parsed = parseJsonc>(await fs.readFile(item.localPath, 'utf8')); + const remapped = remapConfigModels(parsed, remap); + if (isDeepEqual(parsed, remapped)) continue; + const stat = await fs.stat(item.localPath); + await writeJsonFile(item.localPath, remapped, { + jsonc: item.localPath.endsWith('.jsonc'), + mode: stat.mode & 0o777, + }); + } +} + async function applyOverridesToLocalConfig( plan: SyncPlan, overrides: Record diff --git a/src/sync/config.test.ts b/src/sync/config.test.ts index 7e4ff1c..31e5744 100644 --- a/src/sync/config.test.ts +++ b/src/sync/config.test.ts @@ -152,6 +152,16 @@ describe('normalizeSyncConfig', () => { expect(normalized.includeAgentsDir).toBe(false); }); + it('normalizes modelRemap and drops invalid entries', () => { + expect(normalizeSyncConfig({}).modelRemap).toEqual({}); + expect( + normalizeSyncConfig({ + modelRemap: { 'a/b': 'c/d', same: 'same', empty: '', num: 1 as never }, + }).modelRemap + ).toEqual({ 'a/b': 'c/d' }); + expect(normalizeSyncConfig({ modelRemap: 'nope' as never }).modelRemap).toEqual({}); + }); + it('defaults extra path lists when omitted', () => { const normalized = normalizeSyncConfig({ includeSecrets: true }); expect(normalized.extraSecretPaths).toEqual([]); diff --git a/src/sync/config.ts b/src/sync/config.ts index d22e1cc..2a7ded9 100644 --- a/src/sync/config.ts +++ b/src/sync/config.ts @@ -26,6 +26,8 @@ export interface SecretsBackendConfig { export type SessionBackendType = 'git' | 'turso'; +export type ModelRemapConfig = Record; + export interface TursoSessionBackendSettings { database?: string; url?: string; @@ -61,6 +63,7 @@ export interface SyncConfig { includeModelFavorites?: boolean; includeOpencodeSkills?: boolean; includeAgentsDir?: boolean; + modelRemap?: ModelRemapConfig; secretsBackend?: SecretsBackendConfig; extraSecretPaths?: string[]; extraConfigPaths?: string[]; @@ -75,6 +78,7 @@ export interface NormalizedSyncConfig extends SyncConfig { includeModelFavorites: boolean; includeOpencodeSkills: boolean; includeAgentsDir: boolean; + modelRemap: ModelRemapConfig; secretsBackend?: SecretsBackendConfig; extraSecretPaths: string[]; extraConfigPaths: string[]; @@ -168,6 +172,21 @@ export function normalizeSessionBackend( }; } +export function normalizeModelRemap(input: unknown): ModelRemapConfig { + if (!isPlainObject(input)) return {}; + const result: ModelRemapConfig = {}; + for (const [from, to] of Object.entries(input)) { + if (typeof to !== 'string' || !from.trim() || !to.trim() || from === to) continue; + Object.defineProperty(result, from, { + value: to, + enumerable: true, + writable: true, + configurable: true, + }); + } + return result; +} + export function isTursoSessionBackend(config: SyncConfig | NormalizedSyncConfig): boolean { if (!config.includeSessions) return false; const normalized = normalizeSessionBackend(config.sessionBackend); @@ -188,6 +207,7 @@ export function normalizeSyncConfig(config: SyncConfig): NormalizedSyncConfig { includeModelFavorites, includeOpencodeSkills, includeAgentsDir, + modelRemap: normalizeModelRemap(config.modelRemap), secretsBackend: normalizeSecretsBackend(config.secretsBackend), extraSecretPaths: Array.isArray(config.extraSecretPaths) ? config.extraSecretPaths : [], extraConfigPaths: Array.isArray(config.extraConfigPaths) ? config.extraConfigPaths : [], diff --git a/src/sync/model-remap.test.ts b/src/sync/model-remap.test.ts new file mode 100644 index 0000000..bfee5f7 --- /dev/null +++ b/src/sync/model-remap.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest'; +import { + invertModelRemap, + remapConfigModels, + remapFrontmatterModel, + remapModelString, +} from './model-remap.js'; + +const REMAP = { 'claude-agent/opus': 'vercel/anthropic/claude-opus-5.5' }; + +describe('remapModelString', () => { + it('maps exact matches and keeps unknown values', () => { + expect(remapModelString('claude-agent/opus', REMAP)).toBe('vercel/anthropic/claude-opus-5.5'); + expect(remapModelString('other/model', REMAP)).toBe('other/model'); + }); + + it('keeps a variant suffix when only the base model is mapped', () => { + expect(remapModelString('claude-agent/opus#high', REMAP)).toBe( + 'vercel/anthropic/claude-opus-5.5#high' + ); + }); + + it('does not read inherited object properties', () => { + expect(remapModelString('constructor', REMAP)).toBe('constructor'); + expect(remapModelString('__proto__', REMAP)).toBe('__proto__'); + }); +}); + +describe('invertModelRemap', () => { + it('reverses one-to-one entries and drops ambiguous targets', () => { + expect(invertModelRemap({ a: 'x', b: 'y', c: 'y' })).toEqual({ x: 'a' }); + }); +}); + +describe('remapFrontmatterModel', () => { + it('rewrites only the model key of the leading frontmatter', () => { + const input = [ + '---', + 'description: Worker', + 'model: claude-agent/opus', + 'mode: primary', + '---', + '', + 'model: claude-agent/opus is mentioned in the body and must stay.', + '', + ].join('\n'); + const output = remapFrontmatterModel(input, REMAP); + expect(output).toContain('model: vercel/anthropic/claude-opus-5.5\nmode: primary'); + expect(output).toContain('model: claude-agent/opus is mentioned in the body'); + }); + + it('keeps quotes and CRLF line endings', () => { + const input = '---\r\nmodel: "claude-agent/opus"\r\n---\r\nbody\r\n'; + expect(remapFrontmatterModel(input, REMAP)).toBe( + '---\r\nmodel: "vercel/anthropic/claude-opus-5.5"\r\n---\r\nbody\r\n' + ); + }); + + it('leaves files without frontmatter or without a model alone', () => { + expect(remapFrontmatterModel('no frontmatter\nmodel: claude-agent/opus\n', REMAP)).toBe( + 'no frontmatter\nmodel: claude-agent/opus\n' + ); + expect(remapFrontmatterModel('---\nmode: all\n---\nx\n', REMAP)).toBe( + '---\nmode: all\n---\nx\n' + ); + }); + + it('does not touch an indented model key', () => { + const input = '---\noptions:\n model: claude-agent/opus\n---\n'; + expect(remapFrontmatterModel(input, REMAP)).toBe(input); + }); +}); + +describe('remapConfigModels', () => { + it('remaps model and small_model at any depth without mutating the input', () => { + const input = { + model: 'claude-agent/opus', + small_model: 'claude-agent/opus', + agent: { lead: { model: 'claude-agent/opus', description: 'claude-agent/opus' } }, + list: [{ model: 'claude-agent/opus' }], + }; + const output = remapConfigModels(input, REMAP); + expect(output).toEqual({ + model: 'vercel/anthropic/claude-opus-5.5', + small_model: 'vercel/anthropic/claude-opus-5.5', + agent: { + lead: { model: 'vercel/anthropic/claude-opus-5.5', description: 'claude-agent/opus' }, + }, + list: [{ model: 'vercel/anthropic/claude-opus-5.5' }], + }); + expect(input.model).toBe('claude-agent/opus'); + }); +}); diff --git a/src/sync/model-remap.ts b/src/sync/model-remap.ts new file mode 100644 index 0000000..56e81c1 --- /dev/null +++ b/src/sync/model-remap.ts @@ -0,0 +1,124 @@ +import { type Dirent, promises as fs } from 'node:fs'; +import path from 'node:path'; + +/** Maps a canonical `provider/model` string (as stored in the repo) to this machine's value. */ +export type ModelRemap = Record; + +/** Directory names whose markdown files carry a `model:` frontmatter key. */ +export const MODEL_REMAP_DIR_NAMES: ReadonlySet = new Set([ + 'agent', + 'agents', + 'command', + 'commands', + 'mode', + 'modes', +]); + +const MODEL_KEYS: ReadonlySet = new Set(['model', 'small_model']); +const FRONTMATTER = /^(---[ \t]*\r?\n)([\s\S]*?)(\r?\n---[ \t]*(?:\r?\n|$))/; +const MODEL_LINE = /^(model:[ \t]*)(["']?)([^\r\n"']+?)(["']?)([ \t]*)$/gm; + +export function isEmptyRemap(remap: ModelRemap | undefined): boolean { + return !remap || Object.keys(remap).length === 0; +} + +/** + * Reverses a remap so local values can be turned back into canonical ones on push. + * A local value that two canonical values map to is ambiguous and is left out. + */ +export function invertModelRemap(remap: ModelRemap | undefined): ModelRemap { + const inverse: ModelRemap = {}; + const ambiguous = new Set(); + for (const [canonical, local] of Object.entries(remap ?? {})) { + if (hasOwn(inverse, local)) { + ambiguous.add(local); + continue; + } + inverse[local] = canonical; + } + for (const local of ambiguous) { + delete inverse[local]; + } + return inverse; +} + +/** Remaps one model string. A trailing `#variant` is kept when only the base model is mapped. */ +export function remapModelString(value: string, remap: ModelRemap): string { + if (hasOwn(remap, value)) return remap[value] as string; + const hashIndex = value.lastIndexOf('#'); + if (hashIndex <= 0) return value; + const base = value.slice(0, hashIndex); + if (!hasOwn(remap, base)) return value; + return `${remap[base]}${value.slice(hashIndex)}`; +} + +/** Remaps the `model:` key of a markdown file's leading frontmatter block. */ +export function remapFrontmatterModel(content: string, remap: ModelRemap): string { + if (isEmptyRemap(remap)) return content; + const match = FRONTMATTER.exec(content); + if (!match) return content; + const [whole, open, body, close] = match as unknown as [string, string, string, string]; + const rewritten = body.replace( + MODEL_LINE, + (_line, key: string, openQuote: string, value: string, closeQuote: string, tail: string) => + `${key}${openQuote}${remapModelString(value, remap)}${closeQuote}${tail}` + ); + if (rewritten === body) return content; + return `${open}${rewritten}${close}${content.slice(whole.length)}`; +} + +/** Remaps `model` and `small_model` string values anywhere in a parsed config document. */ +export function remapConfigModels(value: T, remap: ModelRemap): T { + if (isEmptyRemap(remap)) return value; + return remapNode(value, remap) as T; +} + +function remapNode(value: unknown, remap: ModelRemap): unknown { + if (Array.isArray(value)) { + return value.map((item) => remapNode(item, remap)); + } + if (!value || typeof value !== 'object') return value; + const result: Record = {}; + for (const [key, child] of Object.entries(value)) { + const remapped = + MODEL_KEYS.has(key) && typeof child === 'string' + ? remapModelString(child, remap) + : remapNode(child, remap); + Object.defineProperty(result, key, { + value: remapped, + enumerable: true, + writable: true, + configurable: true, + }); + } + return result; +} + +/** Rewrites the `model:` frontmatter key of every markdown file below `directory`. */ +export async function remapMarkdownDirectory(directory: string, remap: ModelRemap): Promise { + if (isEmptyRemap(remap)) return; + let entries: Dirent[]; + try { + entries = await fs.readdir(directory, { withFileTypes: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; + throw error; + } + for (const entry of entries) { + const entryPath = path.join(directory, entry.name); + if (entry.isDirectory()) { + await remapMarkdownDirectory(entryPath, remap); + continue; + } + if (!entry.isFile() || !entry.name.endsWith('.md')) continue; + const content = await fs.readFile(entryPath, 'utf8'); + const rewritten = remapFrontmatterModel(content, remap); + if (rewritten !== content) { + await fs.writeFile(entryPath, rewritten, 'utf8'); + } + } +} + +function hasOwn(target: object, key: string): boolean { + return Object.hasOwn(target, key); +} diff --git a/src/sync/service.ts b/src/sync/service.ts index ba27d7a..f685281 100644 --- a/src/sync/service.ts +++ b/src/sync/service.ts @@ -923,7 +923,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { const overrides = await loadOverrides(locations); const plan = buildSyncPlan(config, locations, repoRoot); - await syncRepoToLocal(plan, overrides); + await syncRepoToLocal(plan, overrides, { modelRemap: config.modelRemap }); await updateState(locations, { lastPull: new Date().toISOString(), @@ -1020,7 +1020,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { const overrides = await loadOverrides(locations); const plan = buildSyncPlan(config, locations, repoRoot); - await syncRepoToLocal(plan, overrides); + await syncRepoToLocal(plan, overrides, { modelRemap: config.modelRemap }); await runSecretsPullIfConfigured(config); await updateState(locations, { @@ -1061,6 +1061,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { await syncLocalToRepo(plan, overrides, { overridesPath: locations.overridesPath, allowMcpSecrets: canCommitMcpSecrets(config), + modelRemap: config.modelRemap, }); await assertNoOversizedUnpushedHistory(ctx.$, repoRoot, branch); @@ -1479,7 +1480,7 @@ async function runStartup( log.info('Pulled remote changes', { branch }); const overrides = await loadOverrides(locations); const plan = buildSyncPlan(config, locations, repoRoot); - await syncRepoToLocal(plan, overrides); + await syncRepoToLocal(plan, overrides, { modelRemap: config.modelRemap }); await options.runSecretsPullIfConfigured(config); await updateState(locations, { lastPull: new Date().toISOString(), @@ -1494,6 +1495,7 @@ async function runStartup( await syncLocalToRepo(plan, overrides, { overridesPath: locations.overridesPath, allowMcpSecrets: canCommitMcpSecrets(config), + modelRemap: config.modelRemap, }); await assertNoOversizedUnpushedHistory(ctx.$, repoRoot, branch); const changes = await hasLocalChanges(ctx.$, repoRoot);