@hasna/switcher 0.2.22 → 0.2.23
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 +1 -1
- package/dist/cli/index.js +152 -36
- package/dist/gateway-client.d.ts +1 -0
- package/dist/harness-types.d.ts +2 -0
- package/dist/inference-gateway.d.ts +3 -0
- package/dist/mcp/index.js +2 -2
- package/dist/serve/index.js +2 -2
- package/docs/GATEWAY-SERVICE.md +36 -3
- package/openapi.json +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -621,7 +621,7 @@ Cline uses its native ACP backend with per-launch configuration, durable session
|
|
|
621
621
|
|
|
622
622
|
## Background sessions and the persistent gateway
|
|
623
623
|
|
|
624
|
-
Launches register with one persistent gateway per user on a stable `127.0.0.1` port. A launch's token keeps working for as long as any process it started still runs, including Claude Code's detached background host and its background sessions after `switcher launch` exits. When nothing from the launch remains, the launch ends. For 30 days after that, a request with its token from a process of this user running under a current launch, such as a background session that Claude Code's background host started again, revives it; for a launch without a durable Claude route, a copied token used from anywhere else stays refused, and holding a launch that only its durable route revived does not count as running under a current launch. A Claude launch also writes its route into the session's `--settings` file (mode 0600 in the profile's private session folder), so a session the background host restores after a station restart, or opens from another folder, keeps its route without a current launch. So for 30 days after a Claude launch was last used, the gateway serves its token to any running process of this user that presents it, a shell or script included; another account's process, or a connection the gateway cannot trace, is refused when it would revive an ended launch. While any launch is current, the gateway serves its token on any loopback connection that presents it, without a process check. For the default `~/.hasna/switcher` home the gateway runs under launchd (macOS) or systemd `--user` (Linux), starts at login, and is installed automatically by the first launch of the installed `switcher`. Other homes and other copies of Switcher use a detached gateway that exits when idle.
|
|
624
|
+
Launches register with one persistent gateway per user on a stable `127.0.0.1` port. A launch's token keeps working for as long as any process it started still runs, including Claude Code's detached background host and its background sessions after `switcher launch` exits. When nothing from the launch remains, the launch ends. For 30 days after that, a request with its token from a process of this user running under a current launch, such as a background session that Claude Code's background host started again, revives it; for a launch without a durable Claude route, a copied token used from anywhere else stays refused, and holding a launch that only its durable route revived does not count as running under a current launch. A Claude launch also writes its route into the session's `--settings` file (mode 0600 in the profile's private session folder), so a session the background host restores after a station restart, or opens from another folder, keeps its route without a current launch. Since 0.2.23 that launch also gives its route to the profile's earlier picker-only settings files (`claude-settings-<digest>.json`), so sessions dispatched before 0.2.21 come back logged in when their host next starts them, and the gateway takes it back when it stops accepting the token. A launch without a route uses its own `claude-picker-<digest>.json`, which never carries another launch's route. So for 30 days after a Claude launch was last used, the gateway serves its token to any running process of this user that presents it, a shell or script included; another account's process, or a connection the gateway cannot trace, is refused when it would revive an ended launch. While any launch is current, the gateway serves its token on any loopback connection that presents it, without a process check. For the default `~/.hasna/switcher` home the gateway runs under launchd (macOS) or systemd `--user` (Linux), starts at login, and is installed automatically by the first launch of the installed `switcher`. Other homes and other copies of Switcher use a detached gateway that exits when idle.
|
|
625
625
|
|
|
626
626
|
```sh
|
|
627
627
|
switcher gateway status # running, pid, port, launches and login unit
|
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.23";
|
|
518
518
|
|
|
519
519
|
// src/version.ts
|
|
520
520
|
var VERSION = version;
|
|
@@ -2581,7 +2581,7 @@ var openapi_default = {
|
|
|
2581
2581
|
openapi: "3.0.3",
|
|
2582
2582
|
info: {
|
|
2583
2583
|
title: "Switcher API",
|
|
2584
|
-
version: "0.2.
|
|
2584
|
+
version: "0.2.23",
|
|
2585
2585
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2586
2586
|
},
|
|
2587
2587
|
security: [
|
|
@@ -9010,7 +9010,7 @@ async function readCodexAgentConfig(path) {
|
|
|
9010
9010
|
}
|
|
9011
9011
|
|
|
9012
9012
|
// src/harnesses.ts
|
|
9013
|
-
import { access as access3, lstat as lstat6, mkdir as mkdir10, readFile as readFile6, readdir as readdir4, rename as rename2, writeFile as writeFile13, rm as rm2 } from "fs/promises";
|
|
9013
|
+
import { access as access3, lstat as lstat6, mkdir as mkdir10, open as open3, readFile as readFile6, readdir as readdir4, rename as rename2, writeFile as writeFile13, rm as rm2 } from "fs/promises";
|
|
9014
9014
|
import { basename as basename2, dirname as dirname7, join as join15, isAbsolute as isAbsolute13, resolve as resolve8 } from "path";
|
|
9015
9015
|
import { homedir as homedir8, tmpdir } from "os";
|
|
9016
9016
|
import { createHash as createHash9, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
|
|
@@ -10468,6 +10468,45 @@ async function routeJsonFile(path, value) {
|
|
|
10468
10468
|
}
|
|
10469
10469
|
return path;
|
|
10470
10470
|
}
|
|
10471
|
+
async function adoptClaudeSettingsRoutes(dir, route2) {
|
|
10472
|
+
let adopted = 0;
|
|
10473
|
+
for (const name of await readdir4(dir).catch(() => [])) {
|
|
10474
|
+
if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
|
|
10475
|
+
continue;
|
|
10476
|
+
const path = join15(dir, name);
|
|
10477
|
+
const info = await lstat6(path).catch(() => {
|
|
10478
|
+
return;
|
|
10479
|
+
});
|
|
10480
|
+
if (!info?.isFile() || info.nlink !== 1 || (info.mode & 63) !== 0 || info.uid !== process.getuid?.())
|
|
10481
|
+
continue;
|
|
10482
|
+
let value;
|
|
10483
|
+
try {
|
|
10484
|
+
value = JSON.parse(await readFile6(path, "utf8"));
|
|
10485
|
+
} catch {
|
|
10486
|
+
continue;
|
|
10487
|
+
}
|
|
10488
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || !("modelPicker" in value))
|
|
10489
|
+
continue;
|
|
10490
|
+
const temporary = `${path}.${randomUUID4()}.tmp`;
|
|
10491
|
+
try {
|
|
10492
|
+
const handle = await open3(temporary, "wx", 384);
|
|
10493
|
+
try {
|
|
10494
|
+
await handle.writeFile(JSON.stringify({ ...value, ...route2 }, null, 2) + `
|
|
10495
|
+
`);
|
|
10496
|
+
await handle.sync();
|
|
10497
|
+
} finally {
|
|
10498
|
+
await handle.close();
|
|
10499
|
+
}
|
|
10500
|
+
await rename2(temporary, path);
|
|
10501
|
+
adopted++;
|
|
10502
|
+
} catch {
|
|
10503
|
+
await rm2(temporary, { force: true }).catch(() => {
|
|
10504
|
+
return;
|
|
10505
|
+
});
|
|
10506
|
+
}
|
|
10507
|
+
}
|
|
10508
|
+
return adopted;
|
|
10509
|
+
}
|
|
10471
10510
|
async function projectInstructionPaths(cwd) {
|
|
10472
10511
|
let dir = resolve8(cwd);
|
|
10473
10512
|
while (true) {
|
|
@@ -11145,8 +11184,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
11145
11184
|
env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
|
|
11146
11185
|
const picker = { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: nativeModel(m.id), label: m.name, description: m.description?.slice(0, 300) })) } };
|
|
11147
11186
|
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-
|
|
11187
|
+
const file2 = route2 ? await routeJsonFile(input.routeSettingsFile, { ...picker, ...route2 }) : input.sessionDir ? await durableJsonFile(claudeSettingsDirectory(input.sessionDir), "claude-picker", picker) : await jsonFile(input.stateDir, "claude-settings.json", picker);
|
|
11149
11188
|
configPaths.push(file2);
|
|
11189
|
+
if (route2 && input.adoptRoutes) {
|
|
11190
|
+
const adopted = await adoptClaudeSettingsRoutes(dirname7(file2), route2);
|
|
11191
|
+
if (adopted)
|
|
11192
|
+
warnings.push(`Gave this launch's gateway route to ${adopted} earlier Claude settings file${adopted === 1 ? "" : "s"} of this profile; their background sessions use it when their host next starts them.`);
|
|
11193
|
+
}
|
|
11150
11194
|
warnings.push("Claude managed settings and model allowlists can restrict the generated picker.");
|
|
11151
11195
|
return { executable, args: ["--settings", file2, "--model", nativeModel(input.model), ...args], env, configPaths, warnings };
|
|
11152
11196
|
}
|
|
@@ -11516,7 +11560,7 @@ async function prepareHarnessLaunch(input) {
|
|
|
11516
11560
|
};
|
|
11517
11561
|
try {
|
|
11518
11562
|
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";
|
|
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 });
|
|
11563
|
+
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, adoptRoutes: input.harness === "claude" && bridge.adoptRoutes === true });
|
|
11520
11564
|
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 () => {
|
|
11521
11565
|
try {
|
|
11522
11566
|
await prepared.cleanup?.();
|
|
@@ -11621,7 +11665,7 @@ async function verifyOpenCodeAuthentication(credential, fetchImpl) {
|
|
|
11621
11665
|
import { z as z8 } from "zod-v4";
|
|
11622
11666
|
import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
|
|
11623
11667
|
import { constants as constants5 } from "fs";
|
|
11624
|
-
import { open as
|
|
11668
|
+
import { open as open4, readdir as readdir5, unlink, link, lstat as lstat7 } from "fs/promises";
|
|
11625
11669
|
import { join as join16, isAbsolute as isAbsolute15 } from "path";
|
|
11626
11670
|
import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
|
|
11627
11671
|
import { execFile as execFile3, spawn } from "child_process";
|
|
@@ -11690,7 +11734,7 @@ class CredentialBindings {
|
|
|
11690
11734
|
return;
|
|
11691
11735
|
let file;
|
|
11692
11736
|
try {
|
|
11693
|
-
file = await
|
|
11737
|
+
file = await open4(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
11694
11738
|
} catch (error) {
|
|
11695
11739
|
if (error.code === "ENOENT")
|
|
11696
11740
|
return;
|
|
@@ -11742,7 +11786,7 @@ class CredentialBindings {
|
|
|
11742
11786
|
await privateDirectory(join16(switcherHome(this.env), "config"));
|
|
11743
11787
|
await privateDirectory(this.directory);
|
|
11744
11788
|
const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
|
|
11745
|
-
const file = await
|
|
11789
|
+
const file = await open4(temporary, "wx", 384);
|
|
11746
11790
|
try {
|
|
11747
11791
|
await file.writeFile(JSON.stringify(binding, null, 2) + `
|
|
11748
11792
|
`);
|
|
@@ -12865,7 +12909,7 @@ import { fileURLToPath } from "url";
|
|
|
12865
12909
|
|
|
12866
12910
|
// src/desktop-state.ts
|
|
12867
12911
|
import { constants as constants7, closeSync as closeSync2, fstatSync, lstatSync, openSync as openSync2, readSync as readSync2 } from "fs";
|
|
12868
|
-
import { open as
|
|
12912
|
+
import { open as open5, rm as rm3, lstat as lstat8, rename as rename3, chmod as chmod2, copyFile as copyFile2, link as link2 } from "fs/promises";
|
|
12869
12913
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
12870
12914
|
import { resolve as resolve9 } from "path";
|
|
12871
12915
|
import { createHash as createHash12 } from "crypto";
|
|
@@ -12927,7 +12971,7 @@ async function safeDesktopSnapshot(path) {
|
|
|
12927
12971
|
const info = await lstat8(path);
|
|
12928
12972
|
admitDesktopFile(info);
|
|
12929
12973
|
const metadataHash = admitDesktopMetadata(path, info);
|
|
12930
|
-
const file = await
|
|
12974
|
+
const file = await open5(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
|
|
12931
12975
|
try {
|
|
12932
12976
|
const opened = await file.stat();
|
|
12933
12977
|
admitOpenedDesktopFile(info, opened);
|
|
@@ -13164,7 +13208,7 @@ async function writeDesktopPrivate(path, text, mode = 384, metadataSource, expec
|
|
|
13164
13208
|
await preserveDesktopFile(metadataSource?.path ?? path, temporary, template);
|
|
13165
13209
|
await chmod2(temporary, 384);
|
|
13166
13210
|
}
|
|
13167
|
-
const file = await
|
|
13211
|
+
const file = await open5(temporary, constants7.O_RDWR | constants7.O_NOFOLLOW | (template ? 0 : constants7.O_CREAT | constants7.O_EXCL), 384);
|
|
13168
13212
|
try {
|
|
13169
13213
|
await file.truncate(0);
|
|
13170
13214
|
await file.writeFile(text);
|
|
@@ -13225,7 +13269,7 @@ async function openDesktopLease(path, readOnly2 = false) {
|
|
|
13225
13269
|
}
|
|
13226
13270
|
|
|
13227
13271
|
// src/native-state.ts
|
|
13228
|
-
import { lstat as lstat9, mkdir as mkdir11, open as
|
|
13272
|
+
import { lstat as lstat9, mkdir as mkdir11, open as open6, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
|
|
13229
13273
|
import { constants as constants8, lstatSync as lstatSync2, realpathSync } from "fs";
|
|
13230
13274
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
13231
13275
|
import { homedir as homedir9, userInfo as userInfo3 } from "os";
|
|
@@ -13418,7 +13462,7 @@ async function withNativeStateLock(state, operation) {
|
|
|
13418
13462
|
const path = nativeStateLockPath(state);
|
|
13419
13463
|
let handle;
|
|
13420
13464
|
try {
|
|
13421
|
-
handle = await
|
|
13465
|
+
handle = await open6(path, "wx", 384);
|
|
13422
13466
|
} catch (error) {
|
|
13423
13467
|
if (error.code !== "EEXIST")
|
|
13424
13468
|
throw error;
|
|
@@ -13542,7 +13586,7 @@ async function readCodexStateConfig(home) {
|
|
|
13542
13586
|
return {};
|
|
13543
13587
|
if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
|
|
13544
13588
|
throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
|
|
13545
|
-
const handle = await
|
|
13589
|
+
const handle = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
|
|
13546
13590
|
let config;
|
|
13547
13591
|
try {
|
|
13548
13592
|
const opened = await handle.stat();
|
|
@@ -13576,7 +13620,7 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
|
|
|
13576
13620
|
if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
|
|
13577
13621
|
throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
|
|
13578
13622
|
await assertSafeAncestors(dirname8(path));
|
|
13579
|
-
const handle = await
|
|
13623
|
+
const handle = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW).catch(() => {
|
|
13580
13624
|
throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
|
|
13581
13625
|
});
|
|
13582
13626
|
try {
|
|
@@ -13786,7 +13830,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
|
|
|
13786
13830
|
if (entry.kind === "directory")
|
|
13787
13831
|
await createTrackedDirectory(target, createdDirectories);
|
|
13788
13832
|
else {
|
|
13789
|
-
const file = await
|
|
13833
|
+
const file = await open6(target, "wx", 384);
|
|
13790
13834
|
await file.close();
|
|
13791
13835
|
createdFiles.push(target);
|
|
13792
13836
|
}
|
|
@@ -14261,7 +14305,7 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
|
|
|
14261
14305
|
|
|
14262
14306
|
// src/claude-user-settings.ts
|
|
14263
14307
|
import { constants as constants9 } from "fs";
|
|
14264
|
-
import { lstat as lstat10, open as
|
|
14308
|
+
import { lstat as lstat10, open as open7, writeFile as writeFile16 } from "fs/promises";
|
|
14265
14309
|
import { homedir as homedir10 } from "os";
|
|
14266
14310
|
import { join as join20, relative as relative6, resolve as resolve11 } from "path";
|
|
14267
14311
|
var preferences = new Set([
|
|
@@ -14328,7 +14372,7 @@ async function readSettings(home, created) {
|
|
|
14328
14372
|
return;
|
|
14329
14373
|
if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || writableByOthers(entry) || entry.size > 1024 * 1024)
|
|
14330
14374
|
throw invalid4(path);
|
|
14331
|
-
const handle = await
|
|
14375
|
+
const handle = await open7(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
|
|
14332
14376
|
try {
|
|
14333
14377
|
const opened = await handle.stat();
|
|
14334
14378
|
if (opened.dev !== entry.dev || opened.ino !== entry.ino || opened.nlink !== 1 || opened.size > 1024 * 1024)
|
|
@@ -14709,7 +14753,7 @@ import { join as join24 } from "path";
|
|
|
14709
14753
|
// src/gateway-service.ts
|
|
14710
14754
|
import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
|
|
14711
14755
|
import { constants as constants10 } from "fs";
|
|
14712
|
-
import { chmod as chmod3, lstat as lstat11, mkdir as mkdir12, open as
|
|
14756
|
+
import { chmod as chmod3, lstat as lstat11, mkdir as mkdir12, open as open8, readdir as readdir7, readFile as readFile8, rename as rename5, rm as rm5, unlink as unlink3 } from "fs/promises";
|
|
14713
14757
|
import { basename as basename5, dirname as dirname9, isAbsolute as isAbsolute17, join as join22, resolve as resolve13 } from "path";
|
|
14714
14758
|
import { z as z10 } from "zod-v4";
|
|
14715
14759
|
|
|
@@ -14928,6 +14972,7 @@ var MAX_HOLDERS = 4096;
|
|
|
14928
14972
|
var MAX_PROBE_CANDIDATES = 4096;
|
|
14929
14973
|
var PROBE_INTERVAL_MS = 60000;
|
|
14930
14974
|
var ENDED_MS = 30 * 24 * 3600000;
|
|
14975
|
+
var ADOPTION_TEMP_STALE_MS = 60000;
|
|
14931
14976
|
var MAX_ENDED = 1000;
|
|
14932
14977
|
var REVIVE_RETRY_MS = 5000;
|
|
14933
14978
|
var MAX_EVENTS = 1000;
|
|
@@ -15137,7 +15182,7 @@ async function liveGateway(socket) {
|
|
|
15137
15182
|
}
|
|
15138
15183
|
}
|
|
15139
15184
|
async function readPrivateJson(path) {
|
|
15140
|
-
const file = await
|
|
15185
|
+
const file = await open8(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
|
|
15141
15186
|
try {
|
|
15142
15187
|
const info2 = await file.stat();
|
|
15143
15188
|
if (!info2.isFile() || info2.size > 128 * 1024 * 1024 || (info2.mode & 63) !== 0 || info2.uid !== process.getuid?.())
|
|
@@ -15158,14 +15203,21 @@ async function readRecord(directory, id2) {
|
|
|
15158
15203
|
}
|
|
15159
15204
|
async function writePrivate(path, text) {
|
|
15160
15205
|
const temporary = `${path}.${randomUUID7()}.tmp`;
|
|
15161
|
-
const file = await
|
|
15206
|
+
const file = await open8(temporary, "wx", 384);
|
|
15162
15207
|
try {
|
|
15163
|
-
|
|
15164
|
-
|
|
15165
|
-
|
|
15166
|
-
|
|
15208
|
+
try {
|
|
15209
|
+
await file.writeFile(text);
|
|
15210
|
+
await file.sync();
|
|
15211
|
+
} finally {
|
|
15212
|
+
await file.close();
|
|
15213
|
+
}
|
|
15214
|
+
await rename5(temporary, path);
|
|
15215
|
+
} catch (error) {
|
|
15216
|
+
await rm5(temporary, { force: true }).catch(() => {
|
|
15217
|
+
return;
|
|
15218
|
+
});
|
|
15219
|
+
throw error;
|
|
15167
15220
|
}
|
|
15168
|
-
await rename5(temporary, path);
|
|
15169
15221
|
}
|
|
15170
15222
|
async function routeSettingsDirectory(path) {
|
|
15171
15223
|
const profile = dirname9(path);
|
|
@@ -15309,6 +15361,65 @@ async function startGatewayService(options = {}) {
|
|
|
15309
15361
|
`).catch(() => {
|
|
15310
15362
|
return;
|
|
15311
15363
|
});
|
|
15364
|
+
await releaseAdoptedRoutes(record3);
|
|
15365
|
+
};
|
|
15366
|
+
const releaseAdoptedRoutes = async (record3) => {
|
|
15367
|
+
if (!record3.route)
|
|
15368
|
+
return;
|
|
15369
|
+
const dir = record3.route.settingsDir;
|
|
15370
|
+
const tokenOf = (value) => {
|
|
15371
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
15372
|
+
return;
|
|
15373
|
+
const env2 = value.env;
|
|
15374
|
+
if (!env2 || typeof env2 !== "object" || Array.isArray(env2))
|
|
15375
|
+
return;
|
|
15376
|
+
const keys = env2;
|
|
15377
|
+
const token = [keys.ANTHROPIC_AUTH_TOKEN, keys.ANTHROPIC_API_KEY].find((item2) => typeof item2 === "string" && item2 !== "");
|
|
15378
|
+
return typeof token === "string" ? token : undefined;
|
|
15379
|
+
};
|
|
15380
|
+
for (const name of await readdir7(dir).catch(() => [])) {
|
|
15381
|
+
if (/^claude-settings-[0-9a-f]{32}\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
|
|
15382
|
+
const path2 = join22(dir, name);
|
|
15383
|
+
try {
|
|
15384
|
+
const info2 = await lstat11(path2);
|
|
15385
|
+
if (!info2.isFile() || info2.uid !== process.getuid?.() || info2.size > 1024 * 1024)
|
|
15386
|
+
continue;
|
|
15387
|
+
let value;
|
|
15388
|
+
try {
|
|
15389
|
+
value = JSON.parse(await readFile8(path2, "utf8"));
|
|
15390
|
+
} catch {
|
|
15391
|
+
value = undefined;
|
|
15392
|
+
}
|
|
15393
|
+
if (value === undefined) {
|
|
15394
|
+
if (Date.now() - info2.mtimeMs <= ADOPTION_TEMP_STALE_MS)
|
|
15395
|
+
continue;
|
|
15396
|
+
} else {
|
|
15397
|
+
const token = tokenOf(value);
|
|
15398
|
+
if (token === undefined || sha256(token) !== record3.tokenDigest)
|
|
15399
|
+
continue;
|
|
15400
|
+
}
|
|
15401
|
+
await rm5(path2, { force: true });
|
|
15402
|
+
} catch {}
|
|
15403
|
+
continue;
|
|
15404
|
+
}
|
|
15405
|
+
if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
|
|
15406
|
+
continue;
|
|
15407
|
+
const path = join22(dir, name);
|
|
15408
|
+
try {
|
|
15409
|
+
const info2 = await lstat11(path);
|
|
15410
|
+
if (!info2.isFile() || info2.nlink !== 1)
|
|
15411
|
+
continue;
|
|
15412
|
+
const value = await readPrivateJson(path);
|
|
15413
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
15414
|
+
continue;
|
|
15415
|
+
const { env: _env, ...picker } = value;
|
|
15416
|
+
const token = tokenOf(value);
|
|
15417
|
+
if (token === undefined || sha256(token) !== record3.tokenDigest)
|
|
15418
|
+
continue;
|
|
15419
|
+
await writePrivate(path, JSON.stringify(picker, null, 2) + `
|
|
15420
|
+
`);
|
|
15421
|
+
} catch {}
|
|
15422
|
+
}
|
|
15312
15423
|
};
|
|
15313
15424
|
const expireEnded = async (entry) => {
|
|
15314
15425
|
await forgetEnded(entry);
|
|
@@ -15357,10 +15468,12 @@ async function startGatewayService(options = {}) {
|
|
|
15357
15468
|
return;
|
|
15358
15469
|
});
|
|
15359
15470
|
const route2 = end ? undefined : routeFile(launch.record);
|
|
15360
|
-
if (route2)
|
|
15471
|
+
if (route2) {
|
|
15361
15472
|
await rm5(route2, { force: true }).catch(() => {
|
|
15362
15473
|
return;
|
|
15363
15474
|
});
|
|
15475
|
+
await releaseAdoptedRoutes(launch.record);
|
|
15476
|
+
}
|
|
15364
15477
|
if (removeState && launch.record.stateDir) {
|
|
15365
15478
|
const directory = await launchStateDirectory(launch.record.stateDir).catch(() => {
|
|
15366
15479
|
return;
|
|
@@ -15620,7 +15733,7 @@ async function startGatewayService(options = {}) {
|
|
|
15620
15733
|
await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
|
|
15621
15734
|
await persist(launch, true);
|
|
15622
15735
|
log(`launch ${record3.id.slice(0, 8)} registered (${record3.gateway.harness}, ${record3.gateway.model})`);
|
|
15623
|
-
return { id: record3.id, token, baseUrl: `${url}/${record3.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}
|
|
15736
|
+
return { id: record3.id, token, baseUrl: `${url}/${record3.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}`, ...route2 ? { releasesAdoptedRoutes: true } : {} };
|
|
15624
15737
|
};
|
|
15625
15738
|
const release = async (launch) => {
|
|
15626
15739
|
const table = await processTable().catch(() => {
|
|
@@ -15759,7 +15872,7 @@ async function startGatewayService(options = {}) {
|
|
|
15759
15872
|
|
|
15760
15873
|
// src/gateway-supervisor.ts
|
|
15761
15874
|
import { randomUUID as randomUUID8 } from "crypto";
|
|
15762
|
-
import { lstat as lstat12, mkdir as mkdir13, open as
|
|
15875
|
+
import { lstat as lstat12, mkdir as mkdir13, open as open9, readFile as readFile9, realpath as realpath7, rename as rename6, unlink as unlink4 } from "fs/promises";
|
|
15763
15876
|
import { dirname as dirname10, isAbsolute as isAbsolute18, join as join23 } from "path";
|
|
15764
15877
|
var LAUNCHD_LABEL = "com.hasna.switcher.gateway";
|
|
15765
15878
|
var SYSTEMD_UNIT = "switcher-gateway.service";
|
|
@@ -15902,14 +16015,14 @@ var defaultRunner = async (argv) => {
|
|
|
15902
16015
|
}
|
|
15903
16016
|
};
|
|
15904
16017
|
async function writeUnit(path, content) {
|
|
15905
|
-
const previous = await
|
|
16018
|
+
const previous = await readFile9(path, "utf8").catch(() => {
|
|
15906
16019
|
return;
|
|
15907
16020
|
});
|
|
15908
16021
|
if (previous === content)
|
|
15909
16022
|
return false;
|
|
15910
16023
|
await mkdir13(dirname10(path), { recursive: true, mode: 493 });
|
|
15911
16024
|
const temporary = `${path}.${randomUUID8()}.tmp`;
|
|
15912
|
-
const file = await
|
|
16025
|
+
const file = await open9(temporary, "wx", 420);
|
|
15913
16026
|
try {
|
|
15914
16027
|
await file.writeFile(content);
|
|
15915
16028
|
await file.sync();
|
|
@@ -16135,13 +16248,16 @@ function createServiceGatewayHost(client, context) {
|
|
|
16135
16248
|
return createInferenceGateway(input);
|
|
16136
16249
|
}
|
|
16137
16250
|
const routeSettingsFile = durable && route2 ? join24(route2.settingsDir, `claude-route-${registration.id}.json`) : undefined;
|
|
16251
|
+
const adoptRoutes = routeSettingsFile !== undefined && registration.releasesAdoptedRoutes === true;
|
|
16252
|
+
if (routeSettingsFile && !adoptRoutes)
|
|
16253
|
+
(context.warn ?? console.error)("switcher: The running gateway predates 0.2.23 and cannot take a route back from earlier Claude settings files, so Claude sessions dispatched before 0.2.21 are left as they are. Run `switcher gateway install` to restart it on this version.");
|
|
16138
16254
|
const lease = { id: registration.id, attached: attachedPid !== undefined, retained: false, done: false };
|
|
16139
16255
|
leases.push(lease);
|
|
16140
16256
|
if (attachedPid !== undefined)
|
|
16141
16257
|
attaching.push(client.attach(lease.id, attachedPid).catch(() => {
|
|
16142
16258
|
return;
|
|
16143
16259
|
}));
|
|
16144
|
-
return { baseUrl: registration.baseUrl, token: registration.token, ...routeSettingsFile ? { routeSettingsFile } : {}, retainsState: () => lease.retained, cleanup: async () => {
|
|
16260
|
+
return { baseUrl: registration.baseUrl, token: registration.token, ...routeSettingsFile ? { routeSettingsFile } : {}, ...adoptRoutes ? { adoptRoutes } : {}, retainsState: () => lease.retained, cleanup: async () => {
|
|
16145
16261
|
if (lease.done)
|
|
16146
16262
|
return;
|
|
16147
16263
|
lease.done = true;
|
|
@@ -16744,7 +16860,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
16744
16860
|
// src/native-state-import.ts
|
|
16745
16861
|
import { createHash as createHash18 } from "crypto";
|
|
16746
16862
|
import { constants as constants11 } from "fs";
|
|
16747
|
-
import { lstat as lstat14, open as
|
|
16863
|
+
import { lstat as lstat14, open as open10, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
|
|
16748
16864
|
import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as join26, relative as relative8, resolve as resolve15 } from "path";
|
|
16749
16865
|
var MAX_FILES = 1e5;
|
|
16750
16866
|
var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
|
|
@@ -16767,7 +16883,7 @@ var inside3 = (parent, child) => {
|
|
|
16767
16883
|
var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
|
|
16768
16884
|
async function sessionId(path, expected) {
|
|
16769
16885
|
const nameId = basename6(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
|
|
16770
|
-
const handle = await
|
|
16886
|
+
const handle = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
|
|
16771
16887
|
try {
|
|
16772
16888
|
const before = await handle.stat();
|
|
16773
16889
|
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
|
|
@@ -16855,14 +16971,14 @@ async function checkSessionIdentities(plan) {
|
|
|
16855
16971
|
await scan(join26(plan.state.home, "archived_sessions"));
|
|
16856
16972
|
}
|
|
16857
16973
|
async function fingerprint2(path, copyTo) {
|
|
16858
|
-
const handle = await
|
|
16974
|
+
const handle = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
|
|
16859
16975
|
let output, complete = false;
|
|
16860
16976
|
try {
|
|
16861
16977
|
const before = await handle.stat();
|
|
16862
16978
|
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
|
|
16863
16979
|
throw refused();
|
|
16864
16980
|
if (copyTo)
|
|
16865
|
-
output = await
|
|
16981
|
+
output = await open10(copyTo, "wx", 384);
|
|
16866
16982
|
const hash3 = createHash18("sha256"), buffer = Buffer.alloc(64 * 1024);
|
|
16867
16983
|
let bytes = 0;
|
|
16868
16984
|
for (;; ) {
|
package/dist/gateway-client.d.ts
CHANGED
package/dist/harness-types.d.ts
CHANGED
|
@@ -36,6 +36,8 @@ export type HarnessLaunchInput = {
|
|
|
36
36
|
* route in its env block, so a session the background host restarts keeps it.
|
|
37
37
|
*/
|
|
38
38
|
routeSettingsFile?: string;
|
|
39
|
+
/** Claude only: give the durable route to the profile's earlier picker files (see GatewayLease.adoptRoutes). */
|
|
40
|
+
adoptRoutes?: boolean;
|
|
39
41
|
};
|
|
40
42
|
export type PreparedLaunch = {
|
|
41
43
|
executable: string;
|
|
@@ -23,6 +23,8 @@ export type GatewayInput = HarnessLaunchInput & {
|
|
|
23
23
|
* routeSettingsFile: set when the gateway keeps serving this token to a session of this user
|
|
24
24
|
* after the launch ends and across restarts (a durable route). The harness writes the route
|
|
25
25
|
* into that file, which the gateway removes or empties when it stops accepting the token.
|
|
26
|
+
* adoptRoutes: the gateway also takes the route back from the earlier picker files the harness
|
|
27
|
+
* gives it to, so the harness may give it to them.
|
|
26
28
|
*/
|
|
27
29
|
export type GatewayLease = {
|
|
28
30
|
baseUrl: string;
|
|
@@ -30,6 +32,7 @@ export type GatewayLease = {
|
|
|
30
32
|
cleanup: () => Promise<void>;
|
|
31
33
|
retainsState?: () => boolean;
|
|
32
34
|
routeSettingsFile?: string;
|
|
35
|
+
adoptRoutes?: boolean;
|
|
33
36
|
};
|
|
34
37
|
/** Where a launch's inference gateway runs: its own listener, or a persistent service. */
|
|
35
38
|
export type GatewayHost = {
|
package/dist/mcp/index.js
CHANGED
|
@@ -19495,7 +19495,7 @@ function canonicalPolicyJSON(value) {
|
|
|
19495
19495
|
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);
|
|
19496
19496
|
}
|
|
19497
19497
|
// package.json
|
|
19498
|
-
var version2 = "0.2.
|
|
19498
|
+
var version2 = "0.2.23";
|
|
19499
19499
|
|
|
19500
19500
|
// src/version.ts
|
|
19501
19501
|
var VERSION = version2;
|
|
@@ -22579,7 +22579,7 @@ var openapi_default = {
|
|
|
22579
22579
|
openapi: "3.0.3",
|
|
22580
22580
|
info: {
|
|
22581
22581
|
title: "Switcher API",
|
|
22582
|
-
version: "0.2.
|
|
22582
|
+
version: "0.2.23",
|
|
22583
22583
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
22584
22584
|
},
|
|
22585
22585
|
security: [
|
package/dist/serve/index.js
CHANGED
|
@@ -68,7 +68,7 @@ function canonicalPolicyJSON(value) {
|
|
|
68
68
|
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);
|
|
69
69
|
}
|
|
70
70
|
// package.json
|
|
71
|
-
var version = "0.2.
|
|
71
|
+
var version = "0.2.23";
|
|
72
72
|
|
|
73
73
|
// src/version.ts
|
|
74
74
|
var VERSION = version;
|
|
@@ -922,7 +922,7 @@ var openapi_default = {
|
|
|
922
922
|
openapi: "3.0.3",
|
|
923
923
|
info: {
|
|
924
924
|
title: "Switcher API",
|
|
925
|
-
version: "0.2.
|
|
925
|
+
version: "0.2.23",
|
|
926
926
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
927
927
|
},
|
|
928
928
|
security: [
|
package/docs/GATEWAY-SERVICE.md
CHANGED
|
@@ -119,6 +119,33 @@ SWITCHER_GATEWAY=local switcher launch ... # use the per-launch gateway of 0.2
|
|
|
119
119
|
harness never started removes its file. A running gateway older than 0.2.21 refuses
|
|
120
120
|
the route; the launch then registers as before and prints a warning naming
|
|
121
121
|
`switcher gateway install`.
|
|
122
|
+
Sessions dispatched by 0.2.19 to 0.2.22 without a durable route (before 0.2.21, or
|
|
123
|
+
under a gateway that refused the route) replay a picker-only
|
|
124
|
+
`claude-settings-<digest>.json` from the same folder, and Claude's background host
|
|
125
|
+
restarts them without `ANTHROPIC_BASE_URL` or a token, so they come up "Not logged
|
|
126
|
+
in". Since 0.2.23 a launch with a durable route also writes its `env` block (the same
|
|
127
|
+
loopback base URL and launch token as its route file) into each of those picker
|
|
128
|
+
files: only this user's regular files with a model picker, mode 0600 and a single
|
|
129
|
+
link. Each is rewritten in place by an atomic rename, each time a launch with a route
|
|
130
|
+
starts, so the files carry the newest such launch's route. Such a session reaches
|
|
131
|
+
that launch the next time its host starts it. When the service stops accepting the
|
|
132
|
+
launch's token, or the launch is revoked, it removes the block again from each picker
|
|
133
|
+
file whose token is that launch's (single-link files only), leaving the picker byte
|
|
134
|
+
for byte as it was; a file a later launch gave its own route keeps that route. Each
|
|
135
|
+
rewrite is synced before its rename; a temporary file an interrupted rewrite left
|
|
136
|
+
behind is removed with the route when it carries that launch's token, or when it is a
|
|
137
|
+
partial write last modified more than a minute earlier (so a write still in progress
|
|
138
|
+
is never removed). Taking the route back needs a 0.2.23 or later gateway, which says
|
|
139
|
+
so in its answer to the route registration (`releasesAdoptedRoutes: true`). With an
|
|
140
|
+
older gateway (0.2.21 or 0.2.22) the launch keeps its own route file but gives its
|
|
141
|
+
route to no earlier picker file, and prints a warning naming `switcher gateway install`.
|
|
142
|
+
Since 0.2.23 a launch without a route (`SWITCHER_GATEWAY=local`, a persistent gateway
|
|
143
|
+
that is unavailable or refused the launch or the route) never uses those files: it
|
|
144
|
+
writes its own picker-only `claude-picker-<digest>.json`, and no route is ever written
|
|
145
|
+
into a `claude-picker-*` file, so Claude never applies another launch's route over
|
|
146
|
+
its environment. A session such a launch started is not reached by a later route
|
|
147
|
+
either. A session pinned to a per-launch `launch-XXXXXX/claude-settings.json` from
|
|
148
|
+
before 0.2.19 is not reached and needs a new `switcher launch`.
|
|
122
149
|
|
|
123
150
|
Every request is dispatched by its token to that launch's own handler. One launch
|
|
124
151
|
cannot use another launch's credential, catalog, aliases or fallbacks.
|
|
@@ -172,7 +199,12 @@ While the service runs, a client always gets an HTTP answer it can show:
|
|
|
172
199
|
create the directory first.
|
|
173
200
|
- Provider credentials are never written to disk, logs, unit files or command lines,
|
|
174
201
|
and neither are launch tokens, with one exception: a Claude launch's durable route
|
|
175
|
-
file (step 7) holds that launch's token.
|
|
202
|
+
file (step 7) holds that launch's token. Since 0.2.23 so do the profile's
|
|
203
|
+
`claude-settings-<digest>.json` picker files from earlier launches that the newest
|
|
204
|
+
launch with a route gave its route to (step 7). Those are not created once: each launch
|
|
205
|
+
with a route rewrites them in place by an atomic rename of a private (0600) temporary
|
|
206
|
+
file in the same folder, and only when each is this user's regular 0600 file with a
|
|
207
|
+
single link. The route file itself is created once, exclusively, mode
|
|
176
208
|
0600, in a settings folder that must be a real directory owned by the user with mode
|
|
177
209
|
0700 (otherwise the launch is refused), under the 0700 Switcher state folder. The token
|
|
178
210
|
is accepted only by this gateway on `127.0.0.1` and reaches only that launch's
|
|
@@ -252,8 +284,9 @@ While the service runs, a client always gets an HTTP answer it can show:
|
|
|
252
284
|
launch after a host restart.
|
|
253
285
|
- A launch that ended before the service ran 0.2.19 has no record, so a session that
|
|
254
286
|
still uses it gets `switcher_gateway_launch_unknown`.
|
|
255
|
-
- Claude's picker settings (`--settings`) are written
|
|
256
|
-
`state/sessions/claude/<profile>/settings/claude-
|
|
287
|
+
- Claude's picker settings (`--settings`) of a launch without a durable route are written
|
|
288
|
+
to `state/sessions/claude/<profile>/settings/claude-picker-<digest>.json`
|
|
289
|
+
(`claude-settings-<digest>.json` before 0.2.23), outside the
|
|
257
290
|
launch's temporary folder, because the background host replays that path when it
|
|
258
291
|
restarts a session. Sessions started by 0.2.18 or older name a path in a launch folder
|
|
259
292
|
that may be gone; Claude then refuses to start them ("Settings file not found") until
|
package/openapi.json
CHANGED
package/package.json
CHANGED