@hasna/switcher 0.2.13 → 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/README.md +12 -0
- package/dist/cli/index.js +1470 -91
- package/dist/gateway-client.d.ts +84 -0
- package/dist/gateway-service.d.ts +60 -0
- package/dist/gateway-supervisor.d.ts +73 -0
- package/dist/harness-process.d.ts +1 -0
- package/dist/harness-types.d.ts +3 -1
- package/dist/inference-gateway.d.ts +25 -2
- package/dist/launcher.d.ts +11 -1
- package/dist/mcp/index.js +2 -2
- package/dist/process-table.d.ts +28 -0
- package/dist/serve/index.js +2 -2
- package/docs/GATEWAY-SERVICE.md +179 -0
- package/hasna.contract.json +1 -1
- package/openapi.json +1 -1
- package/package.json +4 -3
package/dist/cli/index.js
CHANGED
|
@@ -514,7 +514,7 @@ function canonicalPolicyJSON(value) {
|
|
|
514
514
|
return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
515
515
|
}
|
|
516
516
|
// package.json
|
|
517
|
-
var version = "0.2.
|
|
517
|
+
var version = "0.2.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
|
|
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.
|
|
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
|
|
8343
|
-
const
|
|
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
|
|
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
|
|
8350
|
-
const
|
|
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
|
|
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
|
-
|
|
8373
|
-
|
|
8374
|
-
|
|
8375
|
-
|
|
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
|
-
|
|
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 (
|
|
8442
|
-
const [name, value] = gemini ? ["x-goog-api-key",
|
|
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,
|
|
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
|
-
|
|
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 {
|
|
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 =
|
|
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
|
|
11377
|
+
await removeCatalog();
|
|
11320
11378
|
}
|
|
11321
11379
|
} };
|
|
11322
11380
|
} catch (error) {
|
|
11323
11381
|
await bridge.cleanup();
|
|
11324
|
-
await
|
|
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
|
|
11357
|
-
import { join as
|
|
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;
|
|
@@ -14255,10 +14318,1213 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
|
|
|
14255
14318
|
}
|
|
14256
14319
|
}
|
|
14257
14320
|
|
|
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;
|
|
14356
|
+
}
|
|
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;
|
|
14405
|
+
}
|
|
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";
|
|
14410
|
+
}
|
|
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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
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
|
+
|
|
14258
15524
|
// src/launcher.ts
|
|
14259
15525
|
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
14260
15526
|
async function writeOriCodexCatalog(stateDir, models) {
|
|
14261
|
-
const path =
|
|
15527
|
+
const path = join24(stateDir, "ori-codex-models.json");
|
|
14262
15528
|
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
14263
15529
|
await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
14264
15530
|
`, { mode: 384, flag: "wx" });
|
|
@@ -14298,7 +15564,7 @@ async function oriRequestForPlan(plan, options = {}) {
|
|
|
14298
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.");
|
|
14299
15565
|
if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
14300
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.");
|
|
14301
|
-
const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ?
|
|
15567
|
+
const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve14(options.cwd) : undefined });
|
|
14302
15568
|
const native = requireOriHarness(contract, target);
|
|
14303
15569
|
if (!native.path)
|
|
14304
15570
|
throw new Error("Ori did not report the native harness executable path.");
|
|
@@ -14346,14 +15612,14 @@ async function prepareOriForPlan(plan, options) {
|
|
|
14346
15612
|
executable: detection.executable,
|
|
14347
15613
|
version: detection.version,
|
|
14348
15614
|
stateDir: options.stateDir,
|
|
14349
|
-
cwd:
|
|
15615
|
+
cwd: resolve14(options.cwd ?? process.cwd()),
|
|
14350
15616
|
args: options.args ?? [],
|
|
14351
15617
|
sharedState: options.sharedState
|
|
14352
15618
|
});
|
|
14353
15619
|
try {
|
|
14354
15620
|
const shim = prepareOriModelPolicy(request.target, native);
|
|
14355
|
-
const dir =
|
|
14356
|
-
await
|
|
15621
|
+
const dir = join24(options.stateDir, "ori-bin"), path = join24(dir, shim.name);
|
|
15622
|
+
await mkdir14(dir, { mode: 448 });
|
|
14357
15623
|
await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
|
|
14358
15624
|
return { contract, prepared: {
|
|
14359
15625
|
...ori,
|
|
@@ -14378,7 +15644,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14378
15644
|
assertHarnessArguments(profile.harness, options.args ?? []);
|
|
14379
15645
|
if (profile.harness === "gemini" || profile.harness === "antigravity")
|
|
14380
15646
|
validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
|
|
14381
|
-
await validateHarnessConfiguration(profile.harness,
|
|
15647
|
+
await validateHarnessConfiguration(profile.harness, resolve14(options.cwd ?? process.cwd()), options.args);
|
|
14382
15648
|
if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
|
|
14383
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.");
|
|
14384
15650
|
if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
@@ -14387,7 +15653,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14387
15653
|
await client.refreshModels(profile.providerId);
|
|
14388
15654
|
const plan = await client.launchPlan(profileId);
|
|
14389
15655
|
assertHarnessArguments(plan.profile.harness, options.args ?? []);
|
|
14390
|
-
await validateHarnessConfiguration(plan.profile.harness,
|
|
15656
|
+
await validateHarnessConfiguration(plan.profile.harness, resolve14(options.cwd ?? process.cwd()), options.args);
|
|
14391
15657
|
if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
|
|
14392
15658
|
throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
|
|
14393
15659
|
const backend = options.backend ?? "direct";
|
|
@@ -14409,9 +15675,9 @@ async function launch(client, profileId, options = {}) {
|
|
|
14409
15675
|
validateHarnessVersion("gemini", detection?.version);
|
|
14410
15676
|
if (backend === "direct" && plan.profile.harness === "aider")
|
|
14411
15677
|
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
14412
|
-
const root =
|
|
15678
|
+
const root = resolve14(options.stateDir ?? join24(switcherHome(), "state"));
|
|
14413
15679
|
await privateDirectory(root);
|
|
14414
|
-
const stateDir = await mkdtemp(
|
|
15680
|
+
const stateDir = await mkdtemp(join24(root, "launch-"));
|
|
14415
15681
|
let credential;
|
|
14416
15682
|
if (backend === "direct") {
|
|
14417
15683
|
try {
|
|
@@ -14419,7 +15685,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14419
15685
|
if (plan.provider.credentialEnv && !credential)
|
|
14420
15686
|
throw new Fault(400, "credential_setup_required", `Provider credential setup is required. Run: ${providerCredentialSetupCommand(plan.provider)}. Or provide ${plan.provider.credentialEnv} in this launch process.`);
|
|
14421
15687
|
} catch (error) {
|
|
14422
|
-
await
|
|
15688
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
14423
15689
|
throw error;
|
|
14424
15690
|
}
|
|
14425
15691
|
}
|
|
@@ -14441,6 +15707,15 @@ async function launch(client, profileId, options = {}) {
|
|
|
14441
15707
|
} else
|
|
14442
15708
|
routingEventsDropped = Math.min(1e6, routingEventsDropped + 1);
|
|
14443
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
|
+
}
|
|
14444
15719
|
const finishRunOnce = async (candidate, body2, message) => {
|
|
14445
15720
|
if (runFinalized)
|
|
14446
15721
|
return;
|
|
@@ -14470,8 +15745,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
14470
15745
|
let nativeHome2;
|
|
14471
15746
|
if (sharedState && !options.desktop && !options.claudeDesktop) {
|
|
14472
15747
|
const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
|
|
14473
|
-
const configured = process.env[variable] ?
|
|
14474
|
-
nativeHome2 = sharedState.tool === "claude" && (!configured || 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;
|
|
14475
15750
|
if (sharedState.tool === "claude")
|
|
14476
15751
|
await prepareClaudeUserSettings(nativeHome2);
|
|
14477
15752
|
await privateDirectory(nativeHome2);
|
|
@@ -14481,12 +15756,12 @@ async function launch(client, profileId, options = {}) {
|
|
|
14481
15756
|
if (options.shareNativeState === false && backend === "direct") {
|
|
14482
15757
|
const tool = plan.profile.harness;
|
|
14483
15758
|
if (options.desktop)
|
|
14484
|
-
await assertNativeStateIsolation(tool,
|
|
15759
|
+
await assertNativeStateIsolation(tool, join24(root, "desktop", desktopState, "codex"));
|
|
14485
15760
|
else if (options.claudeDesktop)
|
|
14486
|
-
await assertNativeStateIsolation(tool,
|
|
15761
|
+
await assertNativeStateIsolation(tool, join24(root, "desktop-claude", desktopState));
|
|
14487
15762
|
else {
|
|
14488
15763
|
const variable = tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
|
|
14489
|
-
nativeHome2 = process.env[variable] ?
|
|
15764
|
+
nativeHome2 = process.env[variable] ? resolve14(process.env[variable]) : join24(root, `native-${tool}`, profileId);
|
|
14490
15765
|
await assertNativeStateIsolation(tool, nativeHome2);
|
|
14491
15766
|
await privateDirectory(nativeHome2);
|
|
14492
15767
|
}
|
|
@@ -14503,10 +15778,10 @@ async function launch(client, profileId, options = {}) {
|
|
|
14503
15778
|
onRoutingEvent,
|
|
14504
15779
|
credential,
|
|
14505
15780
|
stateDir,
|
|
14506
|
-
cwd:
|
|
15781
|
+
cwd: resolve14(options.cwd ?? process.cwd()),
|
|
14507
15782
|
sharedState
|
|
14508
15783
|
};
|
|
14509
|
-
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop,
|
|
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({
|
|
14510
15785
|
harness: plan.profile.harness,
|
|
14511
15786
|
baseUrl: plan.provider.baseUrl,
|
|
14512
15787
|
protocol: plan.provider.protocol,
|
|
@@ -14522,10 +15797,11 @@ async function launch(client, profileId, options = {}) {
|
|
|
14522
15797
|
executable: nativeExecutable ?? detection?.executable,
|
|
14523
15798
|
args: options.args ?? [],
|
|
14524
15799
|
stateDir,
|
|
14525
|
-
cwd:
|
|
15800
|
+
cwd: resolve14(options.cwd ?? process.cwd()),
|
|
14526
15801
|
version: detection?.version,
|
|
14527
15802
|
sharedState,
|
|
14528
|
-
|
|
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) } : {}
|
|
14529
15805
|
});
|
|
14530
15806
|
cleanup = prepared.cleanup;
|
|
14531
15807
|
prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
|
|
@@ -14542,7 +15818,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14542
15818
|
prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
|
|
14543
15819
|
}
|
|
14544
15820
|
if (options.desktop) {
|
|
14545
|
-
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir,
|
|
15821
|
+
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join24(root, "desktop", desktopState), sharedState);
|
|
14546
15822
|
cleanup = prepared.cleanup;
|
|
14547
15823
|
}
|
|
14548
15824
|
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
@@ -14619,7 +15895,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14619
15895
|
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
|
|
14620
15896
|
throw preparationSignal;
|
|
14621
15897
|
}
|
|
14622
|
-
const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd:
|
|
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) });
|
|
14623
15899
|
await cleanup?.();
|
|
14624
15900
|
cleanup = undefined;
|
|
14625
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}.`);
|
|
@@ -14636,8 +15912,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
14636
15912
|
} finally {
|
|
14637
15913
|
if (lateCreateRunFinalization) {
|
|
14638
15914
|
let finalizationTimer;
|
|
14639
|
-
const finalizationTimeout = new Promise((
|
|
14640
|
-
finalizationTimer = setTimeout(
|
|
15915
|
+
const finalizationTimeout = new Promise((resolve15) => {
|
|
15916
|
+
finalizationTimer = setTimeout(resolve15, LATE_RUN_FINALIZATION_TIMEOUT_MS);
|
|
14641
15917
|
});
|
|
14642
15918
|
try {
|
|
14643
15919
|
await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
|
|
@@ -14650,13 +15926,14 @@ async function launch(client, profileId, options = {}) {
|
|
|
14650
15926
|
try {
|
|
14651
15927
|
await cleanup?.();
|
|
14652
15928
|
} finally {
|
|
14653
|
-
|
|
15929
|
+
if (!gatewayHost?.retainedState())
|
|
15930
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
14654
15931
|
}
|
|
14655
15932
|
}
|
|
14656
15933
|
}
|
|
14657
15934
|
|
|
14658
15935
|
// src/direct-launch.ts
|
|
14659
|
-
import { createHash as
|
|
15936
|
+
import { createHash as createHash17 } from "crypto";
|
|
14660
15937
|
import { createInterface as createInterface3 } from "readline/promises";
|
|
14661
15938
|
var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
|
|
14662
15939
|
async function resolveLaunchProvider(client, selector, options = {}) {
|
|
@@ -14737,7 +16014,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
14737
16014
|
const policy = modelPolicy ?? (harness === "codex" ? { version: 1, selection: "catalog" } : undefined);
|
|
14738
16015
|
const normalizedPolicy = policy === undefined ? undefined : parse2(modelPolicySchema, policy);
|
|
14739
16016
|
const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
|
|
14740
|
-
const hash3 =
|
|
16017
|
+
const hash3 = createHash17("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
|
|
14741
16018
|
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
|
|
14742
16019
|
let existing;
|
|
14743
16020
|
try {
|
|
@@ -14761,16 +16038,16 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
14761
16038
|
}
|
|
14762
16039
|
|
|
14763
16040
|
// src/native-state-import.ts
|
|
14764
|
-
import { createHash as
|
|
14765
|
-
import { constants as
|
|
14766
|
-
import { lstat as
|
|
14767
|
-
import { basename as
|
|
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";
|
|
14768
16045
|
var MAX_FILES = 1e5;
|
|
14769
16046
|
var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
|
|
14770
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.");
|
|
14771
16048
|
async function info2(path) {
|
|
14772
16049
|
try {
|
|
14773
|
-
return await
|
|
16050
|
+
return await lstat12(path);
|
|
14774
16051
|
} catch (error) {
|
|
14775
16052
|
if (error.code === "ENOENT")
|
|
14776
16053
|
return;
|
|
@@ -14781,12 +16058,12 @@ var identity = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeM
|
|
|
14781
16058
|
var same = (a, b) => JSON.stringify(identity(a)) === JSON.stringify(identity(b));
|
|
14782
16059
|
var inside3 = (parent, child) => {
|
|
14783
16060
|
const path = relative6(parent, child);
|
|
14784
|
-
return path !== ".." && !path.startsWith("../") && !
|
|
16061
|
+
return path !== ".." && !path.startsWith("../") && !isAbsolute19(path);
|
|
14785
16062
|
};
|
|
14786
16063
|
var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
|
|
14787
16064
|
async function sessionId(path, expected) {
|
|
14788
|
-
const nameId =
|
|
14789
|
-
const handle = await
|
|
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);
|
|
14790
16067
|
try {
|
|
14791
16068
|
const before = await handle.stat();
|
|
14792
16069
|
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
|
|
@@ -14800,7 +16077,7 @@ async function sessionId(path, expected) {
|
|
|
14800
16077
|
length += read.bytesRead;
|
|
14801
16078
|
newline = buffer.indexOf(10, 0);
|
|
14802
16079
|
}
|
|
14803
|
-
const after = await handle.stat(), named = await
|
|
16080
|
+
const after = await handle.stat(), named = await lstat12(path);
|
|
14804
16081
|
if (!same(before, after) || !same(after, named) || after.nlink !== 1 || named.nlink !== 1 || named.isSymbolicLink())
|
|
14805
16082
|
throw refused();
|
|
14806
16083
|
if (newline < 0 && before.size > buffer.length)
|
|
@@ -14829,7 +16106,7 @@ async function checkSessionIdentities(plan) {
|
|
|
14829
16106
|
for (const file of plan.files) {
|
|
14830
16107
|
if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
|
|
14831
16108
|
continue;
|
|
14832
|
-
file.sessionId = await sessionId(
|
|
16109
|
+
file.sessionId = await sessionId(join25(plan.source, file.path), file.source);
|
|
14833
16110
|
if (!file.sessionId)
|
|
14834
16111
|
continue;
|
|
14835
16112
|
const previous = ids.get(file.sessionId);
|
|
@@ -14853,7 +16130,7 @@ async function checkSessionIdentities(plan) {
|
|
|
14853
16130
|
for await (const entry of await opendir2(directory)) {
|
|
14854
16131
|
if (++seen > MAX_FILES || entry.isSymbolicLink())
|
|
14855
16132
|
throw refused();
|
|
14856
|
-
const path =
|
|
16133
|
+
const path = join25(directory, entry.name);
|
|
14857
16134
|
if (entry.isDirectory()) {
|
|
14858
16135
|
await scan(path, depth + 1);
|
|
14859
16136
|
continue;
|
|
@@ -14870,19 +16147,19 @@ async function checkSessionIdentities(plan) {
|
|
|
14870
16147
|
file.existing = true;
|
|
14871
16148
|
}
|
|
14872
16149
|
}
|
|
14873
|
-
await scan(
|
|
14874
|
-
await scan(
|
|
16150
|
+
await scan(join25(plan.state.home, "sessions"));
|
|
16151
|
+
await scan(join25(plan.state.home, "archived_sessions"));
|
|
14875
16152
|
}
|
|
14876
16153
|
async function fingerprint2(path, copyTo) {
|
|
14877
|
-
const handle = await
|
|
16154
|
+
const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
|
|
14878
16155
|
let output, complete = false;
|
|
14879
16156
|
try {
|
|
14880
16157
|
const before = await handle.stat();
|
|
14881
16158
|
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
|
|
14882
16159
|
throw refused();
|
|
14883
16160
|
if (copyTo)
|
|
14884
|
-
output = await
|
|
14885
|
-
const hash3 =
|
|
16161
|
+
output = await open9(copyTo, "wx", 384);
|
|
16162
|
+
const hash3 = createHash18("sha256"), buffer = Buffer.alloc(64 * 1024);
|
|
14886
16163
|
let bytes = 0;
|
|
14887
16164
|
for (;; ) {
|
|
14888
16165
|
const read = await handle.read(buffer, 0, buffer.length, null);
|
|
@@ -14899,7 +16176,7 @@ async function fingerprint2(path, copyTo) {
|
|
|
14899
16176
|
offset += (await output.write(chunk, offset, chunk.length - offset)).bytesWritten;
|
|
14900
16177
|
}
|
|
14901
16178
|
}
|
|
14902
|
-
const after = await handle.stat(), named = await
|
|
16179
|
+
const after = await handle.stat(), named = await lstat12(path);
|
|
14903
16180
|
if (named.isSymbolicLink() || after.nlink !== 1 || named.nlink !== 1 || bytes !== before.size || !same(before, after) || !same(after, named))
|
|
14904
16181
|
throw refused();
|
|
14905
16182
|
await output?.sync();
|
|
@@ -14909,15 +16186,15 @@ async function fingerprint2(path, copyTo) {
|
|
|
14909
16186
|
await output?.close();
|
|
14910
16187
|
await handle.close();
|
|
14911
16188
|
if (copyTo && !complete)
|
|
14912
|
-
await
|
|
16189
|
+
await unlink5(copyTo).catch(() => {
|
|
14913
16190
|
return;
|
|
14914
16191
|
});
|
|
14915
16192
|
}
|
|
14916
16193
|
}
|
|
14917
16194
|
async function planNativeStateImport(state, source, selection) {
|
|
14918
|
-
if (!
|
|
16195
|
+
if (!isAbsolute19(source) || source.includes("\x00"))
|
|
14919
16196
|
throw refused();
|
|
14920
|
-
source =
|
|
16197
|
+
source = resolve15(source);
|
|
14921
16198
|
if (inside3(source, state.home) || inside3(state.home, source))
|
|
14922
16199
|
throw refused();
|
|
14923
16200
|
await assertNativeStateDirectory(source);
|
|
@@ -14931,9 +16208,9 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
14931
16208
|
async function visit(path, kind) {
|
|
14932
16209
|
if (++seen > MAX_FILES || path.split("/").length > 32)
|
|
14933
16210
|
throw refused();
|
|
14934
|
-
await ensureNativeStateDirectory(
|
|
14935
|
-
await ensureNativeStateDirectory(
|
|
14936
|
-
const from =
|
|
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);
|
|
14937
16214
|
if (!entry)
|
|
14938
16215
|
return;
|
|
14939
16216
|
if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
|
|
@@ -14952,7 +16229,7 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
14952
16229
|
}
|
|
14953
16230
|
children.sort((a, b) => a.name.localeCompare(b.name));
|
|
14954
16231
|
for (const child of children)
|
|
14955
|
-
await visit(
|
|
16232
|
+
await visit(join25(path, child.name), child.kind);
|
|
14956
16233
|
} else {
|
|
14957
16234
|
const value = await fingerprint2(from);
|
|
14958
16235
|
plan.bytes += value.bytes;
|
|
@@ -14974,7 +16251,7 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
14974
16251
|
return plan;
|
|
14975
16252
|
}
|
|
14976
16253
|
function nativeStateImportDigest(plan) {
|
|
14977
|
-
return
|
|
16254
|
+
return createHash18("sha256").update(JSON.stringify({
|
|
14978
16255
|
tool: plan.state.tool,
|
|
14979
16256
|
source: plan.source,
|
|
14980
16257
|
destination: plan.state.home,
|
|
@@ -15006,14 +16283,14 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
15006
16283
|
throw refused();
|
|
15007
16284
|
const requiredDirectories = new Set([plan.state.home]);
|
|
15008
16285
|
for (const path of plan.directories) {
|
|
15009
|
-
for (let directory =
|
|
16286
|
+
for (let directory = join25(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname11(directory)) {
|
|
15010
16287
|
requiredDirectories.add(directory);
|
|
15011
16288
|
if (directory === plan.state.home)
|
|
15012
16289
|
break;
|
|
15013
16290
|
}
|
|
15014
16291
|
}
|
|
15015
16292
|
for (const file of plan.files.filter((file2) => !file2.existing)) {
|
|
15016
|
-
for (let directory =
|
|
16293
|
+
for (let directory = dirname11(join25(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname11(directory)) {
|
|
15017
16294
|
requiredDirectories.add(directory);
|
|
15018
16295
|
if (directory === plan.state.home)
|
|
15019
16296
|
break;
|
|
@@ -15034,9 +16311,9 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
15034
16311
|
for (const file of plan.files) {
|
|
15035
16312
|
if (file.existing)
|
|
15036
16313
|
continue;
|
|
15037
|
-
const target =
|
|
16314
|
+
const target = join25(plan.state.home, file.path), temporary = join25(dirname11(target), `.switcher-import-${crypto.randomUUID()}`);
|
|
15038
16315
|
staged.push({ temporary, target });
|
|
15039
|
-
const copied = await fingerprint2(
|
|
16316
|
+
const copied = await fingerprint2(join25(plan.source, file.path), temporary);
|
|
15040
16317
|
if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
|
|
15041
16318
|
throw refused();
|
|
15042
16319
|
}
|
|
@@ -15054,7 +16331,7 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
15054
16331
|
} finally {
|
|
15055
16332
|
for (const item2 of staged) {
|
|
15056
16333
|
try {
|
|
15057
|
-
await
|
|
16334
|
+
await unlink5(item2.temporary);
|
|
15058
16335
|
} catch (error) {
|
|
15059
16336
|
if (error.code !== "ENOENT")
|
|
15060
16337
|
cleanupFailed = true;
|
|
@@ -15089,6 +16366,7 @@ async function applyNativeStateImport(plan) {
|
|
|
15089
16366
|
}
|
|
15090
16367
|
|
|
15091
16368
|
// src/cli.ts
|
|
16369
|
+
import { realpathSync as realpathSync2 } from "fs";
|
|
15092
16370
|
var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
|
|
15093
16371
|
|
|
15094
16372
|
switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
|
|
@@ -15125,6 +16403,8 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
|
|
|
15125
16403
|
switcher credentials list|check|remove [PRESET_OR_REFERENCE]
|
|
15126
16404
|
switcher credentials repair-executable PRESET_OR_REFERENCE --sha256 EXPECTED
|
|
15127
16405
|
switcher credentials repair-executable --vault-cli PATH --sha256 EXPECTED
|
|
16406
|
+
switcher gateway status|install|uninstall|stop
|
|
16407
|
+
switcher gateway run [--exit-when-idle]
|
|
15128
16408
|
switcher doctor
|
|
15129
16409
|
switcher state import codex|claude --from LEGACY_NATIVE_HOME [--entry NAME]... [--dry-run | --apply --plan-digest SHA256]
|
|
15130
16410
|
|
|
@@ -15137,6 +16417,11 @@ Its local Codex conversations use the selected Responses-compatible provider.
|
|
|
15137
16417
|
claude-desktop launches Claude in its separate Claude-3p gateway profile with a
|
|
15138
16418
|
Messages-compatible provider. Quit that instance before switching providers.
|
|
15139
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.
|
|
15140
16425
|
--reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
|
|
15141
16426
|
--dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
|
|
15142
16427
|
PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
|
|
@@ -15261,7 +16546,8 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15261
16546
|
"vault-operator": { type: "string" },
|
|
15262
16547
|
"keychain-service": { type: "string" },
|
|
15263
16548
|
"keychain-account": { type: "string" },
|
|
15264
|
-
origin: { type: "string", multiple: true }
|
|
16549
|
+
origin: { type: "string", multiple: true },
|
|
16550
|
+
"exit-when-idle": { type: "boolean" }
|
|
15265
16551
|
} });
|
|
15266
16552
|
if (values2.help || !positionals.length) {
|
|
15267
16553
|
console.log(HELP);
|
|
@@ -15281,6 +16567,10 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15281
16567
|
output(nativeStateImportSummary(plan, Boolean(values2.apply)));
|
|
15282
16568
|
return;
|
|
15283
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.");
|
|
15284
16574
|
if (values2.from !== undefined || values2.entry !== undefined || values2.apply !== undefined || values2["plan-digest"] !== undefined)
|
|
15285
16575
|
throw new Fault(400, "conflicting_options", "--from, --entry, --plan-digest, --dry-run and --apply belong to switcher state import.");
|
|
15286
16576
|
if (values2["share-native-state"] && values2["no-share-native-state"])
|
|
@@ -15542,9 +16832,9 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15542
16832
|
if (sharedNativeState)
|
|
15543
16833
|
await resolveNativeState(plan.profile.harness, process.env, { create: false });
|
|
15544
16834
|
if (shareNativeState === false) {
|
|
15545
|
-
const tool = plan.profile.harness, root =
|
|
16835
|
+
const tool = plan.profile.harness, root = resolve16(values2["state-dir"] ?? join26(switcherHome(), "state"));
|
|
15546
16836
|
const configured = process.env[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
|
|
15547
|
-
const home = desktop ?
|
|
16837
|
+
const home = desktop ? join26(root, "desktop", profileId, "codex") : claudeApp ? join26(root, "desktop-claude", profileId) : configured ? resolve16(configured) : join26(root, `native-${tool}`, profileId);
|
|
15548
16838
|
await assertNativeStateIsolation(tool, home);
|
|
15549
16839
|
}
|
|
15550
16840
|
if (backend === "ori") {
|
|
@@ -15556,7 +16846,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15556
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" } } : {} });
|
|
15557
16847
|
return;
|
|
15558
16848
|
}
|
|
15559
|
-
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)) });
|
|
15560
16850
|
return;
|
|
15561
16851
|
}
|
|
15562
16852
|
if (editingModel) {
|
|
@@ -15666,6 +16956,95 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15666
16956
|
await runtime.close();
|
|
15667
16957
|
}
|
|
15668
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
|
+
}
|
|
15669
17048
|
if (import.meta.main) {
|
|
15670
17049
|
if (process.argv.slice(2).length === 1 && process.argv[2] === "--version")
|
|
15671
17050
|
console.log(VERSION);
|