Skip to content
Open
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
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ Create `~/.config/opencode/opencode-synced.jsonc`:
"includeModelFavorites": true,
"includeOpencodeSkills": true,
"includeAgentsDir": true,
"modelRemap": {},
"extraSecretPaths": [],
"extraConfigPaths": [],
}
Expand All @@ -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/`
Expand Down
83 changes: 83 additions & 0 deletions src/sync/apply.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
});
48 changes: 46 additions & 2 deletions src/sync/apply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -51,7 +59,7 @@ interface ExtraPathManifest {
export async function syncRepoToLocal(
plan: SyncPlan,
overrides: Record<string, unknown> | null,
options: { chunkOptions?: ChunkOptions } = {}
options: { chunkOptions?: ChunkOptions; modelRemap?: ModelRemap } = {}
): Promise<void> {
for (const item of plan.items) {
if (item.chunkLargeFiles) {
Expand All @@ -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);
}
Expand Down Expand Up @@ -93,8 +105,11 @@ export async function syncLocalToRepo(
overridesPath?: string;
allowMcpSecrets?: boolean;
chunkOptions?: ChunkOptions;
modelRemap?: ModelRemap;
} = {}
): Promise<void> {
const inverseRemap = invertModelRemap(options.modelRemap);
const hasInverseRemap = !isEmptyRemap(inverseRemap);
const configItems = plan.items.filter((item) => item.isConfigFile);
const sanitizedConfigs = new Map<string, Record<string, unknown>>();
let secretOverrides: Record<string, unknown> = {};
Expand All @@ -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<Record<string, unknown>>(content);
const parsed = remapConfigModels(parseJsonc<Record<string, unknown>>(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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -500,6 +520,30 @@ async function readRepoConfig(
return parseJsonc<Record<string, unknown>>(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<void> {
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<Record<string, unknown>>(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<string, unknown>
Expand Down
10 changes: 10 additions & 0 deletions src/sync/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([]);
Expand Down
20 changes: 20 additions & 0 deletions src/sync/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ export interface SecretsBackendConfig {

export type SessionBackendType = 'git' | 'turso';

export type ModelRemapConfig = Record<string, string>;

export interface TursoSessionBackendSettings {
database?: string;
url?: string;
Expand Down Expand Up @@ -61,6 +63,7 @@ export interface SyncConfig {
includeModelFavorites?: boolean;
includeOpencodeSkills?: boolean;
includeAgentsDir?: boolean;
modelRemap?: ModelRemapConfig;
secretsBackend?: SecretsBackendConfig;
extraSecretPaths?: string[];
extraConfigPaths?: string[];
Expand All @@ -75,6 +78,7 @@ export interface NormalizedSyncConfig extends SyncConfig {
includeModelFavorites: boolean;
includeOpencodeSkills: boolean;
includeAgentsDir: boolean;
modelRemap: ModelRemapConfig;
secretsBackend?: SecretsBackendConfig;
extraSecretPaths: string[];
extraConfigPaths: string[];
Expand Down Expand Up @@ -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);
Expand All @@ -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 : [],
Expand Down
93 changes: 93 additions & 0 deletions src/sync/model-remap.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
Loading
Loading