@hasna/switcher 0.2.11 → 0.2.12
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/dist/claude-desktop-gateway.d.ts +30 -0
- package/dist/claude-desktop-launch.d.ts +2 -3
- package/dist/claude-desktop-models.d.ts +2 -0
- package/dist/claude-desktop.d.ts +6 -0
- package/dist/claude-desktop.js +5007 -0
- package/dist/cli/index.js +367 -155
- package/dist/desktop-apps.d.ts +3 -0
- package/dist/desktop-selection.d.ts +20 -0
- package/dist/desktop-state.d.ts +11 -1
- package/dist/index.js +5362 -86
- package/dist/mcp/index.js +6315 -368
- package/dist/native-state.d.ts +2 -0
- package/dist/private-directory.d.ts +2 -0
- package/dist/runtime.d.ts +1 -1
- package/dist/sdk.js +5362 -86
- package/dist/serve/index.js +2 -2
- package/docs/CLAUDE-DESKTOP-GATEWAY.md +69 -0
- package/hasna.contract.json +1 -1
- package/openapi.json +1 -1
- package/package.json +8 -3
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.12";
|
|
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 join24, resolve as resolve14 } from "path";
|
|
1113
1113
|
|
|
1114
1114
|
// src/http.ts
|
|
1115
1115
|
var MAX_BYTES = 16 * 1024 * 1024;
|
|
@@ -1319,7 +1319,7 @@ function providerCredential(provider, env = process.env) {
|
|
|
1319
1319
|
import { execFile } from "child_process";
|
|
1320
1320
|
import { access, stat as stat3 } from "fs/promises";
|
|
1321
1321
|
import { constants as constants2 } from "fs";
|
|
1322
|
-
import { homedir as homedir2 } from "os";
|
|
1322
|
+
import { homedir as homedir2, userInfo as userInfo2 } from "os";
|
|
1323
1323
|
import { isAbsolute as isAbsolute3, join as join3 } from "path";
|
|
1324
1324
|
import { promisify } from "util";
|
|
1325
1325
|
var execute = promisify(execFile);
|
|
@@ -1412,6 +1412,28 @@ async function detectClaudeDesktopApp(appPath, system = host) {
|
|
|
1412
1412
|
}
|
|
1413
1413
|
throw new Fault(404, "app_not_installed", "Install the current Claude macOS desktop app or supply its absolute .app path with --app-path.");
|
|
1414
1414
|
}
|
|
1415
|
+
var claudeDesktopDataDirectory = () => join3(homedir2(), "Library/Application Support/Claude-3p");
|
|
1416
|
+
function validateClaudeDesktopVersion(app) {
|
|
1417
|
+
const version2 = app.version.split(".").map(Number);
|
|
1418
|
+
if (version2.length < 3 || version2.some((n) => !Number.isSafeInteger(n)) || version2[0] < 1 || version2[0] === 1 && version2[1] < 52386)
|
|
1419
|
+
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for the gateway adapter.");
|
|
1420
|
+
}
|
|
1421
|
+
async function assertClaudeDesktopAvailable(userData) {
|
|
1422
|
+
for (const path of [join3("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
1423
|
+
if (await access(path).then(() => true, () => false))
|
|
1424
|
+
throw new Fault(409, "desktop_managed", "Claude has managed preferences; Switcher will not override them.");
|
|
1425
|
+
let openFiles;
|
|
1426
|
+
try {
|
|
1427
|
+
openFiles = (await execute("/usr/sbin/lsof", ["-n", "-P", "-Fpn", "-a", "-u", String(process.getuid?.()), "-c", "Claude"], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, timeout: 8000 })).stdout;
|
|
1428
|
+
} catch (error) {
|
|
1429
|
+
if (error.code === 1)
|
|
1430
|
+
return;
|
|
1431
|
+
throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
|
|
1432
|
+
}
|
|
1433
|
+
if (openFiles.split(`
|
|
1434
|
+
`).some((line) => line.startsWith("n" + userData + "/")))
|
|
1435
|
+
throw new Fault(409, "desktop_busy", "Claude's third-party instance is already running.");
|
|
1436
|
+
}
|
|
1415
1437
|
|
|
1416
1438
|
// src/sdk.ts
|
|
1417
1439
|
class SwitcherError extends Error {
|
|
@@ -1890,7 +1912,6 @@ import { parseTree as parseTree2, getNodeValue } from "jsonc-parser";
|
|
|
1890
1912
|
|
|
1891
1913
|
// src/runtime.ts
|
|
1892
1914
|
import { randomBytes } from "crypto";
|
|
1893
|
-
import { mkdir as mkdir4, lstat } from "fs/promises";
|
|
1894
1915
|
import { homedir as homedir3 } from "os";
|
|
1895
1916
|
import { isAbsolute as isAbsolute4, join as join4, resolve as resolve3 } from "path";
|
|
1896
1917
|
|
|
@@ -2549,7 +2570,7 @@ var openapi_default = {
|
|
|
2549
2570
|
openapi: "3.0.3",
|
|
2550
2571
|
info: {
|
|
2551
2572
|
title: "Switcher API",
|
|
2552
|
-
version: "0.2.
|
|
2573
|
+
version: "0.2.12",
|
|
2553
2574
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2554
2575
|
},
|
|
2555
2576
|
security: [
|
|
@@ -7128,13 +7149,8 @@ function announceSwitcherLocalMode(home, write = (line) => {
|
|
|
7128
7149
|
`);
|
|
7129
7150
|
}
|
|
7130
7151
|
|
|
7131
|
-
// src/
|
|
7132
|
-
|
|
7133
|
-
function switcherHome(env = process.env) {
|
|
7134
|
-
const override = env.HASNA_HOME?.trim();
|
|
7135
|
-
const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
|
|
7136
|
-
return resolve3(env.HASNA_SWITCHER_HOME ?? join4(root, "switcher"));
|
|
7137
|
-
}
|
|
7152
|
+
// src/private-directory.ts
|
|
7153
|
+
import { mkdir as mkdir4, lstat } from "fs/promises";
|
|
7138
7154
|
async function privateDirectory(path) {
|
|
7139
7155
|
await mkdir4(path, { recursive: true, mode: 448 });
|
|
7140
7156
|
const info = await lstat(path);
|
|
@@ -7143,6 +7159,14 @@ async function privateDirectory(path) {
|
|
|
7143
7159
|
if (process.platform !== "win32" && ((info.mode & 63) !== 0 || info.uid !== process.getuid?.()))
|
|
7144
7160
|
throw new Fault(500, "home_permissions", "Switcher data directory must be owned by this user and accessible only to its owner (mode 0700).");
|
|
7145
7161
|
}
|
|
7162
|
+
|
|
7163
|
+
// src/runtime.ts
|
|
7164
|
+
var REMOTE_API_CONFIG_MISSING = "remote_api_config_missing";
|
|
7165
|
+
function switcherHome(env = process.env) {
|
|
7166
|
+
const override = env.HASNA_HOME?.trim();
|
|
7167
|
+
const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
|
|
7168
|
+
return resolve3(env.HASNA_SWITCHER_HOME ?? join4(root, "switcher"));
|
|
7169
|
+
}
|
|
7146
7170
|
async function openCliRuntime(env = process.env, resolveCredential) {
|
|
7147
7171
|
const providerEnv = Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith("SWITCHER_PROVIDER_")));
|
|
7148
7172
|
const remote = () => ({ client: clientFromEnv(env), mode: "remote", providerEnv, close: async () => {} });
|
|
@@ -11330,7 +11354,7 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
|
11330
11354
|
|
|
11331
11355
|
// src/launcher.ts
|
|
11332
11356
|
import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile18 } from "fs/promises";
|
|
11333
|
-
import { join as
|
|
11357
|
+
import { join as join22, resolve as resolve12 } from "path";
|
|
11334
11358
|
|
|
11335
11359
|
// src/provider-credential-onboarding.ts
|
|
11336
11360
|
import { z as z9 } from "zod";
|
|
@@ -12624,29 +12648,103 @@ function oriLaunchWarnings(target) {
|
|
|
12624
12648
|
|
|
12625
12649
|
// src/chatgpt-launch.ts
|
|
12626
12650
|
import { createHash as createHash12 } from "crypto";
|
|
12627
|
-
import { writeFile as
|
|
12651
|
+
import { writeFile as writeFile14, rm as rm4 } from "fs/promises";
|
|
12628
12652
|
import { join as join18 } from "path";
|
|
12629
12653
|
import { fileURLToPath } from "url";
|
|
12630
12654
|
|
|
12631
12655
|
// src/desktop-state.ts
|
|
12632
|
-
import {
|
|
12633
|
-
import {
|
|
12634
|
-
|
|
12656
|
+
import { constants as constants7, closeSync as closeSync2, fstatSync, lstatSync, openSync as openSync2, readSync as readSync2 } from "fs";
|
|
12657
|
+
import { open as open4, rm as rm3, lstat as lstat7, rename as rename2, chmod as chmod2 } from "fs/promises";
|
|
12658
|
+
var desktopReadLimit = 1024 * 1024;
|
|
12659
|
+
function admitDesktopFile(info) {
|
|
12660
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || (info.mode & 18) !== 0 || info.size > desktopReadLimit)
|
|
12661
|
+
throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
|
|
12662
|
+
}
|
|
12663
|
+
function admitOpenedDesktopFile(info, opened) {
|
|
12664
|
+
if (opened.dev !== info.dev || opened.ino !== info.ino || opened.nlink !== 1 || opened.size > desktopReadLimit || opened.mode !== info.mode || opened.uid !== info.uid)
|
|
12665
|
+
throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
|
|
12666
|
+
}
|
|
12667
|
+
function desktopSnapshot(bytes, length, opened, after) {
|
|
12668
|
+
if (length > desktopReadLimit || length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs || after.mode !== opened.mode)
|
|
12669
|
+
throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
|
|
12670
|
+
try {
|
|
12671
|
+
return { text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length)), mode: after.mode & 4095 };
|
|
12672
|
+
} catch {
|
|
12673
|
+
throw new Fault(422, "desktop_state_encoding", "Desktop settings must be valid UTF-8; original bytes were left unchanged.");
|
|
12674
|
+
}
|
|
12675
|
+
}
|
|
12676
|
+
async function safeDesktopSnapshot(path) {
|
|
12635
12677
|
try {
|
|
12636
12678
|
const info = await lstat7(path);
|
|
12637
|
-
|
|
12638
|
-
|
|
12639
|
-
|
|
12679
|
+
admitDesktopFile(info);
|
|
12680
|
+
const file = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
|
|
12681
|
+
try {
|
|
12682
|
+
const opened = await file.stat();
|
|
12683
|
+
admitOpenedDesktopFile(info, opened);
|
|
12684
|
+
const bytes = Buffer.alloc(desktopReadLimit + 1);
|
|
12685
|
+
let length = 0;
|
|
12686
|
+
while (length < bytes.length) {
|
|
12687
|
+
const read = await file.read(bytes, length, bytes.length - length, length);
|
|
12688
|
+
if (read.bytesRead === 0)
|
|
12689
|
+
break;
|
|
12690
|
+
length += read.bytesRead;
|
|
12691
|
+
}
|
|
12692
|
+
return desktopSnapshot(bytes, length, opened, await file.stat());
|
|
12693
|
+
} finally {
|
|
12694
|
+
await file.close();
|
|
12695
|
+
}
|
|
12640
12696
|
} catch (error) {
|
|
12641
12697
|
if (error.code === "ENOENT")
|
|
12642
12698
|
return;
|
|
12643
12699
|
throw error;
|
|
12644
12700
|
}
|
|
12645
12701
|
}
|
|
12646
|
-
|
|
12702
|
+
function safeDesktopSnapshotSync(path) {
|
|
12703
|
+
try {
|
|
12704
|
+
const info = lstatSync(path);
|
|
12705
|
+
admitDesktopFile(info);
|
|
12706
|
+
const file = openSync2(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
|
|
12707
|
+
try {
|
|
12708
|
+
const opened = fstatSync(file);
|
|
12709
|
+
admitOpenedDesktopFile(info, opened);
|
|
12710
|
+
const bytes = Buffer.alloc(desktopReadLimit + 1);
|
|
12711
|
+
let length = 0;
|
|
12712
|
+
while (length < bytes.length) {
|
|
12713
|
+
const count = readSync2(file, bytes, length, bytes.length - length, length);
|
|
12714
|
+
if (count === 0)
|
|
12715
|
+
break;
|
|
12716
|
+
length += count;
|
|
12717
|
+
}
|
|
12718
|
+
const snapshot2 = desktopSnapshot(bytes, length, opened, fstatSync(file));
|
|
12719
|
+
admitOpenedDesktopFile(opened, lstatSync(path));
|
|
12720
|
+
return snapshot2;
|
|
12721
|
+
} finally {
|
|
12722
|
+
closeSync2(file);
|
|
12723
|
+
}
|
|
12724
|
+
} catch (error) {
|
|
12725
|
+
if (error.code === "ENOENT")
|
|
12726
|
+
return;
|
|
12727
|
+
throw error;
|
|
12728
|
+
}
|
|
12729
|
+
}
|
|
12730
|
+
async function safeDesktopRead(path) {
|
|
12731
|
+
return (await safeDesktopSnapshot(path))?.text;
|
|
12732
|
+
}
|
|
12733
|
+
async function writeDesktopPrivate(path, text, mode = 384) {
|
|
12734
|
+
if (!Number.isInteger(mode) || mode < 0 || mode > 4095 || (mode & 18) !== 0)
|
|
12735
|
+
throw new Fault(422, "desktop_state_permissions", "Desktop settings restoration requires an admitted original mode.");
|
|
12647
12736
|
const temporary = path + "." + crypto.randomUUID() + ".tmp";
|
|
12648
12737
|
try {
|
|
12649
|
-
await
|
|
12738
|
+
const file = await open4(temporary, "wx", 384);
|
|
12739
|
+
try {
|
|
12740
|
+
await file.writeFile(text);
|
|
12741
|
+
await file.chmod(mode);
|
|
12742
|
+
} finally {
|
|
12743
|
+
await file.close();
|
|
12744
|
+
}
|
|
12745
|
+
const written = await safeDesktopSnapshot(temporary);
|
|
12746
|
+
if (written?.text !== text || written.mode !== mode)
|
|
12747
|
+
throw new Fault(409, "desktop_state_changed", "Desktop settings restoration readback failed.");
|
|
12650
12748
|
await rename2(temporary, path);
|
|
12651
12749
|
} finally {
|
|
12652
12750
|
await rm3(temporary, { force: true });
|
|
@@ -12655,13 +12753,13 @@ async function writeDesktopPrivate(path, text) {
|
|
|
12655
12753
|
async function desktopLease(path) {
|
|
12656
12754
|
try {
|
|
12657
12755
|
const info = await lstat7(path);
|
|
12658
|
-
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
12756
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || (info.mode & 18) !== 0)
|
|
12659
12757
|
throw new Fault(422, "desktop_state_permissions", "Desktop lease must be a regular file owned by this user.");
|
|
12660
12758
|
} catch (error) {
|
|
12661
12759
|
if (error.code !== "ENOENT")
|
|
12662
12760
|
throw error;
|
|
12663
12761
|
}
|
|
12664
|
-
const lease =
|
|
12762
|
+
const lease = await openDesktopLease(path);
|
|
12665
12763
|
try {
|
|
12666
12764
|
await chmod2(path, 384);
|
|
12667
12765
|
lease.exec("PRAGMA busy_timeout=0; CREATE TABLE IF NOT EXISTS lease (id INTEGER PRIMARY KEY); BEGIN EXCLUSIVE;");
|
|
@@ -12677,10 +12775,25 @@ async function desktopLease(path) {
|
|
|
12677
12775
|
}
|
|
12678
12776
|
};
|
|
12679
12777
|
}
|
|
12778
|
+
async function openDesktopLease(path, readOnly2 = false) {
|
|
12779
|
+
try {
|
|
12780
|
+
if (process.versions.bun) {
|
|
12781
|
+
const { Database: Database3 } = await import("bun:sqlite");
|
|
12782
|
+
return readOnly2 ? new Database3(path, { readonly: true }) : new Database3(path);
|
|
12783
|
+
}
|
|
12784
|
+
const [major, minor] = process.versions.node.split(".").map(Number);
|
|
12785
|
+
if (major !== 24 || minor < 20)
|
|
12786
|
+
throw new Error("unsupported runtime");
|
|
12787
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
12788
|
+
return new DatabaseSync(path, { readOnly: readOnly2 });
|
|
12789
|
+
} catch {
|
|
12790
|
+
throw new Fault(422, "desktop_runtime", "Desktop gateway state requires Bun or Node 24.20 or newer in the Node 24 release line with node:sqlite.");
|
|
12791
|
+
}
|
|
12792
|
+
}
|
|
12680
12793
|
|
|
12681
12794
|
// src/native-state.ts
|
|
12682
|
-
import { lstat as lstat8, mkdir as mkdir11, open as
|
|
12683
|
-
import { constants as
|
|
12795
|
+
import { lstat as lstat8, mkdir as mkdir11, open as open5, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
|
|
12796
|
+
import { constants as constants8, lstatSync as lstatSync2, realpathSync } from "fs";
|
|
12684
12797
|
import { homedir as homedir9 } from "os";
|
|
12685
12798
|
import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
|
|
12686
12799
|
function nativeStateRequested(tool, environment = process.env, explicit) {
|
|
@@ -12736,20 +12849,26 @@ function absolute(value) {
|
|
|
12736
12849
|
function credentialOverlay(path) {
|
|
12737
12850
|
return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
|
|
12738
12851
|
}
|
|
12852
|
+
function assertSafeAncestor(ancestor) {
|
|
12853
|
+
const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
|
|
12854
|
+
if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
|
|
12855
|
+
throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
|
|
12856
|
+
}
|
|
12739
12857
|
async function assertSafeAncestors(path) {
|
|
12740
12858
|
for (let parent = path;; parent = dirname8(parent)) {
|
|
12741
|
-
|
|
12742
|
-
const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
|
|
12743
|
-
if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
|
|
12744
|
-
throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
|
|
12859
|
+
assertSafeAncestor(await lstat8(parent));
|
|
12745
12860
|
if (parent === dirname8(parent))
|
|
12746
12861
|
break;
|
|
12747
12862
|
}
|
|
12748
12863
|
}
|
|
12864
|
+
function assertNativeDirectoryEntry(entry, redirected = false) {
|
|
12865
|
+
if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || redirected)
|
|
12866
|
+
throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
|
|
12867
|
+
}
|
|
12749
12868
|
async function assertNativeStateDirectory(path) {
|
|
12750
12869
|
const entry = await info(path);
|
|
12751
|
-
|
|
12752
|
-
|
|
12870
|
+
assertNativeDirectoryEntry(entry);
|
|
12871
|
+
assertNativeDirectoryEntry(entry, await realpath6(path) !== path);
|
|
12753
12872
|
await assertSafeAncestors(dirname8(path));
|
|
12754
12873
|
}
|
|
12755
12874
|
async function ensureNativeStateDirectory(path, create = true) {
|
|
@@ -12793,7 +12912,7 @@ async function withNativeStateLock(state, operation) {
|
|
|
12793
12912
|
const path = join17(state.home, ".switcher-shared-state.lock");
|
|
12794
12913
|
let handle;
|
|
12795
12914
|
try {
|
|
12796
|
-
handle = await
|
|
12915
|
+
handle = await open5(path, "wx", 384);
|
|
12797
12916
|
} catch (error) {
|
|
12798
12917
|
if (error.code !== "EEXIST")
|
|
12799
12918
|
throw error;
|
|
@@ -12844,7 +12963,7 @@ async function readCodexStateConfig(home) {
|
|
|
12844
12963
|
return {};
|
|
12845
12964
|
if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
|
|
12846
12965
|
throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
|
|
12847
|
-
const handle = await
|
|
12966
|
+
const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
|
|
12848
12967
|
let config;
|
|
12849
12968
|
try {
|
|
12850
12969
|
const opened = await handle.stat();
|
|
@@ -12878,7 +12997,7 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
|
|
|
12878
12997
|
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)
|
|
12879
12998
|
throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
|
|
12880
12999
|
await assertSafeAncestors(dirname8(path));
|
|
12881
|
-
const handle = await
|
|
13000
|
+
const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW).catch(() => {
|
|
12882
13001
|
throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
|
|
12883
13002
|
});
|
|
12884
13003
|
try {
|
|
@@ -13061,7 +13180,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
|
|
|
13061
13180
|
if (entry.kind === "directory")
|
|
13062
13181
|
await createTrackedDirectory(target, createdDirectories);
|
|
13063
13182
|
else {
|
|
13064
|
-
const file = await
|
|
13183
|
+
const file = await open5(target, "wx", 384);
|
|
13065
13184
|
await file.close();
|
|
13066
13185
|
createdFiles.push(target);
|
|
13067
13186
|
}
|
|
@@ -13213,7 +13332,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedSta
|
|
|
13213
13332
|
fi
|
|
13214
13333
|
`;
|
|
13215
13334
|
}
|
|
13216
|
-
await
|
|
13335
|
+
await writeFile14(wrapper, `#!/bin/sh
|
|
13217
13336
|
set -eu
|
|
13218
13337
|
unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
|
|
13219
13338
|
export CODEX_HOME=${quote2(home)}
|
|
@@ -13244,18 +13363,156 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
|
|
|
13244
13363
|
}
|
|
13245
13364
|
|
|
13246
13365
|
// src/claude-desktop-launch.ts
|
|
13247
|
-
import {
|
|
13248
|
-
import {
|
|
13249
|
-
|
|
13250
|
-
import {
|
|
13251
|
-
import {
|
|
13252
|
-
import {
|
|
13366
|
+
import { writeFile as writeFile17 } from "fs/promises";
|
|
13367
|
+
import { join as join21 } from "path";
|
|
13368
|
+
// src/desktop-selection.ts
|
|
13369
|
+
import { createHash as createHash13, randomUUID as randomUUID6 } from "crypto";
|
|
13370
|
+
import { rm as rm5, writeFile as writeFile15 } from "fs/promises";
|
|
13371
|
+
import { join as join19 } from "path";
|
|
13372
|
+
var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
|
|
13373
|
+
var conflict = () => new Fault(409, "desktop_config_changed", "Desktop configuration changed; existing bytes and the recovery receipt were preserved.");
|
|
13374
|
+
var invalid3 = () => new Fault(409, "desktop_recovery", "Desktop selection needs recovery by its owning supported version before another launch.");
|
|
13375
|
+
var identifier = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,80}$/.test(value);
|
|
13376
|
+
var admittedMode = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4095 && (value & 18) === 0;
|
|
13377
|
+
var matches = (actual, text, mode) => (actual?.text ?? null) === text && (actual?.mode ?? null) === mode;
|
|
13378
|
+
function metadata(text) {
|
|
13379
|
+
if (text === null)
|
|
13380
|
+
return { entries: [] };
|
|
13381
|
+
let value;
|
|
13382
|
+
try {
|
|
13383
|
+
value = JSON.parse(text);
|
|
13384
|
+
} catch {
|
|
13385
|
+
throw invalid3();
|
|
13386
|
+
}
|
|
13387
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
13388
|
+
throw invalid3();
|
|
13389
|
+
const m = value;
|
|
13390
|
+
if (!Array.isArray(m.entries) || m.entries.some((x) => !x || typeof x !== "object" || Array.isArray(x)) || m.appliedId !== undefined && !identifier(m.appliedId))
|
|
13391
|
+
throw invalid3();
|
|
13392
|
+
return m;
|
|
13393
|
+
}
|
|
13394
|
+
function receipt(text) {
|
|
13395
|
+
let r;
|
|
13396
|
+
try {
|
|
13397
|
+
r = JSON.parse(text);
|
|
13398
|
+
} catch {
|
|
13399
|
+
throw invalid3();
|
|
13400
|
+
}
|
|
13401
|
+
if (r?.version !== 3 || !identifier(r.id) || !/^[0-9a-f-]{36}$/.test(r.id) || !/^[a-f0-9]{64}$/.test(r.configHash) || r.previousMeta !== null && typeof r.previousMeta !== "string" || typeof r.appliedMeta !== "string" || (r.previousMeta === null ? r.previousMetaMode !== null : !admittedMode(r.previousMetaMode)) || r.previousSelected !== null && (!r.previousSelected || !identifier(r.previousSelected.id) || r.previousSelected.text !== null && typeof r.previousSelected.text !== "string"))
|
|
13402
|
+
throw invalid3();
|
|
13403
|
+
const before = metadata(r.previousMeta), after = metadata(r.appliedMeta);
|
|
13404
|
+
if (after.appliedId !== r.id || before.appliedId === r.id || (before.appliedId ?? null) !== (r.previousSelected?.id ?? null))
|
|
13405
|
+
throw invalid3();
|
|
13406
|
+
return r;
|
|
13407
|
+
}
|
|
13408
|
+
async function selectedUnchanged(library, r) {
|
|
13409
|
+
if (r.previousSelected && (await safeDesktopRead(join19(library, r.previousSelected.id + ".json")) ?? null) !== r.previousSelected.text)
|
|
13410
|
+
throw conflict();
|
|
13411
|
+
}
|
|
13412
|
+
async function recoverDesktopSelection(library) {
|
|
13413
|
+
const path = join19(library, ".switcher-selection.json"), raw = await safeDesktopRead(path);
|
|
13414
|
+
if (raw === undefined)
|
|
13415
|
+
return;
|
|
13416
|
+
const r = receipt(raw), metaPath = join19(library, "_meta.json"), configPath = join19(library, r.id + ".json");
|
|
13417
|
+
const currentMeta = await safeDesktopSnapshot(metaPath), currentConfig = await safeDesktopRead(configPath);
|
|
13418
|
+
const wasOriginal = matches(currentMeta, r.previousMeta, r.previousMetaMode), wasApplied = matches(currentMeta, r.appliedMeta, 384);
|
|
13419
|
+
await selectedUnchanged(library, r);
|
|
13420
|
+
if (!wasOriginal && !wasApplied)
|
|
13421
|
+
throw conflict();
|
|
13422
|
+
if (currentConfig !== undefined && hash2(currentConfig) !== r.configHash || wasApplied && currentConfig === undefined)
|
|
13423
|
+
throw conflict();
|
|
13424
|
+
if (await safeDesktopRead(path) !== raw)
|
|
13425
|
+
throw conflict();
|
|
13426
|
+
if (!matches(await safeDesktopSnapshot(metaPath), currentMeta?.text ?? null, currentMeta?.mode ?? null))
|
|
13427
|
+
throw conflict();
|
|
13428
|
+
if (wasApplied) {
|
|
13429
|
+
if (r.previousMeta === null)
|
|
13430
|
+
await rm5(metaPath);
|
|
13431
|
+
else
|
|
13432
|
+
await writeDesktopPrivate(metaPath, r.previousMeta, r.previousMetaMode);
|
|
13433
|
+
if (!matches(await safeDesktopSnapshot(metaPath), r.previousMeta, r.previousMetaMode))
|
|
13434
|
+
throw conflict();
|
|
13435
|
+
}
|
|
13436
|
+
if (currentConfig !== undefined) {
|
|
13437
|
+
if (hash2(await safeDesktopRead(configPath) ?? "") !== r.configHash)
|
|
13438
|
+
throw conflict();
|
|
13439
|
+
await rm5(configPath);
|
|
13440
|
+
}
|
|
13441
|
+
if (await safeDesktopRead(path) !== raw)
|
|
13442
|
+
throw conflict();
|
|
13443
|
+
await rm5(path);
|
|
13444
|
+
}
|
|
13445
|
+
async function applyDesktopSelection(library, config, label2, checkpoint) {
|
|
13446
|
+
await recoverDesktopSelection(library);
|
|
13447
|
+
const path = join19(library, ".switcher-selection.json"), metaPath = join19(library, "_meta.json");
|
|
13448
|
+
const original = await safeDesktopSnapshot(metaPath), previousMeta = original?.text ?? null, previousMetaMode = original?.mode ?? null, previous = metadata(previousMeta);
|
|
13449
|
+
const previousSelected = previous.appliedId ? { id: previous.appliedId, text: await safeDesktopRead(join19(library, previous.appliedId + ".json")) ?? null } : null;
|
|
13450
|
+
const id2 = randomUUID6(), configPath = join19(library, id2 + ".json"), text = JSON.stringify(config, null, 2) + `
|
|
13451
|
+
`;
|
|
13452
|
+
const appliedMeta = JSON.stringify({ ...previous, appliedId: id2, entries: [...previous.entries, { id: id2, name: label2 }] }, null, 2) + `
|
|
13453
|
+
`;
|
|
13454
|
+
const r = { version: 3, id: id2, configHash: hash2(text), previousMeta, previousMetaMode, appliedMeta, previousSelected };
|
|
13455
|
+
const journal = JSON.stringify(r) + `
|
|
13456
|
+
`;
|
|
13457
|
+
if (Buffer.byteLength(journal) > 1024 * 1024)
|
|
13458
|
+
throw invalid3();
|
|
13459
|
+
await writeFile15(path, journal, { mode: 384, flag: "wx" });
|
|
13460
|
+
const unchanged = async () => {
|
|
13461
|
+
if (await safeDesktopRead(path) !== journal)
|
|
13462
|
+
throw conflict();
|
|
13463
|
+
await selectedUnchanged(library, r);
|
|
13464
|
+
};
|
|
13465
|
+
try {
|
|
13466
|
+
await unchanged();
|
|
13467
|
+
await checkpoint?.("preserved");
|
|
13468
|
+
if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode))
|
|
13469
|
+
throw conflict();
|
|
13470
|
+
await selectedUnchanged(library, r);
|
|
13471
|
+
await writeFile15(configPath, text, { mode: 384, flag: "wx" });
|
|
13472
|
+
if (await safeDesktopRead(configPath) !== text)
|
|
13473
|
+
throw conflict();
|
|
13474
|
+
await checkpoint?.("config");
|
|
13475
|
+
await unchanged();
|
|
13476
|
+
if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode))
|
|
13477
|
+
throw conflict();
|
|
13478
|
+
await writeDesktopPrivate(metaPath, appliedMeta);
|
|
13479
|
+
if (!matches(await safeDesktopSnapshot(metaPath), appliedMeta, 384))
|
|
13480
|
+
throw conflict();
|
|
13481
|
+
await checkpoint?.("selected");
|
|
13482
|
+
} catch (error) {
|
|
13483
|
+
try {
|
|
13484
|
+
if (await safeDesktopRead(path) === journal)
|
|
13485
|
+
await recoverDesktopSelection(library);
|
|
13486
|
+
} catch {}
|
|
13487
|
+
throw error;
|
|
13488
|
+
}
|
|
13489
|
+
const assertCurrentSync = () => {
|
|
13490
|
+
if (safeDesktopSnapshotSync(path)?.text !== journal)
|
|
13491
|
+
throw conflict();
|
|
13492
|
+
if (previousSelected && (safeDesktopSnapshotSync(join19(library, previousSelected.id + ".json"))?.text ?? null) !== previousSelected.text)
|
|
13493
|
+
throw conflict();
|
|
13494
|
+
if (!matches(safeDesktopSnapshotSync(metaPath), appliedMeta, 384) || safeDesktopSnapshotSync(configPath)?.text !== text)
|
|
13495
|
+
throw conflict();
|
|
13496
|
+
};
|
|
13497
|
+
return {
|
|
13498
|
+
configPath,
|
|
13499
|
+
assertCurrentSync,
|
|
13500
|
+
async assertCurrent() {
|
|
13501
|
+
assertCurrentSync();
|
|
13502
|
+
},
|
|
13503
|
+
async restore() {
|
|
13504
|
+
if (await safeDesktopRead(path) !== journal)
|
|
13505
|
+
throw conflict();
|
|
13506
|
+
await recoverDesktopSelection(library);
|
|
13507
|
+
}
|
|
13508
|
+
};
|
|
13509
|
+
}
|
|
13253
13510
|
|
|
13254
13511
|
// src/claude-user-settings.ts
|
|
13255
|
-
import { constants as
|
|
13256
|
-
import { lstat as lstat9, open as
|
|
13512
|
+
import { constants as constants9 } from "fs";
|
|
13513
|
+
import { lstat as lstat9, open as open6, writeFile as writeFile16 } from "fs/promises";
|
|
13257
13514
|
import { homedir as homedir10 } from "os";
|
|
13258
|
-
import { join as
|
|
13515
|
+
import { join as join20, resolve as resolve10 } from "path";
|
|
13259
13516
|
var preferences = new Set([
|
|
13260
13517
|
"$schema",
|
|
13261
13518
|
"permissions",
|
|
@@ -13280,10 +13537,10 @@ var preferences = new Set([
|
|
|
13280
13537
|
"teammateMode"
|
|
13281
13538
|
]);
|
|
13282
13539
|
var routing3 = new Set(["model", "modelPicker", "fallbackModel"]);
|
|
13283
|
-
var
|
|
13540
|
+
var invalid4 = () => new Fault(422, "claude_user_settings", "Claude user settings cannot be safely projected. Use a regular owned JSON settings file with supported preferences and permission policy.");
|
|
13284
13541
|
async function readSettings(home) {
|
|
13285
13542
|
await ensureNativeStateDirectory(home, false);
|
|
13286
|
-
const path =
|
|
13543
|
+
const path = join20(home, "settings.json");
|
|
13287
13544
|
const entry = await lstat9(path).catch((error) => {
|
|
13288
13545
|
if (error.code === "ENOENT")
|
|
13289
13546
|
return;
|
|
@@ -13292,20 +13549,20 @@ async function readSettings(home) {
|
|
|
13292
13549
|
if (!entry)
|
|
13293
13550
|
return;
|
|
13294
13551
|
if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
|
|
13295
|
-
throw
|
|
13296
|
-
const handle = await
|
|
13552
|
+
throw invalid4();
|
|
13553
|
+
const handle = await open6(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
|
|
13297
13554
|
try {
|
|
13298
13555
|
const opened = await handle.stat();
|
|
13299
13556
|
if (opened.dev !== entry.dev || opened.ino !== entry.ino || opened.nlink !== 1 || opened.size > 1024 * 1024)
|
|
13300
|
-
throw
|
|
13557
|
+
throw invalid4();
|
|
13301
13558
|
const value = JSON.parse(await handle.readFile("utf8"));
|
|
13302
13559
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
13303
|
-
throw
|
|
13560
|
+
throw invalid4();
|
|
13304
13561
|
return value;
|
|
13305
13562
|
} catch (error) {
|
|
13306
13563
|
if (error instanceof Fault)
|
|
13307
13564
|
throw error;
|
|
13308
|
-
throw
|
|
13565
|
+
throw invalid4();
|
|
13309
13566
|
} finally {
|
|
13310
13567
|
await handle.close();
|
|
13311
13568
|
}
|
|
@@ -13333,7 +13590,7 @@ async function prepareClaudeUserSettings(overlayHome, environment = process.env)
|
|
|
13333
13590
|
project(existing, true);
|
|
13334
13591
|
return;
|
|
13335
13592
|
}
|
|
13336
|
-
const sourceHome = resolve10(environment.CLAUDE_CONFIG_DIR ??
|
|
13593
|
+
const sourceHome = resolve10(environment.CLAUDE_CONFIG_DIR ?? join20(environment.HOME ?? homedir10(), ".claude"));
|
|
13337
13594
|
if (sourceHome === overlayHome)
|
|
13338
13595
|
return;
|
|
13339
13596
|
const source = await readSettings(sourceHome);
|
|
@@ -13342,7 +13599,7 @@ async function prepareClaudeUserSettings(overlayHome, environment = process.env)
|
|
|
13342
13599
|
const settings2 = project(source, false);
|
|
13343
13600
|
await ensureNativeStateDirectory(overlayHome);
|
|
13344
13601
|
try {
|
|
13345
|
-
await writeFile16(
|
|
13602
|
+
await writeFile16(join20(overlayHome, "settings.json"), JSON.stringify(settings2, null, 2) + `
|
|
13346
13603
|
`, { mode: 384, flag: "wx" });
|
|
13347
13604
|
} catch (error) {
|
|
13348
13605
|
if (error.code !== "EEXIST")
|
|
@@ -13354,31 +13611,6 @@ async function prepareClaudeUserSettings(overlayHome, environment = process.env)
|
|
|
13354
13611
|
}
|
|
13355
13612
|
|
|
13356
13613
|
// src/claude-desktop-launch.ts
|
|
13357
|
-
var execute4 = promisify5(execFile5);
|
|
13358
|
-
var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
|
|
13359
|
-
var claudeDesktopDataDirectory = () => join20(homedir11(), "Library/Application Support/Claude-3p");
|
|
13360
|
-
async function assertAvailable(userData) {
|
|
13361
|
-
for (const path of [join20("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
13362
|
-
if (await access4(path).then(() => true, () => false))
|
|
13363
|
-
throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
|
|
13364
|
-
let openFiles;
|
|
13365
|
-
try {
|
|
13366
|
-
openFiles = (await execute4("/usr/sbin/lsof", ["-n", "-P", "-Fpn", "-a", "-u", String(process.getuid?.()), "-c", "Claude"], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, timeout: 8000 })).stdout;
|
|
13367
|
-
} catch (error) {
|
|
13368
|
-
if (error.code === 1)
|
|
13369
|
-
return;
|
|
13370
|
-
throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
|
|
13371
|
-
}
|
|
13372
|
-
if (openFiles.split(`
|
|
13373
|
-
`).some((line) => line.startsWith("n" + userData + "/")))
|
|
13374
|
-
throw new Fault(409, "desktop_busy", "Claude's third-party instance is already running. Quit that instance before changing its provider; the normal Claude instance can stay open.");
|
|
13375
|
-
}
|
|
13376
|
-
function metadata(text) {
|
|
13377
|
-
const value = text === undefined ? { entries: [] } : JSON.parse(text);
|
|
13378
|
-
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item2) => !item2 || typeof item2 !== "object" || Array.isArray(item2)))
|
|
13379
|
-
throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
|
|
13380
|
-
return value;
|
|
13381
|
-
}
|
|
13382
13614
|
async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
13383
13615
|
if (input.harness !== "claude")
|
|
13384
13616
|
throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
|
|
@@ -13387,51 +13619,35 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
13387
13619
|
validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
|
|
13388
13620
|
if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
|
|
13389
13621
|
throw new Fault(400, "desktop_arguments", "Claude desktop uses its own effort and permission controls; native CLI arguments and Codex-only launch controls are not accepted.");
|
|
13390
|
-
|
|
13391
|
-
if (version2.length < 3 || version2.some((n) => !Number.isSafeInteger(n)) || version2[0] < 1 || version2[0] === 1 && version2[1] < 52386)
|
|
13392
|
-
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
|
|
13622
|
+
validateClaudeDesktopVersion(app);
|
|
13393
13623
|
const userData = system?.userData ?? claudeDesktopDataDirectory();
|
|
13394
|
-
const check2 = system?.assertAvailable ?? (() =>
|
|
13624
|
+
const check2 = system?.assertAvailable ?? (() => assertClaudeDesktopAvailable(userData));
|
|
13395
13625
|
await check2();
|
|
13396
13626
|
await privateDirectory(userData);
|
|
13397
|
-
const library =
|
|
13627
|
+
const library = join21(userData, "configLibrary");
|
|
13398
13628
|
await privateDirectory(library);
|
|
13399
|
-
const release = await desktopLease(
|
|
13400
|
-
|
|
13401
|
-
let receipt, gateway, closed = false;
|
|
13402
|
-
const restore = async (record3) => {
|
|
13403
|
-
if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
|
|
13404
|
-
throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
|
|
13405
|
-
const configPath = join20(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
|
|
13406
|
-
if (current !== undefined && hash2(current) !== record3.configHash)
|
|
13407
|
-
throw new Fault(409, "desktop_config_changed", "The Switcher Claude configuration was edited outside this launch. Switcher will preserve it; review the configuration library before relaunching.");
|
|
13408
|
-
const currentMeta = await safeDesktopRead(metaPath);
|
|
13409
|
-
if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
|
|
13410
|
-
throw new Fault(409, "desktop_config_changed", "Claude's selected configuration changed during this launch. Switcher will preserve the changed selection; review its configuration library before relaunching.");
|
|
13411
|
-
if (record3.previousMeta === null)
|
|
13412
|
-
await rm5(metaPath, { force: true });
|
|
13413
|
-
else
|
|
13414
|
-
await writeDesktopPrivate(metaPath, record3.previousMeta);
|
|
13415
|
-
await rm5(configPath, { force: true });
|
|
13416
|
-
await rm5(receiptPath, { force: true });
|
|
13417
|
-
};
|
|
13629
|
+
const release = await desktopLease(join21(library, ".switcher-lease.sqlite"));
|
|
13630
|
+
let selection, gateway, closed = false, cleanupError;
|
|
13418
13631
|
const cleanup = async () => {
|
|
13419
|
-
if (closed)
|
|
13632
|
+
if (closed) {
|
|
13633
|
+
if (cleanupError)
|
|
13634
|
+
throw cleanupError;
|
|
13420
13635
|
return;
|
|
13421
|
-
|
|
13636
|
+
}
|
|
13422
13637
|
try {
|
|
13423
13638
|
await gateway?.cleanup();
|
|
13424
|
-
|
|
13425
|
-
|
|
13639
|
+
await selection?.restore();
|
|
13640
|
+
} catch (error) {
|
|
13641
|
+
cleanupError = error;
|
|
13642
|
+
throw error;
|
|
13426
13643
|
} finally {
|
|
13644
|
+
closed = true;
|
|
13427
13645
|
release();
|
|
13428
13646
|
}
|
|
13429
13647
|
};
|
|
13430
13648
|
try {
|
|
13431
|
-
|
|
13432
|
-
|
|
13433
|
-
await restore(JSON.parse(recovery));
|
|
13434
|
-
const localConfig = await safeDesktopRead(join20(userData, "claude_desktop_config.json"));
|
|
13649
|
+
await recoverDesktopSelection(library);
|
|
13650
|
+
const localConfig = await safeDesktopRead(join21(userData, "claude_desktop_config.json"));
|
|
13435
13651
|
if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
|
|
13436
13652
|
throw new Fault(409, "desktop_mode", "Claude's third-party profile is set to standard account mode. Select third-party mode in Claude before launching this gateway.");
|
|
13437
13653
|
if (input.sharedState)
|
|
@@ -13446,31 +13662,27 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
13446
13662
|
if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
|
|
13447
13663
|
throw new Fault(409, "desktop_alias_conflict", "The model policy conflicts with Claude desktop's reserved switcher/sonnet, switcher/opus or switcher/haiku routing aliases.");
|
|
13448
13664
|
const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
|
|
13449
|
-
const catalogPath =
|
|
13665
|
+
const catalogPath = join21(input.stateDir, "claude-desktop-policy.json");
|
|
13450
13666
|
await writeFile17(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
|
|
13451
13667
|
gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
13452
|
-
|
|
13453
|
-
const config = JSON.stringify({
|
|
13668
|
+
selection = await applyDesktopSelection(library, {
|
|
13454
13669
|
inferenceProvider: "gateway",
|
|
13455
13670
|
inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
|
|
13456
13671
|
inferenceGatewayApiKey: gateway.token,
|
|
13457
13672
|
inferenceGatewayAuthScheme: "bearer",
|
|
13458
13673
|
modelDiscoveryEnabled: false,
|
|
13459
13674
|
inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
|
|
13460
|
-
});
|
|
13461
|
-
const
|
|
13462
|
-
const meta = metadata(previousMeta);
|
|
13463
|
-
const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
|
|
13464
|
-
receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
|
|
13465
|
-
await writeDesktopPrivate(configPath, config);
|
|
13466
|
-
await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
|
|
13467
|
-
await writeDesktopPrivate(metaPath, appliedMeta);
|
|
13675
|
+
}, `Switcher: ${input.providerId ?? "provider"} / ${input.model}`);
|
|
13676
|
+
const configPath = selection.configPath;
|
|
13468
13677
|
return {
|
|
13469
13678
|
executable: app.executable,
|
|
13470
13679
|
args: [],
|
|
13471
13680
|
env: { ...input.sharedState ? nativeStateEnvironment(input.sharedState) : {}, CLAUDE_CONFIG_DIR: sessionDir },
|
|
13472
13681
|
configPaths: [catalogPath, configPath],
|
|
13473
|
-
beforeLaunch:
|
|
13682
|
+
beforeLaunch: async () => {
|
|
13683
|
+
await check2();
|
|
13684
|
+
await selection.assertCurrent();
|
|
13685
|
+
},
|
|
13474
13686
|
cleanup,
|
|
13475
13687
|
warnings: [`Claude desktop gateway: ${input.providerId ?? "provider"} / ${input.model}. Uses the shared Claude-3p profile, separate from the normal Claude account. Quit this instance before switching providers; keep Switcher running until then. The previous configuration selection is restored on exit. Managed settings and native permissions remain authoritative.`]
|
|
13476
13688
|
};
|
|
@@ -13687,7 +13899,7 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
|
|
|
13687
13899
|
// src/launcher.ts
|
|
13688
13900
|
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
13689
13901
|
async function writeOriCodexCatalog(stateDir, models) {
|
|
13690
|
-
const path =
|
|
13902
|
+
const path = join22(stateDir, "ori-codex-models.json");
|
|
13691
13903
|
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
13692
13904
|
await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
13693
13905
|
`, { mode: 384, flag: "wx" });
|
|
@@ -13781,7 +13993,7 @@ async function prepareOriForPlan(plan, options) {
|
|
|
13781
13993
|
});
|
|
13782
13994
|
try {
|
|
13783
13995
|
const shim = prepareOriModelPolicy(request.target, native);
|
|
13784
|
-
const dir =
|
|
13996
|
+
const dir = join22(options.stateDir, "ori-bin"), path = join22(dir, shim.name);
|
|
13785
13997
|
await mkdir12(dir, { mode: 448 });
|
|
13786
13998
|
await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
|
|
13787
13999
|
return { contract, prepared: {
|
|
@@ -13838,9 +14050,9 @@ async function launch(client, profileId, options = {}) {
|
|
|
13838
14050
|
validateHarnessVersion("gemini", detection?.version);
|
|
13839
14051
|
if (backend === "direct" && plan.profile.harness === "aider")
|
|
13840
14052
|
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
13841
|
-
const root = resolve12(options.stateDir ??
|
|
14053
|
+
const root = resolve12(options.stateDir ?? join22(switcherHome(), "state"));
|
|
13842
14054
|
await privateDirectory(root);
|
|
13843
|
-
const stateDir = await mkdtemp(
|
|
14055
|
+
const stateDir = await mkdtemp(join22(root, "launch-"));
|
|
13844
14056
|
let credential;
|
|
13845
14057
|
if (backend === "direct") {
|
|
13846
14058
|
try {
|
|
@@ -13900,7 +14112,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
13900
14112
|
if (sharedState && !options.desktop && !options.claudeDesktop) {
|
|
13901
14113
|
const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
|
|
13902
14114
|
const configured = process.env[variable] ? resolve12(process.env[variable]) : undefined;
|
|
13903
|
-
nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ?
|
|
14115
|
+
nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join22(root, "native-claude", profileId) : configured ?? sharedState.home;
|
|
13904
14116
|
if (sharedState.tool === "claude")
|
|
13905
14117
|
await prepareClaudeUserSettings(nativeHome2);
|
|
13906
14118
|
await privateDirectory(nativeHome2);
|
|
@@ -13910,12 +14122,12 @@ async function launch(client, profileId, options = {}) {
|
|
|
13910
14122
|
if (options.shareNativeState === false && backend === "direct") {
|
|
13911
14123
|
const tool = plan.profile.harness;
|
|
13912
14124
|
if (options.desktop)
|
|
13913
|
-
await assertNativeStateIsolation(tool,
|
|
14125
|
+
await assertNativeStateIsolation(tool, join22(root, "desktop", desktopState, "codex"));
|
|
13914
14126
|
else if (options.claudeDesktop)
|
|
13915
|
-
await assertNativeStateIsolation(tool,
|
|
14127
|
+
await assertNativeStateIsolation(tool, join22(root, "desktop-claude", desktopState));
|
|
13916
14128
|
else {
|
|
13917
14129
|
const variable = tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
|
|
13918
|
-
nativeHome2 = process.env[variable] ? resolve12(process.env[variable]) :
|
|
14130
|
+
nativeHome2 = process.env[variable] ? resolve12(process.env[variable]) : join22(root, `native-${tool}`, profileId);
|
|
13919
14131
|
await assertNativeStateIsolation(tool, nativeHome2);
|
|
13920
14132
|
await privateDirectory(nativeHome2);
|
|
13921
14133
|
}
|
|
@@ -13935,7 +14147,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
13935
14147
|
cwd: resolve12(options.cwd ?? process.cwd()),
|
|
13936
14148
|
sharedState
|
|
13937
14149
|
};
|
|
13938
|
-
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop,
|
|
14150
|
+
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join22(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
|
|
13939
14151
|
harness: plan.profile.harness,
|
|
13940
14152
|
baseUrl: plan.provider.baseUrl,
|
|
13941
14153
|
protocol: plan.provider.protocol,
|
|
@@ -13954,7 +14166,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
13954
14166
|
cwd: resolve12(options.cwd ?? process.cwd()),
|
|
13955
14167
|
version: detection?.version,
|
|
13956
14168
|
sharedState,
|
|
13957
|
-
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir:
|
|
14169
|
+
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir: join22(root, "sessions", plan.profile.harness, profileId) } : {}
|
|
13958
14170
|
});
|
|
13959
14171
|
cleanup = prepared.cleanup;
|
|
13960
14172
|
prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
|
|
@@ -13971,7 +14183,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
13971
14183
|
prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
|
|
13972
14184
|
}
|
|
13973
14185
|
if (options.desktop) {
|
|
13974
|
-
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir,
|
|
14186
|
+
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join22(root, "desktop", desktopState), sharedState);
|
|
13975
14187
|
cleanup = prepared.cleanup;
|
|
13976
14188
|
}
|
|
13977
14189
|
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
@@ -14191,9 +14403,9 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
14191
14403
|
|
|
14192
14404
|
// src/native-state-import.ts
|
|
14193
14405
|
import { createHash as createHash15 } from "crypto";
|
|
14194
|
-
import { constants as
|
|
14195
|
-
import { lstat as lstat10, open as
|
|
14196
|
-
import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as
|
|
14406
|
+
import { constants as constants10 } from "fs";
|
|
14407
|
+
import { lstat as lstat10, open as open7, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
|
|
14408
|
+
import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join23, relative as relative6, resolve as resolve13 } from "path";
|
|
14197
14409
|
var MAX_FILES = 1e5;
|
|
14198
14410
|
var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
|
|
14199
14411
|
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.");
|
|
@@ -14215,7 +14427,7 @@ var inside3 = (parent, child) => {
|
|
|
14215
14427
|
var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
|
|
14216
14428
|
async function sessionId(path, expected) {
|
|
14217
14429
|
const nameId = basename4(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
|
|
14218
|
-
const handle = await
|
|
14430
|
+
const handle = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
|
|
14219
14431
|
try {
|
|
14220
14432
|
const before = await handle.stat();
|
|
14221
14433
|
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
|
|
@@ -14258,7 +14470,7 @@ async function checkSessionIdentities(plan) {
|
|
|
14258
14470
|
for (const file of plan.files) {
|
|
14259
14471
|
if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
|
|
14260
14472
|
continue;
|
|
14261
|
-
file.sessionId = await sessionId(
|
|
14473
|
+
file.sessionId = await sessionId(join23(plan.source, file.path), file.source);
|
|
14262
14474
|
if (!file.sessionId)
|
|
14263
14475
|
continue;
|
|
14264
14476
|
const previous = ids.get(file.sessionId);
|
|
@@ -14282,7 +14494,7 @@ async function checkSessionIdentities(plan) {
|
|
|
14282
14494
|
for await (const entry of await opendir2(directory)) {
|
|
14283
14495
|
if (++seen > MAX_FILES || entry.isSymbolicLink())
|
|
14284
14496
|
throw refused();
|
|
14285
|
-
const path =
|
|
14497
|
+
const path = join23(directory, entry.name);
|
|
14286
14498
|
if (entry.isDirectory()) {
|
|
14287
14499
|
await scan(path, depth + 1);
|
|
14288
14500
|
continue;
|
|
@@ -14299,18 +14511,18 @@ async function checkSessionIdentities(plan) {
|
|
|
14299
14511
|
file.existing = true;
|
|
14300
14512
|
}
|
|
14301
14513
|
}
|
|
14302
|
-
await scan(
|
|
14303
|
-
await scan(
|
|
14514
|
+
await scan(join23(plan.state.home, "sessions"));
|
|
14515
|
+
await scan(join23(plan.state.home, "archived_sessions"));
|
|
14304
14516
|
}
|
|
14305
14517
|
async function fingerprint2(path, copyTo) {
|
|
14306
|
-
const handle = await
|
|
14518
|
+
const handle = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
|
|
14307
14519
|
let output, complete = false;
|
|
14308
14520
|
try {
|
|
14309
14521
|
const before = await handle.stat();
|
|
14310
14522
|
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
|
|
14311
14523
|
throw refused();
|
|
14312
14524
|
if (copyTo)
|
|
14313
|
-
output = await
|
|
14525
|
+
output = await open7(copyTo, "wx", 384);
|
|
14314
14526
|
const hash3 = createHash15("sha256"), buffer = Buffer.alloc(64 * 1024);
|
|
14315
14527
|
let bytes = 0;
|
|
14316
14528
|
for (;; ) {
|
|
@@ -14360,9 +14572,9 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
14360
14572
|
async function visit(path, kind) {
|
|
14361
14573
|
if (++seen > MAX_FILES || path.split("/").length > 32)
|
|
14362
14574
|
throw refused();
|
|
14363
|
-
await ensureNativeStateDirectory(dirname9(
|
|
14364
|
-
await ensureNativeStateDirectory(dirname9(
|
|
14365
|
-
const from =
|
|
14575
|
+
await ensureNativeStateDirectory(dirname9(join23(source, path)), false);
|
|
14576
|
+
await ensureNativeStateDirectory(dirname9(join23(state.home, path)), false);
|
|
14577
|
+
const from = join23(source, path), to = join23(state.home, path), entry = await info2(from), target = await info2(to);
|
|
14366
14578
|
if (!entry)
|
|
14367
14579
|
return;
|
|
14368
14580
|
if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
|
|
@@ -14381,7 +14593,7 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
14381
14593
|
}
|
|
14382
14594
|
children.sort((a, b) => a.name.localeCompare(b.name));
|
|
14383
14595
|
for (const child of children)
|
|
14384
|
-
await visit(
|
|
14596
|
+
await visit(join23(path, child.name), child.kind);
|
|
14385
14597
|
} else {
|
|
14386
14598
|
const value = await fingerprint2(from);
|
|
14387
14599
|
plan.bytes += value.bytes;
|
|
@@ -14435,14 +14647,14 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
14435
14647
|
throw refused();
|
|
14436
14648
|
const requiredDirectories = new Set([plan.state.home]);
|
|
14437
14649
|
for (const path of plan.directories) {
|
|
14438
|
-
for (let directory =
|
|
14650
|
+
for (let directory = join23(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
|
|
14439
14651
|
requiredDirectories.add(directory);
|
|
14440
14652
|
if (directory === plan.state.home)
|
|
14441
14653
|
break;
|
|
14442
14654
|
}
|
|
14443
14655
|
}
|
|
14444
14656
|
for (const file of plan.files.filter((file2) => !file2.existing)) {
|
|
14445
|
-
for (let directory = dirname9(
|
|
14657
|
+
for (let directory = dirname9(join23(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
|
|
14446
14658
|
requiredDirectories.add(directory);
|
|
14447
14659
|
if (directory === plan.state.home)
|
|
14448
14660
|
break;
|
|
@@ -14463,9 +14675,9 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
14463
14675
|
for (const file of plan.files) {
|
|
14464
14676
|
if (file.existing)
|
|
14465
14677
|
continue;
|
|
14466
|
-
const target =
|
|
14678
|
+
const target = join23(plan.state.home, file.path), temporary = join23(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
|
|
14467
14679
|
staged.push({ temporary, target });
|
|
14468
|
-
const copied = await fingerprint2(
|
|
14680
|
+
const copied = await fingerprint2(join23(plan.source, file.path), temporary);
|
|
14469
14681
|
if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
|
|
14470
14682
|
throw refused();
|
|
14471
14683
|
}
|
|
@@ -14971,9 +15183,9 @@ async function main(args = process.argv.slice(2)) {
|
|
|
14971
15183
|
if (sharedNativeState)
|
|
14972
15184
|
await resolveNativeState(plan.profile.harness, process.env, { create: false });
|
|
14973
15185
|
if (shareNativeState === false) {
|
|
14974
|
-
const tool = plan.profile.harness, root = resolve14(values2["state-dir"] ??
|
|
15186
|
+
const tool = plan.profile.harness, root = resolve14(values2["state-dir"] ?? join24(switcherHome(), "state"));
|
|
14975
15187
|
const configured = process.env[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
|
|
14976
|
-
const home = desktop ?
|
|
15188
|
+
const home = desktop ? join24(root, "desktop", profileId, "codex") : claudeApp ? join24(root, "desktop-claude", profileId) : configured ? resolve14(configured) : join24(root, `native-${tool}`, profileId);
|
|
14977
15189
|
await assertNativeStateIsolation(tool, home);
|
|
14978
15190
|
}
|
|
14979
15191
|
if (backend === "ori") {
|