@hasna/switcher 0.2.12 → 0.2.14

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/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.12";
517
+ var version = "0.2.14";
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 join24, resolve as resolve14 } from "path";
1112
+ import { join as join26, resolve as resolve16 } from "path";
1113
1113
 
1114
1114
  // src/http.ts
1115
1115
  var MAX_BYTES = 16 * 1024 * 1024;
@@ -2570,7 +2570,7 @@ var openapi_default = {
2570
2570
  openapi: "3.0.3",
2571
2571
  info: {
2572
2572
  title: "Switcher API",
2573
- version: "0.2.12",
2573
+ version: "0.2.14",
2574
2574
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2575
2575
  },
2576
2576
  security: [
@@ -8334,28 +8334,53 @@ var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "depl
8334
8334
  var MIN_REQUEST_BODY_BYTES = 4 * 1024 * 1024;
8335
8335
  var MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
8336
8336
  var REQUEST_BYTES_PER_CONTEXT_TOKEN = 16;
8337
+ var CLOSING_MESSAGE = "Switcher gateway: this launch is shutting down. Start a new session with `switcher launch`.";
8338
+ var PROVIDER_FIX = "Check the provider's status and your network, then retry.";
8337
8339
  function requestBodyLimit(models, policy) {
8338
8340
  const allowed = new Set(policy.allowedModels);
8339
8341
  const contextWindow = Math.max(0, ...models.filter((model) => allowed.has(model.id)).map((model) => Number.isSafeInteger(model.contextWindow) && model.contextWindow > 0 ? model.contextWindow : 0));
8340
8342
  return Math.min(MAX_REQUEST_BODY_BYTES, Math.max(MIN_REQUEST_BODY_BYTES, contextWindow * REQUEST_BYTES_PER_CONTEXT_TOKEN));
8341
8343
  }
8342
- function createInferenceGateway(input, timing = {}) {
8343
- const token = crypto.randomUUID() + crypto.randomUUID();
8344
+ async function readJsonBody(request, limit) {
8345
+ const declared = request.headers.get("content-length");
8346
+ if (declared !== null && Number(declared) > limit)
8347
+ return { status: 413, code: "request_too_large" };
8348
+ try {
8349
+ if (!request.body)
8350
+ return { value: await request.json() };
8351
+ const reader = request.body.getReader(), chunks = [];
8352
+ let size = 0;
8353
+ for (;; ) {
8354
+ const { done, value } = await reader.read();
8355
+ if (done)
8356
+ break;
8357
+ size += value.byteLength;
8358
+ if (size > limit) {
8359
+ await reader.cancel().catch(() => {
8360
+ return;
8361
+ });
8362
+ return { status: 413, code: "request_too_large" };
8363
+ }
8364
+ chunks.push(value);
8365
+ }
8366
+ return { value: JSON.parse(Buffer.concat(chunks).toString("utf8")) };
8367
+ } catch {
8368
+ return { status: 400, code: "invalid_json" };
8369
+ }
8370
+ }
8371
+ function createInferenceHandler(input, timing = {}, options = {}) {
8344
8372
  const openCodeSession = crypto.randomUUID();
8345
8373
  const openCodeState = new Map;
8346
- const digest = (value) => createHash6("sha256").update(value).digest();
8347
- const expected = digest(token), policy = input.compiledPolicy;
8374
+ const policy = input.compiledPolicy;
8348
8375
  const known = new Set(input.models.map((m) => m.id));
8349
- const safeModel = (value) => typeof value === "string" && value !== input.credential && (known.has(value) || Object.hasOwn(policy.aliases, value) || input.harness === "antigravity" && value === antigravityHelperModel) ? value : "<unrecognized>";
8350
- const fail = (status, code, message) => Response.json({ error: { type: "switcher_model_policy", code, message: message ?? (code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : `Switcher inference gateway: ${code}.`) } }, { status });
8376
+ const bodyLimit = requestBodyLimit(input.models, input.compiledPolicy);
8377
+ const safeModelFor = (credential) => (value) => typeof value === "string" && value !== credential && (known.has(value) || Object.hasOwn(policy.aliases, value) || input.harness === "antigravity" && value === antigravityHelperModel) ? value : "<unrecognized>";
8378
+ const fail = (status, code, message) => Response.json({ error: { type: "switcher_model_policy", code, message: message ?? (code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : code === "closing" ? CLOSING_MESSAGE : `Switcher inference gateway: ${code}.`) } }, { status });
8351
8379
  let closing = false, stopped;
8352
8380
  const active = new Set;
8353
- const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: requestBodyLimit(input.models, input.compiledPolicy), idleTimeout: 255, async fetch(request, server2) {
8381
+ const handle = async (request, server) => {
8354
8382
  if (closing)
8355
8383
  return fail(503, "closing");
8356
- const credential = request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
8357
- if (!timingSafeEqual3(expected, digest(credential)))
8358
- return fail(401, "unauthorized");
8359
8384
  const url = new URL(request.url);
8360
8385
  if (request.method === "GET" && url.pathname === "/v1/models" && !url.search)
8361
8386
  return Response.json({ object: "list", data: input.models.filter((m) => !modelExpired(m)).map((m) => ({ ...m, object: "model" })) });
@@ -8369,14 +8394,21 @@ function createInferenceGateway(input, timing = {}) {
8369
8394
  const betaQuery = input.protocol === "anthropic-messages" && [...url.searchParams.keys()].every((k) => k === "beta") && url.searchParams.getAll("beta").length === 1 && url.searchParams.get("beta") === "true";
8370
8395
  if (gemini ? [...url.searchParams.keys()].some((k) => k !== "alt") || url.searchParams.getAll("alt").length > 1 || url.searchParams.has("alt") && url.searchParams.get("alt") !== "sse" : !!url.search && !betaQuery)
8371
8396
  return fail(400, "unsupported_query");
8372
- let body;
8373
- try {
8374
- body = await request.json();
8375
- } catch {
8376
- return fail(400, "invalid_json");
8377
- }
8397
+ const parsed = await readJsonBody(request, bodyLimit);
8398
+ if ("status" in parsed)
8399
+ return fail(parsed.status, parsed.code);
8400
+ const body = parsed.value;
8378
8401
  if (!body || typeof body !== "object" || Array.isArray(body))
8379
8402
  return fail(400, "invalid_request");
8403
+ let credential;
8404
+ try {
8405
+ credential = options.credential ? await options.credential() : input.credential;
8406
+ } catch (error) {
8407
+ if (error instanceof Fault)
8408
+ return Response.json({ error: { type: "switcher_gateway", code: error.code, message: error.message } }, { status: error.status });
8409
+ return fail(503, "credential_unavailable", "Switcher gateway: the provider credential for this launch is unavailable. Start a new session with `switcher launch`.");
8410
+ }
8411
+ const safeModel = safeModelFor(credential);
8380
8412
  let requested = body.model;
8381
8413
  if (gemini)
8382
8414
  try {
@@ -8435,11 +8467,11 @@ function createInferenceGateway(input, timing = {}) {
8435
8467
  };
8436
8468
  active.add(record2);
8437
8469
  const signal = activity.fetchOptions.signal;
8438
- server2.timeout(request, 0);
8470
+ server.timeout(request, 0);
8439
8471
  const headers = { "content-type": "application/json" };
8440
8472
  Object.assign(headers, openCodeHeaders(input.baseUrl, request.headers, body, openCodeSession));
8441
- if (input.credential) {
8442
- const [name, value] = gemini ? ["x-goog-api-key", input.credential] : authHeader(input.authStyle ?? "bearer", input.credential);
8473
+ if (credential) {
8474
+ const [name, value] = gemini ? ["x-goog-api-key", credential] : authHeader(input.authStyle ?? "bearer", credential);
8443
8475
  headers[name] = value;
8444
8476
  }
8445
8477
  if (input.protocol === "anthropic-messages") {
@@ -8472,7 +8504,7 @@ function createInferenceGateway(input, timing = {}) {
8472
8504
  const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
8473
8505
  const compatible2 = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
8474
8506
  const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
8475
- const translated = input.protocol === "anthropic-messages" ? prepareOpenCodeMessages(input.baseUrl, outgoing, suffix, input.credential, openCodeState) : undefined;
8507
+ const translated = input.protocol === "anthropic-messages" ? prepareOpenCodeMessages(input.baseUrl, outgoing, suffix, credential, openCodeState) : undefined;
8476
8508
  const path = translated?.path ?? (gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : ""));
8477
8509
  const upstreamHeaders = { ...headers };
8478
8510
  if (translated) {
@@ -8570,10 +8602,11 @@ function createInferenceGateway(input, timing = {}) {
8570
8602
  current.reason = "provider_idle_timeout";
8571
8603
  const networkError = !(error instanceof Fault) && current.reason === "network_error";
8572
8604
  release();
8573
- return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : networkError ? "provider_network_error" : "provider_request_failed", error instanceof Fault && error.code === "opencode_translation_unsupported" ? error.message : networkError ? "The upstream provider connection ended before response headers. Switcher did not attempt a fallback because delivery is uncertain." : undefined);
8605
+ const origin = new URL(endpoint(input.baseUrl)).origin;
8606
+ return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : networkError ? "provider_network_error" : "provider_request_failed", error instanceof Fault ? error.code === "opencode_translation_unsupported" ? error.message : undefined : networkError ? `The upstream provider connection ended before response headers. Switcher did not attempt a fallback because delivery is uncertain. ${PROVIDER_FIX}` : activity.timedOut() ? `Switcher gateway: the provider at ${origin} stopped sending data before the request finished. ${PROVIDER_FIX}` : `Switcher gateway: the request to the provider at ${origin} failed before a response arrived. ${PROVIDER_FIX}`);
8574
8607
  }
8575
- } });
8576
- return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
8608
+ };
8609
+ return { bodyLimit, closing: () => closing, handle, close: () => stopped ??= (async () => {
8577
8610
  closing = true;
8578
8611
  const pending = [...active];
8579
8612
  for (const request of pending)
@@ -8582,6 +8615,24 @@ function createInferenceGateway(input, timing = {}) {
8582
8615
  await request.cancel?.();
8583
8616
  await request.done;
8584
8617
  }));
8618
+ })() };
8619
+ }
8620
+ function createInferenceGateway(input, timing = {}) {
8621
+ const token = crypto.randomUUID() + crypto.randomUUID();
8622
+ const digest = (value) => createHash6("sha256").update(value).digest();
8623
+ const expected = digest(token);
8624
+ const handler = createInferenceHandler(input, timing);
8625
+ let stopped;
8626
+ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: handler.bodyLimit, idleTimeout: 255, async fetch(request, server2) {
8627
+ if (handler.closing())
8628
+ return Response.json({ error: { type: "switcher_model_policy", code: "closing", message: CLOSING_MESSAGE } }, { status: 503 });
8629
+ const credential = request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
8630
+ if (!timingSafeEqual3(expected, digest(credential)))
8631
+ return Response.json({ error: { type: "switcher_model_policy", code: "unauthorized", message: "Switcher inference gateway: unauthorized." } }, { status: 401 });
8632
+ return handler.handle(request, server2);
8633
+ } });
8634
+ return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
8635
+ await handler.close();
8585
8636
  await server.stop(true);
8586
8637
  })() };
8587
8638
  }
@@ -11307,7 +11358,14 @@ async function prepareHarnessLaunch(input) {
11307
11358
  throw new Error(`${input.harness} does not expose native model controls for: ${unsupported3.join(", ")}.`);
11308
11359
  await mkdir10(input.stateDir, { recursive: true, mode: 448 });
11309
11360
  const catalogPath = await jsonFile(input.stateDir, `switcher-model-policy-${randomUUID4()}.json`, { policy: compiledPolicy, models: input.models });
11310
- const bridge = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
11361
+ const bridge = input.gatewayHost ? await input.gatewayHost.open({ ...input, compiledPolicy, catalogPath }).catch(async (error) => {
11362
+ await rm2(catalogPath, { force: true });
11363
+ throw error;
11364
+ }) : createInferenceGateway({ ...input, compiledPolicy, catalogPath });
11365
+ const removeCatalog = async () => {
11366
+ if (!bridge.retainsState?.())
11367
+ await rm2(catalogPath, { force: true });
11368
+ };
11311
11369
  try {
11312
11370
  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";
11313
11371
  const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy });
@@ -11316,12 +11374,12 @@ async function prepareHarnessLaunch(input) {
11316
11374
  await prepared.cleanup?.();
11317
11375
  } finally {
11318
11376
  await bridge.cleanup();
11319
- await rm2(catalogPath, { force: true });
11377
+ await removeCatalog();
11320
11378
  }
11321
11379
  } };
11322
11380
  } catch (error) {
11323
11381
  await bridge.cleanup();
11324
- await rm2(catalogPath, { force: true });
11382
+ await removeCatalog();
11325
11383
  throw error;
11326
11384
  }
11327
11385
  }
@@ -11353,8 +11411,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11353
11411
  }
11354
11412
 
11355
11413
  // src/launcher.ts
11356
- import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile18 } from "fs/promises";
11357
- import { join as join22, resolve as resolve12 } from "path";
11414
+ import { mkdir as mkdir14, mkdtemp, rm as rm6, writeFile as writeFile18 } from "fs/promises";
11415
+ import { join as join24, resolve as resolve14 } from "path";
11358
11416
 
11359
11417
  // src/provider-credential-onboarding.ts
11360
11418
  import { z as z9 } from "zod";
@@ -12232,6 +12290,11 @@ async function runHarnessProcess(options) {
12232
12290
  };
12233
12291
  return events;
12234
12292
  })();
12293
+ if (child.pid) {
12294
+ try {
12295
+ options.onSpawn?.(child.pid);
12296
+ } catch {}
12297
+ }
12235
12298
  let interrupted = false;
12236
12299
  let interruptionExitCode;
12237
12300
  let killTimer;
@@ -12647,28 +12710,66 @@ function oriLaunchWarnings(target) {
12647
12710
  }
12648
12711
 
12649
12712
  // src/chatgpt-launch.ts
12650
- import { createHash as createHash12 } from "crypto";
12713
+ import { createHash as createHash13 } from "crypto";
12651
12714
  import { writeFile as writeFile14, rm as rm4 } from "fs/promises";
12652
12715
  import { join as join18 } from "path";
12653
12716
  import { fileURLToPath } from "url";
12654
12717
 
12655
12718
  // src/desktop-state.ts
12656
12719
  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";
12720
+ import { open as open4, rm as rm3, lstat as lstat7, rename as rename2, chmod as chmod2, copyFile as copyFile2, link as link2 } from "fs/promises";
12721
+ import { spawnSync as spawnSync2 } from "child_process";
12722
+ import { resolve as resolve9 } from "path";
12723
+ import { createHash as createHash12 } from "crypto";
12658
12724
  var desktopReadLimit = 1024 * 1024;
12659
12725
  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.");
12726
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || info.gid !== process.getgid?.() || (info.mode & 18) !== 0 || info.size > desktopReadLimit)
12727
+ throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user and their primary group.");
12728
+ }
12729
+ function admitDesktopMetadata(path, info) {
12730
+ const attributes = [];
12731
+ const hash2 = () => createHash12("sha256").update(JSON.stringify({ gid: info.gid, attributes })).digest("hex");
12732
+ if (process.platform !== "darwin")
12733
+ return hash2();
12734
+ const deadline = Date.now() + 2000;
12735
+ const inspect = (executable, args, maxBuffer) => {
12736
+ const remaining = deadline - Date.now();
12737
+ if (remaining <= 0)
12738
+ throw new Fault(422, "desktop_state_permissions", "Desktop metadata inspection timed out.");
12739
+ const result = spawnSync2(executable, args, { encoding: "utf8", env: { LC_ALL: "C" }, stdio: ["ignore", "pipe", "ignore"], timeout: remaining, maxBuffer });
12740
+ if (result.error || result.status !== 0)
12741
+ throw new Fault(422, "desktop_state_permissions", `Desktop security metadata could not be verified (${result.error?.code === "ETIMEDOUT" ? "inspection_timeout" : "inspection_exit"}).`);
12742
+ return result.stdout;
12743
+ };
12744
+ const listing = inspect("/bin/ls", ["-ldneO@", resolve9(path)], 64 * 1024);
12745
+ const lines = listing.trimEnd().split(`
12746
+ `), fields = lines[0]?.trim().split(/\s+/);
12747
+ const refused = !fields || !/^-[-rwxStTs]{9}@?$/.test(fields[0] ?? "") ? "mode_or_acl" : fields[1] !== "1" ? "link_count" : fields[2] !== String(info.uid) ? "owner" : fields[3] !== String(info.gid) ? "group" : fields[4] !== "-" ? "file_flags" : lines.slice(1).some((line) => !line.startsWith("\t") || /^\s*\d+:/.test(line)) ? "metadata_records" : undefined;
12748
+ if (refused)
12749
+ throw new Fault(422, "desktop_state_permissions", `Desktop settings security metadata cannot be safely restored (${refused}).`);
12750
+ const names = inspect("/usr/bin/xattr", [resolve9(path)], 64 * 1024).trimEnd().split(`
12751
+ `).filter(Boolean).sort();
12752
+ if (names.length > 64 || new Set(names).size !== names.length || names.some((name) => name.length > 255 || /[\x00-\x1f\x7f]/.test(name)))
12753
+ throw new Fault(422, "desktop_state_permissions", "Desktop extended attributes exceed bounded inspection.");
12754
+ let total = 0;
12755
+ for (const name of names) {
12756
+ const hex = inspect("/usr/bin/xattr", ["-px", name, resolve9(path)], 2 * desktopReadLimit + 64 * 1024).replace(/\s/g, "");
12757
+ total += hex.length / 2;
12758
+ if (hex.length % 2 || !/^[0-9a-fA-F]*$/.test(hex) || total > desktopReadLimit)
12759
+ throw new Fault(422, "desktop_state_permissions", "Desktop extended attributes exceed bounded inspection.");
12760
+ attributes.push({ name, digest: createHash12("sha256").update(Buffer.from(hex, "hex")).digest("hex") });
12761
+ }
12762
+ return hash2();
12662
12763
  }
12663
12764
  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)
12765
+ if (opened.dev !== info.dev || opened.ino !== info.ino || opened.nlink !== 1 || opened.size > desktopReadLimit || opened.mode !== info.mode || opened.uid !== info.uid || opened.gid !== info.gid || opened.ctimeMs !== info.ctimeMs)
12665
12766
  throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
12666
12767
  }
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)
12768
+ function desktopSnapshot(bytes, length, opened, after, metadataHash) {
12769
+ if (length > desktopReadLimit || length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs || after.mode !== opened.mode || after.gid !== opened.gid)
12669
12770
  throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
12670
12771
  try {
12671
- return { text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length)), mode: after.mode & 4095 };
12772
+ return { text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length)), mode: after.mode & 4095, metadataHash };
12672
12773
  } catch {
12673
12774
  throw new Fault(422, "desktop_state_encoding", "Desktop settings must be valid UTF-8; original bytes were left unchanged.");
12674
12775
  }
