mixdog 0.7.17 → 0.7.18
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/UNINSTALL.md +7 -4
- package/bin/statusline-lib.mjs +29 -6
- package/bin/statusline-route.mjs +273 -0
- package/bin/statusline.mjs +31 -8
- package/commands/model.md +61 -0
- package/hooks/session-start.cjs +15 -1
- package/native/prebuilt/linux-aarch64/mixdog-shim +0 -0
- package/native/prebuilt/linux-x86_64/mixdog-shim +0 -0
- package/native/prebuilt/macos-aarch64/mixdog-shim +0 -0
- package/native/prebuilt/macos-x86_64/mixdog-shim +0 -0
- package/native/prebuilt/windows-x86_64/mixdog-shim.exe +0 -0
- package/package.json +1 -1
- package/rules/lead/01-general.md +3 -0
- package/scripts/gateway-model.mjs +596 -0
- package/scripts/lib/gateway-inventory.mjs +178 -0
- package/scripts/lib/gateway-settings.mjs +78 -0
- package/scripts/run-mcp.mjs +26 -1
- package/scripts/statusline-launcher-smoke.mjs +155 -2
- package/scripts/uninstall.mjs +44 -7
- package/server-main.mjs +252 -11
- package/src/agent/index.mjs +96 -5
- package/src/agent/orchestrator/bridge-trace.mjs +18 -0
- package/src/agent/orchestrator/providers/anthropic-oauth.mjs +4 -1
- package/src/agent/orchestrator/providers/anthropic.mjs +6 -2
- package/src/agent/orchestrator/session/loop.mjs +145 -4
- package/src/agent/orchestrator/session/trim.mjs +1 -1
- package/src/agent/orchestrator/tools/builtin/arg-guard.mjs +62 -6
- package/src/agent/orchestrator/tools/graph-manifest.json +11 -11
- package/src/agent/orchestrator/tools/patch-manifest.json +7 -7
- package/src/agent/tool-defs.mjs +10 -3
- package/src/channels/lib/runtime-paths.mjs +39 -4
- package/src/gateway/claude-current.mjs +255 -0
- package/src/gateway/oauth-usage.mjs +598 -0
- package/src/gateway/route-meta.mjs +629 -0
- package/src/gateway/server.mjs +713 -0
- package/src/shared/llm/cost.mjs +1 -1
- package/src/shared/seed.mjs +25 -0
- package/tools.json +21 -3
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* mixdog gateway model selector — backs the /mixdog:model slash command.
|
|
4
|
+
*
|
|
5
|
+
* Usage:
|
|
6
|
+
* bun scripts/gateway-model.mjs # list providers/models + current target
|
|
7
|
+
* bun scripts/gateway-model.mjs --json # same, machine-readable
|
|
8
|
+
* bun scripts/gateway-model.mjs --set <provider> [model] # set routing target (config only)
|
|
9
|
+
* bun scripts/gateway-model.mjs --enable <provider> [model] # set routing + modules.gateway.enabled
|
|
10
|
+
* # AND point Claude Code at the gateway
|
|
11
|
+
* bun scripts/gateway-model.mjs --disable # remove the settings.json env entry
|
|
12
|
+
* # (and set modules.gateway.enabled=false)
|
|
13
|
+
* bun scripts/gateway-model.mjs on [provider] [model] # alias of --enable; bare `on` reuses
|
|
14
|
+
* # the current target
|
|
15
|
+
* bun scripts/gateway-model.mjs off # alias of --disable
|
|
16
|
+
*
|
|
17
|
+
* --set / --enable write gateway.defaultProvider / gateway.defaultModel and
|
|
18
|
+
* modules.gateway.enabled into mixdog-config.json through the SAME write path
|
|
19
|
+
* the setup UI uses (updateSection from src/shared/config.mjs: file lock +
|
|
20
|
+
* atomic RMW + backup restore). When <model> is omitted, the provider's first
|
|
21
|
+
* preset model (or its configured `model`) is used.
|
|
22
|
+
*
|
|
23
|
+
* Only --enable / --disable ever touch Claude Code's settings.json:
|
|
24
|
+
* • --enable writes env.ANTHROPIC_BASE_URL = http://127.0.0.1:<gatewayPort>
|
|
25
|
+
* • --disable removes that one env key (restore), leaving env otherwise intact
|
|
26
|
+
* via the SAME safe read-merge-write path injectStatusLine() uses in
|
|
27
|
+
* hooks/session-start.cjs (.mixdog-tmp sibling + atomic rename).
|
|
28
|
+
*
|
|
29
|
+
* If the gateway child is RUNNING, it re-reads gateway.defaultProvider /
|
|
30
|
+
* gateway.defaultModel per request (1.5s TTL cache) and lazily inits the
|
|
31
|
+
* selected provider, so a routing change takes effect on the NEXT request
|
|
32
|
+
* WITHOUT a gateway restart. server-main also watches modules.gateway.enabled,
|
|
33
|
+
* so --enable/`on` live-starts the gateway child and --disable/`off` live-stops
|
|
34
|
+
* it in the current daemon. Claude Code itself still reads ANTHROPIC_BASE_URL
|
|
35
|
+
* only at process start, so settings.json changes require a Claude Code restart
|
|
36
|
+
* if the current process did not already load that env.
|
|
37
|
+
*
|
|
38
|
+
* Pure Node/Bun built-ins + the shared config module. Exit 0 on success,
|
|
39
|
+
* 1 on error / unknown provider.
|
|
40
|
+
*/
|
|
41
|
+
import { dirname, join, basename } from 'path';
|
|
42
|
+
import { existsSync, readFileSync } from 'fs';
|
|
43
|
+
import { tmpdir, homedir } from 'os';
|
|
44
|
+
import { fileURLToPath, pathToFileURL } from 'url';
|
|
45
|
+
import net from 'net';
|
|
46
|
+
import { execFileSync } from 'child_process';
|
|
47
|
+
// Shared settings.json env writer — SAME helper uninstall.mjs uses, so
|
|
48
|
+
// --enable / --disable / uninstall never diverge on path or write mechanics.
|
|
49
|
+
import { resolveSettingsPath, setAnthropicBaseUrl } from './lib/gateway-settings.mjs';
|
|
50
|
+
// Shared inventory + target-write helpers — SAME module the gateway_select_model
|
|
51
|
+
// elicitation tool (src/agent/index.mjs) uses, so the CLI and the interactive
|
|
52
|
+
// dropdown build the model list and persist the target through one code path.
|
|
53
|
+
import { buildInventory as buildInventoryFromConfig, inventoryChoices, resolveTargetChoice, writeGatewayTarget } from './lib/gateway-inventory.mjs';
|
|
54
|
+
import { CLAUDE_CURRENT_CHOICE_ID, CLAUDE_CURRENT_MODE } from '../src/gateway/claude-current.mjs';
|
|
55
|
+
|
|
56
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
57
|
+
const PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT || dirname(__dirname);
|
|
58
|
+
|
|
59
|
+
// The /mixdog:model slash command (commands/model.md) runs
|
|
60
|
+
// `!bun ".../scripts/gateway-model.mjs"` and only interpolates
|
|
61
|
+
// ${CLAUDE_PLUGIN_ROOT} into the PATH argument — it does NOT propagate
|
|
62
|
+
// CLAUDE_PLUGIN_DATA / CLAUDE_PLUGIN_ROOT into the child process env. The
|
|
63
|
+
// shared config module (src/shared/config.mjs) resolves the plugin-data dir at
|
|
64
|
+
// IMPORT time via resolvePluginData() (src/shared/plugin-paths.mjs), which
|
|
65
|
+
// THROWS when both env vars are unset.
|
|
66
|
+
//
|
|
67
|
+
// We CANNOT just seed CLAUDE_PLUGIN_ROOT and let the shared resolver derive the
|
|
68
|
+
// data dir: plugin-paths.mjs derives from homedir()/.claude and IGNORES
|
|
69
|
+
// CLAUDE_CONFIG_DIR. The daemon and doctor.mjs both key off
|
|
70
|
+
// CLAUDE_CONFIG_DIR || ~/.claude, so on a custom-CLAUDE_CONFIG_DIR install that
|
|
71
|
+
// would point /mixdog:model at ~/.claude/.../mixdog-config.json while the
|
|
72
|
+
// daemon writes $CLAUDE_CONFIG_DIR/.../mixdog-config.json — divergent config.
|
|
73
|
+
//
|
|
74
|
+
// Instead, replicate doctor.mjs's self-contained resolvePluginData (which
|
|
75
|
+
// RESPECTS CLAUDE_CONFIG_DIR) and seed CLAUDE_PLUGIN_DATA directly, so the
|
|
76
|
+
// shared resolvePluginData() short-circuits on it and returns the SAME dir the
|
|
77
|
+
// daemon uses. Keep the CLAUDE_PLUGIN_ROOT seed too (harmless; helps any other
|
|
78
|
+
// code that reads it). This keeps both config reads (readSection) and writes
|
|
79
|
+
// (updateSection RMW) targeting the daemon's config file in the slash context.
|
|
80
|
+
if (!process.env.CLAUDE_PLUGIN_ROOT) process.env.CLAUDE_PLUGIN_ROOT = PLUGIN_ROOT;
|
|
81
|
+
function resolveActivePluginData() {
|
|
82
|
+
try {
|
|
83
|
+
const activePath = join(process.env.MIXDOG_RUNTIME_ROOT ? process.env.MIXDOG_RUNTIME_ROOT : join(tmpdir(), 'mixdog'), 'active-instance.json');
|
|
84
|
+
const active = JSON.parse(readFileSync(activePath, 'utf8'));
|
|
85
|
+
const pgData = typeof active?.pg_pgdata === 'string' ? active.pg_pgdata : '';
|
|
86
|
+
if (!pgData) return null;
|
|
87
|
+
const dataDir = dirname(pgData);
|
|
88
|
+
if (existsSync(join(dataDir, 'mixdog-config.json'))) return dataDir;
|
|
89
|
+
} catch { /* fall through */ }
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
if (!process.env.CLAUDE_PLUGIN_DATA) {
|
|
93
|
+
// Exact mirror of doctor.mjs resolvePluginData() (scripts/doctor.mjs:32-49):
|
|
94
|
+
// base = CLAUDE_CONFIG_DIR || ~/.claude, then plugins/data/<plugin>-<marketplace>.
|
|
95
|
+
const claudeConfigBase = () => process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
|
|
96
|
+
const dirName = basename(PLUGIN_ROOT);
|
|
97
|
+
let dataDir = resolveActivePluginData();
|
|
98
|
+
if (dataDir) {
|
|
99
|
+
// Source-tree dev commands should operate on the live daemon's data dir,
|
|
100
|
+
// not on a guessed mixdog-mixdog path.
|
|
101
|
+
} else if (/^\d+\.\d+\.\d+/.test(dirName)) {
|
|
102
|
+
// Cache layout: .../cache/{marketplace}/{plugin}/{version}/
|
|
103
|
+
const pluginName = basename(join(PLUGIN_ROOT, '..'));
|
|
104
|
+
const marketplace = basename(join(PLUGIN_ROOT, '..', '..'));
|
|
105
|
+
dataDir = join(claudeConfigBase(), 'plugins', 'data', `${pluginName}-${marketplace}`);
|
|
106
|
+
} else {
|
|
107
|
+
// Marketplace layout: PLUGIN_ROOT itself is the marketplace dir.
|
|
108
|
+
const marketplace = dirName;
|
|
109
|
+
let pluginName = 'mixdog';
|
|
110
|
+
try {
|
|
111
|
+
const manifest = JSON.parse(readFileSync(join(PLUGIN_ROOT, '.claude-plugin', 'plugin.json'), 'utf8'));
|
|
112
|
+
if (typeof manifest?.name === 'string' && manifest.name.trim()) pluginName = manifest.name.trim();
|
|
113
|
+
} catch { /* fall through to default */ }
|
|
114
|
+
dataDir = join(claudeConfigBase(), 'plugins', 'data', `${pluginName}-${marketplace}`);
|
|
115
|
+
}
|
|
116
|
+
process.env.CLAUDE_PLUGIN_DATA = dataDir;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const { readSection, updateSection } = await import(
|
|
120
|
+
pathToFileURL(`${PLUGIN_ROOT}/src/shared/config.mjs`).href
|
|
121
|
+
);
|
|
122
|
+
const { loadConfig } = await import(
|
|
123
|
+
pathToFileURL(`${PLUGIN_ROOT}/src/agent/orchestrator/config.mjs`).href
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
// ── Running-state detection ──────────────────────────────────────────
|
|
127
|
+
// The gateway advertises gateway_port + gateway_server_pid into the shared
|
|
128
|
+
// active-instance.json (see advertiseGatewayPort in src/gateway/server.mjs),
|
|
129
|
+
// under RUNTIME_ROOT. The gateway is "running" iff a port is advertised AND
|
|
130
|
+
// the advertising pid is alive. Mirrors RUNTIME_ROOT + isPidAlive there.
|
|
131
|
+
const RUNTIME_ROOT = process.env.MIXDOG_RUNTIME_ROOT
|
|
132
|
+
? process.env.MIXDOG_RUNTIME_ROOT
|
|
133
|
+
: join(tmpdir(), 'mixdog');
|
|
134
|
+
const ACTIVE_INSTANCE_FILE = join(RUNTIME_ROOT, 'active-instance.json');
|
|
135
|
+
|
|
136
|
+
function isPidAlive(pid) {
|
|
137
|
+
const n = Number(pid);
|
|
138
|
+
if (!Number.isFinite(n) || n <= 0) return false;
|
|
139
|
+
try { process.kill(n, 0); return true; }
|
|
140
|
+
catch (err) { return err && err.code === 'EPERM'; }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function isGatewayRunning() {
|
|
144
|
+
let active = {};
|
|
145
|
+
try { active = JSON.parse(readFileSync(ACTIVE_INSTANCE_FILE, 'utf8')); }
|
|
146
|
+
catch { return { running: false, port: null, pid: null }; }
|
|
147
|
+
const port = Number(active && active.gateway_port);
|
|
148
|
+
const pid = Number(active && active.gateway_server_pid);
|
|
149
|
+
const running = Number.isFinite(port) && port > 0 && isPidAlive(pid);
|
|
150
|
+
return { running, port: running ? port : null, pid: running ? pid : null };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
154
|
+
|
|
155
|
+
function canConnectPort(port, timeoutMs = 400) {
|
|
156
|
+
const n = Number(port);
|
|
157
|
+
if (!Number.isFinite(n) || n <= 0) return Promise.resolve(false);
|
|
158
|
+
return new Promise((resolve) => {
|
|
159
|
+
const socket = net.createConnection({ host: '127.0.0.1', port: n });
|
|
160
|
+
let settled = false;
|
|
161
|
+
const done = (ok) => {
|
|
162
|
+
if (settled) return;
|
|
163
|
+
settled = true;
|
|
164
|
+
try { socket.destroy(); } catch {}
|
|
165
|
+
resolve(!!ok);
|
|
166
|
+
};
|
|
167
|
+
socket.setTimeout(timeoutMs, () => done(false));
|
|
168
|
+
socket.once('connect', () => done(true));
|
|
169
|
+
socket.once('error', () => done(false));
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function pingGatewayModels(port, timeoutMs = 800) {
|
|
174
|
+
const n = Number(port);
|
|
175
|
+
if (!Number.isFinite(n) || n <= 0) return false;
|
|
176
|
+
const ctrl = new AbortController();
|
|
177
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
178
|
+
try {
|
|
179
|
+
const res = await fetch(`http://127.0.0.1:${n}/v1/models`, { signal: ctrl.signal });
|
|
180
|
+
return !!res && res.ok;
|
|
181
|
+
} catch {
|
|
182
|
+
return false;
|
|
183
|
+
} finally {
|
|
184
|
+
clearTimeout(timer);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function waitForGatewayReady(expectedPort, timeoutMs = 12000) {
|
|
189
|
+
const deadline = Date.now() + timeoutMs;
|
|
190
|
+
const expected = Number(expectedPort);
|
|
191
|
+
while (Date.now() < deadline) {
|
|
192
|
+
const gw = isGatewayRunning();
|
|
193
|
+
if (gw.running && Number(gw.port) === expected) {
|
|
194
|
+
const ready = await pingGatewayModels(gw.port);
|
|
195
|
+
if (ready) return { ...gw, ready: true };
|
|
196
|
+
}
|
|
197
|
+
await sleep(250);
|
|
198
|
+
}
|
|
199
|
+
const gw = isGatewayRunning();
|
|
200
|
+
const ready = gw.running && Number(gw.port) === expected && await pingGatewayModels(gw.port);
|
|
201
|
+
return { ...gw, ready: !!ready };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function waitForGatewayStopped(expectedPort, timeoutMs = 8000) {
|
|
205
|
+
const deadline = Date.now() + timeoutMs;
|
|
206
|
+
const expected = Number(expectedPort);
|
|
207
|
+
while (Date.now() < deadline) {
|
|
208
|
+
const gw = isGatewayRunning();
|
|
209
|
+
const portOpen = await canConnectPort(expected);
|
|
210
|
+
if (!gw.running && !portOpen) {
|
|
211
|
+
return { stopped: true, running: false, port: expected, pid: null, portOpen: false };
|
|
212
|
+
}
|
|
213
|
+
await sleep(250);
|
|
214
|
+
}
|
|
215
|
+
const gw = isGatewayRunning();
|
|
216
|
+
const portOpen = await canConnectPort(expected);
|
|
217
|
+
return { stopped: !gw.running && !portOpen, ...gw, port: gw.port || expected, portOpen };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function signalGatewayPid(pid, force = false) {
|
|
221
|
+
const n = Number(pid);
|
|
222
|
+
if (!Number.isFinite(n) || n <= 0) return false;
|
|
223
|
+
try {
|
|
224
|
+
if (force && process.platform === 'win32') {
|
|
225
|
+
execFileSync('taskkill', ['/PID', String(n), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 3000 });
|
|
226
|
+
} else {
|
|
227
|
+
process.kill(n, force ? 'SIGKILL' : 'SIGTERM');
|
|
228
|
+
}
|
|
229
|
+
return true;
|
|
230
|
+
} catch {
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function forceStopGatewayUntilClosed(expectedPort, timeoutMs = 8000) {
|
|
236
|
+
const expected = Number(expectedPort);
|
|
237
|
+
const deadline = Date.now() + timeoutMs;
|
|
238
|
+
const phases = new Map();
|
|
239
|
+
const attemptedPids = [];
|
|
240
|
+
while (Date.now() < deadline) {
|
|
241
|
+
const gw = isGatewayRunning();
|
|
242
|
+
const portOpen = await canConnectPort(expected);
|
|
243
|
+
if (!gw.running && !portOpen) {
|
|
244
|
+
return { stopped: true, running: false, port: expected, pid: null, portOpen: false, forceStopAttempted: attemptedPids.length > 0, forceStopPids: attemptedPids };
|
|
245
|
+
}
|
|
246
|
+
if (gw.pid) {
|
|
247
|
+
const phase = phases.get(gw.pid) || 0;
|
|
248
|
+
if (phase === 0) {
|
|
249
|
+
if (signalGatewayPid(gw.pid, false)) attemptedPids.push(gw.pid);
|
|
250
|
+
phases.set(gw.pid, 1);
|
|
251
|
+
} else if (phase === 1 && Date.now() + 1000 < deadline) {
|
|
252
|
+
signalGatewayPid(gw.pid, true);
|
|
253
|
+
phases.set(gw.pid, 2);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
await sleep(500);
|
|
257
|
+
}
|
|
258
|
+
const gw = isGatewayRunning();
|
|
259
|
+
const portOpen = await canConnectPort(expected);
|
|
260
|
+
return { stopped: !gw.running && !portOpen, ...gw, port: gw.port || expected, portOpen, forceStopAttempted: attemptedPids.length > 0, forceStopPids: attemptedPids };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ── Gateway port resolution ──────────────────────────────────────────
|
|
264
|
+
// Mirrors readGatewayConfig() in src/gateway/server.mjs: env pin →
|
|
265
|
+
// gateway.port → DEFAULT_GATEWAY_PORT (3468). Used to build the
|
|
266
|
+
// ANTHROPIC_BASE_URL written into Claude Code settings.json on --enable.
|
|
267
|
+
const DEFAULT_GATEWAY_PORT = 3468;
|
|
268
|
+
function resolveGatewayPort() {
|
|
269
|
+
const envPort = Number(process.env.MIXDOG_GATEWAY_PORT);
|
|
270
|
+
if (Number.isFinite(envPort) && envPort > 0) return envPort;
|
|
271
|
+
let section = {};
|
|
272
|
+
try { section = readSection('gateway') || {}; } catch { section = {}; }
|
|
273
|
+
const cfgPort = Number(section.port);
|
|
274
|
+
if (Number.isFinite(cfgPort) && cfgPort > 0) return cfgPort;
|
|
275
|
+
return DEFAULT_GATEWAY_PORT;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// settings.json env read-merge-write lives in ./lib/gateway-settings.mjs
|
|
279
|
+
// (resolveSettingsPath / setAnthropicBaseUrl) — the SAME helper uninstall.mjs
|
|
280
|
+
// uses, so --enable / --disable / uninstall share one code path.
|
|
281
|
+
|
|
282
|
+
// ── Inventory: enabled providers + their candidate models ────────────
|
|
283
|
+
// Delegates to the shared lib (./lib/gateway-inventory.mjs) — loadConfig()
|
|
284
|
+
// overlays keychain keys + marks providers enabled; the lib surfaces, per
|
|
285
|
+
// enabled provider, the preset models plus its own configured `model`.
|
|
286
|
+
function buildInventory() {
|
|
287
|
+
return buildInventoryFromConfig(loadConfig());
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function readCurrentTarget() {
|
|
291
|
+
let section = {};
|
|
292
|
+
try { section = readSection('gateway') || {}; } catch { section = {}; }
|
|
293
|
+
let modules = {};
|
|
294
|
+
try { modules = readSection('modules') || {}; } catch { modules = {}; }
|
|
295
|
+
const enabled = !!(modules && typeof modules === 'object' && modules.gateway && modules.gateway.enabled === true);
|
|
296
|
+
return {
|
|
297
|
+
mode: typeof section.mode === 'string' ? section.mode : null,
|
|
298
|
+
provider: typeof section.defaultProvider === 'string' ? section.defaultProvider : null,
|
|
299
|
+
model: typeof section.defaultModel === 'string' ? section.defaultModel : null,
|
|
300
|
+
enabled,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// ── Write path: shared lib (updateSection RMW under lock) ─────────────
|
|
305
|
+
// Delegates to writeGatewayTarget so the CLI --set/--enable and the
|
|
306
|
+
// gateway_select_model elicitation tool persist through one code path.
|
|
307
|
+
function setTarget(provider, model, meta = {}) {
|
|
308
|
+
writeGatewayTarget(updateSection, provider, model, meta);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// modules.gateway.enabled toggle — preserve sibling module toggles.
|
|
312
|
+
function setModuleEnabled(enabled) {
|
|
313
|
+
updateSection('modules', (current) => {
|
|
314
|
+
const cur = current && typeof current === 'object' ? current : {};
|
|
315
|
+
return { ...cur, gateway: { ...(cur.gateway || {}), enabled: !!enabled } };
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function resolveModelForProvider(inventory, provider, explicitModel) {
|
|
320
|
+
if (provider === CLAUDE_CURRENT_CHOICE_ID || provider === CLAUDE_CURRENT_MODE) {
|
|
321
|
+
return resolveTargetChoice(inventory, provider, explicitModel || null, false).model;
|
|
322
|
+
}
|
|
323
|
+
if (explicitModel) return explicitModel;
|
|
324
|
+
const entry = inventory.find((e) => e.provider === provider);
|
|
325
|
+
return entry && entry.models.length ? entry.models[0] : null;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function resolveTargetForProvider(inventory, provider, explicitModel) {
|
|
329
|
+
if (provider === CLAUDE_CURRENT_CHOICE_ID || provider === CLAUDE_CURRENT_MODE) {
|
|
330
|
+
const meta = resolveTargetChoice(inventory, provider, explicitModel || null, false);
|
|
331
|
+
return { model: meta.model, meta };
|
|
332
|
+
}
|
|
333
|
+
const model = resolveModelForProvider(inventory, provider, explicitModel);
|
|
334
|
+
const meta = resolveTargetChoice(inventory, provider, model, !!explicitModel);
|
|
335
|
+
return { model, meta };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function isClaudeCurrentProvider(provider) {
|
|
339
|
+
return provider === CLAUDE_CURRENT_CHOICE_ID || provider === CLAUDE_CURRENT_MODE;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function targetDisplay(provider, model, meta = {}) {
|
|
343
|
+
if (meta?.mode === CLAUDE_CURRENT_MODE || isClaudeCurrentProvider(provider)) {
|
|
344
|
+
const label = meta?.modelDisplay || model || 'current model';
|
|
345
|
+
const suffix = [
|
|
346
|
+
meta?.effort ? String(meta.effort).toUpperCase() : '',
|
|
347
|
+
meta?.fast === true ? 'fast' : '',
|
|
348
|
+
].filter(Boolean).join(' · ');
|
|
349
|
+
return `Claude Code current (${label}${suffix ? ` · ${suffix}` : ''})`;
|
|
350
|
+
}
|
|
351
|
+
return `${provider} / ${model}${meta?.effort ? ` · ${String(meta.effort).toUpperCase()}` : ''}${meta?.fast ? ' · fast' : ''}`;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// ── CLI ──────────────────────────────────────────────────────────────
|
|
355
|
+
const argv = process.argv.slice(2);
|
|
356
|
+
const asJson = argv.includes('--json');
|
|
357
|
+
// Positional aliases backing the slash command's quick toggle:
|
|
358
|
+
// `on` == --enable, reusing the already-configured routing target when no
|
|
359
|
+
// provider is given (or `on <provider> [model]` to also re-point).
|
|
360
|
+
// `off` == --disable.
|
|
361
|
+
const positional = argv.find((a) => !a.startsWith('--'));
|
|
362
|
+
const wantOn = positional === 'on';
|
|
363
|
+
const wantOff = positional === 'off';
|
|
364
|
+
const setIdx = argv.indexOf('--set');
|
|
365
|
+
const enableIdx = argv.indexOf('--enable');
|
|
366
|
+
const wantDisable = argv.includes('--disable') || wantOff;
|
|
367
|
+
|
|
368
|
+
// ── --enable / `on`: config write (routing + module on) + settings.json env ─
|
|
369
|
+
// Only --enable / --disable (and their `on`/`off` aliases) touch settings.json.
|
|
370
|
+
if (enableIdx !== -1 || wantOn) {
|
|
371
|
+
let provider = null;
|
|
372
|
+
let explicitModel = null;
|
|
373
|
+
if (enableIdx !== -1) {
|
|
374
|
+
const nextArg = argv[enableIdx + 1];
|
|
375
|
+
provider = nextArg && !nextArg.startsWith('--') ? nextArg : null;
|
|
376
|
+
const maybeModel = argv[enableIdx + 2];
|
|
377
|
+
explicitModel = maybeModel && !maybeModel.startsWith('--') ? maybeModel : null;
|
|
378
|
+
} else {
|
|
379
|
+
// `on [provider] [model]` — args after the `on` token; when omitted, fall
|
|
380
|
+
// back to the currently configured target so a bare `on` just re-enables it.
|
|
381
|
+
const onIdx = argv.indexOf('on');
|
|
382
|
+
const a1 = argv[onIdx + 1];
|
|
383
|
+
provider = a1 && !a1.startsWith('--') ? a1 : null;
|
|
384
|
+
const a2 = argv[onIdx + 2];
|
|
385
|
+
explicitModel = a2 && !a2.startsWith('--') ? a2 : null;
|
|
386
|
+
if (!provider) {
|
|
387
|
+
const cur = readCurrentTarget();
|
|
388
|
+
provider = cur.mode === CLAUDE_CURRENT_MODE ? CLAUDE_CURRENT_CHOICE_ID : cur.provider;
|
|
389
|
+
explicitModel = cur.model;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (!provider) {
|
|
393
|
+
console.error('error: no provider to enable. Pass one (`on <provider> [model]` / `--enable <provider> [model]`) or set a target first with --set.');
|
|
394
|
+
process.exit(1);
|
|
395
|
+
}
|
|
396
|
+
const inventory = buildInventory();
|
|
397
|
+
const known = inventory.find((e) => e.provider === provider);
|
|
398
|
+
if (!known && !isClaudeCurrentProvider(provider)) {
|
|
399
|
+
const names = inventory.map((e) => e.provider).join(', ') || '(none enabled)';
|
|
400
|
+
console.error(`error: provider "${provider}" is not enabled in the agent config. Enabled: ${names}`);
|
|
401
|
+
process.exit(1);
|
|
402
|
+
}
|
|
403
|
+
const { model, meta } = resolveTargetForProvider(inventory, provider, explicitModel);
|
|
404
|
+
if (!model) {
|
|
405
|
+
console.error(`error: no model resolved for "${provider}" — pass one explicitly: --enable ${provider} <model>`);
|
|
406
|
+
process.exit(1);
|
|
407
|
+
}
|
|
408
|
+
// 1) config: routing + modules.gateway.enabled=true (same path as --set).
|
|
409
|
+
setTarget(provider, model, meta);
|
|
410
|
+
// 2) live daemon: wait for server-main's config watcher to start the child
|
|
411
|
+
// and for the HTTP endpoint to answer before pointing Claude Code at it.
|
|
412
|
+
const port = resolveGatewayPort();
|
|
413
|
+
const url = `http://127.0.0.1:${port}`;
|
|
414
|
+
const ready = await waitForGatewayReady(port);
|
|
415
|
+
if (!ready.ready) {
|
|
416
|
+
if (asJson) {
|
|
417
|
+
console.log(JSON.stringify({
|
|
418
|
+
ok: false,
|
|
419
|
+
provider,
|
|
420
|
+
model,
|
|
421
|
+
effort: meta?.effort || undefined,
|
|
422
|
+
fast: meta?.fast === true || undefined,
|
|
423
|
+
enabled: true,
|
|
424
|
+
baseUrl: url,
|
|
425
|
+
gatewayReady: false,
|
|
426
|
+
gatewayRunning: ready.running,
|
|
427
|
+
gatewayPort: ready.port,
|
|
428
|
+
gatewayPid: ready.pid,
|
|
429
|
+
error: `gateway did not become ready on ${url}`,
|
|
430
|
+
}));
|
|
431
|
+
} else {
|
|
432
|
+
console.error(`Gateway config saved (${provider} / ${model}), but the gateway did not become ready on ${url}.`);
|
|
433
|
+
console.error('settings.json was NOT changed, so Claude Code will not be pointed at a dead gateway.');
|
|
434
|
+
console.error('Run /mixdog:model off to restore the module flag, or restart Claude Code and try /mixdog:model on again.');
|
|
435
|
+
}
|
|
436
|
+
process.exit(1);
|
|
437
|
+
}
|
|
438
|
+
// 3) settings.json: point Claude Code's main model at the ready gateway.
|
|
439
|
+
const sres = setAnthropicBaseUrl(url);
|
|
440
|
+
if (!sres.ok) {
|
|
441
|
+
// Config is already written; surface the settings.json failure clearly so
|
|
442
|
+
// the user can fix it (e.g. missing ~/.claude/settings.json) and re-run.
|
|
443
|
+
if (asJson) console.log(JSON.stringify({ ok: false, provider, model, effort: meta?.effort || undefined, fast: meta?.fast === true || undefined, baseUrl: url, gatewayReady: true, gatewayPort: ready.port, gatewayPid: ready.pid, error: sres.error }));
|
|
444
|
+
else {
|
|
445
|
+
console.error(`Gateway config saved (${provider} / ${model}), but settings.json update FAILED: ${sres.error}`);
|
|
446
|
+
console.error(`Add this manually to ${resolveSettingsPath()} under "env": "ANTHROPIC_BASE_URL": "${url}"`);
|
|
447
|
+
}
|
|
448
|
+
process.exit(1);
|
|
449
|
+
}
|
|
450
|
+
if (asJson) {
|
|
451
|
+
console.log(JSON.stringify({ ok: true, provider, model, effort: meta?.effort || undefined, fast: meta?.fast === true || undefined, enabled: true, baseUrl: url, gatewayReady: true, gatewayRunning: true, gatewayPort: ready.port, gatewayPid: ready.pid, settingsPath: sres.path, settingsChanged: sres.changed }));
|
|
452
|
+
} else {
|
|
453
|
+
console.log(`Gateway ENABLED: ${targetDisplay(provider, model, meta)}`);
|
|
454
|
+
console.log(`Gateway is running and ready on ${url} (pid ${ready.pid || 'unknown'}).`);
|
|
455
|
+
console.log(`settings.json env.ANTHROPIC_BASE_URL = ${url} (${sres.path})`);
|
|
456
|
+
console.log('');
|
|
457
|
+
console.log('⚠ This routes the ENTIRE main Claude Code model through the mixdog gateway');
|
|
458
|
+
console.log(` to ${provider}/${model}. mixdog\'s own Anthropic subagents stay on`);
|
|
459
|
+
console.log(' api.anthropic.com (hardcoded), so they are unaffected.');
|
|
460
|
+
console.log('RESTART Claude Code for ANTHROPIC_BASE_URL to take effect if this process has not already loaded it.');
|
|
461
|
+
console.log('Run /mixdog:model --disable (or this script --disable) to restore settings.json.');
|
|
462
|
+
}
|
|
463
|
+
process.exit(0);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// ── --disable: remove settings.json env entry (restore) + module off ─────
|
|
467
|
+
if (wantDisable) {
|
|
468
|
+
const port = resolveGatewayPort();
|
|
469
|
+
const sres = setAnthropicBaseUrl(null);
|
|
470
|
+
// Also flip the module off so a restart doesn't re-spawn the gateway.
|
|
471
|
+
let moduleErr = null;
|
|
472
|
+
try { setModuleEnabled(false); } catch (e) { moduleErr = e?.message || String(e); }
|
|
473
|
+
let stopped = moduleErr ? { stopped: false, running: null, port, pid: null, portOpen: null } : await waitForGatewayStopped(port);
|
|
474
|
+
if (!moduleErr && !stopped.stopped) {
|
|
475
|
+
stopped = await forceStopGatewayUntilClosed(port);
|
|
476
|
+
}
|
|
477
|
+
if (!sres.ok) {
|
|
478
|
+
if (asJson) console.log(JSON.stringify({ ok: false, error: sres.error, moduleDisabled: !moduleErr, gatewayStopped: stopped.stopped, gatewayPort: stopped.port }));
|
|
479
|
+
else console.error(`settings.json restore FAILED: ${sres.error}`);
|
|
480
|
+
process.exit(1);
|
|
481
|
+
}
|
|
482
|
+
const ok = !moduleErr && stopped.stopped;
|
|
483
|
+
if (asJson) {
|
|
484
|
+
console.log(JSON.stringify({
|
|
485
|
+
ok,
|
|
486
|
+
enabled: false,
|
|
487
|
+
settingsPath: sres.path,
|
|
488
|
+
settingsChanged: sres.changed,
|
|
489
|
+
moduleDisabled: !moduleErr,
|
|
490
|
+
moduleError: moduleErr,
|
|
491
|
+
gatewayStopped: stopped.stopped,
|
|
492
|
+
gatewayRunning: stopped.running,
|
|
493
|
+
gatewayPort: stopped.port,
|
|
494
|
+
gatewayPid: stopped.pid,
|
|
495
|
+
gatewayPortOpen: stopped.portOpen,
|
|
496
|
+
gatewayForceStopAttempted: stopped.forceStopAttempted === true,
|
|
497
|
+
gatewayForceStopPids: stopped.forceStopPids || [],
|
|
498
|
+
}));
|
|
499
|
+
} else {
|
|
500
|
+
console.log(ok ? 'Gateway DISABLED.' : 'Gateway disable requested.');
|
|
501
|
+
console.log(sres.changed
|
|
502
|
+
? `Removed env.ANTHROPIC_BASE_URL from ${sres.path} — Claude Code reverts to api.anthropic.com.`
|
|
503
|
+
: `No env.ANTHROPIC_BASE_URL was set in ${sres.path} — nothing to remove.`);
|
|
504
|
+
console.log('modules.gateway.enabled = false' + (moduleErr ? ` (config write failed: ${moduleErr})` : ''));
|
|
505
|
+
if (stopped.stopped) {
|
|
506
|
+
console.log(`Gateway process stopped and port ${stopped.port} is closed.`);
|
|
507
|
+
if (stopped.forceStopAttempted) console.log(`Gateway child stop fallback used for pid(s): ${(stopped.forceStopPids || []).join(', ')}`);
|
|
508
|
+
} else {
|
|
509
|
+
console.log(`WARNING: gateway did not fully stop within the wait window (running=${stopped.running}, portOpen=${stopped.portOpen}).`);
|
|
510
|
+
}
|
|
511
|
+
console.log('RESTART Claude Code for the settings change to take effect if this process has already loaded ANTHROPIC_BASE_URL.');
|
|
512
|
+
}
|
|
513
|
+
process.exit(ok ? 0 : 1);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
if (setIdx !== -1) {
|
|
517
|
+
const provider = argv[setIdx + 1];
|
|
518
|
+
const explicitModel = argv[setIdx + 2] && !argv[setIdx + 2].startsWith('--') ? argv[setIdx + 2] : null;
|
|
519
|
+
if (!provider) {
|
|
520
|
+
console.error('error: --set requires a <provider> argument');
|
|
521
|
+
process.exit(1);
|
|
522
|
+
}
|
|
523
|
+
const inventory = buildInventory();
|
|
524
|
+
const known = inventory.find((e) => e.provider === provider);
|
|
525
|
+
if (!known && !isClaudeCurrentProvider(provider)) {
|
|
526
|
+
const names = inventory.map((e) => e.provider).join(', ') || '(none enabled)';
|
|
527
|
+
console.error(`error: provider "${provider}" is not enabled in the agent config. Enabled: ${names}`);
|
|
528
|
+
process.exit(1);
|
|
529
|
+
}
|
|
530
|
+
const { model, meta } = resolveTargetForProvider(inventory, provider, explicitModel);
|
|
531
|
+
if (!model) {
|
|
532
|
+
console.error(`error: no model resolved for "${provider}" — pass one explicitly: --set ${provider} <model>`);
|
|
533
|
+
process.exit(1);
|
|
534
|
+
}
|
|
535
|
+
setTarget(provider, model, meta);
|
|
536
|
+
// Detect whether a gateway child is actually running RIGHT NOW. server-main
|
|
537
|
+
// watches modules.gateway.enabled, so a stopped gateway should live-start
|
|
538
|
+
// shortly after this write when the daemon is active.
|
|
539
|
+
const port = resolveGatewayPort();
|
|
540
|
+
const gw = await waitForGatewayReady(port, 4000);
|
|
541
|
+
const result = { ok: true, provider, model, effort: meta?.effort || undefined, fast: meta?.fast === true || undefined, enabled: true, gatewayReady: gw.ready, gatewayRunning: gw.running, gatewayPort: gw.port, gatewayPid: gw.pid };
|
|
542
|
+
if (asJson) {
|
|
543
|
+
console.log(JSON.stringify(result));
|
|
544
|
+
} else {
|
|
545
|
+
console.log(`Gateway routing set: ${targetDisplay(provider, model, meta)}`);
|
|
546
|
+
console.log('modules.gateway.enabled = true');
|
|
547
|
+
if (gw.ready) {
|
|
548
|
+
console.log(`Gateway is ready (port ${gw.port}) — live on the NEXT request, no gateway restart needed.`);
|
|
549
|
+
} else {
|
|
550
|
+
console.log('NOTE: config is saved, but the gateway did not report ready within the short wait window.');
|
|
551
|
+
console.log('If the daemon is running, it should keep reconciling this setting; rerun /mixdog:model to check.');
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
process.exit(0);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// Default action: list.
|
|
558
|
+
const inventory = buildInventory();
|
|
559
|
+
const current = readCurrentTarget();
|
|
560
|
+
const gw = isGatewayRunning();
|
|
561
|
+
|
|
562
|
+
if (asJson) {
|
|
563
|
+
console.log(JSON.stringify({ current, providers: inventory, gatewayRunning: gw.running, gatewayPort: gw.port }));
|
|
564
|
+
process.exit(0);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
console.log('== mixdog gateway model ==');
|
|
568
|
+
console.log(
|
|
569
|
+
`Current target: ${current.mode === CLAUDE_CURRENT_MODE
|
|
570
|
+
? `Claude Code current (${current.model || 'current model'})`
|
|
571
|
+
: current.provider ? `${current.provider} / ${current.model || '(no model)'}` : '(unset)'}` +
|
|
572
|
+
` | module ${current.enabled ? 'ENABLED' : 'disabled'}` +
|
|
573
|
+
` | gateway ${gw.running ? `RUNNING (port ${gw.port})` : 'not running'}`
|
|
574
|
+
);
|
|
575
|
+
console.log('');
|
|
576
|
+
if (inventory.length === 0) {
|
|
577
|
+
console.log('No enabled agent providers found. Enable a provider in /mixdog:config first.');
|
|
578
|
+
} else {
|
|
579
|
+
const choices = inventoryChoices(inventory);
|
|
580
|
+
const currentChoice = choices.find(c => c.id === CLAUDE_CURRENT_CHOICE_ID);
|
|
581
|
+
if (currentChoice) {
|
|
582
|
+
console.log(`Default: ${currentChoice.label}`);
|
|
583
|
+
console.log('');
|
|
584
|
+
}
|
|
585
|
+
console.log('Available providers (enabled) and candidate models:');
|
|
586
|
+
for (const e of inventory) {
|
|
587
|
+
const models = e.models.length ? e.models.join(', ') : '(no preset/model — pass one explicitly)';
|
|
588
|
+
console.log(` • ${e.provider}: ${models}`);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
console.log('');
|
|
592
|
+
console.log('Switch routing: bun scripts/gateway-model.mjs --set <provider> [model]');
|
|
593
|
+
console.log('Enable gateway: bun scripts/gateway-model.mjs --enable <provider> [model] (live-starts + writes settings.json)');
|
|
594
|
+
console.log('Disable gateway: bun scripts/gateway-model.mjs --disable (live-stops + restores settings.json)');
|
|
595
|
+
console.log('Quick toggle: bun scripts/gateway-model.mjs on [provider] [model] | off (aliases of --enable/--disable)');
|
|
596
|
+
process.exit(0);
|