@hasna/switcher 0.2.20 → 0.2.22
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/README.md +3 -1
- package/dist/claude-context.d.ts +16 -0
- package/dist/claude-desktop.js +95 -95
- package/dist/cli/index.js +148 -60
- package/dist/harness-types.d.ts +6 -0
- package/dist/index.js +96 -96
- package/dist/inference-gateway.d.ts +6 -0
- package/dist/mcp/index.js +100 -100
- package/dist/sdk.js +96 -96
- package/dist/serve/index.js +2 -2
- package/docs/GATEWAY-SERVICE.md +59 -10
- package/openapi.json +1 -1
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -514,7 +514,7 @@ function canonicalPolicyJSON(value) {
|
|
|
514
514
|
return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
515
515
|
}
|
|
516
516
|
// package.json
|
|
517
|
-
var version = "0.2.
|
|
517
|
+
var version = "0.2.22";
|
|
518
518
|
|
|
519
519
|
// src/version.ts
|
|
520
520
|
var VERSION = version;
|
|
@@ -1109,7 +1109,7 @@ function assertHarnessArguments(harness, args, options = {}) {
|
|
|
1109
1109
|
|
|
1110
1110
|
// src/cli.ts
|
|
1111
1111
|
import { parseArgs } from "util";
|
|
1112
|
-
import { join as
|
|
1112
|
+
import { join as join27, resolve as resolve16 } from "path";
|
|
1113
1113
|
|
|
1114
1114
|
// src/http.ts
|
|
1115
1115
|
var MAX_BYTES = 16 * 1024 * 1024;
|
|
@@ -1836,6 +1836,17 @@ function claudeContextEnvironment(providerBaseUrl, environment = process.env) {
|
|
|
1836
1836
|
return { CLAUDE_CODE_AUTO_COMPACT_WINDOW: "786432" };
|
|
1837
1837
|
return {};
|
|
1838
1838
|
}
|
|
1839
|
+
var CLAUDE_ONE_MILLION_CONTEXT = 1e6;
|
|
1840
|
+
function claudeNativeModelId(id, models) {
|
|
1841
|
+
if (/\[1m\]$/i.test(id))
|
|
1842
|
+
return id;
|
|
1843
|
+
const window = models.find((model) => model.id === id)?.contextWindow;
|
|
1844
|
+
return window !== undefined && window >= CLAUDE_ONE_MILLION_CONTEXT ? `${id}[1m]` : id;
|
|
1845
|
+
}
|
|
1846
|
+
var CLAUDE_MODEL_VARIABLES = new Set(["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_FABLE_MODEL"]);
|
|
1847
|
+
function claudeNativeModelEnvironment(env, models) {
|
|
1848
|
+
return Object.fromEntries(Object.entries(env ?? {}).map(([name, value]) => [name, CLAUDE_MODEL_VARIABLES.has(name) ? claudeNativeModelId(value, models) : value]));
|
|
1849
|
+
}
|
|
1839
1850
|
|
|
1840
1851
|
// src/opencode-model-policy.ts
|
|
1841
1852
|
var routeForAgent = (agent) => {
|
|
@@ -2570,7 +2581,7 @@ var openapi_default = {
|
|
|
2570
2581
|
openapi: "3.0.3",
|
|
2571
2582
|
info: {
|
|
2572
2583
|
title: "Switcher API",
|
|
2573
|
-
version: "0.2.
|
|
2584
|
+
version: "0.2.22",
|
|
2574
2585
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2575
2586
|
},
|
|
2576
2587
|
security: [
|
|
@@ -10444,6 +10455,19 @@ async function durableJsonFile(dir, prefix, value) {
|
|
|
10444
10455
|
}
|
|
10445
10456
|
return path;
|
|
10446
10457
|
}
|
|
10458
|
+
async function routeJsonFile(path, value) {
|
|
10459
|
+
if (!/^claude-route-[0-9a-f-]{36}\.json$/.test(basename2(path)))
|
|
10460
|
+
throw new Error("A Claude route settings file must be named claude-route-<launch id>.json.");
|
|
10461
|
+
await privateDirectory(dirname7(path));
|
|
10462
|
+
await writeFile13(path, JSON.stringify(value, null, 2) + `
|
|
10463
|
+
`, { mode: 384, flag: "wx" });
|
|
10464
|
+
const info = await lstat6(path);
|
|
10465
|
+
if (!info.isFile() || (info.mode & 63) !== 0 || info.uid !== process.getuid?.()) {
|
|
10466
|
+
await rm2(path, { force: true });
|
|
10467
|
+
throw new Error("The Claude route settings file could not be created owner-only.");
|
|
10468
|
+
}
|
|
10469
|
+
return path;
|
|
10470
|
+
}
|
|
10447
10471
|
async function projectInstructionPaths(cwd) {
|
|
10448
10472
|
let dir = resolve8(cwd);
|
|
10449
10473
|
while (true) {
|
|
@@ -11110,19 +11134,21 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
11110
11134
|
return prepareAider(input);
|
|
11111
11135
|
if (input.harness === "claude") {
|
|
11112
11136
|
env.ANTHROPIC_BASE_URL = input.baseUrl.replace(/\/v1$/, "");
|
|
11113
|
-
|
|
11137
|
+
const nativeModel = (id2) => claudeNativeModelId(id2, input.models);
|
|
11138
|
+
Object.assign(env, claudeNativeModelEnvironment(input.nativePolicy?.env, input.models));
|
|
11114
11139
|
Object.assign(env, claudeContextEnvironment(providerBaseUrl));
|
|
11115
|
-
env.ANTHROPIC_MODEL = input.model;
|
|
11116
|
-
env.ANTHROPIC_DEFAULT_MODEL = input.model;
|
|
11117
|
-
env.CLAUDE_CODE_SUBAGENT_MODEL = input.compiledPolicy?.roles.subagent ?? input.model;
|
|
11140
|
+
env.ANTHROPIC_MODEL = nativeModel(input.model);
|
|
11141
|
+
env.ANTHROPIC_DEFAULT_MODEL = nativeModel(input.model);
|
|
11142
|
+
env.CLAUDE_CODE_SUBAGENT_MODEL = nativeModel(input.compiledPolicy?.roles.subagent ?? input.model);
|
|
11118
11143
|
env.ANTHROPIC_API_KEY = "";
|
|
11119
11144
|
env.ANTHROPIC_AUTH_TOKEN = "";
|
|
11120
11145
|
env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
|
|
11121
|
-
const picker = { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: m.id, label: m.name, description: m.description?.slice(0, 300) })) } };
|
|
11122
|
-
const
|
|
11146
|
+
const picker = { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: nativeModel(m.id), label: m.name, description: m.description?.slice(0, 300) })) } };
|
|
11147
|
+
const route2 = input.routeSettingsFile && input.credential ? { env: { ANTHROPIC_BASE_URL: env.ANTHROPIC_BASE_URL, ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", [input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"]: input.credential } } : undefined;
|
|
11148
|
+
const file2 = route2 ? await routeJsonFile(input.routeSettingsFile, { ...picker, ...route2 }) : input.sessionDir ? await durableJsonFile(claudeSettingsDirectory(input.sessionDir), "claude-settings", picker) : await jsonFile(input.stateDir, "claude-settings.json", picker);
|
|
11123
11149
|
configPaths.push(file2);
|
|
11124
11150
|
warnings.push("Claude managed settings and model allowlists can restrict the generated picker.");
|
|
11125
|
-
return { executable, args: ["--settings", file2, "--model", input.model, ...args], env, configPaths, warnings };
|
|
11151
|
+
return { executable, args: ["--settings", file2, "--model", nativeModel(input.model), ...args], env, configPaths, warnings };
|
|
11126
11152
|
}
|
|
11127
11153
|
if (input.harness === "codex") {
|
|
11128
11154
|
const rolePolicy2 = await prepareCodexModelPolicy({ home: input.sharedState?.home, cwd: input.cwd, stateDir: input.stateDir, model: input.model, policy: input.modelPolicy ? { version: 1, ...input.modelPolicy } : undefined, switcherProvider: "switcher", switcherBaseUrl: input.baseUrl });
|
|
@@ -11490,7 +11516,7 @@ async function prepareHarnessLaunch(input) {
|
|
|
11490
11516
|
};
|
|
11491
11517
|
try {
|
|
11492
11518
|
const nativeAuth = input.protocol === "gemini-generate-content" ? "x-api-key" : input.harness === "claude" ? input.authStyle === "x-api-key" ? "x-api-key" : "bearer" : input.protocol === "anthropic-messages" ? "x-api-key" : "bearer";
|
|
11493
|
-
const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy });
|
|
11519
|
+
const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy, routeSettingsFile: input.harness === "claude" ? bridge.routeSettingsFile : undefined });
|
|
11494
11520
|
return { ...prepared, configPaths: [...prepared.configPaths, catalogPath], warnings: [...prepared.warnings, "Switcher injects model guidance into every managed inference request and permits only models authorized by the launch policy, including catalog selection when enabled. The gateway translates the selected credential to the provider authentication header. The full catalog remains discoverable."], cleanup: async () => {
|
|
11495
11521
|
try {
|
|
11496
11522
|
await prepared.cleanup?.();
|
|
@@ -11533,8 +11559,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
|
11533
11559
|
}
|
|
11534
11560
|
|
|
11535
11561
|
// src/launcher.ts
|
|
11536
|
-
import { lstat as lstat13, mkdir as mkdir14, mkdtemp, realpath as realpath8, rm as
|
|
11537
|
-
import { join as
|
|
11562
|
+
import { lstat as lstat13, mkdir as mkdir14, mkdtemp, realpath as realpath8, rm as rm7, writeFile as writeFile18 } from "fs/promises";
|
|
11563
|
+
import { join as join25, relative as relative7, resolve as resolve14 } from "path";
|
|
11538
11564
|
|
|
11539
11565
|
// src/provider-credential-onboarding.ts
|
|
11540
11566
|
import { z as z9 } from "zod-v4";
|
|
@@ -14677,6 +14703,8 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
|
|
|
14677
14703
|
// src/gateway-client.ts
|
|
14678
14704
|
import { spawn as spawn4 } from "child_process";
|
|
14679
14705
|
import { closeSync as closeSync3, openSync as openSync3 } from "fs";
|
|
14706
|
+
import { rm as rm6 } from "fs/promises";
|
|
14707
|
+
import { join as join24 } from "path";
|
|
14680
14708
|
|
|
14681
14709
|
// src/gateway-service.ts
|
|
14682
14710
|
import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
|
|
@@ -15056,12 +15084,14 @@ var gatewaySchema = z10.object({
|
|
|
15056
15084
|
cwd: z10.string().max(4096).refine(isAbsolute17, "Use an absolute working directory.")
|
|
15057
15085
|
}).strict();
|
|
15058
15086
|
var credentialEnvSchema = z10.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
|
|
15087
|
+
var routeSchema = z10.object({ settingsDir: z10.string().max(4096) }).strict();
|
|
15059
15088
|
var registrationSchema = z10.object({
|
|
15060
15089
|
holderPid: z10.number().int().positive(),
|
|
15061
15090
|
gateway: gatewaySchema,
|
|
15062
15091
|
credential: z10.string().min(1).max(64000).refine((value) => !/[\x00-\x1f\x7f]/.test(value), "Credential contains control characters.").optional(),
|
|
15063
15092
|
credentialEnv: credentialEnvSchema.optional(),
|
|
15064
|
-
stateDir: z10.string().max(4096).optional()
|
|
15093
|
+
stateDir: z10.string().max(4096).optional(),
|
|
15094
|
+
route: routeSchema.optional()
|
|
15065
15095
|
}).strict();
|
|
15066
15096
|
var holderSchema = z10.object({ pid: z10.number().int().positive(), start: z10.string().min(1).max(200) }).strict();
|
|
15067
15097
|
var credentialSourceSchema = z10.discriminatedUnion("source", [
|
|
@@ -15077,7 +15107,9 @@ var staticSchema = z10.object({
|
|
|
15077
15107
|
launcherPid: z10.number().int().positive(),
|
|
15078
15108
|
gateway: gatewaySchema,
|
|
15079
15109
|
credential: credentialSourceSchema,
|
|
15080
|
-
stateDir: z10.string().max(4096).optional()
|
|
15110
|
+
stateDir: z10.string().max(4096).optional(),
|
|
15111
|
+
route: routeSchema.optional(),
|
|
15112
|
+
routeRevived: z10.literal(true).optional()
|
|
15081
15113
|
}).strict();
|
|
15082
15114
|
var holderStateSchema = z10.object({ lastUsedAt: z10.number(), lastHolderAt: z10.number(), released: z10.boolean(), holders: z10.array(holderSchema).max(MAX_HOLDERS), extendedAt: z10.number().optional() }).strict();
|
|
15083
15115
|
var endedSchema = staticSchema.omit({ stateDir: true }).extend({ endedAt: z10.number() }).strict();
|
|
@@ -15135,6 +15167,18 @@ async function writePrivate(path, text) {
|
|
|
15135
15167
|
}
|
|
15136
15168
|
await rename5(temporary, path);
|
|
15137
15169
|
}
|
|
15170
|
+
async function routeSettingsDirectory(path) {
|
|
15171
|
+
const profile = dirname9(path);
|
|
15172
|
+
if (!isAbsolute17(path) || resolve13(path) !== path || basename5(path) !== "settings" || basename5(dirname9(profile)) !== "claude" || basename5(dirname9(dirname9(profile))) !== "sessions")
|
|
15173
|
+
throw new Fault(400, "invalid_route", "A durable route's settings folder must be an absolute <state>/sessions/claude/<profile>/settings directory.");
|
|
15174
|
+
const info2 = await lstat11(path).catch(() => {
|
|
15175
|
+
return;
|
|
15176
|
+
});
|
|
15177
|
+
if (!info2?.isDirectory() || info2.isSymbolicLink() || info2.uid !== process.getuid?.() || (info2.mode & 63) !== 0)
|
|
15178
|
+
throw new Fault(400, "invalid_route", "A durable route's settings folder must be a private directory owned by this user (mode 0700).");
|
|
15179
|
+
return path;
|
|
15180
|
+
}
|
|
15181
|
+
var routeFile = (record3) => record3.route ? join22(record3.route.settingsDir, `claude-route-${record3.id}.json`) : undefined;
|
|
15138
15182
|
async function launchStateDirectory(path) {
|
|
15139
15183
|
if (path === undefined)
|
|
15140
15184
|
return;
|
|
@@ -15253,11 +15297,28 @@ async function startGatewayService(options = {}) {
|
|
|
15253
15297
|
return;
|
|
15254
15298
|
});
|
|
15255
15299
|
};
|
|
15300
|
+
const retireRoute = async (record3) => {
|
|
15301
|
+
const file = routeFile(record3);
|
|
15302
|
+
if (!file)
|
|
15303
|
+
return;
|
|
15304
|
+
const info2 = await lstat11(file).catch(() => {
|
|
15305
|
+
return;
|
|
15306
|
+
});
|
|
15307
|
+
if (info2?.isFile() && info2.uid === process.getuid?.())
|
|
15308
|
+
await writePrivate(file, `{}
|
|
15309
|
+
`).catch(() => {
|
|
15310
|
+
return;
|
|
15311
|
+
});
|
|
15312
|
+
};
|
|
15313
|
+
const expireEnded = async (entry) => {
|
|
15314
|
+
await forgetEnded(entry);
|
|
15315
|
+
await retireRoute(entry.record);
|
|
15316
|
+
};
|
|
15256
15317
|
const pruneEnded = async (at) => {
|
|
15257
15318
|
const entries = [...ended.values()].sort((a, b) => a.record.endedAt - b.record.endedAt);
|
|
15258
15319
|
for (const [index, entry] of entries.entries())
|
|
15259
15320
|
if (at - entry.record.endedAt > ENDED_MS || entries.length - index > MAX_ENDED)
|
|
15260
|
-
await
|
|
15321
|
+
await expireEnded(entry);
|
|
15261
15322
|
};
|
|
15262
15323
|
const endedEntry = (launch) => {
|
|
15263
15324
|
const { stateDir: _state, ...fixed } = staticFields(launch.record);
|
|
@@ -15295,6 +15356,11 @@ async function startGatewayService(options = {}) {
|
|
|
15295
15356
|
await rm5(join22(paths.launches, `${launch.record.id}.json`), { force: true }).catch(() => {
|
|
15296
15357
|
return;
|
|
15297
15358
|
});
|
|
15359
|
+
const route2 = end ? undefined : routeFile(launch.record);
|
|
15360
|
+
if (route2)
|
|
15361
|
+
await rm5(route2, { force: true }).catch(() => {
|
|
15362
|
+
return;
|
|
15363
|
+
});
|
|
15298
15364
|
if (removeState && launch.record.stateDir) {
|
|
15299
15365
|
const directory = await launchStateDirectory(launch.record.stateDir).catch(() => {
|
|
15300
15366
|
return;
|
|
@@ -15365,7 +15431,7 @@ async function startGatewayService(options = {}) {
|
|
|
15365
15431
|
return entry.reviving;
|
|
15366
15432
|
const at = now();
|
|
15367
15433
|
if (at - entry.record.endedAt > ENDED_MS) {
|
|
15368
|
-
|
|
15434
|
+
expireEnded(entry);
|
|
15369
15435
|
return;
|
|
15370
15436
|
}
|
|
15371
15437
|
const failedAt = entry.failed.get(clientPort);
|
|
@@ -15389,27 +15455,28 @@ async function startGatewayService(options = {}) {
|
|
|
15389
15455
|
try {
|
|
15390
15456
|
await entry.settled;
|
|
15391
15457
|
const [peers, table] = await Promise.all([connectionPeers(clientPort, serverPort), processTable()]);
|
|
15392
|
-
const held = new Set([...launches.values()].flatMap((launch2) => liveHolders(launch2, table).map((holder) => holder.pid)));
|
|
15458
|
+
const held = new Set([...launches.values()].filter((launch2) => !launch2.record.routeRevived).flatMap((launch2) => liveHolders(launch2, table).map((holder) => holder.pid)));
|
|
15393
15459
|
const underHolder = (pid) => {
|
|
15394
15460
|
for (let current = pid, depth = 0;current !== undefined && current > 1 && depth < 256; current = table.get(current)?.ppid, depth++)
|
|
15395
15461
|
if (held.has(current))
|
|
15396
15462
|
return true;
|
|
15397
15463
|
return false;
|
|
15398
15464
|
};
|
|
15399
|
-
const
|
|
15465
|
+
const durable = entry.record.route !== undefined;
|
|
15466
|
+
const holders = [...new Set(peers)].filter((pid) => pid !== process.pid && table.has(pid) && (durable || underHolder(pid))).slice(0, MAX_HOLDERS).map((pid) => ({ pid, start: table.get(pid).start }));
|
|
15400
15467
|
if (byDigest.has(digest2) || ended.get(digest2) !== entry)
|
|
15401
15468
|
return byDigest.get(digest2);
|
|
15402
15469
|
if (!holders.length)
|
|
15403
15470
|
return fail();
|
|
15404
15471
|
const { endedAt: _endedAt, ...fixed } = entry.record;
|
|
15405
|
-
const record3 = { ...fixed, lastUsedAt: at, lastHolderAt: at, released: true, holders };
|
|
15472
|
+
const record3 = { ...fixed, ...durable ? { routeRevived: true } : {}, lastUsedAt: at, lastHolderAt: at, released: true, holders };
|
|
15406
15473
|
await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
|
|
15407
15474
|
const launch = adopt(record3, entry.credential);
|
|
15408
15475
|
launch.probedAfterLauncher = true;
|
|
15409
15476
|
track(launch, table, at);
|
|
15410
15477
|
await persist(launch, true);
|
|
15411
15478
|
await forgetEnded(entry);
|
|
15412
|
-
log(`launch ${record3.id.slice(0, 8)} revived for a process that still uses it under a current launch`);
|
|
15479
|
+
log(`launch ${record3.id.slice(0, 8)} revived for a process that still uses it ${durable ? "through its durable route" : "under a current launch"}`);
|
|
15413
15480
|
return launch;
|
|
15414
15481
|
} catch {
|
|
15415
15482
|
return fail();
|
|
@@ -15469,7 +15536,7 @@ async function startGatewayService(options = {}) {
|
|
|
15469
15536
|
const digest2 = sha256(token);
|
|
15470
15537
|
const launch = byDigest.get(digest2) ?? await revive(digest2, server.requestIP(request)?.port, server.port);
|
|
15471
15538
|
if (!launch)
|
|
15472
|
-
return errorBody(401, "switcher_gateway_launch_unknown", `Switcher gateway: this session's launch is no longer registered (it was revoked, it ended more than 30 days ago, or the gateway state was reset), or this request did not come from a process of this user running under a current launch. ${LAUNCH_HINT}`);
|
|
15539
|
+
return errorBody(401, "switcher_gateway_launch_unknown", `Switcher gateway: this session's launch is no longer registered (it was revoked, it ended more than 30 days ago, or the gateway state was reset), or this request for the ended launch did not come from a process of this user running under a current launch, or from any running process of this user for a durable Claude route. ${LAUNCH_HINT}`);
|
|
15473
15540
|
const at = now();
|
|
15474
15541
|
launch.record.lastUsedAt = at;
|
|
15475
15542
|
if (at - launch.usedPersistedAt >= USE_PERSIST_INTERVAL_MS) {
|
|
@@ -15515,6 +15582,9 @@ async function startGatewayService(options = {}) {
|
|
|
15515
15582
|
if (!holder)
|
|
15516
15583
|
throw new Fault(400, "holder_not_running", "The registering process is not running.");
|
|
15517
15584
|
const stateDir = await launchStateDirectory(input.stateDir);
|
|
15585
|
+
const route2 = input.route ? { settingsDir: await routeSettingsDirectory(input.route.settingsDir) } : undefined;
|
|
15586
|
+
if (route2 && input.gateway.harness !== "claude")
|
|
15587
|
+
throw new Fault(400, "invalid_route", "Only Claude launches keep a durable route.");
|
|
15518
15588
|
const policy = compiledPolicy(input.gateway.compiledPolicy);
|
|
15519
15589
|
if (policy.model !== input.gateway.model)
|
|
15520
15590
|
throw new Fault(400, "invalid_request", "The compiled policy does not belong to the selected model.");
|
|
@@ -15542,7 +15612,8 @@ async function startGatewayService(options = {}) {
|
|
|
15542
15612
|
holders: [{ pid: holder.pid, start: holder.start }],
|
|
15543
15613
|
gateway: { ...input.gateway, compiledPolicy: policy },
|
|
15544
15614
|
credential,
|
|
15545
|
-
...stateDir ? { stateDir } : {}
|
|
15615
|
+
...stateDir ? { stateDir } : {},
|
|
15616
|
+
...route2 ? { route: route2 } : {}
|
|
15546
15617
|
};
|
|
15547
15618
|
const launch = adopt(record3, input.credential);
|
|
15548
15619
|
launch.baseline = new Set([...table.values()].map(processKey));
|
|
@@ -15580,7 +15651,7 @@ async function startGatewayService(options = {}) {
|
|
|
15580
15651
|
if (method === "GET" && url2.pathname === "/v1/status")
|
|
15581
15652
|
return Response.json({ service: "switcher-gateway", protocol: GATEWAY_PROTOCOL, version: VERSION, pid: process.pid, port, baseUrl: `http://127.0.0.1:${port}`, launches: launches.size, supervisor: options.supervisor ?? "none" });
|
|
15582
15653
|
if (method === "GET" && url2.pathname === "/v1/launches")
|
|
15583
|
-
return Response.json({ data: [...launches.values()].map(({ record: record3 }) => ({ id: record3.id, harness: record3.gateway.harness, model: record3.gateway.model, createdAt: new Date(record3.createdAt).toISOString(), lastUsedAt: new Date(record3.lastUsedAt).toISOString(), holders: record3.holders.length, released: record3.released, credential: record3.credential.source })) });
|
|
15654
|
+
return Response.json({ data: [...launches.values()].map(({ record: record3 }) => ({ id: record3.id, harness: record3.gateway.harness, model: record3.gateway.model, createdAt: new Date(record3.createdAt).toISOString(), lastUsedAt: new Date(record3.lastUsedAt).toISOString(), holders: record3.holders.length, released: record3.released, credential: record3.credential.source, durable: record3.route !== undefined })) });
|
|
15584
15655
|
if (method === "POST" && url2.pathname === "/v1/launches")
|
|
15585
15656
|
return Response.json(await register(registrationSchema.parse(await json(request))), { status: 201 });
|
|
15586
15657
|
if (method === "POST" && url2.pathname === "/v1/stop") {
|
|
@@ -16038,26 +16109,39 @@ function createServiceGatewayHost(client, context) {
|
|
|
16038
16109
|
catalogPath: input.catalogPath,
|
|
16039
16110
|
cwd: input.cwd
|
|
16040
16111
|
};
|
|
16041
|
-
|
|
16112
|
+
const route2 = input.harness === "claude" && input.sessionDir ? { settingsDir: join24(input.sessionDir, "settings") } : undefined;
|
|
16113
|
+
if (route2)
|
|
16114
|
+
await privateDirectory(route2.settingsDir);
|
|
16115
|
+
const body2 = {
|
|
16116
|
+
holderPid: context.holderPid,
|
|
16117
|
+
gateway,
|
|
16118
|
+
...input.credential ? { credential: input.credential } : {},
|
|
16119
|
+
...context.credentialEnv ? { credentialEnv: context.credentialEnv } : {},
|
|
16120
|
+
...context.stateDir ? { stateDir: context.stateDir } : {}
|
|
16121
|
+
};
|
|
16122
|
+
let registration, durable = Boolean(route2);
|
|
16042
16123
|
try {
|
|
16043
|
-
|
|
16044
|
-
|
|
16045
|
-
|
|
16046
|
-
|
|
16047
|
-
|
|
16048
|
-
|
|
16049
|
-
|
|
16124
|
+
try {
|
|
16125
|
+
registration = await client.register(route2 ? { ...body2, route: route2 } : body2);
|
|
16126
|
+
} catch (error) {
|
|
16127
|
+
if (!(route2 && error instanceof Fault && error.code === "invalid_request" && /route/.test(error.message)))
|
|
16128
|
+
throw error;
|
|
16129
|
+
(context.warn ?? console.error)("switcher: The running gateway predates durable Claude routes; a background session restarted after this launch ends may lose its route. Run `switcher gateway install` to restart it on this version.");
|
|
16130
|
+
registration = await client.register(body2);
|
|
16131
|
+
durable = false;
|
|
16132
|
+
}
|
|
16050
16133
|
} catch (error) {
|
|
16051
16134
|
(context.warn ?? console.error)(`switcher: The persistent gateway refused this launch (${error instanceof Fault ? error.code : "unavailable"}); it uses a per-launch gateway that stops when this command exits.`);
|
|
16052
16135
|
return createInferenceGateway(input);
|
|
16053
16136
|
}
|
|
16137
|
+
const routeSettingsFile = durable && route2 ? join24(route2.settingsDir, `claude-route-${registration.id}.json`) : undefined;
|
|
16054
16138
|
const lease = { id: registration.id, attached: attachedPid !== undefined, retained: false, done: false };
|
|
16055
16139
|
leases.push(lease);
|
|
16056
16140
|
if (attachedPid !== undefined)
|
|
16057
16141
|
attaching.push(client.attach(lease.id, attachedPid).catch(() => {
|
|
16058
16142
|
return;
|
|
16059
16143
|
}));
|
|
16060
|
-
return { baseUrl: registration.baseUrl, token: registration.token, retainsState: () => lease.retained, cleanup: async () => {
|
|
16144
|
+
return { baseUrl: registration.baseUrl, token: registration.token, ...routeSettingsFile ? { routeSettingsFile } : {}, retainsState: () => lease.retained, cleanup: async () => {
|
|
16061
16145
|
if (lease.done)
|
|
16062
16146
|
return;
|
|
16063
16147
|
lease.done = true;
|
|
@@ -16066,6 +16150,10 @@ function createServiceGatewayHost(client, context) {
|
|
|
16066
16150
|
await client.revoke(lease.id).catch(() => {
|
|
16067
16151
|
return;
|
|
16068
16152
|
});
|
|
16153
|
+
if (routeSettingsFile)
|
|
16154
|
+
await rm6(routeSettingsFile, { force: true }).catch(() => {
|
|
16155
|
+
return;
|
|
16156
|
+
});
|
|
16069
16157
|
return;
|
|
16070
16158
|
}
|
|
16071
16159
|
try {
|
|
@@ -16094,7 +16182,7 @@ function createServiceGatewayHost(client, context) {
|
|
|
16094
16182
|
// src/launcher.ts
|
|
16095
16183
|
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
16096
16184
|
async function writeOriCodexCatalog(stateDir, models) {
|
|
16097
|
-
const path =
|
|
16185
|
+
const path = join25(stateDir, "ori-codex-models.json");
|
|
16098
16186
|
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
16099
16187
|
await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
16100
16188
|
`, { mode: 384, flag: "wx" });
|
|
@@ -16188,7 +16276,7 @@ async function prepareOriForPlan(plan, options) {
|
|
|
16188
16276
|
});
|
|
16189
16277
|
try {
|
|
16190
16278
|
const shim = prepareOriModelPolicy(request.target, native);
|
|
16191
|
-
const dir =
|
|
16279
|
+
const dir = join25(options.stateDir, "ori-bin"), path = join25(dir, shim.name);
|
|
16192
16280
|
await mkdir14(dir, { mode: 448 });
|
|
16193
16281
|
await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
|
|
16194
16282
|
return { contract, prepared: {
|
|
@@ -16208,12 +16296,12 @@ async function sharedNativeHome(state, root, profileId, environment = process.en
|
|
|
16208
16296
|
const variable = state.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
|
|
16209
16297
|
const configured = environment[variable] ? resolve14(environment[variable]) : undefined;
|
|
16210
16298
|
const configuredCorpus = configured !== undefined && await realpath8(configured).catch(() => configured) === state.home;
|
|
16211
|
-
const home = state.tool === "claude" && (!configured || configured === state.home || configuredCorpus) ?
|
|
16299
|
+
const home = state.tool === "claude" && (!configured || configured === state.home || configuredCorpus) ? join25(root, "native-claude", profileId) : configured ?? state.home;
|
|
16212
16300
|
return { home, settingsEnvironment: configuredCorpus ? { ...environment, CLAUDE_CONFIG_DIR: undefined } : environment };
|
|
16213
16301
|
}
|
|
16214
16302
|
var SESSION_DIRECTORY_HARNESSES = ["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie", "claude"];
|
|
16215
16303
|
function launchSessionDirectory(root, harness, profileId) {
|
|
16216
|
-
return
|
|
16304
|
+
return join25(root, "sessions", harness, profileId);
|
|
16217
16305
|
}
|
|
16218
16306
|
async function checkSharedNativeLaunch(state, root, profileId, options = {}) {
|
|
16219
16307
|
const warnings = await legacyNativeStateWarnings(root, state);
|
|
@@ -16235,11 +16323,11 @@ async function checkSharedNativeLaunch(state, root, profileId, options = {}) {
|
|
|
16235
16323
|
}
|
|
16236
16324
|
function isolatedNativeHome(tool, root, profileId, options = {}, environment = process.env) {
|
|
16237
16325
|
if (options.desktop)
|
|
16238
|
-
return { home:
|
|
16326
|
+
return { home: join25(root, "desktop", profileId, "codex"), private: false };
|
|
16239
16327
|
if (options.claudeDesktop)
|
|
16240
|
-
return { home:
|
|
16328
|
+
return { home: join25(root, "desktop-claude", profileId), private: false };
|
|
16241
16329
|
const configured = environment[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
|
|
16242
|
-
return { home: configured ? resolve14(configured) :
|
|
16330
|
+
return { home: configured ? resolve14(configured) : join25(root, `native-${tool}`, profileId), private: true };
|
|
16243
16331
|
}
|
|
16244
16332
|
async function checkDirectLaunch(root, profileId, harness, options = {}) {
|
|
16245
16333
|
const desktop = Boolean(options.desktop || options.claudeDesktop);
|
|
@@ -16296,9 +16384,9 @@ async function launch(client, profileId, options = {}) {
|
|
|
16296
16384
|
validateHarnessVersion("gemini", detection?.version);
|
|
16297
16385
|
if (backend === "direct" && plan.profile.harness === "aider")
|
|
16298
16386
|
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
16299
|
-
const root = resolve14(options.stateDir ??
|
|
16387
|
+
const root = resolve14(options.stateDir ?? join25(switcherHome(), "state"));
|
|
16300
16388
|
await privateDirectory(root);
|
|
16301
|
-
const stateDir = await mkdtemp(
|
|
16389
|
+
const stateDir = await mkdtemp(join25(root, "launch-"));
|
|
16302
16390
|
let credential;
|
|
16303
16391
|
if (backend === "direct") {
|
|
16304
16392
|
try {
|
|
@@ -16306,7 +16394,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
16306
16394
|
if (plan.provider.credentialEnv && !credential)
|
|
16307
16395
|
throw new Fault(400, "credential_setup_required", `Provider credential setup is required. Run: ${providerCredentialSetupCommand(plan.provider)}. Or provide ${plan.provider.credentialEnv} in this launch process.`);
|
|
16308
16396
|
} catch (error) {
|
|
16309
|
-
await
|
|
16397
|
+
await rm7(stateDir, { recursive: true, force: true });
|
|
16310
16398
|
throw error;
|
|
16311
16399
|
}
|
|
16312
16400
|
}
|
|
@@ -16397,7 +16485,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
16397
16485
|
cwd: resolve14(options.cwd ?? process.cwd()),
|
|
16398
16486
|
sharedState
|
|
16399
16487
|
};
|
|
16400
|
-
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop,
|
|
16488
|
+
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join25(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
|
|
16401
16489
|
harness: plan.profile.harness,
|
|
16402
16490
|
baseUrl: plan.provider.baseUrl,
|
|
16403
16491
|
protocol: plan.provider.protocol,
|
|
@@ -16434,7 +16522,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
16434
16522
|
prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
|
|
16435
16523
|
}
|
|
16436
16524
|
if (options.desktop) {
|
|
16437
|
-
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir,
|
|
16525
|
+
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join25(root, "desktop", desktopState), sharedState);
|
|
16438
16526
|
cleanup = prepared.cleanup;
|
|
16439
16527
|
}
|
|
16440
16528
|
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
@@ -16543,7 +16631,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
16543
16631
|
await cleanup?.();
|
|
16544
16632
|
} finally {
|
|
16545
16633
|
if (!gatewayHost?.retainedState())
|
|
16546
|
-
await
|
|
16634
|
+
await rm7(stateDir, { recursive: true, force: true });
|
|
16547
16635
|
}
|
|
16548
16636
|
}
|
|
16549
16637
|
}
|
|
@@ -16657,7 +16745,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
16657
16745
|
import { createHash as createHash18 } from "crypto";
|
|
16658
16746
|
import { constants as constants11 } from "fs";
|
|
16659
16747
|
import { lstat as lstat14, open as open9, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
|
|
16660
|
-
import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as
|
|
16748
|
+
import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as join26, relative as relative8, resolve as resolve15 } from "path";
|
|
16661
16749
|
var MAX_FILES = 1e5;
|
|
16662
16750
|
var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
|
|
16663
16751
|
var refused = () => new Fault(409, "native_state_import_conflict", "Native state import found changed, unsafe or divergent data. No existing file will be replaced. Keep the original directory and resolve the conflict explicitly.");
|
|
@@ -16722,7 +16810,7 @@ async function checkSessionIdentities(plan) {
|
|
|
16722
16810
|
for (const file of plan.files) {
|
|
16723
16811
|
if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
|
|
16724
16812
|
continue;
|
|
16725
|
-
file.sessionId = await sessionId(
|
|
16813
|
+
file.sessionId = await sessionId(join26(plan.source, file.path), file.source);
|
|
16726
16814
|
if (!file.sessionId)
|
|
16727
16815
|
continue;
|
|
16728
16816
|
const previous = ids.get(file.sessionId);
|
|
@@ -16746,7 +16834,7 @@ async function checkSessionIdentities(plan) {
|
|
|
16746
16834
|
for await (const entry of await opendir2(directory)) {
|
|
16747
16835
|
if (++seen > MAX_FILES || entry.isSymbolicLink())
|
|
16748
16836
|
throw refused();
|
|
16749
|
-
const path =
|
|
16837
|
+
const path = join26(directory, entry.name);
|
|
16750
16838
|
if (entry.isDirectory()) {
|
|
16751
16839
|
await scan(path, depth + 1);
|
|
16752
16840
|
continue;
|
|
@@ -16763,8 +16851,8 @@ async function checkSessionIdentities(plan) {
|
|
|
16763
16851
|
file.existing = true;
|
|
16764
16852
|
}
|
|
16765
16853
|
}
|
|
16766
|
-
await scan(
|
|
16767
|
-
await scan(
|
|
16854
|
+
await scan(join26(plan.state.home, "sessions"));
|
|
16855
|
+
await scan(join26(plan.state.home, "archived_sessions"));
|
|
16768
16856
|
}
|
|
16769
16857
|
async function fingerprint2(path, copyTo) {
|
|
16770
16858
|
const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
|
|
@@ -16824,9 +16912,9 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
16824
16912
|
async function visit(path, kind) {
|
|
16825
16913
|
if (++seen > MAX_FILES || path.split("/").length > 32)
|
|
16826
16914
|
throw refused();
|
|
16827
|
-
await ensureNativeStateDirectory(dirname11(
|
|
16828
|
-
await ensureNativeStateDirectory(dirname11(
|
|
16829
|
-
const from =
|
|
16915
|
+
await ensureNativeStateDirectory(dirname11(join26(source, path)), false);
|
|
16916
|
+
await ensureNativeStateDirectory(dirname11(join26(state.home, path)), false);
|
|
16917
|
+
const from = join26(source, path), to = join26(state.home, path), entry = await info2(from), target = await info2(to);
|
|
16830
16918
|
if (!entry)
|
|
16831
16919
|
return;
|
|
16832
16920
|
if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
|
|
@@ -16845,7 +16933,7 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
16845
16933
|
}
|
|
16846
16934
|
children.sort((a, b) => a.name.localeCompare(b.name));
|
|
16847
16935
|
for (const child of children)
|
|
16848
|
-
await visit(
|
|
16936
|
+
await visit(join26(path, child.name), child.kind);
|
|
16849
16937
|
} else {
|
|
16850
16938
|
const value = await fingerprint2(from);
|
|
16851
16939
|
plan.bytes += value.bytes;
|
|
@@ -16899,14 +16987,14 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
16899
16987
|
throw refused();
|
|
16900
16988
|
const requiredDirectories = new Set([plan.state.home]);
|
|
16901
16989
|
for (const path of plan.directories) {
|
|
16902
|
-
for (let directory =
|
|
16990
|
+
for (let directory = join26(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname11(directory)) {
|
|
16903
16991
|
requiredDirectories.add(directory);
|
|
16904
16992
|
if (directory === plan.state.home)
|
|
16905
16993
|
break;
|
|
16906
16994
|
}
|
|
16907
16995
|
}
|
|
16908
16996
|
for (const file of plan.files.filter((file2) => !file2.existing)) {
|
|
16909
|
-
for (let directory = dirname11(
|
|
16997
|
+
for (let directory = dirname11(join26(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname11(directory)) {
|
|
16910
16998
|
requiredDirectories.add(directory);
|
|
16911
16999
|
if (directory === plan.state.home)
|
|
16912
17000
|
break;
|
|
@@ -16927,9 +17015,9 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
16927
17015
|
for (const file of plan.files) {
|
|
16928
17016
|
if (file.existing)
|
|
16929
17017
|
continue;
|
|
16930
|
-
const target =
|
|
17018
|
+
const target = join26(plan.state.home, file.path), temporary = join26(dirname11(target), `.switcher-import-${crypto.randomUUID()}`);
|
|
16931
17019
|
staged.push({ temporary, target });
|
|
16932
|
-
const copied = await fingerprint2(
|
|
17020
|
+
const copied = await fingerprint2(join26(plan.source, file.path), temporary);
|
|
16933
17021
|
if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
|
|
16934
17022
|
throw refused();
|
|
16935
17023
|
}
|
|
@@ -17444,7 +17532,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
17444
17532
|
const marked = process.env[`HASNA_${suffix}_STATE_HOME`] !== undefined || process.env[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
|
|
17445
17533
|
if ((sharedNativeState || shareNativeState === false) && plan.profile.harness === "codex")
|
|
17446
17534
|
assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
|
|
17447
|
-
const root = resolve16(values2["state-dir"] ??
|
|
17535
|
+
const root = resolve16(values2["state-dir"] ?? join27(switcherHome(), "state"));
|
|
17448
17536
|
if (backend !== "direct")
|
|
17449
17537
|
await checkPrivateDirectory(root);
|
|
17450
17538
|
const nativeWarnings = backend === "direct" ? await checkDirectLaunch(root, profileId, plan.profile.harness, {
|
package/dist/harness-types.d.ts
CHANGED
|
@@ -30,6 +30,12 @@ export type HarnessLaunchInput = {
|
|
|
30
30
|
sharedState?: NativeState;
|
|
31
31
|
/** Hosts the launch's inference gateway; a per-launch listener when absent. */
|
|
32
32
|
gatewayHost?: GatewayHost;
|
|
33
|
+
/**
|
|
34
|
+
* Claude only: where to write the session's --settings file when its gateway token
|
|
35
|
+
* outlives the launch (see GatewayLease.routeSettingsFile). The file then carries the
|
|
36
|
+
* route in its env block, so a session the background host restarts keeps it.
|
|
37
|
+
*/
|
|
38
|
+
routeSettingsFile?: string;
|
|
33
39
|
};
|
|
34
40
|
export type PreparedLaunch = {
|
|
35
41
|
executable: string;
|