@@ -12677,6 +12778,7 @@ async function safeDesktopSnapshot(path) {
12677
12778
  try {
12678
12779
  const info = await lstat7(path);
12679
12780
  admitDesktopFile(info);
12781
+ const metadataHash = admitDesktopMetadata(path, info);
12680
12782
  const file = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12681
12783
  try {
12682
12784
  const opened = await file.stat();
@@ -12689,7 +12791,9 @@ async function safeDesktopSnapshot(path) {
12689
12791
  break;
12690
12792
  length += read.bytesRead;
12691
12793
  }
12692
- return desktopSnapshot(bytes, length, opened, await file.stat());
12794
+ const snapshot2 = desktopSnapshot(bytes, length, opened, await file.stat(), metadataHash);
12795
+ admitOpenedDesktopFile(opened, lstatSync(path));
12796
+ return snapshot2;
12693
12797
  } finally {
12694
12798
  await file.close();
12695
12799
  }
@@ -12703,6 +12807,7 @@ function safeDesktopSnapshotSync(path) {
12703
12807
  try {
12704
12808
  const info = lstatSync(path);
12705
12809
  admitDesktopFile(info);
12810
+ const metadataHash = admitDesktopMetadata(path, info);
12706
12811
  const file = openSync2(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12707
12812
  try {
12708
12813
  const opened = fstatSync(file);
@@ -12715,7 +12820,7 @@ function safeDesktopSnapshotSync(path) {
12715
12820
  break;
12716
12821
  length += count;
12717
12822
  }
12718
- const snapshot2 = desktopSnapshot(bytes, length, opened, fstatSync(file));
12823
+ const snapshot2 = desktopSnapshot(bytes, length, opened, fstatSync(file), metadataHash);
12719
12824
  admitOpenedDesktopFile(opened, lstatSync(path));
12720
12825
  return snapshot2;
12721
12826
  } finally {
@@ -12730,24 +12835,204 @@ function safeDesktopSnapshotSync(path) {
12730
12835
  async function safeDesktopRead(path) {
12731
12836
  return (await safeDesktopSnapshot(path))?.text;
12732
12837
  }
12733
- async function writeDesktopPrivate(path, text, mode = 384) {
12838
+ function sameDesktopSnapshot(a, b) {
12839
+ return a?.text === b?.text && a?.mode === b?.mode && a?.metadataHash === b?.metadataHash;
12840
+ }
12841
+ async function preserveDesktopFile(source, destination, expected) {
12842
+ if (await safeDesktopSnapshot(destination) !== undefined || !sameDesktopSnapshot(await safeDesktopSnapshot(source), expected))
12843
+ throw new Fault(409, "desktop_state_changed", "Desktop preservation target or source changed.");
12844
+ if (process.platform === "darwin") {
12845
+ const copied = spawnSync2("/bin/cp", ["-pn", resolve9(source), resolve9(destination)], { env: { LC_ALL: "C" }, stdio: "ignore", timeout: 2000 });
12846
+ if (copied.error || copied.status !== 0)
12847
+ throw new Fault(422, "desktop_state_permissions", "Desktop metadata preservation failed.");
12848
+ } else
12849
+ await copyFile2(source, destination, constants7.COPYFILE_EXCL);
12850
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(source), expected) || !sameDesktopSnapshot(await safeDesktopSnapshot(destination), expected))
12851
+ throw new Fault(409, "desktop_state_changed", "Desktop original preservation readback failed.");
12852
+ }
12853
+ var conflictPath = (path, suffix) => path + "." + crypto.randomUUID() + "." + suffix;
12854
+ async function exists(path) {
12855
+ try {
12856
+ await lstat7(path);
12857
+ return true;
12858
+ } catch (error) {
12859
+ if (error.code === "ENOENT")
12860
+ return false;
12861
+ throw error;
12862
+ }
12863
+ }
12864
+ async function preserveConflict(path) {
12865
+ const target = conflictPath(path, "conflict");
12866
+ await rename2(path, target);
12867
+ return target;
12868
+ }
12869
+ async function restoreDisplaced(backup, path) {
12870
+ const snapshot2 = await safeDesktopSnapshot(backup);
12871
+ if (!snapshot2)
12872
+ throw new Fault(409, "desktop_state_changed", "Desktop displaced state is missing; existing state was preserved.");
12873
+ const temporary = conflictPath(path, "restore");
12874
+ try {
12875
+ await preserveDesktopFile(backup, temporary, snapshot2);
12876
+ try {
12877
+ await link2(temporary, path);
12878
+ } catch (error) {
12879
+ if (error.code === "EEXIST") {
12880
+ const preserved = await preserveConflict(path);
12881
+ throw new Fault(409, "desktop_state_changed", `Desktop settings changed; foreign file preserved at ${preserved}; original retained at ${backup}.`);
12882
+ }
12883
+ throw error;
12884
+ }
12885
+ await rm3(temporary, { force: true });
12886
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), snapshot2))
12887
+ throw new Fault(409, "desktop_state_changed", `Desktop settings changed after restoration; original retained at ${backup}.`);
12888
+ } finally {
12889
+ if (await safeDesktopSnapshot(temporary).catch(() => {
12890
+ return;
12891
+ }) !== undefined)
12892
+ await rm3(temporary, { force: true });
12893
+ }
12894
+ }
12895
+ async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew) {
12896
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(temporary), expectedNew))
12897
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement bytes changed before installation.");
12898
+ if (expectedCurrent === undefined) {
12899
+ if (await exists(path))
12900
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target appeared concurrently; existing state was preserved.");
12901
+ try {
12902
+ await link2(temporary, path);
12903
+ } catch (error) {
12904
+ if (error.code === "EEXIST")
12905
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target appeared concurrently; existing state was preserved.");
12906
+ throw error;
12907
+ }
12908
+ await rm3(temporary, { force: true });
12909
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), expectedNew)) {
12910
+ const preserved = await preserveConflict(path);
12911
+ throw new Fault(409, "desktop_state_changed", `Desktop replacement changed after installation; foreign file preserved at ${preserved}.`);
12912
+ }
12913
+ return;
12914
+ }
12915
+ const backup = conflictPath(path, "previous");
12916
+ let displaced = false;
12917
+ try {
12918
+ try {
12919
+ await rename2(path, backup);
12920
+ displaced = true;
12921
+ } catch (error) {
12922
+ if (error.code === "ENOENT")
12923
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target disappeared; existing state was preserved.");
12924
+ throw error;
12925
+ }
12926
+ let current;
12927
+ try {
12928
+ current = await safeDesktopSnapshot(backup);
12929
+ } catch {
12930
+ await restoreDisplaced(backup, path);
12931
+ displaced = false;
12932
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target changed; existing state was preserved.");
12933
+ }
12934
+ if (!sameDesktopSnapshot(current, expectedCurrent)) {
12935
+ await restoreDisplaced(backup, path);
12936
+ displaced = false;
12937
+ throw new Fault(409, "desktop_state_changed", "Desktop settings changed before replacement; existing state was preserved.");
12938
+ }
12939
+ try {
12940
+ await link2(temporary, path);
12941
+ } catch (error) {
12942
+ if (error.code === "EEXIST") {
12943
+ await restoreDisplaced(backup, path);
12944
+ displaced = false;
12945
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target appeared concurrently; existing state was preserved.");
12946
+ }
12947
+ throw error;
12948
+ }
12949
+ await rm3(temporary, { force: true });
12950
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), expectedNew)) {
12951
+ await restoreDisplaced(backup, path);
12952
+ displaced = false;
12953
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement changed after installation; existing state was preserved.");
12954
+ }
12955
+ displaced = false;
12956
+ } finally {
12957
+ if (displaced) {
12958
+ try {
12959
+ await restoreDisplaced(backup, path);
12960
+ } catch {}
12961
+ }
12962
+ }
12963
+ }
12964
+ async function removeDesktopFile(path, expected, guard) {
12965
+ if (expected === undefined) {
12966
+ if (await exists(path))
12967
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target appeared concurrently; existing state was preserved.");
12968
+ return;
12969
+ }
12970
+ const quarantine = conflictPath(path, "remove");
12971
+ try {
12972
+ await rename2(path, quarantine);
12973
+ } catch (error) {
12974
+ if (error.code === "ENOENT")
12975
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target disappeared; existing state was preserved.");
12976
+ throw error;
12977
+ }
12978
+ let moved;
12979
+ try {
12980
+ moved = await safeDesktopSnapshot(quarantine);
12981
+ } catch {
12982
+ await restoreDisplaced(quarantine, path);
12983
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target changed; existing state was preserved.");
12984
+ }
12985
+ if (!sameDesktopSnapshot(moved, expected)) {
12986
+ await restoreDisplaced(quarantine, path);
12987
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target changed; existing state was preserved.");
12988
+ }
12989
+ if (guard) {
12990
+ try {
12991
+ await guard();
12992
+ } catch (error) {
12993
+ try {
12994
+ await restoreDisplaced(quarantine, path);
12995
+ } catch {}
12996
+ throw error;
12997
+ }
12998
+ }
12999
+ await rm3(quarantine, { force: true });
13000
+ if (await exists(path))
13001
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target appeared concurrently; existing state was preserved.");
13002
+ }
13003
+ async function writeDesktopPrivate(path, text, mode = 384, metadataSource, expectation) {
12734
13004
  if (!Number.isInteger(mode) || mode < 0 || mode > 4095 || (mode & 18) !== 0)
12735
13005
  throw new Fault(422, "desktop_state_permissions", "Desktop settings restoration requires an admitted original mode.");
13006
+ const observed = await safeDesktopSnapshot(path);
13007
+ if (expectation && !sameDesktopSnapshot(observed, expectation.current))
13008
+ throw new Fault(409, "desktop_state_changed", "Desktop settings changed before restoration; existing state was preserved.");
13009
+ const expectedCurrent = expectation ? expectation.current : observed;
13010
+ const template = metadataSource?.snapshot ?? expectedCurrent;
13011
+ if (metadataSource && !sameDesktopSnapshot(await safeDesktopSnapshot(metadataSource.path), template))
13012
+ throw new Fault(409, "desktop_state_changed", "Desktop restoration original changed or is missing.");
12736
13013
  const temporary = path + "." + crypto.randomUUID() + ".tmp";
12737
13014
  try {
12738
- const file = await open4(temporary, "wx", 384);
13015
+ if (template) {
13016
+ await preserveDesktopFile(metadataSource?.path ?? path, temporary, template);
13017
+ await chmod2(temporary, 384);
13018
+ }
13019
+ const file = await open4(temporary, constants7.O_RDWR | constants7.O_NOFOLLOW | (template ? 0 : constants7.O_CREAT | constants7.O_EXCL), 384);
12739
13020
  try {
13021
+ await file.truncate(0);
12740
13022
  await file.writeFile(text);
12741
13023
  await file.chmod(mode);
12742
13024
  } finally {
12743
13025
  await file.close();
12744
13026
  }
12745
13027
  const written = await safeDesktopSnapshot(temporary);
12746
- if (written?.text !== text || written.mode !== mode)
13028
+ if (written?.text !== text || written.mode !== mode || template && written.metadataHash !== template.metadataHash)
12747
13029
  throw new Fault(409, "desktop_state_changed", "Desktop settings restoration readback failed.");
12748
- await rename2(temporary, path);
13030
+ await replaceDesktopFile(path, temporary, expectedCurrent, written);
12749
13031
  } finally {
12750
- await rm3(temporary, { force: true });
13032
+ if (await safeDesktopSnapshot(temporary).catch(() => {
13033
+ return;
13034
+ }) !== undefined)
13035
+ await rm3(temporary, { force: true });
12751
13036
  }
12752
13037
  }
12753
13038
  async function desktopLease(path) {
@@ -12795,7 +13080,7 @@ async function openDesktopLease(path, readOnly2 = false) {
12795
13080
  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
13081
  import { constants as constants8, lstatSync as lstatSync2, realpathSync } from "fs";
12797
13082
  import { homedir as homedir9 } from "os";
12798
- import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
13083
+ import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve10 } from "path";
12799
13084
  function nativeStateRequested(tool, environment = process.env, explicit) {
12800
13085
  if (explicit !== undefined)
12801
13086
  return explicit;
@@ -12844,7 +13129,7 @@ async function info(path) {
12844
13129
  function absolute(value) {
12845
13130
  if (!isAbsolute16(value) || value.includes("\x00"))
12846
13131
  throw new Fault(422, "native_state_path", "The shared native state directory must be an absolute path.");
12847
- return resolve9(value);
13132
+ return resolve10(value);
12848
13133
  }
12849
13134
  function credentialOverlay(path) {
12850
13135
  return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
@@ -12992,7 +13277,7 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
12992
13277
  if (!valid)
12993
13278
  throw new Fault(422, "native_state_instructions", "Codex instruction configuration has an unsupported value.");
12994
13279
  if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
12995
- const path = resolve9(home, value), entry = await info(path);
13280
+ const path = resolve10(home, value), entry = await info(path);
12996
13281
  const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
12997
13282
  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)
12998
13283
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
@@ -13157,7 +13442,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13157
13442
  throw new Fault(422, "native_state_entry", "A shared native state entry has an unsupported type, owner or permissions.");
13158
13443
  if (source?.isDirectory())
13159
13444
  await assertShareableTree(target);
13160
- if (existing && (!existing.isSymbolicLink() || resolve9(dirname8(destination), await readlink(destination)) !== target))
13445
+ if (existing && (!existing.isSymbolicLink() || resolve10(dirname8(destination), await readlink(destination)) !== target))
13161
13446
  throw new Fault(409, "native_state_migration_required", "This launch profile already contains native state. Preserve and migrate its noncredential state before linking the shared corpus.");
13162
13447
  }
13163
13448
  const createdLinks = [];
@@ -13193,7 +13478,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13193
13478
  } catch (error) {
13194
13479
  for (const item2 of createdLinks.reverse()) {
13195
13480
  try {
13196
- if ((await info(item2.destination))?.isSymbolicLink() && resolve9(dirname8(item2.destination), await readlink(item2.destination)) === item2.target)
13481
+ if ((await info(item2.destination))?.isSymbolicLink() && resolve10(dirname8(item2.destination), await readlink(item2.destination)) === item2.target)
13197
13482
  await unlink2(item2.destination);
13198
13483
  } catch {}
13199
13484
  }
@@ -13249,7 +13534,7 @@ function clearSwitcherModelState(config) {
13249
13534
  delete config.memories;
13250
13535
  }
13251
13536
  }
13252
- var digest = (value) => createHash12("sha256").update(value).digest("hex");
13537
+ var digest = (value) => createHash13("sha256").update(value).digest("hex");
13253
13538
  var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
13254
13539
  async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedState) {
13255
13540
  if (sharedState && sharedState.tool !== "codex")
@@ -13366,15 +13651,17 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
13366
13651
  import { writeFile as writeFile17 } from "fs/promises";
13367
13652
  import { join as join21 } from "path";
13368
13653
  // 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";
13654
+ import { createHash as createHash14, randomUUID as randomUUID6 } from "crypto";
13655
+ import { writeFile as writeFile15, rename as rename3 } from "fs/promises";
13371
13656
  import { join as join19 } from "path";
13372
- var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
13657
+ var hash2 = (text) => createHash14("sha256").update(text).digest("hex");
13373
13658
  var conflict = () => new Fault(409, "desktop_config_changed", "Desktop configuration changed; existing bytes and the recovery receipt were preserved.");
13374
13659
  var invalid3 = () => new Fault(409, "desktop_recovery", "Desktop selection needs recovery by its owning supported version before another launch.");
13375
13660
  var identifier = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,80}$/.test(value);
13376
13661
  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;
13662
+ var matches = (actual, text, mode, metadataHash) => (actual?.text ?? null) === text && (actual?.mode ?? null) === mode && (actual?.metadataHash ?? null) === metadataHash;
13663
+ var originalPath = (library, id2) => join19(library, `.switcher-original-${id2}.bak`);
13664
+ var preparedPath = (library, id2) => join19(library, `.switcher-selected-${id2}.tmp`);
13378
13665
  function metadata(text) {
13379
13666
  if (text === null)
13380
13667
  return { entries: [] };
@@ -13391,31 +13678,94 @@ function metadata(text) {
13391
13678
  throw invalid3();
13392
13679
  return m;
13393
13680
  }
13681
+ function v4Receipt(value) {
13682
+ const r = value;
13683
+ if (r?.version !== 4 || !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.previousMeta === null ? r.previousMetadataHash !== null : typeof r.previousMetadataHash !== "string" || !/^[a-f0-9]{64}$/.test(r.previousMetadataHash)) || typeof r.appliedMetadataHash !== "string" || !/^[a-f0-9]{64}$/.test(r.appliedMetadataHash) || r.previousMetadataHash !== null && r.appliedMetadataHash !== r.previousMetadataHash || r.previousSelected !== null && (!r.previousSelected || !identifier(r.previousSelected.id) || r.previousSelected.hash === undefined && r.previousSelected.text === undefined || r.previousSelected.hash !== undefined && r.previousSelected.text !== undefined || r.previousSelected.hash !== undefined && r.previousSelected.hash !== null && (typeof r.previousSelected.hash !== "string" || !/^[a-f0-9]{64}$/.test(r.previousSelected.hash)) || r.previousSelected.text !== undefined && r.previousSelected.text !== null && typeof r.previousSelected.text !== "string"))
13684
+ throw invalid3();
13685
+ const before = metadata(r.previousMeta), after = metadata(r.appliedMeta);
13686
+ if (after.appliedId !== r.id || before.appliedId === r.id || (before.appliedId ?? null) !== (r.previousSelected?.id ?? null))
13687
+ throw invalid3();
13688
+ return r;
13689
+ }
13394
13690
  function receipt(text) {
13395
- let r;
13691
+ let value;
13396
13692
  try {
13397
- r = JSON.parse(text);
13693
+ value = JSON.parse(text);
13398
13694
  } catch {
13399
13695
  throw invalid3();
13400
13696
  }
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))
13697
+ if (value?.version === 4)
13698
+ return v4Receipt(value);
13699
+ const r = value;
13700
+ if (!r || typeof r !== "object" || Array.isArray(r) || Object.keys(r).sort().join(",") !== "appliedMeta,configHash,id,previousMeta" || !identifier(r.id) || !/^[0-9a-f-]{36}$/.test(r.id) || typeof r.configHash !== "string" || !/^[a-f0-9]{64}$/.test(r.configHash) || r.previousMeta !== null || typeof r.appliedMeta !== "string")
13405
13701
  throw invalid3();
13406
- return r;
13702
+ return { id: r.id, configHash: r.configHash, previousMeta: null, appliedMeta: r.appliedMeta };
13703
+ }
13704
+ function upgradeReceipt(r, currentMeta) {
13705
+ if ("version" in r)
13706
+ return r;
13707
+ return {
13708
+ version: 4,
13709
+ id: r.id,
13710
+ configHash: r.configHash,
13711
+ previousMeta: null,
13712
+ previousMetaMode: null,
13713
+ previousMetadataHash: null,
13714
+ appliedMeta: r.appliedMeta,
13715
+ appliedMetadataHash: currentMeta?.metadataHash ?? "0".repeat(64),
13716
+ previousSelected: null
13717
+ };
13407
13718
  }
13408
13719
  async function selectedUnchanged(library, r) {
13409
- if (r.previousSelected && (await safeDesktopRead(join19(library, r.previousSelected.id + ".json")) ?? null) !== r.previousSelected.text)
13720
+ const selected = r.previousSelected;
13721
+ if (!selected)
13722
+ return;
13723
+ const current = await safeDesktopRead(join19(library, selected.id + ".json"));
13724
+ if (selected.hash !== undefined) {
13725
+ if (selected.hash === null ? current !== undefined : current === undefined || hash2(current) !== selected.hash)
13726
+ throw conflict();
13727
+ } else if ((current ?? null) !== (selected.text ?? null))
13728
+ throw conflict();
13729
+ }
13730
+ function selectedUnchangedSync(library, selected) {
13731
+ if (!selected)
13732
+ return true;
13733
+ const current = safeDesktopSnapshotSync(join19(library, selected.id + ".json"))?.text;
13734
+ if (selected.hash !== undefined)
13735
+ return selected.hash === null ? current === undefined : current !== undefined && hash2(current) === selected.hash;
13736
+ return (current ?? null) === (selected.text ?? null);
13737
+ }
13738
+ function retainedReceipt(r) {
13739
+ const selected = r.previousSelected;
13740
+ if (!selected || selected.text === undefined)
13741
+ return JSON.stringify(r) + `
13742
+ `;
13743
+ return JSON.stringify({ ...r, previousSelected: { id: selected.id, hash: selected.hash ?? (selected.text === null ? null : hash2(selected.text)) } }) + `
13744
+ `;
13745
+ }
13746
+ async function preservedSelection(library, r, wasApplied) {
13747
+ const backup = await safeDesktopSnapshot(originalPath(library, r.id)), prepared = await safeDesktopSnapshot(preparedPath(library, r.id));
13748
+ if (backup && !matches(backup, r.previousMeta, r.previousMetaMode, r.previousMetadataHash) || wasApplied && r.previousMeta !== null && !backup || prepared && !matches(prepared, r.appliedMeta, 384, r.appliedMetadataHash))
13410
13749
  throw conflict();
13750
+ return { backup, prepared };
13411
13751
  }
13412
13752
  async function recoverDesktopSelection(library) {
13413
13753
  const path = join19(library, ".switcher-selection.json"), raw = await safeDesktopRead(path);
13414
13754
  if (raw === undefined)
13415
13755
  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);
13756
+ const parsed = receipt(raw), metaPath = join19(library, "_meta.json"), configPath = join19(library, parsed.id + ".json");
13757
+ let currentMeta = await safeDesktopSnapshot(metaPath);
13758
+ const r = upgradeReceipt(parsed, currentMeta);
13759
+ const currentConfig = await safeDesktopRead(configPath);
13760
+ if (currentMeta === undefined && r.previousMeta !== null) {
13761
+ const preserved = await safeDesktopSnapshot(originalPath(library, r.id));
13762
+ if (!matches(preserved, r.previousMeta, r.previousMetaMode, r.previousMetadataHash))
13763
+ throw conflict();
13764
+ await writeDesktopPrivate(metaPath, r.previousMeta, r.previousMetaMode, { path: originalPath(library, r.id), snapshot: { text: r.previousMeta, mode: r.previousMetaMode, metadataHash: r.previousMetadataHash } }, { current: undefined });
13765
+ currentMeta = await safeDesktopSnapshot(metaPath);
13766
+ }
13767
+ const wasOriginal = matches(currentMeta, r.previousMeta, r.previousMetaMode, r.previousMetadataHash), wasApplied = matches(currentMeta, r.appliedMeta, 384, r.appliedMetadataHash);
13768
+ const { backup, prepared } = await preservedSelection(library, r, wasApplied);
13419
13769
  await selectedUnchanged(library, r);
13420
13770
  if (!wasOriginal && !wasApplied)
13421
13771
  throw conflict();
@@ -13423,35 +13773,101 @@ async function recoverDesktopSelection(library) {
13423
13773
  throw conflict();
13424
13774
  if (await safeDesktopRead(path) !== raw)
13425
13775
  throw conflict();
13426
- if (!matches(await safeDesktopSnapshot(metaPath), currentMeta?.text ?? null, currentMeta?.mode ?? null))
13776
+ if (!matches(await safeDesktopSnapshot(metaPath), currentMeta?.text ?? null, currentMeta?.mode ?? null, currentMeta?.metadataHash ?? null))
13427
13777
  throw conflict();
13778
+ const assertMetaRestored = async () => {
13779
+ if (!matches(await safeDesktopSnapshot(metaPath), r.previousMeta, r.previousMetaMode, r.previousMetadataHash))
13780
+ throw conflict();
13781
+ };
13782
+ const assertRestored = async () => {
13783
+ await assertMetaRestored();
13784
+ if (await safeDesktopRead(path) !== raw)
13785
+ throw conflict();
13786
+ };
13428
13787
  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))
13788
+ if (r.previousMeta === null) {
13789
+ if (!currentMeta)
13790
+ throw conflict();
13791
+ await removeDesktopFile(metaPath, currentMeta);
13792
+ } else
13793
+ await writeDesktopPrivate(metaPath, r.previousMeta, r.previousMetaMode, { path: originalPath(library, r.id), snapshot: { text: r.previousMeta, mode: r.previousMetaMode, metadataHash: r.previousMetadataHash } }, { current: currentMeta });
13794
+ await assertRestored();
13795
+ }
13796
+ if (prepared) {
13797
+ if (!matches(safeDesktopSnapshotSync(preparedPath(library, r.id)), r.appliedMeta, 384, r.appliedMetadataHash))
13434
13798
  throw conflict();
13799
+ await removeDesktopFile(preparedPath(library, r.id), prepared, assertRestored);
13435
13800
  }
13801
+ if (backup && !matches(safeDesktopSnapshotSync(originalPath(library, r.id)), r.previousMeta, r.previousMetaMode, r.previousMetadataHash))
13802
+ throw conflict();
13436
13803
  if (currentConfig !== undefined) {
13437
- if (hash2(await safeDesktopRead(configPath) ?? "") !== r.configHash)
13804
+ const configSnapshot = await safeDesktopSnapshot(configPath);
13805
+ if (!configSnapshot || hash2(configSnapshot.text) !== r.configHash)
13438
13806
  throw conflict();
13439
- await rm5(configPath);
13807
+ await removeDesktopFile(configPath, configSnapshot, assertRestored);
13440
13808
  }
13441
- if (await safeDesktopRead(path) !== raw)
13809
+ await assertRestored();
13810
+ const receiptSnapshot = await safeDesktopSnapshot(path);
13811
+ if (!receiptSnapshot || receiptSnapshot.text !== raw)
13442
13812
  throw conflict();
13443
- await rm5(path);
13813
+ const recoveredPath = path + ".recovered-" + randomUUID6(), retained = retainedReceipt(r);
13814
+ if (retained !== raw) {
13815
+ await writeFile15(recoveredPath, retained, { mode: 384, flag: "wx" });
13816
+ const redacted = await safeDesktopSnapshot(recoveredPath);
13817
+ if (!redacted || redacted.text !== retained || redacted.mode !== 384)
13818
+ throw conflict();
13819
+ if (await safeDesktopRead(path) !== raw)
13820
+ throw conflict();
13821
+ await removeDesktopFile(path, receiptSnapshot, assertMetaRestored);
13822
+ await assertMetaRestored();
13823
+ const finalReceipt2 = await safeDesktopSnapshot(recoveredPath);
13824
+ if (!sameDesktopSnapshot(finalReceipt2, redacted)) {
13825
+ const foreignPath = recoveredPath + ".foreign-" + randomUUID6();
13826
+ if (finalReceipt2 !== undefined)
13827
+ await rename3(recoveredPath, foreignPath);
13828
+ await writeDesktopPrivate(recoveredPath, retained, 384, undefined, { current: undefined });
13829
+ throw new Fault(409, "desktop_config_changed", `Desktop recovery receipt changed; redacted receipt preserved at ${recoveredPath}; foreign receipt preserved at ${foreignPath}.`);
13830
+ }
13831
+ return;
13832
+ }
13833
+ await rename3(path, recoveredPath);
13834
+ const preserveRecovered = async (snapshot2) => {
13835
+ const foreignPath = recoveredPath + ".foreign-" + randomUUID6();
13836
+ if (snapshot2 !== undefined)
13837
+ await rename3(recoveredPath, foreignPath);
13838
+ await writeDesktopPrivate(recoveredPath, raw, 384, undefined, { current: undefined });
13839
+ throw new Fault(409, "desktop_config_changed", `Desktop recovery receipt changed; original receipt preserved at ${recoveredPath}; foreign receipt preserved at ${foreignPath}.`);
13840
+ };
13841
+ const recoveredSnapshot = await safeDesktopSnapshot(recoveredPath);
13842
+ if (!sameDesktopSnapshot(recoveredSnapshot, receiptSnapshot))
13843
+ await preserveRecovered(recoveredSnapshot);
13844
+ await assertMetaRestored();
13845
+ const finalReceipt = await safeDesktopSnapshot(recoveredPath);
13846
+ if (!sameDesktopSnapshot(finalReceipt, receiptSnapshot))
13847
+ await preserveRecovered(finalReceipt);
13444
13848
  }
13445
13849
  async function applyDesktopSelection(library, config, label2, checkpoint) {
13446
13850
  await recoverDesktopSelection(library);
13447
13851
  const path = join19(library, ".switcher-selection.json"), metaPath = join19(library, "_meta.json");
13448
13852
  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;
13853
+ const previousSelectedText = previous.appliedId ? await safeDesktopRead(join19(library, previous.appliedId + ".json")) : undefined;
13854
+ const previousSelected = previous.appliedId ? { id: previous.appliedId, hash: previousSelectedText === undefined ? null : hash2(previousSelectedText) } : null;
13450
13855
  const id2 = randomUUID6(), configPath = join19(library, id2 + ".json"), text = JSON.stringify(config, null, 2) + `
13451
13856
  `;
13452
13857
  const appliedMeta = JSON.stringify({ ...previous, appliedId: id2, entries: [...previous.entries, { id: id2, name: label2 }] }, null, 2) + `
13453
13858
  `;
13454
- const r = { version: 3, id: id2, configHash: hash2(text), previousMeta, previousMetaMode, appliedMeta, previousSelected };
13859
+ const previousMetadataHash = original?.metadataHash ?? null;
13860
+ const r = { version: 4, id: id2, configHash: hash2(text), previousMeta, previousMetaMode, previousMetadataHash, appliedMeta, appliedMetadataHash: "0".repeat(64), previousSelected };
13861
+ if (Buffer.byteLength(JSON.stringify(r) + `
13862
+ `) > 1024 * 1024)
13863
+ throw invalid3();
13864
+ if (original)
13865
+ await preserveDesktopFile(metaPath, originalPath(library, id2), original);
13866
+ await writeDesktopPrivate(preparedPath(library, id2), appliedMeta, 384, original ? { path: originalPath(library, id2), snapshot: original } : undefined, { current: undefined });
13867
+ const prepared = await safeDesktopSnapshot(preparedPath(library, id2));
13868
+ if (!prepared || prepared.text !== appliedMeta || prepared.mode !== 384)
13869
+ throw conflict();
13870
+ r.appliedMetadataHash = prepared.metadataHash;
13455
13871
  const journal = JSON.stringify(r) + `
13456
13872
  `;
13457
13873
  if (Buffer.byteLength(journal) > 1024 * 1024)
@@ -13465,7 +13881,7 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
13465
13881
  try {
13466
13882
  await unchanged();
13467
13883
  await checkpoint?.("preserved");
13468
- if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode))
13884
+ if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode, previousMetadataHash))
13469
13885
  throw conflict();
13470
13886
  await selectedUnchanged(library, r);
13471
13887
  await writeFile15(configPath, text, { mode: 384, flag: "wx" });
@@ -13473,10 +13889,14 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
13473
13889
  throw conflict();
13474
13890
  await checkpoint?.("config");
13475
13891
  await unchanged();
13476
- if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode))
13892
+ const preparedCurrent = await safeDesktopSnapshot(preparedPath(library, id2));
13893
+ if (!preparedCurrent || !matches(preparedCurrent, appliedMeta, 384, r.appliedMetadataHash))
13894
+ throw conflict();
13895
+ const currentMeta = await safeDesktopSnapshot(metaPath);
13896
+ if (!matches(currentMeta, previousMeta, previousMetaMode, previousMetadataHash))
13477
13897
  throw conflict();
13478
- await writeDesktopPrivate(metaPath, appliedMeta);
13479
- if (!matches(await safeDesktopSnapshot(metaPath), appliedMeta, 384))
13898
+ await replaceDesktopFile(metaPath, preparedPath(library, id2), currentMeta, preparedCurrent);
13899
+ if (!matches(await safeDesktopSnapshot(metaPath), appliedMeta, 384, r.appliedMetadataHash))
13480
13900
  throw conflict();
13481
13901
  await checkpoint?.("selected");
13482
13902
  } catch (error) {
@@ -13489,9 +13909,11 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
13489
13909
  const assertCurrentSync = () => {
13490
13910
  if (safeDesktopSnapshotSync(path)?.text !== journal)
13491
13911
  throw conflict();
13492
- if (previousSelected && (safeDesktopSnapshotSync(join19(library, previousSelected.id + ".json"))?.text ?? null) !== previousSelected.text)
13912
+ if (original && !matches(safeDesktopSnapshotSync(originalPath(library, id2)), previousMeta, previousMetaMode, previousMetadataHash))
13493
13913
  throw conflict();
13494
- if (!matches(safeDesktopSnapshotSync(metaPath), appliedMeta, 384) || safeDesktopSnapshotSync(configPath)?.text !== text)
13914
+ if (!selectedUnchangedSync(library, previousSelected))
13915
+ throw conflict();
13916
+ if (!matches(safeDesktopSnapshotSync(metaPath), appliedMeta, 384, r.appliedMetadataHash) || safeDesktopSnapshotSync(configPath)?.text !== text)
13495
13917
  throw conflict();
13496
13918
  };
13497
13919
  return {
@@ -13512,7 +13934,7 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
13512
13934
  import { constants as constants9 } from "fs";
13513
13935
  import { lstat as lstat9, open as open6, writeFile as writeFile16 } from "fs/promises";
13514
13936
  import { homedir as homedir10 } from "os";
13515
- import { join as join20, resolve as resolve10 } from "path";
13937
+ import { join as join20, resolve as resolve11 } from "path";
13516
13938
  var preferences = new Set([
13517
13939
  "$schema",
13518
13940
  "permissions",
@@ -13584,13 +14006,13 @@ function project(settings2, existing) {
13584
14006
  return result;
13585
14007
  }
13586
14008
  async function prepareClaudeUserSettings(overlayHome, environment = process.env) {
13587
- overlayHome = resolve10(overlayHome);
14009
+ overlayHome = resolve11(overlayHome);
13588
14010
  const existing = await readSettings(overlayHome);
13589
14011
  if (existing !== undefined) {
13590
14012
  project(existing, true);
13591
14013
  return;
13592
14014
  }
13593
- const sourceHome = resolve10(environment.CLAUDE_CONFIG_DIR ?? join20(environment.HOME ?? homedir10(), ".claude"));
14015
+ const sourceHome = resolve11(environment.CLAUDE_CONFIG_DIR ?? join20(environment.HOME ?? homedir10(), ".claude"));
13594
14016
  if (sourceHome === overlayHome)
13595
14017
  return;
13596
14018
  const source = await readSettings(sourceHome);
@@ -13697,7 +14119,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13697
14119
  // src/codex-session-discovery.ts
13698
14120
  import { spawn as spawn3 } from "child_process";
13699
14121
  import { createInterface as createInterface2 } from "readline/promises";
13700
- import { basename as basename3, resolve as resolve11 } from "path";
14122
+ import { basename as basename3, resolve as resolve12 } from "path";
13701
14123
  var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13702
14124
  var unavailable2 = () => new Fault(422, "codex_session_discovery", "Native Codex session discovery failed. No conversation was started. Retry discovery or provide an exact session ID.");
13703
14125
  async function listCodexSessions(prepared, cwd, query) {
@@ -13712,11 +14134,11 @@ async function listCodexSessions(prepared, cwd, query) {
13712
14134
  let done = false, initialized = false, pending = Buffer.alloc(0), responseBytes = 0;
13713
14135
  let killTimer;
13714
14136
  let resolvePage, rejectPage;
13715
- const result = new Promise((resolve12, reject2) => {
13716
- resolvePage = resolve12;
14137
+ const result = new Promise((resolve13, reject2) => {
14138
+ resolvePage = resolve13;
13717
14139
  rejectPage = reject2;
13718
14140
  });
13719
- const closed = new Promise((resolve12) => child.once("close", () => resolve12()));
14141
+ const closed = new Promise((resolve13) => child.once("close", () => resolve13()));
13720
14142
  const stop = () => {
13721
14143
  child.stdin.destroy();
13722
14144
  child.kill("SIGTERM");
@@ -13815,16 +14237,16 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
13815
14237
  break;
13816
14238
  }
13817
14239
  if (nativeArgs[i].startsWith("--cd="))
13818
- effectiveCwd = resolve11(cwd, nativeArgs[i].slice(5));
14240
+ effectiveCwd = resolve12(cwd, nativeArgs[i].slice(5));
13819
14241
  else if (nativeArgs[i].startsWith("-C") && nativeArgs[i].length > 2)
13820
- effectiveCwd = resolve11(cwd, nativeArgs[i].slice(2));
14242
+ effectiveCwd = resolve12(cwd, nativeArgs[i].slice(2));
13821
14243
  if (codexOptionRequestsHelp(nativeArgs[i]))
13822
14244
  return nativeArgs;
13823
14245
  if (codexOptionTakesValue(nativeArgs[i])) {
13824
14246
  if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
13825
14247
  if (!nativeArgs[i + 1])
13826
14248
  throw unavailable2();
13827
- effectiveCwd = resolve11(cwd, nativeArgs[i + 1]);
14249
+ effectiveCwd = resolve12(cwd, nativeArgs[i + 1]);
13828
14250
  }
13829
14251
  i++;
13830
14252
  continue;
@@ -13896,64 +14318,1267 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
13896
14318
  }
13897
14319
  }
13898
14320
 
13899
- // src/launcher.ts
13900
- var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
13901
- async function writeOriCodexCatalog(stateDir, models) {
13902
- const path = join22(stateDir, "ori-codex-models.json");
13903
- const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
13904
- await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
13905
- `, { mode: 384, flag: "wx" });
13906
- return path;
14321
+ // src/gateway-client.ts
14322
+ import { spawn as spawn4 } from "child_process";
14323
+ import { closeSync as closeSync3, openSync as openSync3 } from "fs";
14324
+
14325
+ // src/gateway-service.ts
14326
+ import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
14327
+ import { constants as constants10 } from "fs";
14328
+ import { chmod as chmod3, lstat as lstat10, mkdir as mkdir12, open as open7, readdir as readdir7, rename as rename4, rm as rm5, unlink as unlink3 } from "fs/promises";
14329
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join22, resolve as resolve13 } from "path";
14330
+ import { z as z10 } from "zod";
14331
+
14332
+ // src/process-table.ts
14333
+ import { createHash as createHash15 } from "crypto";
14334
+ import { readdir as readdir6, readFile as readFile7 } from "fs/promises";
14335
+ var MAX_PROCESSES = 1e5;
14336
+ async function darwinTable() {
14337
+ const child = Bun.spawn(["/bin/ps", "-A", "-o", "pid=", "-o", "ppid=", "-o", "lstart="], {
14338
+ env: { PATH: "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC" },
14339
+ stdin: "ignore",
14340
+ stdout: "pipe",
14341
+ stderr: "ignore"
14342
+ });
14343
+ const [text, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
14344
+ if (code !== 0)
14345
+ throw new Error("The process table could not be read.");
14346
+ const table = new Map;
14347
+ for (const line of text.split(`
14348
+ `)) {
14349
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S.*?)\s*$/.exec(line);
14350
+ if (!match || table.size >= MAX_PROCESSES)
14351
+ continue;
14352
+ const pid = Number(match[1]);
14353
+ table.set(pid, { pid, ppid: Number(match[2]), start: match[3] });
14354
+ }
14355
+ return table;
13907
14356
  }
13908
- function oriTarget(harness) {
13909
- if (harness === "antigravity" || harness === "junie")
13910
- throw new Error("This CLI is supported through the direct Switcher backend only.");
13911
- if (harness === "kilo")
13912
- throw new Error("Ori does not launch Kilo; use the direct backend.");
13913
- if (harness === "opencode")
13914
- throw new Error("Ori does not launch legacy OpenCode; use the direct backend.");
13915
- if (harness === "aider")
13916
- throw new Error("Ori does not launch Aider; use the direct backend.");
13917
- if (harness === "gemini")
13918
- throw new Error("Ori does not launch Gemini CLI; use the direct backend.");
13919
- if (harness === "prime-agent")
13920
- throw new Error("Ori does not launch Prime Agent; use the direct backend.");
13921
- if (harness === "omp")
13922
- throw new Error("Ori does not support OMP; use the direct OMP adapter.");
13923
- if (harness === "cline")
13924
- throw new Error("Ori does not support Cline; use the direct Cline adapter.");
13925
- if (harness === "hermes")
13926
- throw new Error("Ori does not provide a Hermes adapter; use the direct Hermes backend.");
13927
- return harness;
14357
+ async function linuxTable() {
14358
+ const boot = (await readFile7("/proc/sys/kernel/random/boot_id", "utf8").catch(() => "")).trim();
14359
+ const table = new Map;
14360
+ for (const name of await readdir6("/proc")) {
14361
+ if (!/^\d+$/.test(name) || table.size >= MAX_PROCESSES)
14362
+ continue;
14363
+ let stat6;
14364
+ try {
14365
+ stat6 = await readFile7(`/proc/${name}/stat`, "utf8");
14366
+ } catch {
14367
+ continue;
14368
+ }
14369
+ const fields = stat6.slice(stat6.lastIndexOf(")") + 2).split(" ");
14370
+ const pid = Number(name), ppid = Number(fields[1]), ticks = fields[19];
14371
+ if (!Number.isSafeInteger(ppid) || !ticks)
14372
+ continue;
14373
+ table.set(pid, { pid, ppid, start: `${boot}:${ticks}`, comm: stat6.slice(stat6.indexOf("(") + 1, stat6.lastIndexOf(")")) });
14374
+ }
14375
+ return table;
14376
+ }
14377
+ function readProcessTable() {
14378
+ if (process.platform === "darwin")
14379
+ return darwinTable();
14380
+ if (process.platform === "linux")
14381
+ return linuxTable();
14382
+ return Promise.reject(new Error("Process tracking is supported on macOS and Linux only."));
14383
+ }
14384
+ function descendants(table, roots, exclude = []) {
14385
+ const children = new Map;
14386
+ for (const entry of table.values())
14387
+ if (entry.pid !== entry.ppid)
14388
+ (children.get(entry.ppid) ?? children.set(entry.ppid, []).get(entry.ppid)).push(entry.pid);
14389
+ const blocked = new Set(exclude), seen = new Set, found = [];
14390
+ const queue = [...roots].filter((pid) => !blocked.has(pid));
14391
+ while (queue.length) {
14392
+ const pid = queue.shift();
14393
+ for (const child of children.get(pid) ?? []) {
14394
+ if (seen.has(child) || blocked.has(child))
14395
+ continue;
14396
+ seen.add(child);
14397
+ const entry = table.get(child);
14398
+ if (entry) {
14399
+ found.push(entry);
14400
+ queue.push(child);
14401
+ }
14402
+ }
14403
+ }
14404
+ return found;
13928
14405
  }
13929
- async function oriRequestForPlan(plan, options = {}) {
13930
- validateHarnessProvider(plan.profile.harness, plan.provider);
13931
- if (options.oriExecutable === "")
13932
- throw new Error("--ori-executable requires a non-empty executable path.");
13933
- const target = oriTarget(plan.profile.harness);
13934
- if (plan.provider.authStyle !== "bearer")
13935
- throw new Error("Ori requires the OpenRouter Bearer authentication contract; use the direct adapter for other auth styles.");
13936
- assertOriLoginAllowed({ ...process.env, ...options.credentialEnv });
13937
- const policyEnvironment = { ...process.env, ...options.credentialEnv };
13938
- if (plan.profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((policyEnvironment.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
13939
- throw new Error("Grok API-key authentication is disabled by GROK_DISABLE_API_KEY_AUTH. This provider launch cannot proceed under that native authentication policy.");
13940
- if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
13941
- throw new Error("Grok requires a native team login through GROK_FORCE_LOGIN_TEAM_ID. This provider launch cannot proceed under that native authentication policy.");
13942
- const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve12(options.cwd) : undefined });
13943
- const native = requireOriHarness(contract, target);
13944
- if (!native.path)
13945
- throw new Error("Ori did not report the native harness executable path.");
13946
- const detection = await detectHarness(target, native.path);
13947
- if (!detection.available)
13948
- throw new Error("The native harness reported by Ori could not report its version.");
13949
- validateHarnessVersion(target, detection.version);
13950
- const catalogPath = target === "codex" && options.stateDir ? await writeOriCodexCatalog(options.stateDir, plan.catalog.models) : undefined;
13951
- const request = buildOriRequest(plan, target, catalogPath, options.args ?? []);
13952
- validateOriLaunchRequest(request);
13953
- return { contract, request, detection };
14406
+ function isOrphan(entry, table) {
14407
+ if (entry.ppid === 1)
14408
+ return true;
14409
+ return entry.ppid !== entry.pid && table.get(entry.ppid)?.comm === "systemd";
13954
14410
  }
13955
- async function validateOriForPlan(plan, options = {}) {
13956
- const result = await oriRequestForPlan(plan, options);
14411
+ var TOKEN_ENTRY = /^[A-Za-z_][A-Za-z0-9_]*=([A-Za-z0-9_-]{43})$/;
14412
+ var holdsDigest = (entries, digest2) => {
14413
+ for (const entry of entries) {
14414
+ const match = TOKEN_ENTRY.exec(entry);
14415
+ if (match && createHash15("sha256").update(match[1]).digest("hex") === digest2)
14416
+ return true;
14417
+ }
14418
+ return false;
14419
+ };
14420
+ var PROBE_CHUNK = 200;
14421
+ async function darwinDigestHolders(pids, digest2) {
14422
+ const found = [];
14423
+ for (let index = 0;index < pids.length; index += PROBE_CHUNK) {
14424
+ const child = Bun.spawn(["/bin/ps", "-E", "-ww", "-o", "pid=", "-o", "command=", "-p", pids.slice(index, index + PROBE_CHUNK).join(",")], {
14425
+ env: { PATH: "/usr/bin:/bin", LC_ALL: "C" },
14426
+ stdin: "ignore",
14427
+ stdout: "pipe",
14428
+ stderr: "ignore"
14429
+ });
14430
+ const [text] = await Promise.all([new Response(child.stdout).text(), child.exited]);
14431
+ for (const line of text.split(`
14432
+ `)) {
14433
+ const match = /^\s*(\d+)\s(.*)$/.exec(line);
14434
+ if (match && holdsDigest(match[2].split(" "), digest2))
14435
+ found.push(Number(match[1]));
14436
+ }
14437
+ }
14438
+ return found;
14439
+ }
14440
+ async function linuxDigestHolders(pids, digest2) {
14441
+ const found = [];
14442
+ for (const pid of pids) {
14443
+ let environment;
14444
+ try {
14445
+ environment = await readFile7(`/proc/${pid}/environ`, "latin1");
14446
+ } catch {
14447
+ continue;
14448
+ }
14449
+ if (holdsDigest(environment.split("\x00"), digest2))
14450
+ found.push(pid);
14451
+ }
14452
+ return found;
14453
+ }
14454
+ function processesHoldingTokenDigest(pids, digest2) {
14455
+ if (!pids.length)
14456
+ return Promise.resolve([]);
14457
+ if (process.platform === "darwin")
14458
+ return darwinDigestHolders(pids, digest2);
14459
+ if (process.platform === "linux")
14460
+ return linuxDigestHolders(pids, digest2);
14461
+ return Promise.resolve([]);
14462
+ }
14463
+
14464
+ // src/gateway-service.ts
14465
+ var GATEWAY_PROTOCOL = 1;
14466
+ var SOCKET_PATH_LIMIT = 100;
14467
+ var MAX_HOLDERS = 4096;
14468
+ var MAX_ORPHAN_CANDIDATES = 1000;
14469
+ var MAX_EVENTS = 1000;
14470
+ var MAX_EVENT_BYTES = 512 * 1024;
14471
+ var DEFAULT_GRACE_MS = 10 * 60000;
14472
+ var DEFAULT_SCAN_MS = 1000;
14473
+ var PERSIST_INTERVAL_MS = 5000;
14474
+ var USE_PERSIST_INTERVAL_MS = 60000;
14475
+ function gatewayPaths(env = process.env) {
14476
+ const root = join22(switcherHome(env), "gateway");
14477
+ const preferred = join22(root, "control.sock");
14478
+ const name = `${createHash16("sha256").update(root).digest("hex").slice(0, 16)}.sock`;
14479
+ const runtime = process.platform === "linux" && env.XDG_RUNTIME_DIR && isAbsolute17(env.XDG_RUNTIME_DIR) ? join22(env.XDG_RUNTIME_DIR, "switcher", name) : undefined;
14480
+ const socket = Buffer.byteLength(preferred) <= SOCKET_PATH_LIMIT ? preferred : runtime && Buffer.byteLength(runtime) <= SOCKET_PATH_LIMIT ? runtime : join22("/tmp", `switcher-${process.getuid?.() ?? 0}`, name);
14481
+ return { root, socket, launches: join22(root, "launches"), config: join22(root, "config.json"), log: join22(root, "service.log") };
14482
+ }
14483
+ var UNTRUSTED_FIX = "Another account may have created it: remove it (or set HASNA_SWITCHER_HOME to a shorter path) and launch again.";
14484
+ async function assertPrivateSocketDirectory(directory) {
14485
+ const info2 = await lstat10(directory);
14486
+ if (!info2.isDirectory() || info2.isSymbolicLink() || (info2.mode & 63) !== 0 || info2.uid !== process.getuid?.())
14487
+ throw new Fault(503, "gateway_socket_untrusted", `The Switcher gateway socket directory ${directory} is not a private directory owned by this user (mode 0700), so Switcher will not use it. ${UNTRUSTED_FIX}`);
14488
+ }
14489
+ async function assertTrustedControlSocket(socket) {
14490
+ const missing = () => new Fault(503, "gateway_unavailable", "The Switcher gateway service is not running. Run `switcher gateway status`.");
14491
+ try {
14492
+ await assertPrivateSocketDirectory(dirname9(socket));
14493
+ } catch (error) {
14494
+ if (error.code === "ENOENT")
14495
+ throw missing();
14496
+ throw error;
14497
+ }
14498
+ let info2;
14499
+ try {
14500
+ info2 = await lstat10(socket);
14501
+ } catch (error) {
14502
+ if (error.code === "ENOENT")
14503
+ throw missing();
14504
+ throw new Fault(503, "gateway_socket_untrusted", `The Switcher gateway socket ${socket} could not be checked.`);
14505
+ }
14506
+ if (!info2.isSocket() || info2.uid !== process.getuid?.())
14507
+ throw new Fault(503, "gateway_socket_untrusted", `${socket} is not a socket owned by this user, so Switcher will not send it a launch. ${UNTRUSTED_FIX}`);
14508
+ }
14509
+ function defaultGatewayPort(uid = process.getuid?.() ?? 0) {
14510
+ return 47000 + uid % 1000;
14511
+ }
14512
+ var passwdHome;
14513
+ function accountHome() {
14514
+ if (passwdHome !== undefined)
14515
+ return passwdHome ?? undefined;
14516
+ passwdHome = null;
14517
+ const uid = process.getuid?.();
14518
+ if (uid === undefined)
14519
+ return;
14520
+ try {
14521
+ const command = process.platform === "darwin" ? ["/usr/bin/id", "-P", String(uid)] : process.platform === "linux" ? ["getent", "passwd", String(uid)] : undefined;
14522
+ if (!command)
14523
+ return;
14524
+ const result = Bun.spawnSync(command, { env: { PATH: "/usr/bin:/bin" }, stdin: "ignore", stdout: "pipe", stderr: "ignore" });
14525
+ const fields = result.exitCode === 0 ? result.stdout.toString().trim().split(`
14526
+ `)[0].split(":") : [];
14527
+ const home = fields[process.platform === "darwin" ? 8 : 5];
14528
+ if (home && isAbsolute17(home))
14529
+ passwdHome = resolve13(home);
14530
+ } catch {}
14531
+ return passwdHome ?? undefined;
14532
+ }
14533
+ function isDefaultSwitcherHome(env = process.env, home = accountHome()) {
14534
+ if (!home)
14535
+ return false;
14536
+ return resolve13(env.HOME?.trim() || home) === resolve13(home) && switcherHome(env) === resolve13(home, ".hasna", "switcher");
14537
+ }
14538
+ function envNumber(env, name, fallback, min, max) {
14539
+ const raw = env[name]?.trim();
14540
+ if (!raw)
14541
+ return fallback;
14542
+ const value = Number(raw);
14543
+ if (!Number.isSafeInteger(value) || value < min || value > max)
14544
+ throw new Fault(400, "invalid_gateway_setting", `${name} must be an integer from ${min} to ${max}.`);
14545
+ return value;
14546
+ }
14547
+ function gatewaySettings(env = process.env) {
14548
+ const port = env.SWITCHER_GATEWAY_PORT?.trim() ? envNumber(env, "SWITCHER_GATEWAY_PORT", 0, 1024, 65535) : undefined;
14549
+ return {
14550
+ port,
14551
+ graceMs: envNumber(env, "SWITCHER_GATEWAY_GRACE_SECONDS", DEFAULT_GRACE_MS / 1000, 1, 7 * 24 * 3600) * 1000,
14552
+ scanMs: envNumber(env, "SWITCHER_GATEWAY_SCAN_MS", DEFAULT_SCAN_MS, 50, 60000),
14553
+ exitIdleMs: envNumber(env, "SWITCHER_GATEWAY_EXIT_IDLE_SECONDS", 60, 1, 24 * 3600) * 1000
14554
+ };
14555
+ }
14556
+ async function socketDirectory(paths) {
14557
+ const directory = dirname9(paths.socket);
14558
+ if (directory === paths.root)
14559
+ return;
14560
+ await mkdir12(directory, { mode: 448, recursive: true });
14561
+ await assertPrivateSocketDirectory(directory);
14562
+ }
14563
+ var sha256 = (value) => createHash16("sha256").update(value).digest("hex");
14564
+ var forbiddenKeys = new Set(["__proto__", "prototype", "constructor"]);
14565
+ function nullRecord(value, item2, limit) {
14566
+ if (!value || typeof value !== "object" || Array.isArray(value))
14567
+ throw new Fault(400, "invalid_request", "Model policy maps must be objects.");
14568
+ const entries = Object.entries(value);
14569
+ if (entries.length > limit)
14570
+ throw new Fault(400, "invalid_request", "Model policy map is too large.");
14571
+ const result = Object.create(null);
14572
+ for (const [key, entry] of entries) {
14573
+ if (forbiddenKeys.has(key) || key.length > 300)
14574
+ throw new Fault(400, "invalid_request", "Model policy key is invalid.");
14575
+ result[key] = item2(entry);
14576
+ }
14577
+ return result;
14578
+ }
14579
+ var modelId = (value) => {
14580
+ if (typeof value !== "string" || !value || value.length > 300 || /[\x00-\x1f\x7f]/.test(value))
14581
+ throw new Fault(400, "invalid_request", "Model policy entry is invalid.");
14582
+ return value;
14583
+ };
14584
+ function compiledPolicy(value) {
14585
+ if (!value || typeof value !== "object" || Array.isArray(value))
14586
+ throw new Fault(400, "invalid_request", "A compiled model policy is required.");
14587
+ const input = value;
14588
+ if (input.version !== 1 || typeof input.digest !== "string" || !/^[a-f0-9]{64}$/.test(input.digest) || !Array.isArray(input.allowedModels) || input.allowedModels.length > 20000)
14589
+ throw new Fault(400, "invalid_request", "The compiled model policy is invalid.");
14590
+ return {
14591
+ version: 1,
14592
+ model: modelId(input.model),
14593
+ digest: input.digest,
14594
+ roles: nullRecord(input.roles, modelId, 20),
14595
+ allowedModels: input.allowedModels.map(modelId),
14596
+ aliases: nullRecord(input.aliases, modelId, 200),
14597
+ fallbacks: nullRecord(input.fallbacks, (entry) => {
14598
+ if (!Array.isArray(entry) || entry.length > 20)
14599
+ throw new Fault(400, "invalid_request", "Fallback list is invalid.");
14600
+ return entry.map(modelId);
14601
+ }, 200)
14602
+ };
14603
+ }
14604
+ var gatewaySchema = z10.object({
14605
+ harness: harnessSchema,
14606
+ baseUrl: z10.string().max(2000).refine((value) => {
14607
+ try {
14608
+ return ["http:", "https:"].includes(new URL(value).protocol);
14609
+ } catch {
14610
+ return false;
14611
+ }
14612
+ }, "Use an http(s) provider URL."),
14613
+ protocol: protocolSchema,
14614
+ authStyle: z10.enum(["bearer", "x-api-key", "api-key"]).optional(),
14615
+ model: z10.string().min(1).max(300),
14616
+ models: z10.array(modelSchema.strip()).min(1).max(20000),
14617
+ compiledPolicy: z10.unknown(),
14618
+ providerId: z10.string().max(200).optional(),
14619
+ catalogPath: z10.string().max(4096).refine(isAbsolute17, "Use an absolute catalog path."),
14620
+ cwd: z10.string().max(4096).refine(isAbsolute17, "Use an absolute working directory.")
14621
+ }).strict();
14622
+ var credentialEnvSchema = z10.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
14623
+ var registrationSchema = z10.object({
14624
+ holderPid: z10.number().int().positive(),
14625
+ gateway: gatewaySchema,
14626
+ credential: z10.string().min(1).max(64000).refine((value) => !/[\x00-\x1f\x7f]/.test(value), "Credential contains control characters.").optional(),
14627
+ credentialEnv: credentialEnvSchema.optional(),
14628
+ stateDir: z10.string().max(4096).optional()
14629
+ }).strict();
14630
+ var holderSchema = z10.object({ pid: z10.number().int().positive(), start: z10.string().min(1).max(200) }).strict();
14631
+ var credentialSourceSchema = z10.discriminatedUnion("source", [
14632
+ z10.object({ source: z10.literal("none") }).strict(),
14633
+ z10.object({ source: z10.literal("ephemeral"), credentialEnv: credentialEnvSchema.optional() }).strict(),
14634
+ z10.object({ source: z10.literal("binding"), credentialEnv: credentialEnvSchema, bindingDigest: z10.string().regex(/^[a-f0-9]{64}$/) }).strict()
14635
+ ]);
14636
+ var staticSchema = z10.object({
14637
+ schema: z10.literal(1),
14638
+ id: z10.string().uuid(),
14639
+ tokenDigest: z10.string().regex(/^[a-f0-9]{64}$/),
14640
+ createdAt: z10.number(),
14641
+ launcherPid: z10.number().int().positive(),
14642
+ gateway: gatewaySchema,
14643
+ credential: credentialSourceSchema,
14644
+ stateDir: z10.string().max(4096).optional()
14645
+ }).strict();
14646
+ var holderStateSchema = z10.object({ lastUsedAt: z10.number(), lastHolderAt: z10.number(), released: z10.boolean(), holders: z10.array(holderSchema).max(MAX_HOLDERS), extendedAt: z10.number().optional() }).strict();
14647
+ var processKey = (entry) => `${entry.pid}@${entry.start}`;
14648
+ var SETTLED_MS = 120000;
14649
+ var SETTLED_SCAN_FACTOR = 5;
14650
+ var staticFields = (record3) => {
14651
+ const { lastUsedAt: _used, lastHolderAt: _holder, released: _released, holders: _holders, extendedAt: _extended, ...rest } = record3;
14652
+ return rest;
14653
+ };
14654
+ var holderFields = (record3) => ({ lastUsedAt: record3.lastUsedAt, lastHolderAt: record3.lastHolderAt, released: record3.released, holders: record3.holders, ...record3.extendedAt !== undefined ? { extendedAt: record3.extendedAt } : {} });
14655
+ var LAUNCH_HINT = "Start a new session with `switcher launch`. If this is a Claude Code background session, its background host still carries the ended launch: exit that host too, so the next `switcher launch` starts a new one.";
14656
+ var loopbackHosts = (port) => new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
14657
+ var errorBody = (status, code, message) => Response.json({ type: "error", error: { type: status === 401 ? "authentication_error" : status === 403 ? "permission_error" : status === 404 ? "not_found_error" : status === 400 ? "invalid_request_error" : "api_error", code, message } }, { status });
14658
+ var presented = (request) => request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
14659
+ async function liveGateway(socket) {
14660
+ try {
14661
+ const response = await fetch("http://switcher-gateway/v1/status", { unix: socket, signal: AbortSignal.timeout(1500) });
14662
+ const body2 = await response.json();
14663
+ return response.ok && body2.service === "switcher-gateway";
14664
+ } catch {
14665
+ return false;
14666
+ }
14667
+ }
14668
+ async function readPrivateJson(path) {
14669
+ const file = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
14670
+ try {
14671
+ const info2 = await file.stat();
14672
+ if (!info2.isFile() || info2.size > 128 * 1024 * 1024 || (info2.mode & 63) !== 0 || info2.uid !== process.getuid?.())
14673
+ throw new Error("unsafe launch record");
14674
+ return JSON.parse(await file.readFile("utf8"));
14675
+ } finally {
14676
+ await file.close();
14677
+ }
14678
+ }
14679
+ async function readRecord(directory, id2) {
14680
+ const fixed = staticSchema.parse(await readPrivateJson(join22(directory, `${id2}.json`)));
14681
+ if (fixed.id !== id2)
14682
+ throw new Error("launch record id mismatch");
14683
+ const state = await readPrivateJson(join22(directory, `${id2}.holders.json`)).then((value) => holderStateSchema.parse(value), () => {
14684
+ return;
14685
+ });
14686
+ return { ...fixed, ...state ?? { lastUsedAt: fixed.createdAt, lastHolderAt: fixed.createdAt, released: false, holders: [] } };
14687
+ }
14688
+ async function writePrivate(path, text) {
14689
+ const temporary = `${path}.${randomUUID7()}.tmp`;
14690
+ const file = await open7(temporary, "wx", 384);
14691
+ try {
14692
+ await file.writeFile(text);
14693
+ await file.sync();
14694
+ } finally {
14695
+ await file.close();
14696
+ }
14697
+ await rename4(temporary, path);
14698
+ }
14699
+ async function launchStateDirectory(path) {
14700
+ if (path === undefined)
14701
+ return;
14702
+ if (!isAbsolute17(path) || resolve13(path) !== path || !/^launch-[A-Za-z0-9]{6}$/.test(basename4(path)))
14703
+ throw new Fault(400, "invalid_state_dir", "The launch state directory must be an absolute launch-XXXXXX directory.");
14704
+ const info2 = await lstat10(path).catch(() => {
14705
+ return;
14706
+ });
14707
+ if (!info2?.isDirectory() || info2.isSymbolicLink() || info2.uid !== process.getuid?.() || (info2.mode & 63) !== 0)
14708
+ throw new Fault(400, "invalid_state_dir", "The launch state directory must be a private directory owned by this user.");
14709
+ return path;
14710
+ }
14711
+ async function startGatewayService(options = {}) {
14712
+ if (process.platform === "win32")
14713
+ throw new Fault(422, "gateway_unsupported", "The persistent Switcher gateway supports macOS and Linux.");
14714
+ const env = options.env ?? process.env;
14715
+ const settings2 = gatewaySettings(env);
14716
+ const paths = gatewayPaths(env);
14717
+ const now = options.now ?? Date.now;
14718
+ const graceMs = options.graceMs ?? settings2.graceMs, scanMs = options.scanMs ?? settings2.scanMs;
14719
+ const processTable = options.processTable ?? readProcessTable;
14720
+ const environmentProbe = options.environmentProbe ?? processesHoldingTokenDigest;
14721
+ const log = options.log ?? ((line) => console.error(`switcher-gateway ${new Date().toISOString()} ${line}`));
14722
+ const resolver = new CredentialResolver(env);
14723
+ const resolveCredential2 = options.resolveCredential ?? ((provider) => resolver.resolve(provider));
14724
+ const bindings = new CredentialBindings(env);
14725
+ await privateDirectory(switcherHome(env));
14726
+ await privateDirectory(paths.root);
14727
+ await privateDirectory(paths.launches);
14728
+ await socketDirectory(paths);
14729
+ let persisted = {};
14730
+ try {
14731
+ const config = await Bun.file(paths.config).json();
14732
+ if (Number.isSafeInteger(config.port))
14733
+ persisted = { port: config.port };
14734
+ } catch {}
14735
+ const requestedPort = options.port ?? settings2.port ?? persisted.port ?? (isDefaultSwitcherHome(env) ? defaultGatewayPort() : 0);
14736
+ const launches = new Map, byDigest = new Map;
14737
+ let closing = false, stopping, resolveClosed, idleSince = now();
14738
+ const closed = new Promise((resolve14) => {
14739
+ resolveClosed = resolve14;
14740
+ });
14741
+ const persist = async (launch, force = false) => {
14742
+ if (!force && !launch.dirty)
14743
+ return;
14744
+ launch.dirty = false;
14745
+ launch.persistedAt = now();
14746
+ if (!launches.has(launch.record.id))
14747
+ return;
14748
+ await writePrivate(join22(paths.launches, `${launch.record.id}.holders.json`), JSON.stringify(holderFields(launch.record))).catch(() => {
14749
+ launch.dirty = true;
14750
+ });
14751
+ };
14752
+ const credentialFor = (launch) => async () => {
14753
+ if (launch.credential !== undefined)
14754
+ return launch.credential;
14755
+ const source = launch.record.credential;
14756
+ if (source.source === "none")
14757
+ return;
14758
+ if (source.source === "ephemeral") {
14759
+ const reference2 = source.credentialEnv ?? "SWITCHER_PROVIDER_<NAME>";
14760
+ throw new Fault(401, "switcher_gateway_credential_unavailable", `Switcher gateway restarted and no longer holds this launch's provider credential: it came from the launch environment (${reference2}), which the gateway never stores. ${LAUNCH_HINT} To let sessions survive gateway restarts, bind it once with \`switcher credentials bind ${reference2} --vault-key <key>\`.`);
14761
+ }
14762
+ return launch.pending ??= (async () => {
14763
+ try {
14764
+ const binding = await bindings.get(source.credentialEnv);
14765
+ if (!binding || sha256(JSON.stringify(binding)) !== source.bindingDigest)
14766
+ throw new Fault(401, "switcher_gateway_credential_changed", `Switcher gateway: the credential binding ${source.credentialEnv} changed or was removed after this launch started. ${LAUNCH_HINT}`);
14767
+ const provider = { id: launch.record.gateway.providerId ?? "provider", name: "provider", baseUrl: launch.record.gateway.baseUrl, protocol: launch.record.gateway.protocol, credentialEnv: source.credentialEnv, authStyle: launch.record.gateway.authStyle };
14768
+ let value;
14769
+ try {
14770
+ value = await resolveCredential2(provider);
14771
+ } catch (error) {
14772
+ throw new Fault(503, "switcher_gateway_credential_unavailable", `Switcher gateway could not read the provider credential from binding ${source.credentialEnv}${error instanceof Fault ? ` (${error.code})` : ""}. Check it with \`switcher credentials check ${source.credentialEnv}\`, then retry.`);
14773
+ }
14774
+ if (!value)
14775
+ throw new Fault(503, "switcher_gateway_credential_unavailable", `Switcher gateway: binding ${source.credentialEnv} returned no credential. Check it with \`switcher credentials check ${source.credentialEnv}\`, then retry.`);
14776
+ launch.credential = value;
14777
+ return value;
14778
+ } finally {
14779
+ launch.pending = undefined;
14780
+ }
14781
+ })();
14782
+ };
14783
+ const handlerFor = (launch) => createInferenceHandler({
14784
+ ...launch.record.gateway,
14785
+ compiledPolicy: compiledPolicy(launch.record.gateway.compiledPolicy),
14786
+ stateDir: launch.record.stateDir ?? paths.root,
14787
+ credential: undefined,
14788
+ onRoutingEvent: (event) => {
14789
+ if (launch.record.released)
14790
+ return;
14791
+ const bytes = Buffer.byteLength(JSON.stringify(event));
14792
+ if (launch.events.length < MAX_EVENTS && launch.eventBytes + bytes <= MAX_EVENT_BYTES) {
14793
+ launch.events.push(event);
14794
+ launch.eventBytes += bytes;
14795
+ } else
14796
+ launch.eventsDropped = Math.min(1e6, launch.eventsDropped + 1);
14797
+ }
14798
+ }, options.timing, { credential: () => credentialFor(launch)() });
14799
+ const adopt = (record3, credential) => {
14800
+ const launch = { record: record3, credential, events: [], eventBytes: 0, eventsDropped: 0, dirty: false, persistedAt: 0, usedPersistedAt: 0, recentAt: now() };
14801
+ launch.handler = handlerFor(launch);
14802
+ launches.set(record3.id, launch);
14803
+ byDigest.set(record3.tokenDigest, launch);
14804
+ return launch;
14805
+ };
14806
+ const remove = async (launch, reason, removeState) => {
14807
+ if (!launches.delete(launch.record.id))
14808
+ return;
14809
+ byDigest.delete(launch.record.tokenDigest);
14810
+ launch.credential = undefined;
14811
+ await launch.handler.close().catch(() => {
14812
+ return;
14813
+ });
14814
+ await rm5(join22(paths.launches, `${launch.record.id}.holders.json`), { force: true }).catch(() => {
14815
+ return;
14816
+ });
14817
+ await rm5(join22(paths.launches, `${launch.record.id}.json`), { force: true }).catch(() => {
14818
+ return;
14819
+ });
14820
+ if (removeState && launch.record.stateDir) {
14821
+ const directory = await launchStateDirectory(launch.record.stateDir).catch(() => {
14822
+ return;
14823
+ });
14824
+ if (directory)
14825
+ await rm5(directory, { recursive: true, force: true }).catch(() => {
14826
+ return;
14827
+ });
14828
+ }
14829
+ log(`launch ${launch.record.id.slice(0, 8)} ${reason}`);
14830
+ if (!launches.size)
14831
+ idleSince = now();
14832
+ };
14833
+ const liveHolders = (launch, table) => launch.record.holders.filter((holder) => table.get(holder.pid)?.start === holder.start);
14834
+ const track = (launch, table, at) => {
14835
+ const live = liveHolders(launch, table);
14836
+ const next = new Map(live.map((holder) => [holder.pid, holder]));
14837
+ for (const entry of descendants(table, live.map((holder) => holder.pid), [process.pid]))
14838
+ if (!next.has(entry.pid) && next.size < MAX_HOLDERS)
14839
+ next.set(entry.pid, { pid: entry.pid, start: entry.start });
14840
+ const key = (holders) => [...holders].map((holder) => `${holder.pid}@${holder.start}`).sort().join("|");
14841
+ const changed = key(next.values()) !== key(launch.record.holders);
14842
+ launch.record.holders = [...next.values()];
14843
+ if (next.size)
14844
+ launch.record.lastHolderAt = at;
14845
+ if (changed)
14846
+ launch.dirty = true;
14847
+ };
14848
+ const adoptOrphans = async (launch, table) => {
14849
+ const baseline = launch.orphanBaseline;
14850
+ if (!baseline)
14851
+ return;
14852
+ launch.orphanBaseline = undefined;
14853
+ const known = new Set(launch.record.holders.map(processKey));
14854
+ const candidates = [...table.values()].filter((entry) => entry.pid !== process.pid && isOrphan(entry, table) && !baseline.has(processKey(entry)) && !known.has(processKey(entry)));
14855
+ if (!candidates.length)
14856
+ return;
14857
+ let found;
14858
+ try {
14859
+ found = await environmentProbe(candidates.slice(-MAX_ORPHAN_CANDIDATES).map((entry) => entry.pid), launch.record.tokenDigest);
14860
+ } catch {
14861
+ return;
14862
+ }
14863
+ let adopted = 0;
14864
+ for (const pid of new Set(found)) {
14865
+ const entry = table.get(pid);
14866
+ if (!entry || known.has(processKey(entry)) || launch.record.holders.length >= MAX_HOLDERS)
14867
+ continue;
14868
+ launch.record.holders.push({ pid, start: entry.start });
14869
+ known.add(processKey(entry));
14870
+ adopted++;
14871
+ }
14872
+ if (!adopted)
14873
+ return;
14874
+ launch.dirty = true;
14875
+ log(`launch ${launch.record.id.slice(0, 8)} adopted ${adopted} detached process(es) started with its token`);
14876
+ };
14877
+ const launcherGone = (launch) => !launch.record.holders.some((holder) => holder.pid === launch.record.launcherPid);
14878
+ let scanning;
14879
+ const runScan = async () => {
14880
+ if (!launches.size)
14881
+ return;
14882
+ let table;
14883
+ try {
14884
+ table = await processTable();
14885
+ } catch {
14886
+ return;
14887
+ }
14888
+ const at = now();
14889
+ for (const launch of [...launches.values()]) {
14890
+ track(launch, table, at);
14891
+ if (launch.orphanBaseline && launcherGone(launch)) {
14892
+ await adoptOrphans(launch, table);
14893
+ track(launch, table, at);
14894
+ }
14895
+ if (!launch.record.holders.length && at - Math.max(launch.record.lastHolderAt, launch.record.lastUsedAt) > graceMs)
14896
+ await remove(launch, "expired: no process holds it", true);
14897
+ else if (launch.dirty && at - launch.persistedAt >= PERSIST_INTERVAL_MS)
14898
+ await persist(launch);
14899
+ }
14900
+ };
14901
+ const scan = () => scanning ??= runScan().finally(() => {
14902
+ scanning = undefined;
14903
+ });
14904
+ let inference;
14905
+ try {
14906
+ inference = Bun.serve({ hostname: "127.0.0.1", port: requestedPort, maxRequestBodySize: MAX_REQUEST_BODY_BYTES, idleTimeout: 255, async fetch(request, server) {
14907
+ const host2 = request.headers.get("host")?.toLowerCase();
14908
+ if (host2 !== undefined && !loopbackHosts(server.port).has(host2))
14909
+ return errorBody(403, "switcher_gateway_host_refused", `Switcher gateway answers only requests addressed to 127.0.0.1:${server.port}. Use the base URL that \`switcher launch\` gave the harness.`);
14910
+ const url2 = new URL(request.url);
14911
+ if (request.method === "GET" && url2.pathname === "/health")
14912
+ return Response.json({ status: "ok", service: "switcher-gateway", protocol: GATEWAY_PROTOCOL });
14913
+ if (closing)
14914
+ return errorBody(503, "switcher_gateway_stopping", `Switcher gateway is restarting. Retry in a few seconds; if this persists, run \`switcher gateway status\`.`);
14915
+ const token = presented(request);
14916
+ if (!token)
14917
+ return errorBody(401, "switcher_gateway_token_missing", `Switcher gateway: the request carries no launch token. ${LAUNCH_HINT}`);
14918
+ const launch = byDigest.get(sha256(token));
14919
+ if (!launch)
14920
+ return errorBody(401, "switcher_gateway_launch_unknown", `Switcher gateway: this session's launch is no longer registered (it ended and no process held it, or the gateway state was reset). ${LAUNCH_HINT}`);
14921
+ const at = now();
14922
+ launch.record.lastUsedAt = at;
14923
+ if (at - launch.usedPersistedAt >= USE_PERSIST_INTERVAL_MS) {
14924
+ launch.usedPersistedAt = at;
14925
+ launch.dirty = true;
14926
+ }
14927
+ return launch.handler.handle(request, server);
14928
+ } });
14929
+ } catch (error) {
14930
+ if (await liveGateway(paths.socket))
14931
+ throw new Fault(409, "gateway_running", "A Switcher gateway is already running for this home.");
14932
+ throw new Fault(409, "gateway_port_in_use", `Port ${requestedPort} on 127.0.0.1 is unavailable for the Switcher gateway (${error.code ?? "bind failed"}). Free it, or set SWITCHER_GATEWAY_PORT to another port and run \`switcher gateway install\` again.`);
14933
+ }
14934
+ const port = inference.port;
14935
+ const url = `http://127.0.0.1:${port}`;
14936
+ if (await liveGateway(paths.socket)) {
14937
+ await inference.stop(true);
14938
+ throw new Fault(409, "gateway_running", "A Switcher gateway is already running for this home.");
14939
+ }
14940
+ await unlink3(paths.socket).catch((error) => {
14941
+ if (error.code !== "ENOENT")
14942
+ throw error;
14943
+ });
14944
+ if (persisted.port !== port)
14945
+ await writePrivate(paths.config, JSON.stringify({ port }) + `
14946
+ `);
14947
+ const json = async (request) => {
14948
+ try {
14949
+ return await request.json();
14950
+ } catch {
14951
+ throw new Fault(400, "invalid_json", "The control request must be JSON.");
14952
+ }
14953
+ };
14954
+ const launchFor = (id2) => {
14955
+ const launch = launches.get(id2);
14956
+ if (!launch)
14957
+ throw new Fault(404, "launch_not_found", "No such launch is registered with the gateway.");
14958
+ return launch;
14959
+ };
14960
+ const register = async (input) => {
14961
+ const table = await processTable();
14962
+ const holder = table.get(input.holderPid);
14963
+ if (!holder)
14964
+ throw new Fault(400, "holder_not_running", "The registering process is not running.");
14965
+ const stateDir = await launchStateDirectory(input.stateDir);
14966
+ const policy = compiledPolicy(input.gateway.compiledPolicy);
14967
+ if (policy.model !== input.gateway.model)
14968
+ throw new Fault(400, "invalid_request", "The compiled policy does not belong to the selected model.");
14969
+ let credential = { source: "none" };
14970
+ if (input.credential !== undefined) {
14971
+ credential = { source: "ephemeral", ...input.credentialEnv ? { credentialEnv: input.credentialEnv } : {} };
14972
+ if (input.credentialEnv) {
14973
+ const binding = await bindings.get(input.credentialEnv).catch(() => {
14974
+ return;
14975
+ });
14976
+ if (binding && binding.origins.includes(new URL(input.gateway.baseUrl).origin))
14977
+ credential = { source: "binding", credentialEnv: input.credentialEnv, bindingDigest: sha256(JSON.stringify(binding)) };
14978
+ }
14979
+ }
14980
+ const token = randomBytes2(32).toString("base64url"), at = now();
14981
+ const record3 = {
14982
+ schema: 1,
14983
+ id: randomUUID7(),
14984
+ tokenDigest: sha256(token),
14985
+ createdAt: at,
14986
+ lastUsedAt: at,
14987
+ lastHolderAt: at,
14988
+ launcherPid: holder.pid,
14989
+ released: false,
14990
+ holders: [{ pid: holder.pid, start: holder.start }],
14991
+ gateway: { ...input.gateway, compiledPolicy: policy },
14992
+ credential,
14993
+ ...stateDir ? { stateDir } : {}
14994
+ };
14995
+ const launch = adopt(record3, input.credential);
14996
+ launch.orphanBaseline = new Set([...table.values()].filter((entry) => isOrphan(entry, table)).map(processKey));
14997
+ await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
14998
+ await persist(launch, true);
14999
+ log(`launch ${record3.id.slice(0, 8)} registered (${record3.gateway.harness}, ${record3.gateway.model})`);
15000
+ return { id: record3.id, token, baseUrl: `${url}/${record3.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}` };
15001
+ };
15002
+ const release = async (launch) => {
15003
+ const table = await processTable().catch(() => {
15004
+ return;
15005
+ });
15006
+ if (table) {
15007
+ track(launch, table, now());
15008
+ await adoptOrphans(launch, table);
15009
+ track(launch, table, now());
15010
+ }
15011
+ const others = table ? liveHolders(launch, table).filter((holder) => holder.pid !== launch.record.launcherPid) : launch.record.holders;
15012
+ const { events, eventsDropped } = launch;
15013
+ launch.events = [];
15014
+ launch.eventBytes = 0;
15015
+ if (!others.length) {
15016
+ await remove(launch, "revoked: launch ended", false);
15017
+ return { retained: false, holders: 0, events, eventsDropped };
15018
+ }
15019
+ launch.record.released = true;
15020
+ await persist(launch, true);
15021
+ log(`launch ${launch.record.id.slice(0, 8)} released; ${others.length} process(es) still hold it`);
15022
+ return { retained: true, holders: others.length, events, eventsDropped };
15023
+ };
15024
+ const control = async (request) => {
15025
+ const url2 = new URL(request.url), method = request.method, parts = url2.pathname.split("/").filter(Boolean);
15026
+ try {
15027
+ if (method === "GET" && url2.pathname === "/v1/status")
15028
+ return Response.json({ service: "switcher-gateway", protocol: GATEWAY_PROTOCOL, version: VERSION, pid: process.pid, port, baseUrl: `http://127.0.0.1:${port}`, launches: launches.size, supervisor: options.supervisor ?? "none" });
15029
+ if (method === "GET" && url2.pathname === "/v1/launches")
15030
+ return Response.json({ data: [...launches.values()].map(({ record: record3 }) => ({ id: record3.id, harness: record3.gateway.harness, model: record3.gateway.model, createdAt: new Date(record3.createdAt).toISOString(), lastUsedAt: new Date(record3.lastUsedAt).toISOString(), holders: record3.holders.length, released: record3.released, credential: record3.credential.source })) });
15031
+ if (method === "POST" && url2.pathname === "/v1/launches")
15032
+ return Response.json(await register(registrationSchema.parse(await json(request))), { status: 201 });
15033
+ if (method === "POST" && url2.pathname === "/v1/stop") {
15034
+ setTimeout(() => void close(), 10);
15035
+ return Response.json({ stopping: true });
15036
+ }
15037
+ if (parts.length >= 3 && parts[0] === "v1" && parts[1] === "launches") {
15038
+ const launch = launchFor(parts[2]);
15039
+ if (method === "DELETE" && parts.length === 3) {
15040
+ await remove(launch, "revoked by its launcher", false);
15041
+ return Response.json({ revoked: true });
15042
+ }
15043
+ if (method === "POST" && parts[3] === "holders" && parts.length === 4) {
15044
+ const { pid } = z10.object({ pid: z10.number().int().positive() }).strict().parse(await json(request));
15045
+ const table = await processTable();
15046
+ const entry = table.get(pid);
15047
+ if (entry && !launch.record.holders.some((holder) => holder.pid === pid && holder.start === entry.start) && launch.record.holders.length < MAX_HOLDERS)
15048
+ launch.record.holders.push({ pid, start: entry.start });
15049
+ track(launch, table, now());
15050
+ launch.recentAt = now();
15051
+ await persist(launch, true);
15052
+ return Response.json({ holders: launch.record.holders.length });
15053
+ }
15054
+ if (method === "POST" && parts[3] === "release" && parts.length === 4)
15055
+ return Response.json(await release(launch));
15056
+ }
15057
+ return errorBody(404, "unsupported_route", "Unsupported gateway control route.");
15058
+ } catch (error) {
15059
+ if (error instanceof z10.ZodError)
15060
+ return errorBody(400, "invalid_request", error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ").slice(0, 1000));
15061
+ if (error instanceof Fault)
15062
+ return errorBody(error.status, error.code, error.message);
15063
+ return errorBody(500, "gateway_error", "The gateway could not complete the control request.");
15064
+ }
15065
+ };
15066
+ const controlServer = Bun.serve({ unix: paths.socket, maxRequestBodySize: 256 * 1024 * 1024, fetch: control });
15067
+ await chmod3(paths.socket, 384);
15068
+ const restoredAt = now();
15069
+ for (const name of await readdir7(paths.launches)) {
15070
+ if (!/^[0-9a-f-]{36}\.json$/.test(name))
15071
+ continue;
15072
+ try {
15073
+ const record3 = await readRecord(paths.launches, name.slice(0, -5));
15074
+ const extend = record3.extendedAt === undefined || Math.max(record3.lastHolderAt, record3.lastUsedAt) > record3.extendedAt;
15075
+ if (extend) {
15076
+ record3.lastHolderAt = Math.max(record3.lastHolderAt, restoredAt);
15077
+ record3.extendedAt = restoredAt;
15078
+ }
15079
+ const launch = adopt(record3);
15080
+ if (extend)
15081
+ await persist(launch, true);
15082
+ } catch {
15083
+ log(`ignored unreadable launch record ${name.slice(0, 8)}`);
15084
+ }
15085
+ }
15086
+ log(`listening on ${url} (pid ${process.pid}, version ${VERSION}, ${launches.size} launch(es) restored)`);
15087
+ await scan();
15088
+ let tick = 0;
15089
+ const timer = setInterval(() => {
15090
+ tick++;
15091
+ const at = now(), settled = [...launches.values()].every((launch) => at - launch.recentAt > SETTLED_MS);
15092
+ (settled && tick % SETTLED_SCAN_FACTOR ? Promise.resolve() : scan()).then(() => {
15093
+ if (options.exitWhenIdleMs !== undefined && !launches.size && now() - idleSince >= options.exitWhenIdleMs) {
15094
+ log("exiting: no launches");
15095
+ close();
15096
+ }
15097
+ });
15098
+ }, scanMs);
15099
+ const close = () => stopping ??= (async () => {
15100
+ closing = true;
15101
+ clearInterval(timer);
15102
+ await scanning?.catch(() => {
15103
+ return;
15104
+ });
15105
+ for (const launch of launches.values())
15106
+ await persist(launch, true);
15107
+ await Promise.allSettled([...launches.values()].map((launch) => launch.handler.close()));
15108
+ await inference.stop(true);
15109
+ await controlServer.stop(true);
15110
+ await unlink3(paths.socket).catch(() => {
15111
+ return;
15112
+ });
15113
+ log("stopped");
15114
+ resolveClosed();
15115
+ })();
15116
+ return { url, port, socket: paths.socket, pid: process.pid, close, closed, scan };
15117
+ }
15118
+
15119
+ // src/gateway-supervisor.ts
15120
+ import { randomUUID as randomUUID8 } from "crypto";
15121
+ import { lstat as lstat11, mkdir as mkdir13, open as open8, readFile as readFile8, realpath as realpath7, rename as rename5, unlink as unlink4 } from "fs/promises";
15122
+ import { dirname as dirname10, isAbsolute as isAbsolute18, join as join23 } from "path";
15123
+ var LAUNCHD_LABEL = "com.hasna.switcher.gateway";
15124
+ var SYSTEMD_UNIT = "switcher-gateway.service";
15125
+ var SERVICE_ENV = /^(HOME|USER|LOGNAME|PATH|LANG|LC_ALL|TMPDIR|XDG_RUNTIME_DIR|XDG_CONFIG_HOME|XDG_STATE_HOME|HASNA_HOME|HASNA_CONFIG_HOME|HASNA_SWITCHER_HOME|SWITCHER_GATEWAY_PORT|SWITCHER_GATEWAY_GRACE_SECONDS|SWITCHER_GATEWAY_SCAN_MS|SWITCHER_GATEWAY_EXIT_IDLE_SECONDS)$/;
15126
+ function serviceEnvironment(env = process.env) {
15127
+ return Object.fromEntries(Object.entries(env).filter((entry) => SERVICE_ENV.test(entry[0]) && typeof entry[1] === "string" && !/[\x00-\x1f\x7f]/.test(entry[1])));
15128
+ }
15129
+ function unitEnvironment(env = process.env) {
15130
+ const { TMPDIR: _temporary, ...rest } = serviceEnvironment(env);
15131
+ return rest;
15132
+ }
15133
+ var TEMPORARY_ROOTS = ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp", "/dev/shm"];
15134
+ async function assertSafeServiceCommand(command, temporaryRoots = TEMPORARY_ROOTS) {
15135
+ checkCommand(command);
15136
+ const uid = process.getuid?.();
15137
+ const refuse = (path, reason) => new Fault(400, "unsafe_gateway_command", `The gateway login service would run ${path}, but ${reason}. Install switcher in a directory only you can change (for example through Subscriptions, or remove group and other write access with chmod go-w), then run \`switcher gateway install\`.`);
15138
+ for (const path of command) {
15139
+ const real = await realpath7(path).catch(() => {
15140
+ throw refuse(path, "it does not exist");
15141
+ });
15142
+ for (const candidate of new Set([real, path])) {
15143
+ if (temporaryRoots.some((root) => candidate === root || candidate.startsWith(`${root}/`)))
15144
+ throw refuse(path, `${candidate} is under a temporary directory`);
15145
+ for (let current = candidate;; current = dirname10(current)) {
15146
+ const info2 = await lstat11(current).catch(() => {
15147
+ throw refuse(path, `${current} could not be checked`);
15148
+ });
15149
+ if (!info2.isSymbolicLink()) {
15150
+ if (info2.uid !== uid && info2.uid !== 0)
15151
+ throw refuse(path, `${current} is owned by another account`);
15152
+ if ((info2.mode & 18) !== 0)
15153
+ throw refuse(path, `${current} is writable by other accounts`);
15154
+ }
15155
+ if (current === dirname10(current))
15156
+ break;
15157
+ }
15158
+ }
15159
+ }
15160
+ }
15161
+ function supervisorFor(env = process.env, platform = process.platform, home = accountHome()) {
15162
+ const requested = env.SWITCHER_GATEWAY_SUPERVISOR?.trim() || "auto";
15163
+ if (!["auto", "none"].includes(requested))
15164
+ throw new Fault(400, "invalid_gateway_setting", "SWITCHER_GATEWAY_SUPERVISOR must be auto or none.");
15165
+ if (requested === "none" || !isDefaultSwitcherHome(env, home))
15166
+ return "none";
15167
+ return platform === "darwin" ? "launchd" : platform === "linux" ? "systemd" : "none";
15168
+ }
15169
+ function launchdLogPath(home) {
15170
+ return join23(home, "Library", "Logs", "Hasna", "switcher-gateway.log");
15171
+ }
15172
+ function requireHome(home) {
15173
+ if (!home)
15174
+ throw new Fault(422, "gateway_supervisor_unavailable", "The account home could not be read from the user database, so no login supervisor is used.");
15175
+ return home;
15176
+ }
15177
+ function unitPath(supervisor, env = process.env, home = requireHome(accountHome())) {
15178
+ if (supervisor === "launchd")
15179
+ return join23(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
15180
+ const config = env.XDG_CONFIG_HOME && isAbsolute18(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join23(home, ".config");
15181
+ return join23(config, "systemd", "user", SYSTEMD_UNIT);
15182
+ }
15183
+ function checkCommand(command) {
15184
+ if (command.length < 2 || !command.every((part) => isAbsolute18(part) && !/[\x00-\x1f\x7f"\\%$`]/.test(part)))
15185
+ throw new Fault(400, "invalid_gateway_command", "The gateway service command must be absolute paths without quotes, backslashes, $, % or control characters.");
15186
+ }
15187
+ var xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
15188
+ function renderLaunchdPlist(command, env = process.env, home = requireHome(accountHome())) {
15189
+ checkCommand(command);
15190
+ const log = launchdLogPath(home);
15191
+ const variables = { ...unitEnvironment(env), SWITCHER_GATEWAY_SUPERVISED: "launchd" };
15192
+ const strings2 = (values2) => values2.map((value) => ` <string>${xml(value)}</string>`).join(`
15193
+ `);
15194
+ return `<?xml version="1.0" encoding="UTF-8"?>
15195
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
15196
+ <plist version="1.0">
15197
+ <dict>
15198
+ <key>Label</key>
15199
+ <string>${LAUNCHD_LABEL}</string>
15200
+ <key>ProgramArguments</key>
15201
+ <array>
15202
+ ${strings2([...command, "gateway", "run"])}
15203
+ </array>
15204
+ <key>EnvironmentVariables</key>
15205
+ <dict>
15206
+ ${Object.entries(variables).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => ` <key>${xml(key)}</key>
15207
+ <string>${xml(value)}</string>`).join(`
15208
+ `)}
15209
+ </dict>
15210
+ <key>LimitLoadToSessionType</key>
15211
+ <array>
15212
+ <string>Aqua</string>
15213
+ <string>Background</string>
15214
+ </array>
15215
+ <key>RunAtLoad</key>
15216
+ <true/>
15217
+ <key>KeepAlive</key>
15218
+ <dict>
15219
+ <key>SuccessfulExit</key>
15220
+ <false/>
15221
+ </dict>
15222
+ <key>ThrottleInterval</key>
15223
+ <integer>5</integer>
15224
+ <key>Umask</key>
15225
+ <integer>63</integer>
15226
+ <key>StandardOutPath</key>
15227
+ <string>${xml(log)}</string>
15228
+ <key>StandardErrorPath</key>
15229
+ <string>${xml(log)}</string>
15230
+ </dict>
15231
+ </plist>
15232
+ `;
15233
+ }
15234
+ function renderSystemdUnit(command, env = process.env) {
15235
+ checkCommand(command);
15236
+ const variables = { ...unitEnvironment(env), SWITCHER_GATEWAY_SUPERVISED: "systemd" };
15237
+ const quote3 = (value) => `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/%/g, "%%")}"`;
15238
+ return `[Unit]
15239
+ Description=Switcher inference gateway
15240
+ After=network.target
15241
+
15242
+ [Service]
15243
+ ExecStart=${[...command, "gateway", "run"].map(quote3).join(" ")}
15244
+ ${Object.entries(variables).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `Environment=${quote3(`${key}=${value}`)}`).join(`
15245
+ `)}
15246
+ Restart=on-failure
15247
+ RestartSec=5
15248
+
15249
+ [Install]
15250
+ WantedBy=default.target
15251
+ `;
15252
+ }
15253
+ var defaultRunner = async (argv) => {
15254
+ const child = Bun.spawn(argv, { stdin: "ignore", stdout: "pipe", stderr: "pipe", env: { PATH: "/usr/bin:/bin:/usr/sbin:/sbin", HOME: process.env.HOME ?? "", XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR ?? "", DBUS_SESSION_BUS_ADDRESS: process.env.DBUS_SESSION_BUS_ADDRESS ?? "" } });
15255
+ const timer = setTimeout(() => child.kill("SIGKILL"), 15000);
15256
+ try {
15257
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
15258
+ return { code, stdout: stdout.slice(0, 4096), stderr: stderr.slice(0, 4096) };
15259
+ } finally {
15260
+ clearTimeout(timer);
15261
+ }
15262
+ };
15263
+ async function writeUnit(path, content) {
15264
+ const previous = await readFile8(path, "utf8").catch(() => {
15265
+ return;
15266
+ });
15267
+ if (previous === content)
15268
+ return false;
15269
+ await mkdir13(dirname10(path), { recursive: true, mode: 493 });
15270
+ const temporary = `${path}.${randomUUID8()}.tmp`;
15271
+ const file = await open8(temporary, "wx", 420);
15272
+ try {
15273
+ await file.writeFile(content);
15274
+ await file.sync();
15275
+ } finally {
15276
+ await file.close();
15277
+ }
15278
+ await rename5(temporary, path);
15279
+ return true;
15280
+ }
15281
+ async function installGatewayService(options) {
15282
+ const env = options.env ?? process.env, runner = options.runner ?? defaultRunner, home = options.home ?? accountHome();
15283
+ const supervisor = options.supervisor ?? supervisorFor(env, process.platform, home);
15284
+ if (supervisor === "none")
15285
+ throw new Fault(422, "gateway_supervisor_unavailable", "No login supervisor is used for this home: install the gateway service from your default ~/.hasna/switcher home on macOS (launchd) or Linux (systemd --user), without SWITCHER_GATEWAY_SUPERVISOR=none.");
15286
+ await (options.verifyCommand ?? assertSafeServiceCommand)(options.command);
15287
+ const path = unitPath(supervisor, env, requireHome(home));
15288
+ if (supervisor === "launchd") {
15289
+ const changed2 = await writeUnit(path, renderLaunchdPlist(options.command, env, requireHome(home)));
15290
+ const uid = process.getuid?.() ?? 0;
15291
+ for (const domain of [`gui/${uid}`, `user/${uid}`]) {
15292
+ const loaded = (await runner(["/bin/launchctl", "print", `${domain}/${LAUNCHD_LABEL}`])).code === 0;
15293
+ if (loaded && changed2)
15294
+ await runner(["/bin/launchctl", "bootout", `${domain}/${LAUNCHD_LABEL}`]);
15295
+ if (!loaded || changed2) {
15296
+ await runner(["/bin/launchctl", "enable", `${domain}/${LAUNCHD_LABEL}`]);
15297
+ if ((await runner(["/bin/launchctl", "bootstrap", domain, path])).code !== 0)
15298
+ continue;
15299
+ } else if ((await runner(["/bin/launchctl", "kickstart", `${domain}/${LAUNCHD_LABEL}`])).code !== 0)
15300
+ continue;
15301
+ return { supervisor, path, changed: changed2, domain };
15302
+ }
15303
+ throw new Fault(503, "gateway_supervisor_failed", `launchd did not accept ${path}. Check \`launchctl print gui/${uid}/${LAUNCHD_LABEL}\`.`);
15304
+ }
15305
+ const changed = await writeUnit(path, renderSystemdUnit(options.command, env));
15306
+ const systemctl = (...args) => runner(["/usr/bin/env", "systemctl", "--user", ...args]);
15307
+ if ((await systemctl("daemon-reload")).code !== 0)
15308
+ throw new Fault(503, "gateway_supervisor_failed", "systemd --user is unavailable in this session (systemctl --user daemon-reload failed).");
15309
+ const started = await systemctl(changed ? "restart" : "start", SYSTEMD_UNIT);
15310
+ await systemctl("enable", SYSTEMD_UNIT);
15311
+ if (started.code !== 0)
15312
+ throw new Fault(503, "gateway_supervisor_failed", `systemd --user could not start ${SYSTEMD_UNIT}. Check \`systemctl --user status ${SYSTEMD_UNIT}\`.`);
15313
+ return { supervisor, path, changed };
15314
+ }
15315
+ async function uninstallGatewayService(options = {}) {
15316
+ const env = options.env ?? process.env, runner = options.runner ?? defaultRunner, home = options.home ?? accountHome();
15317
+ const supervisor = options.supervisor ?? supervisorFor(env, process.platform, home);
15318
+ if (supervisor === "none")
15319
+ return { removed: false, supervisor };
15320
+ const path = unitPath(supervisor, env, requireHome(home));
15321
+ if (supervisor === "launchd") {
15322
+ const uid = process.getuid?.() ?? 0;
15323
+ for (const domain of [`gui/${uid}`, `user/${uid}`])
15324
+ await runner(["/bin/launchctl", "bootout", `${domain}/${LAUNCHD_LABEL}`]);
15325
+ } else
15326
+ await runner(["/usr/bin/env", "systemctl", "--user", "disable", "--now", SYSTEMD_UNIT]);
15327
+ const removed = await unlink4(path).then(() => true, () => false);
15328
+ if (supervisor === "systemd")
15329
+ await runner(["/usr/bin/env", "systemctl", "--user", "daemon-reload"]);
15330
+ return { removed, supervisor, path };
15331
+ }
15332
+ async function unitInstalled(env = process.env, home = accountHome()) {
15333
+ const supervisor = supervisorFor(env, process.platform, home);
15334
+ if (supervisor === "none" || !home)
15335
+ return { supervisor: "none", installed: false };
15336
+ const path = unitPath(supervisor, env, home);
15337
+ return { supervisor, path, ...supervisor === "launchd" ? { log: launchdLogPath(home) } : {}, installed: await Bun.file(path).exists() };
15338
+ }
15339
+
15340
+ // src/gateway-client.ts
15341
+ class GatewayControlClient {
15342
+ socket;
15343
+ timeoutMs;
15344
+ constructor(socket, timeoutMs = 1e4) {
15345
+ this.socket = socket;
15346
+ this.timeoutMs = timeoutMs;
15347
+ }
15348
+ async request(method, path, body2) {
15349
+ await assertTrustedControlSocket(this.socket);
15350
+ let response;
15351
+ try {
15352
+ response = await fetch(`http://switcher-gateway${path}`, { method, unix: this.socket, headers: body2 === undefined ? {} : { "content-type": "application/json" }, body: body2 === undefined ? undefined : JSON.stringify(body2), signal: AbortSignal.timeout(this.timeoutMs) });
15353
+ } catch {
15354
+ throw new Fault(503, "gateway_unavailable", "The Switcher gateway service is not running. Run `switcher gateway status`.");
15355
+ }
15356
+ const value = await response.json().catch(() => {
15357
+ return;
15358
+ });
15359
+ if (!response.ok)
15360
+ throw new Fault(response.status, typeof value?.error?.code === "string" ? value.error.code : "gateway_error", typeof value?.error?.message === "string" ? value.error.message : `The Switcher gateway refused the request (HTTP ${response.status}).`);
15361
+ return value;
15362
+ }
15363
+ status() {
15364
+ return this.request("GET", "/v1/status");
15365
+ }
15366
+ launches() {
15367
+ return this.request("GET", "/v1/launches");
15368
+ }
15369
+ register(body2) {
15370
+ return this.request("POST", "/v1/launches", body2);
15371
+ }
15372
+ attach(id2, pid) {
15373
+ return this.request("POST", `/v1/launches/${encodeURIComponent(id2)}/holders`, { pid });
15374
+ }
15375
+ release(id2) {
15376
+ return this.request("POST", `/v1/launches/${encodeURIComponent(id2)}/release`, {});
15377
+ }
15378
+ revoke(id2) {
15379
+ return this.request("DELETE", `/v1/launches/${encodeURIComponent(id2)}`);
15380
+ }
15381
+ stop() {
15382
+ return this.request("POST", "/v1/stop", {});
15383
+ }
15384
+ }
15385
+ var untrusted = (error) => error instanceof Fault && error.code === "gateway_socket_untrusted";
15386
+ async function gatewayStatus(env = process.env) {
15387
+ return new GatewayControlClient(gatewayPaths(env).socket, 2000).status().catch((error) => {
15388
+ if (untrusted(error))
15389
+ throw error;
15390
+ return;
15391
+ });
15392
+ }
15393
+ var gatewayOutdated = (status) => status.version !== VERSION || status.protocol !== GATEWAY_PROTOCOL;
15394
+ async function spawnDetached(command, env) {
15395
+ const paths = gatewayPaths(env);
15396
+ await privateDirectory(switcherHome(env));
15397
+ await privateDirectory(paths.root);
15398
+ const log = openSync3(paths.log, "a", 384);
15399
+ try {
15400
+ const child = spawn4(command[0], [...command.slice(1), "gateway", "run", "--exit-when-idle"], { detached: true, stdio: ["ignore", log, log], env: serviceEnvironment(env), cwd: paths.root });
15401
+ child.on("error", () => {
15402
+ return;
15403
+ });
15404
+ child.unref();
15405
+ } finally {
15406
+ closeSync3(log);
15407
+ }
15408
+ }
15409
+ async function ensureGatewayService(options) {
15410
+ const env = options.env ?? process.env;
15411
+ if (process.platform === "win32")
15412
+ throw new Fault(422, "gateway_unsupported", "The persistent Switcher gateway supports macOS and Linux.");
15413
+ const warn = options.warn ?? ((message) => console.error(message));
15414
+ const client = new GatewayControlClient(gatewayPaths(env).socket);
15415
+ const check2 = async () => {
15416
+ const status = await new GatewayControlClient(client.socket, 2000).status().catch((error) => {
15417
+ if (untrusted(error))
15418
+ throw error;
15419
+ return;
15420
+ });
15421
+ if (status && status.protocol !== GATEWAY_PROTOCOL)
15422
+ throw new Fault(409, "gateway_protocol_mismatch", `The running Switcher gateway (version ${status.version}) speaks a different control protocol. Run \`switcher gateway install\` to restart it on version ${VERSION}.`);
15423
+ return status;
15424
+ };
15425
+ const existing = await check2();
15426
+ if (existing) {
15427
+ if (gatewayOutdated(existing))
15428
+ warn(`switcher: The running gateway is version ${existing.version}; this switcher is ${VERSION}. Run \`switcher gateway install\` to restart it on ${VERSION} (sessions whose credential came only from the launch environment then need a new launch).`);
15429
+ return { client, status: existing, started: "existing" };
15430
+ }
15431
+ const supervisor = options.supervise === false ? "none" : supervisorFor(env);
15432
+ let started = "detached";
15433
+ if (supervisor !== "none") {
15434
+ try {
15435
+ await installGatewayService({ command: options.command, env, supervisor, runner: options.runner });
15436
+ started = supervisor;
15437
+ } catch (error) {
15438
+ warn(`switcher: The gateway login service could not be installed (${error instanceof Fault ? error.message : "unknown error"}); using a gateway that stops when idle and does not return after a restart.`);
15439
+ await spawnDetached(options.command, env);
15440
+ }
15441
+ } else
15442
+ await spawnDetached(options.command, env);
15443
+ const deadline = Date.now() + (options.waitMs ?? 1e4);
15444
+ for (;; ) {
15445
+ const status = await check2();
15446
+ if (status)
15447
+ return { client, status, started };
15448
+ if (Date.now() > deadline)
15449
+ throw new Fault(503, "gateway_unavailable", `The Switcher gateway did not start. See ${gatewayPaths(env).log}.`);
15450
+ await new Promise((resolve14) => setTimeout(resolve14, 100));
15451
+ }
15452
+ }
15453
+ function createServiceGatewayHost(client, context) {
15454
+ const leases = [];
15455
+ const attaching = [];
15456
+ let attachedPid;
15457
+ return {
15458
+ async open(input) {
15459
+ const gateway = {
15460
+ harness: input.harness,
15461
+ baseUrl: input.baseUrl,
15462
+ protocol: input.protocol,
15463
+ ...input.authStyle ? { authStyle: input.authStyle } : {},
15464
+ model: input.model,
15465
+ models: input.models,
15466
+ compiledPolicy: input.compiledPolicy,
15467
+ ...input.providerId ? { providerId: input.providerId } : {},
15468
+ catalogPath: input.catalogPath,
15469
+ cwd: input.cwd
15470
+ };
15471
+ let registration;
15472
+ try {
15473
+ registration = await client.register({
15474
+ holderPid: context.holderPid,
15475
+ gateway,
15476
+ ...input.credential ? { credential: input.credential } : {},
15477
+ ...context.credentialEnv ? { credentialEnv: context.credentialEnv } : {},
15478
+ ...context.stateDir ? { stateDir: context.stateDir } : {}
15479
+ });
15480
+ } catch (error) {
15481
+ (context.warn ?? console.error)(`switcher: The persistent gateway refused this launch (${error instanceof Fault ? error.code : "unavailable"}); it uses a per-launch gateway that stops when this command exits.`);
15482
+ return createInferenceGateway(input);
15483
+ }
15484
+ const lease = { id: registration.id, attached: attachedPid !== undefined, retained: false, done: false };
15485
+ leases.push(lease);
15486
+ if (attachedPid !== undefined)
15487
+ attaching.push(client.attach(lease.id, attachedPid).catch(() => {
15488
+ return;
15489
+ }));
15490
+ return { baseUrl: registration.baseUrl, token: registration.token, retainsState: () => lease.retained, cleanup: async () => {
15491
+ if (lease.done)
15492
+ return;
15493
+ lease.done = true;
15494
+ await Promise.allSettled(attaching);
15495
+ if (!lease.attached) {
15496
+ await client.revoke(lease.id).catch(() => {
15497
+ return;
15498
+ });
15499
+ return;
15500
+ }
15501
+ try {
15502
+ const result = await client.release(lease.id);
15503
+ lease.retained = result.retained;
15504
+ for (const event of result.events ?? [])
15505
+ context.onRoutingEvent?.(event);
15506
+ } catch (error) {
15507
+ lease.retained = !(error instanceof Fault && error.status === 404);
15508
+ }
15509
+ } };
15510
+ },
15511
+ attach(pid) {
15512
+ attachedPid = pid;
15513
+ for (const lease of leases) {
15514
+ lease.attached = true;
15515
+ attaching.push(client.attach(lease.id, pid).catch(() => {
15516
+ return;
15517
+ }));
15518
+ }
15519
+ },
15520
+ retainedState: () => leases.some((lease) => lease.retained)
15521
+ };
15522
+ }
15523
+
15524
+ // src/launcher.ts
15525
+ var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
15526
+ async function writeOriCodexCatalog(stateDir, models) {
15527
+ const path = join24(stateDir, "ori-codex-models.json");
15528
+ const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
15529
+ await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
15530
+ `, { mode: 384, flag: "wx" });
15531
+ return path;
15532
+ }
15533
+ function oriTarget(harness) {
15534
+ if (harness === "antigravity" || harness === "junie")
15535
+ throw new Error("This CLI is supported through the direct Switcher backend only.");
15536
+ if (harness === "kilo")
15537
+ throw new Error("Ori does not launch Kilo; use the direct backend.");
15538
+ if (harness === "opencode")
15539
+ throw new Error("Ori does not launch legacy OpenCode; use the direct backend.");
15540
+ if (harness === "aider")
15541
+ throw new Error("Ori does not launch Aider; use the direct backend.");
15542
+ if (harness === "gemini")
15543
+ throw new Error("Ori does not launch Gemini CLI; use the direct backend.");
15544
+ if (harness === "prime-agent")
15545
+ throw new Error("Ori does not launch Prime Agent; use the direct backend.");
15546
+ if (harness === "omp")
15547
+ throw new Error("Ori does not support OMP; use the direct OMP adapter.");
15548
+ if (harness === "cline")
15549
+ throw new Error("Ori does not support Cline; use the direct Cline adapter.");
15550
+ if (harness === "hermes")
15551
+ throw new Error("Ori does not provide a Hermes adapter; use the direct Hermes backend.");
15552
+ return harness;
15553
+ }
15554
+ async function oriRequestForPlan(plan, options = {}) {
15555
+ validateHarnessProvider(plan.profile.harness, plan.provider);
15556
+ if (options.oriExecutable === "")
15557
+ throw new Error("--ori-executable requires a non-empty executable path.");
15558
+ const target = oriTarget(plan.profile.harness);
15559
+ if (plan.provider.authStyle !== "bearer")
15560
+ throw new Error("Ori requires the OpenRouter Bearer authentication contract; use the direct adapter for other auth styles.");
15561
+ assertOriLoginAllowed({ ...process.env, ...options.credentialEnv });
15562
+ const policyEnvironment = { ...process.env, ...options.credentialEnv };
15563
+ if (plan.profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((policyEnvironment.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
15564
+ throw new Error("Grok API-key authentication is disabled by GROK_DISABLE_API_KEY_AUTH. This provider launch cannot proceed under that native authentication policy.");
15565
+ if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
15566
+ throw new Error("Grok requires a native team login through GROK_FORCE_LOGIN_TEAM_ID. This provider launch cannot proceed under that native authentication policy.");
15567
+ const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve14(options.cwd) : undefined });
15568
+ const native = requireOriHarness(contract, target);
15569
+ if (!native.path)
15570
+ throw new Error("Ori did not report the native harness executable path.");
15571
+ const detection = await detectHarness(target, native.path);
15572
+ if (!detection.available)
15573
+ throw new Error("The native harness reported by Ori could not report its version.");
15574
+ validateHarnessVersion(target, detection.version);
15575
+ const catalogPath = target === "codex" && options.stateDir ? await writeOriCodexCatalog(options.stateDir, plan.catalog.models) : undefined;
15576
+ const request = buildOriRequest(plan, target, catalogPath, options.args ?? []);
15577
+ validateOriLaunchRequest(request);
15578
+ return { contract, request, detection };
15579
+ }
15580
+ async function validateOriForPlan(plan, options = {}) {
15581
+ const result = await oriRequestForPlan(plan, options);
13957
15582
  return { ...result, warnings: oriLaunchWarnings(result.request.target) };
13958
15583
  }
13959
15584
  function buildOriRequest(plan, target, catalogPath, args) {
@@ -13987,14 +15612,14 @@ async function prepareOriForPlan(plan, options) {
13987
15612
  executable: detection.executable,
13988
15613
  version: detection.version,
13989
15614
  stateDir: options.stateDir,
13990
- cwd: resolve12(options.cwd ?? process.cwd()),
15615
+ cwd: resolve14(options.cwd ?? process.cwd()),
13991
15616
  args: options.args ?? [],
13992
15617
  sharedState: options.sharedState
13993
15618
  });
13994
15619
  try {
13995
15620
  const shim = prepareOriModelPolicy(request.target, native);
13996
- const dir = join22(options.stateDir, "ori-bin"), path = join22(dir, shim.name);
13997
- await mkdir12(dir, { mode: 448 });
15621
+ const dir = join24(options.stateDir, "ori-bin"), path = join24(dir, shim.name);
15622
+ await mkdir14(dir, { mode: 448 });
13998
15623
  await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
13999
15624
  return { contract, prepared: {
14000
15625
  ...ori,
@@ -14019,7 +15644,7 @@ async function launch(client, profileId, options = {}) {
14019
15644
  assertHarnessArguments(profile.harness, options.args ?? []);
14020
15645
  if (profile.harness === "gemini" || profile.harness === "antigravity")
14021
15646
  validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
14022
- await validateHarnessConfiguration(profile.harness, resolve12(options.cwd ?? process.cwd()), options.args);
15647
+ await validateHarnessConfiguration(profile.harness, resolve14(options.cwd ?? process.cwd()), options.args);
14023
15648
  if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
14024
15649
  throw new Error("Grok API-key authentication is disabled by GROK_DISABLE_API_KEY_AUTH. This provider launch cannot proceed under that native authentication policy.");
14025
15650
  if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
@@ -14028,7 +15653,7 @@ async function launch(client, profileId, options = {}) {
14028
15653
  await client.refreshModels(profile.providerId);
14029
15654
  const plan = await client.launchPlan(profileId);
14030
15655
  assertHarnessArguments(plan.profile.harness, options.args ?? []);
14031
- await validateHarnessConfiguration(plan.profile.harness, resolve12(options.cwd ?? process.cwd()), options.args);
15656
+ await validateHarnessConfiguration(plan.profile.harness, resolve14(options.cwd ?? process.cwd()), options.args);
14032
15657
  if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
14033
15658
  throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
14034
15659
  const backend = options.backend ?? "direct";
@@ -14050,9 +15675,9 @@ async function launch(client, profileId, options = {}) {
14050
15675
  validateHarnessVersion("gemini", detection?.version);
14051
15676
  if (backend === "direct" && plan.profile.harness === "aider")
14052
15677
  validateHarnessVersion(plan.profile.harness, detection?.version);
14053
- const root = resolve12(options.stateDir ?? join22(switcherHome(), "state"));
15678
+ const root = resolve14(options.stateDir ?? join24(switcherHome(), "state"));
14054
15679
  await privateDirectory(root);
14055
- const stateDir = await mkdtemp(join22(root, "launch-"));
15680
+ const stateDir = await mkdtemp(join24(root, "launch-"));
14056
15681
  let credential;
14057
15682
  if (backend === "direct") {
14058
15683
  try {
@@ -14082,6 +15707,15 @@ async function launch(client, profileId, options = {}) {
14082
15707
  } else
14083
15708
  routingEventsDropped = Math.min(1e6, routingEventsDropped + 1);
14084
15709
  };
15710
+ let gatewayHost;
15711
+ if (options.gateway === "service" && backend === "direct" && !options.claudeDesktop && process.platform !== "win32") {
15712
+ try {
15713
+ const client2 = options.connectGateway ? await options.connectGateway() : (await ensureGatewayService({ command: options.gatewayCommand ?? [process.execPath, Bun.main], supervise: options.gatewaySupervise ?? false })).client;
15714
+ gatewayHost = createServiceGatewayHost(client2, { holderPid: process.pid, stateDir, credentialEnv: credential ? plan.provider.credentialEnv : undefined, onRoutingEvent });
15715
+ } catch (error) {
15716
+ console.error(`switcher: The persistent gateway is unavailable (${error instanceof Fault ? error.message : "it could not start"}); this launch uses a per-launch gateway that stops when this command exits.`);
15717
+ }
15718
+ }
14085
15719
  const finishRunOnce = async (candidate, body2, message) => {
14086
15720
  if (runFinalized)
14087
15721
  return;
@@ -14111,8 +15745,8 @@ async function launch(client, profileId, options = {}) {
14111
15745
  let nativeHome2;
14112
15746
  if (sharedState && !options.desktop && !options.claudeDesktop) {
14113
15747
  const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
14114
- const configured = process.env[variable] ? resolve12(process.env[variable]) : undefined;
14115
- nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join22(root, "native-claude", profileId) : configured ?? sharedState.home;
15748
+ const configured = process.env[variable] ? resolve14(process.env[variable]) : undefined;
15749
+ nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join24(root, "native-claude", profileId) : configured ?? sharedState.home;
14116
15750
  if (sharedState.tool === "claude")
14117
15751
  await prepareClaudeUserSettings(nativeHome2);
14118
15752
  await privateDirectory(nativeHome2);
@@ -14122,12 +15756,12 @@ async function launch(client, profileId, options = {}) {
14122
15756
  if (options.shareNativeState === false && backend === "direct") {
14123
15757
  const tool = plan.profile.harness;
14124
15758
  if (options.desktop)
14125
- await assertNativeStateIsolation(tool, join22(root, "desktop", desktopState, "codex"));
15759
+ await assertNativeStateIsolation(tool, join24(root, "desktop", desktopState, "codex"));
14126
15760
  else if (options.claudeDesktop)
14127
- await assertNativeStateIsolation(tool, join22(root, "desktop-claude", desktopState));
15761
+ await assertNativeStateIsolation(tool, join24(root, "desktop-claude", desktopState));
14128
15762
  else {
14129
15763
  const variable = tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
14130
- nativeHome2 = process.env[variable] ? resolve12(process.env[variable]) : join22(root, `native-${tool}`, profileId);
15764
+ nativeHome2 = process.env[variable] ? resolve14(process.env[variable]) : join24(root, `native-${tool}`, profileId);
14131
15765
  await assertNativeStateIsolation(tool, nativeHome2);
14132
15766
  await privateDirectory(nativeHome2);
14133
15767
  }
@@ -14144,10 +15778,10 @@ async function launch(client, profileId, options = {}) {
14144
15778
  onRoutingEvent,
14145
15779
  credential,
14146
15780
  stateDir,
14147
- cwd: resolve12(options.cwd ?? process.cwd()),
15781
+ cwd: resolve14(options.cwd ?? process.cwd()),
14148
15782
  sharedState
14149
15783
  };
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({
15784
+ let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join24(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
14151
15785
  harness: plan.profile.harness,
14152
15786
  baseUrl: plan.provider.baseUrl,
14153
15787
  protocol: plan.provider.protocol,
@@ -14163,10 +15797,11 @@ async function launch(client, profileId, options = {}) {
14163
15797
  executable: nativeExecutable ?? detection?.executable,
14164
15798
  args: options.args ?? [],
14165
15799
  stateDir,
14166
- cwd: resolve12(options.cwd ?? process.cwd()),
15800
+ cwd: resolve14(options.cwd ?? process.cwd()),
14167
15801
  version: detection?.version,
14168
15802
  sharedState,
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) } : {}
15803
+ gatewayHost,
15804
+ ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir: join24(root, "sessions", plan.profile.harness, profileId) } : {}
14170
15805
  });
14171
15806
  cleanup = prepared.cleanup;
14172
15807
  prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
@@ -14183,7 +15818,7 @@ async function launch(client, profileId, options = {}) {
14183
15818
  prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
14184
15819
  }
14185
15820
  if (options.desktop) {
14186
- prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join22(root, "desktop", desktopState), sharedState);
15821
+ prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join24(root, "desktop", desktopState), sharedState);
14187
15822
  cleanup = prepared.cleanup;
14188
15823
  }
14189
15824
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -14260,7 +15895,7 @@ async function launch(client, profileId, options = {}) {
14260
15895
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
14261
15896
  throw preparationSignal;
14262
15897
  }
14263
- const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve12(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
15898
+ const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve14(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime, onSpawn: (pid) => gatewayHost?.attach(pid) });
14264
15899
  await cleanup?.();
14265
15900
  cleanup = undefined;
14266
15901
  await finishRunOnce(run, { status: interrupted ? "interrupted" : code === 0 ? "exited" : "failed", exitCode: code }, `switcher: Harness exited ${code}; final metadata could not be saved for run ${run.id}.`);
@@ -14277,8 +15912,8 @@ async function launch(client, profileId, options = {}) {
14277
15912
  } finally {
14278
15913
  if (lateCreateRunFinalization) {
14279
15914
  let finalizationTimer;
14280
- const finalizationTimeout = new Promise((resolve13) => {
14281
- finalizationTimer = setTimeout(resolve13, LATE_RUN_FINALIZATION_TIMEOUT_MS);
15915
+ const finalizationTimeout = new Promise((resolve15) => {
15916
+ finalizationTimer = setTimeout(resolve15, LATE_RUN_FINALIZATION_TIMEOUT_MS);
14282
15917
  });
14283
15918
  try {
14284
15919
  await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
@@ -14291,13 +15926,14 @@ async function launch(client, profileId, options = {}) {
14291
15926
  try {
14292
15927
  await cleanup?.();
14293
15928
  } finally {
14294
- await rm6(stateDir, { recursive: true, force: true });
15929
+ if (!gatewayHost?.retainedState())
15930
+ await rm6(stateDir, { recursive: true, force: true });
14295
15931
  }
14296
15932
  }
14297
15933
  }
14298
15934
 
14299
15935
  // src/direct-launch.ts
14300
- import { createHash as createHash14 } from "crypto";
15936
+ import { createHash as createHash17 } from "crypto";
14301
15937
  import { createInterface as createInterface3 } from "readline/promises";
14302
15938
  var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
14303
15939
  async function resolveLaunchProvider(client, selector, options = {}) {
@@ -14378,7 +16014,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
14378
16014
  const policy = modelPolicy ?? (harness === "codex" ? { version: 1, selection: "catalog" } : undefined);
14379
16015
  const normalizedPolicy = policy === undefined ? undefined : parse2(modelPolicySchema, policy);
14380
16016
  const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
14381
- const hash3 = createHash14("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
16017
+ const hash3 = createHash17("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
14382
16018
  const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
14383
16019
  let existing;
14384
16020
  try {
@@ -14402,16 +16038,16 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
14402
16038
  }
14403
16039
 
14404
16040
  // src/native-state-import.ts
14405
- import { createHash as createHash15 } from "crypto";
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";
16041
+ import { createHash as createHash18 } from "crypto";
16042
+ import { constants as constants11 } from "fs";
16043
+ import { lstat as lstat12, open as open9, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
16044
+ import { basename as basename5, dirname as dirname11, isAbsolute as isAbsolute19, join as join25, relative as relative6, resolve as resolve15 } from "path";
14409
16045
  var MAX_FILES = 1e5;
14410
16046
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
14411
16047
  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.");
14412
16048
  async function info2(path) {
14413
16049
  try {
14414
- return await lstat10(path);
16050
+ return await lstat12(path);
14415
16051
  } catch (error) {
14416
16052
  if (error.code === "ENOENT")
14417
16053
  return;
@@ -14422,12 +16058,12 @@ var identity = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeM
14422
16058
  var same = (a, b) => JSON.stringify(identity(a)) === JSON.stringify(identity(b));
14423
16059
  var inside3 = (parent, child) => {
14424
16060
  const path = relative6(parent, child);
14425
- return path !== ".." && !path.startsWith("../") && !isAbsolute17(path);
16061
+ return path !== ".." && !path.startsWith("../") && !isAbsolute19(path);
14426
16062
  };
14427
16063
  var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
14428
16064
  async function sessionId(path, expected) {
14429
- const nameId = basename4(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
14430
- const handle = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
16065
+ const nameId = basename5(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
16066
+ const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
14431
16067
  try {
14432
16068
  const before = await handle.stat();
14433
16069
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
@@ -14441,7 +16077,7 @@ async function sessionId(path, expected) {
14441
16077
  length += read.bytesRead;
14442
16078
  newline = buffer.indexOf(10, 0);
14443
16079
  }
14444
- const after = await handle.stat(), named = await lstat10(path);
16080
+ const after = await handle.stat(), named = await lstat12(path);
14445
16081
  if (!same(before, after) || !same(after, named) || after.nlink !== 1 || named.nlink !== 1 || named.isSymbolicLink())
14446
16082
  throw refused();
14447
16083
  if (newline < 0 && before.size > buffer.length)
@@ -14470,7 +16106,7 @@ async function checkSessionIdentities(plan) {
14470
16106
  for (const file of plan.files) {
14471
16107
  if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
14472
16108
  continue;
14473
- file.sessionId = await sessionId(join23(plan.source, file.path), file.source);
16109
+ file.sessionId = await sessionId(join25(plan.source, file.path), file.source);
14474
16110
  if (!file.sessionId)
14475
16111
  continue;
14476
16112
  const previous = ids.get(file.sessionId);
@@ -14494,7 +16130,7 @@ async function checkSessionIdentities(plan) {
14494
16130
  for await (const entry of await opendir2(directory)) {
14495
16131
  if (++seen > MAX_FILES || entry.isSymbolicLink())
14496
16132
  throw refused();
14497
- const path = join23(directory, entry.name);
16133
+ const path = join25(directory, entry.name);
14498
16134
  if (entry.isDirectory()) {
14499
16135
  await scan(path, depth + 1);
14500
16136
  continue;
@@ -14511,19 +16147,19 @@ async function checkSessionIdentities(plan) {
14511
16147
  file.existing = true;
14512
16148
  }
14513
16149
  }
14514
- await scan(join23(plan.state.home, "sessions"));
14515
- await scan(join23(plan.state.home, "archived_sessions"));
16150
+ await scan(join25(plan.state.home, "sessions"));
16151
+ await scan(join25(plan.state.home, "archived_sessions"));
14516
16152
  }
14517
16153
  async function fingerprint2(path, copyTo) {
14518
- const handle = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
16154
+ const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
14519
16155
  let output, complete = false;
14520
16156
  try {
14521
16157
  const before = await handle.stat();
14522
16158
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
14523
16159
  throw refused();
14524
16160
  if (copyTo)
14525
- output = await open7(copyTo, "wx", 384);
14526
- const hash3 = createHash15("sha256"), buffer = Buffer.alloc(64 * 1024);
16161
+ output = await open9(copyTo, "wx", 384);
16162
+ const hash3 = createHash18("sha256"), buffer = Buffer.alloc(64 * 1024);
14527
16163
  let bytes = 0;
14528
16164
  for (;; ) {
14529
16165
  const read = await handle.read(buffer, 0, buffer.length, null);
@@ -14540,7 +16176,7 @@ async function fingerprint2(path, copyTo) {
14540
16176
  offset += (await output.write(chunk, offset, chunk.length - offset)).bytesWritten;
14541
16177
  }
14542
16178
  }
14543
- const after = await handle.stat(), named = await lstat10(path);
16179
+ const after = await handle.stat(), named = await lstat12(path);
14544
16180
  if (named.isSymbolicLink() || after.nlink !== 1 || named.nlink !== 1 || bytes !== before.size || !same(before, after) || !same(after, named))
14545
16181
  throw refused();
14546
16182
  await output?.sync();
@@ -14550,15 +16186,15 @@ async function fingerprint2(path, copyTo) {
14550
16186
  await output?.close();
14551
16187
  await handle.close();
14552
16188
  if (copyTo && !complete)
14553
- await unlink3(copyTo).catch(() => {
16189
+ await unlink5(copyTo).catch(() => {
14554
16190
  return;
14555
16191
  });
14556
16192
  }
14557
16193
  }
14558
16194
  async function planNativeStateImport(state, source, selection) {
14559
- if (!isAbsolute17(source) || source.includes("\x00"))
16195
+ if (!isAbsolute19(source) || source.includes("\x00"))
14560
16196
  throw refused();
14561
- source = resolve13(source);
16197
+ source = resolve15(source);
14562
16198
  if (inside3(source, state.home) || inside3(state.home, source))
14563
16199
  throw refused();
14564
16200
  await assertNativeStateDirectory(source);
@@ -14572,9 +16208,9 @@ async function planNativeStateImport(state, source, selection) {
14572
16208
  async function visit(path, kind) {
14573
16209
  if (++seen > MAX_FILES || path.split("/").length > 32)
14574
16210
  throw refused();
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);
16211
+ await ensureNativeStateDirectory(dirname11(join25(source, path)), false);
16212
+ await ensureNativeStateDirectory(dirname11(join25(state.home, path)), false);
16213
+ const from = join25(source, path), to = join25(state.home, path), entry = await info2(from), target = await info2(to);
14578
16214
  if (!entry)
14579
16215
  return;
14580
16216
  if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
@@ -14593,7 +16229,7 @@ async function planNativeStateImport(state, source, selection) {
14593
16229
  }
14594
16230
  children.sort((a, b) => a.name.localeCompare(b.name));
14595
16231
  for (const child of children)
14596
- await visit(join23(path, child.name), child.kind);
16232
+ await visit(join25(path, child.name), child.kind);
14597
16233
  } else {
14598
16234
  const value = await fingerprint2(from);
14599
16235
  plan.bytes += value.bytes;
@@ -14615,7 +16251,7 @@ async function planNativeStateImport(state, source, selection) {
14615
16251
  return plan;
14616
16252
  }
14617
16253
  function nativeStateImportDigest(plan) {
14618
- return createHash15("sha256").update(JSON.stringify({
16254
+ return createHash18("sha256").update(JSON.stringify({
14619
16255
  tool: plan.state.tool,
14620
16256
  source: plan.source,
14621
16257
  destination: plan.state.home,
@@ -14647,14 +16283,14 @@ async function applyNativeStateImportUnlocked(plan) {
14647
16283
  throw refused();
14648
16284
  const requiredDirectories = new Set([plan.state.home]);
14649
16285
  for (const path of plan.directories) {
14650
- for (let directory = join23(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
16286
+ for (let directory = join25(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname11(directory)) {
14651
16287
  requiredDirectories.add(directory);
14652
16288
  if (directory === plan.state.home)
14653
16289
  break;
14654
16290
  }
14655
16291
  }
14656
16292
  for (const file of plan.files.filter((file2) => !file2.existing)) {
14657
- for (let directory = dirname9(join23(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
16293
+ for (let directory = dirname11(join25(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname11(directory)) {
14658
16294
  requiredDirectories.add(directory);
14659
16295
  if (directory === plan.state.home)
14660
16296
  break;
@@ -14675,15 +16311,15 @@ async function applyNativeStateImportUnlocked(plan) {
14675
16311
  for (const file of plan.files) {
14676
16312
  if (file.existing)
14677
16313
  continue;
14678
- const target = join23(plan.state.home, file.path), temporary = join23(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
16314
+ const target = join25(plan.state.home, file.path), temporary = join25(dirname11(target), `.switcher-import-${crypto.randomUUID()}`);
14679
16315
  staged.push({ temporary, target });
14680
- const copied = await fingerprint2(join23(plan.source, file.path), temporary);
16316
+ const copied = await fingerprint2(join25(plan.source, file.path), temporary);
14681
16317
  if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
14682
16318
  throw refused();
14683
16319
  }
14684
16320
  for (const item2 of staged) {
14685
16321
  try {
14686
- await link2(item2.temporary, item2.target);
16322
+ await link3(item2.temporary, item2.target);
14687
16323
  published++;
14688
16324
  } catch (error) {
14689
16325
  if (published)
@@ -14695,7 +16331,7 @@ async function applyNativeStateImportUnlocked(plan) {
14695
16331
  } finally {
14696
16332
  for (const item2 of staged) {
14697
16333
  try {
14698
- await unlink3(item2.temporary);
16334
+ await unlink5(item2.temporary);
14699
16335
  } catch (error) {
14700
16336
  if (error.code !== "ENOENT")
14701
16337
  cleanupFailed = true;
@@ -14730,6 +16366,7 @@ async function applyNativeStateImport(plan) {
14730
16366
  }
14731
16367
 
14732
16368
  // src/cli.ts
16369
+ import { realpathSync as realpathSync2 } from "fs";
14733
16370
  var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
14734
16371
 
14735
16372
  switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
@@ -14766,6 +16403,8 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
14766
16403
  switcher credentials list|check|remove [PRESET_OR_REFERENCE]
14767
16404
  switcher credentials repair-executable PRESET_OR_REFERENCE --sha256 EXPECTED
14768
16405
  switcher credentials repair-executable --vault-cli PATH --sha256 EXPECTED
16406
+ switcher gateway status|install|uninstall|stop
16407
+ switcher gateway run [--exit-when-idle]
14769
16408
  switcher doctor
14770
16409
  switcher state import codex|claude --from LEGACY_NATIVE_HOME [--entry NAME]... [--dry-run | --apply --plan-digest SHA256]
14771
16410
 
@@ -14778,6 +16417,11 @@ Its local Codex conversations use the selected Responses-compatible provider.
14778
16417
  claude-desktop launches Claude in its separate Claude-3p gateway profile with a
14779
16418
  Messages-compatible provider. Quit that instance before switching providers.
14780
16419
  Keep Switcher running while using the app; quit that app instance to end the launch.
16420
+ Launches register with one persistent per-user gateway on a stable 127.0.0.1 port,
16421
+ so background processes the harness leaves running (such as Claude Code's daemon)
16422
+ keep working after the launch exits. It runs under launchd (macOS) or systemd --user
16423
+ (Linux) for the default home and starts automatically. SWITCHER_GATEWAY=local uses
16424
+ the older per-launch gateway that stops with the launch.
14781
16425
  --reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
14782
16426
  --dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
14783
16427
  PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
@@ -14902,7 +16546,8 @@ async function main(args = process.argv.slice(2)) {
14902
16546
  "vault-operator": { type: "string" },
14903
16547
  "keychain-service": { type: "string" },
14904
16548
  "keychain-account": { type: "string" },
14905
- origin: { type: "string", multiple: true }
16549
+ origin: { type: "string", multiple: true },
16550
+ "exit-when-idle": { type: "boolean" }
14906
16551
  } });
14907
16552
  if (values2.help || !positionals.length) {
14908
16553
  console.log(HELP);
@@ -14922,6 +16567,10 @@ async function main(args = process.argv.slice(2)) {
14922
16567
  output(nativeStateImportSummary(plan, Boolean(values2.apply)));
14923
16568
  return;
14924
16569
  }
16570
+ if (command === "gateway")
16571
+ return gatewayCommand(action2, positionals, values2, nativeArgs, output);
16572
+ if (values2["exit-when-idle"] !== undefined)
16573
+ throw new Fault(400, "conflicting_options", "--exit-when-idle belongs to switcher gateway run.");
14925
16574
  if (values2.from !== undefined || values2.entry !== undefined || values2.apply !== undefined || values2["plan-digest"] !== undefined)
14926
16575
  throw new Fault(400, "conflicting_options", "--from, --entry, --plan-digest, --dry-run and --apply belong to switcher state import.");
14927
16576
  if (values2["share-native-state"] && values2["no-share-native-state"])
@@ -15183,9 +16832,9 @@ async function main(args = process.argv.slice(2)) {
15183
16832
  if (sharedNativeState)
15184
16833
  await resolveNativeState(plan.profile.harness, process.env, { create: false });
15185
16834
  if (shareNativeState === false) {
15186
- const tool = plan.profile.harness, root = resolve14(values2["state-dir"] ?? join24(switcherHome(), "state"));
16835
+ const tool = plan.profile.harness, root = resolve16(values2["state-dir"] ?? join26(switcherHome(), "state"));
15187
16836
  const configured = process.env[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
15188
- const home = desktop ? join24(root, "desktop", profileId, "codex") : claudeApp ? join24(root, "desktop-claude", profileId) : configured ? resolve14(configured) : join24(root, `native-${tool}`, profileId);
16837
+ const home = desktop ? join26(root, "desktop", profileId, "codex") : claudeApp ? join26(root, "desktop-claude", profileId) : configured ? resolve16(configured) : join26(root, `native-${tool}`, profileId);
15189
16838
  await assertNativeStateIsolation(tool, home);
15190
16839
  }
15191
16840
  if (backend === "ori") {
@@ -15197,7 +16846,7 @@ async function main(args = process.argv.slice(2)) {
15197
16846
  output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: sharedNativeState ? "shared-state-private-auth" : "isolated-provider", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...nativeState ? { nativeState } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
15198
16847
  return;
15199
16848
  }
15200
- process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, shareNativeState, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
16849
+ process.exitCode = await launch(client, profileId, { gateway: launchGatewayMode(), gatewayCommand: gatewayServiceCommand().command, gatewaySupervise: gatewayServiceCommand().linked, desktop, claudeDesktop: claudeApp, shareNativeState, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
15201
16850
  return;
15202
16851
  }
15203
16852
  if (editingModel) {
@@ -15307,6 +16956,95 @@ async function main(args = process.argv.slice(2)) {
15307
16956
  await runtime.close();
15308
16957
  }
15309
16958
  }
16959
+ function launchGatewayMode() {
16960
+ const mode = process.env.SWITCHER_GATEWAY?.trim() || "service";
16961
+ if (mode !== "local" && mode !== "service")
16962
+ throw new Fault(400, "invalid_gateway_setting", "SWITCHER_GATEWAY must be service or local.");
16963
+ return mode;
16964
+ }
16965
+ function gatewayServiceCommand() {
16966
+ const script = Bun.main;
16967
+ const linked = Bun.which("switcher");
16968
+ try {
16969
+ if (linked && realpathSync2(linked) === realpathSync2(script))
16970
+ return { command: [process.execPath, linked], linked: true };
16971
+ } catch {}
16972
+ return { command: [process.execPath, script], linked: false };
16973
+ }
16974
+ async function stopGateway(status, socket) {
16975
+ await new GatewayControlClient(socket).stop();
16976
+ for (let i = 0;i < 100; i++) {
16977
+ try {
16978
+ process.kill(status.pid, 0);
16979
+ } catch {
16980
+ return true;
16981
+ }
16982
+ await Bun.sleep(50);
16983
+ }
16984
+ return false;
16985
+ }
16986
+ async function gatewayCommand(action2, positionals, values2, nativeArgs, output) {
16987
+ const allowed = action2 === "run" ? ["exit-when-idle", "json"] : ["json"];
16988
+ if (positionals.length !== 2 || nativeArgs.length || Object.keys(values2).some((name) => !allowed.includes(name)))
16989
+ throw new Fault(400, "invalid_request", "Use switcher gateway status|install|uninstall|stop, or switcher gateway run [--exit-when-idle].");
16990
+ const paths = gatewayPaths();
16991
+ const describe = async () => {
16992
+ const status = await gatewayStatus();
16993
+ const unit = await unitInstalled().catch(() => ({ supervisor: "none", installed: false }));
16994
+ const log = unit.log ?? (unit.supervisor === "systemd" ? "journalctl --user -u switcher-gateway.service" : paths.log);
16995
+ return { running: Boolean(status), ...status ?? {}, socket: paths.socket, log, unit };
16996
+ };
16997
+ if (action2 === "run") {
16998
+ process.umask(63);
16999
+ const settings2 = gatewaySettings();
17000
+ let service;
17001
+ try {
17002
+ service = await startGatewayService({ exitWhenIdleMs: values2["exit-when-idle"] ? settings2.exitIdleMs : undefined, supervisor: process.env.SWITCHER_GATEWAY_SUPERVISED ?? "none" });
17003
+ } catch (error) {
17004
+ if (error instanceof Fault && error.code === "gateway_running") {
17005
+ console.error("switcher gateway: already running for this home.");
17006
+ return;
17007
+ }
17008
+ throw error;
17009
+ }
17010
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
17011
+ process.on(signal, () => void service.close());
17012
+ await service.closed;
17013
+ return;
17014
+ }
17015
+ if (action2 === "status") {
17016
+ const result = await describe();
17017
+ output(result);
17018
+ if (!result.running)
17019
+ process.exitCode = 1;
17020
+ return;
17021
+ }
17022
+ if (action2 === "install") {
17023
+ const running = await gatewayStatus();
17024
+ const replaced = running && gatewayOutdated(running) ? { replaced: { version: running.version, pid: running.pid, stopped: await stopGateway(running, paths.socket) } } : {};
17025
+ const { command } = gatewayServiceCommand();
17026
+ const installed = await installGatewayService({ command });
17027
+ const ensured = await ensureGatewayService({ command, waitMs: 15000 });
17028
+ output({ ...installed, ...replaced, ...await describe(), started: ensured.started });
17029
+ return;
17030
+ }
17031
+ if (action2 === "uninstall") {
17032
+ const removed = await uninstallGatewayService();
17033
+ output({ ...removed, ...await describe() });
17034
+ return;
17035
+ }
17036
+ if (action2 === "stop") {
17037
+ const status = await gatewayStatus();
17038
+ if (!status) {
17039
+ output({ stopped: false, running: false });
17040
+ return;
17041
+ }
17042
+ await stopGateway(status, paths.socket);
17043
+ output({ stopped: true, pid: status.pid });
17044
+ return;
17045
+ }
17046
+ throw new Fault(400, "invalid_request", "Use switcher gateway status|install|uninstall|stop, or switcher gateway run [--exit-when-idle].");
17047
+ }
15310
17048
  if (import.meta.main) {
15311
17049
  if (process.argv.slice(2).length === 1 && process.argv[2] === "--version")
15312
17050
  console.log(VERSION);