@hasna/switcher 0.2.13 → 0.2.15
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/claude-desktop.js +8 -8
- package/dist/cli/index.js +1500 -93
- 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/index.js +9 -9
- package/dist/inference-gateway.d.ts +25 -2
- package/dist/launcher.d.ts +11 -1
- package/dist/mcp/index.js +13 -13
- package/dist/process-table.d.ts +28 -0
- package/dist/sdk.js +9 -9
- 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 +8 -4
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.15";
|
|
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.15",
|
|
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,78 @@ 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.";
|
|
8339
|
+
var EXPLAINED_UPSTREAM_STATUSES = new Set([400, 413, 422]);
|
|
8340
|
+
var LARGE_TOOL_COUNT = 128;
|
|
8341
|
+
var LARGE_REQUEST_BYTES = 256 * 1024;
|
|
8342
|
+
function toolDefinitionCount(body) {
|
|
8343
|
+
const record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
8344
|
+
const count = (value) => {
|
|
8345
|
+
if (!value)
|
|
8346
|
+
return 0;
|
|
8347
|
+
let total = Array.isArray(value.functions) ? value.functions.length : 0;
|
|
8348
|
+
for (const tool of Array.isArray(value.tools) ? value.tools : []) {
|
|
8349
|
+
const declarations = record2(tool)?.functionDeclarations ?? record2(tool)?.function_declarations;
|
|
8350
|
+
total += Array.isArray(declarations) ? declarations.length : 1;
|
|
8351
|
+
}
|
|
8352
|
+
return total;
|
|
8353
|
+
};
|
|
8354
|
+
const top = record2(body);
|
|
8355
|
+
return count(top) + count(record2(top?.generateContentRequest));
|
|
8356
|
+
}
|
|
8357
|
+
function upstreamRejectionMessage(status, providerId, sent) {
|
|
8358
|
+
const provider = idSchema.safeParse(providerId).success ? `the provider ${providerId}` : "the provider";
|
|
8359
|
+
const message = `Switcher inference gateway: ${provider} rejected the request with HTTP ${status} (upstream_http_${status}). Switcher sent ${sent.tools} tool definition${sent.tools === 1 ? "" : "s"} in a ${Math.ceil(sent.bytes / 1024)} KB request.`;
|
|
8360
|
+
if (sent.tools <= LARGE_TOOL_COUNT && sent.bytes <= LARGE_REQUEST_BYTES)
|
|
8361
|
+
return message;
|
|
8362
|
+
return `${message} Some providers reject large tool sets or large requests. Start a new session instead of resuming this one, or reduce the MCP servers enabled for this harness.`;
|
|
8363
|
+
}
|
|
8337
8364
|
function requestBodyLimit(models, policy) {
|
|
8338
8365
|
const allowed = new Set(policy.allowedModels);
|
|
8339
8366
|
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
8367
|
return Math.min(MAX_REQUEST_BODY_BYTES, Math.max(MIN_REQUEST_BODY_BYTES, contextWindow * REQUEST_BYTES_PER_CONTEXT_TOKEN));
|
|
8341
8368
|
}
|
|
8342
|
-
function
|
|
8343
|
-
const
|
|
8369
|
+
async function readJsonBody(request, limit) {
|
|
8370
|
+
const declared = request.headers.get("content-length");
|
|
8371
|
+
if (declared !== null && Number(declared) > limit)
|
|
8372
|
+
return { status: 413, code: "request_too_large" };
|
|
8373
|
+
try {
|
|
8374
|
+
if (!request.body)
|
|
8375
|
+
return { value: await request.json() };
|
|
8376
|
+
const reader = request.body.getReader(), chunks = [];
|
|
8377
|
+
let size = 0;
|
|
8378
|
+
for (;; ) {
|
|
8379
|
+
const { done, value } = await reader.read();
|
|
8380
|
+
if (done)
|
|
8381
|
+
break;
|
|
8382
|
+
size += value.byteLength;
|
|
8383
|
+
if (size > limit) {
|
|
8384
|
+
await reader.cancel().catch(() => {
|
|
8385
|
+
return;
|
|
8386
|
+
});
|
|
8387
|
+
return { status: 413, code: "request_too_large" };
|
|
8388
|
+
}
|
|
8389
|
+
chunks.push(value);
|
|
8390
|
+
}
|
|
8391
|
+
return { value: JSON.parse(Buffer.concat(chunks).toString("utf8")) };
|
|
8392
|
+
} catch {
|
|
8393
|
+
return { status: 400, code: "invalid_json" };
|
|
8394
|
+
}
|
|
8395
|
+
}
|
|
8396
|
+
function createInferenceHandler(input, timing = {}, options = {}) {
|
|
8344
8397
|
const openCodeSession = crypto.randomUUID();
|
|
8345
8398
|
const openCodeState = new Map;
|
|
8346
|
-
const
|
|
8347
|
-
const expected = digest(token), policy = input.compiledPolicy;
|
|
8399
|
+
const policy = input.compiledPolicy;
|
|
8348
8400
|
const known = new Set(input.models.map((m) => m.id));
|
|
8349
|
-
const
|
|
8350
|
-
const
|
|
8401
|
+
const bodyLimit = requestBodyLimit(input.models, input.compiledPolicy);
|
|
8402
|
+
const safeModelFor = (credential) => (value) => typeof value === "string" && value !== credential && (known.has(value) || Object.hasOwn(policy.aliases, value) || input.harness === "antigravity" && value === antigravityHelperModel) ? value : "<unrecognized>";
|
|
8403
|
+
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
8404
|
let closing = false, stopped;
|
|
8352
8405
|
const active = new Set;
|
|
8353
|
-
const
|
|
8406
|
+
const handle = async (request, server) => {
|
|
8354
8407
|
if (closing)
|
|
8355
8408
|
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
8409
|
const url = new URL(request.url);
|
|
8360
8410
|
if (request.method === "GET" && url.pathname === "/v1/models" && !url.search)
|
|
8361
8411
|
return Response.json({ object: "list", data: input.models.filter((m) => !modelExpired(m)).map((m) => ({ ...m, object: "model" })) });
|
|
@@ -8369,14 +8419,21 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8369
8419
|
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
8420
|
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
8421
|
return fail(400, "unsupported_query");
|
|
8372
|
-
|
|
8373
|
-
|
|
8374
|
-
|
|
8375
|
-
|
|
8376
|
-
return fail(400, "invalid_json");
|
|
8377
|
-
}
|
|
8422
|
+
const parsed = await readJsonBody(request, bodyLimit);
|
|
8423
|
+
if ("status" in parsed)
|
|
8424
|
+
return fail(parsed.status, parsed.code);
|
|
8425
|
+
const body = parsed.value;
|
|
8378
8426
|
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
8379
8427
|
return fail(400, "invalid_request");
|
|
8428
|
+
let credential;
|
|
8429
|
+
try {
|
|
8430
|
+
credential = options.credential ? await options.credential() : input.credential;
|
|
8431
|
+
} catch (error) {
|
|
8432
|
+
if (error instanceof Fault)
|
|
8433
|
+
return Response.json({ error: { type: "switcher_gateway", code: error.code, message: error.message } }, { status: error.status });
|
|
8434
|
+
return fail(503, "credential_unavailable", "Switcher gateway: the provider credential for this launch is unavailable. Start a new session with `switcher launch`.");
|
|
8435
|
+
}
|
|
8436
|
+
const safeModel = safeModelFor(credential);
|
|
8380
8437
|
let requested = body.model;
|
|
8381
8438
|
if (gemini)
|
|
8382
8439
|
try {
|
|
@@ -8435,11 +8492,11 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8435
8492
|
};
|
|
8436
8493
|
active.add(record2);
|
|
8437
8494
|
const signal = activity.fetchOptions.signal;
|
|
8438
|
-
|
|
8495
|
+
server.timeout(request, 0);
|
|
8439
8496
|
const headers = { "content-type": "application/json" };
|
|
8440
8497
|
Object.assign(headers, openCodeHeaders(input.baseUrl, request.headers, body, openCodeSession));
|
|
8441
|
-
if (
|
|
8442
|
-
const [name, value] = gemini ? ["x-goog-api-key",
|
|
8498
|
+
if (credential) {
|
|
8499
|
+
const [name, value] = gemini ? ["x-goog-api-key", credential] : authHeader(input.authStyle ?? "bearer", credential);
|
|
8443
8500
|
headers[name] = value;
|
|
8444
8501
|
}
|
|
8445
8502
|
if (input.protocol === "anthropic-messages") {
|
|
@@ -8448,6 +8505,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8448
8505
|
headers["anthropic-beta"] = request.headers.get("anthropic-beta");
|
|
8449
8506
|
}
|
|
8450
8507
|
const candidates = [resolved, ...policy.fallbacks[resolved] ?? []];
|
|
8508
|
+
let sent = { tools: 0, bytes: 0 };
|
|
8451
8509
|
try {
|
|
8452
8510
|
if (candidates.some((model) => !known.has(model) || !policy.allowedModels.includes(model)))
|
|
8453
8511
|
throw new Error("invalid_fallback_policy");
|
|
@@ -8472,7 +8530,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8472
8530
|
const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
|
|
8473
8531
|
const compatible2 = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
|
|
8474
8532
|
const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
|
|
8475
|
-
const translated = input.protocol === "anthropic-messages" ? prepareOpenCodeMessages(input.baseUrl, outgoing, suffix,
|
|
8533
|
+
const translated = input.protocol === "anthropic-messages" ? prepareOpenCodeMessages(input.baseUrl, outgoing, suffix, credential, openCodeState) : undefined;
|
|
8476
8534
|
const path = translated?.path ?? (gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : ""));
|
|
8477
8535
|
const upstreamHeaders = { ...headers };
|
|
8478
8536
|
if (translated) {
|
|
@@ -8482,8 +8540,10 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8482
8540
|
delete upstreamHeaders["anthropic-beta"];
|
|
8483
8541
|
Object.assign(upstreamHeaders, translated.auth);
|
|
8484
8542
|
}
|
|
8543
|
+
const sentBody = translated?.body ?? outgoing, serialized = JSON.stringify(sentBody);
|
|
8544
|
+
sent = { tools: toolDefinitionCount(sentBody), bytes: Buffer.byteLength(serialized) };
|
|
8485
8545
|
try {
|
|
8486
|
-
response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers: upstreamHeaders, body:
|
|
8546
|
+
response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers: upstreamHeaders, body: serialized, redirect: "manual", ...activity.fetchOptions }));
|
|
8487
8547
|
} catch {
|
|
8488
8548
|
current.reason = activity.timedOut() ? "provider_idle_timeout" : signal.aborted ? "request_cancelled" : "network_error";
|
|
8489
8549
|
throw new Error("provider_request_failed");
|
|
@@ -8514,7 +8574,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8514
8574
|
return Response.json({ type: "error", error: { type: "invalid_request_error", code: "context_length_exceeded", message: "prompt is too long: the provider context window was exceeded. Compact the conversation or start a new session." } }, { status: 400 });
|
|
8515
8575
|
if (paymentRequired)
|
|
8516
8576
|
return fail(402, "provider_payment_required", "The selected provider rejected this request for billing or credit limits (HTTP 402). Check the account balance, API-key spending limit, and requested output-token budget before retrying.");
|
|
8517
|
-
const rejected = fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}
|
|
8577
|
+
const rejected = fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}`, EXPLAINED_UPSTREAM_STATUSES.has(response.status) ? upstreamRejectionMessage(response.status, input.providerId, sent) : undefined);
|
|
8518
8578
|
const retryAfter = response.headers.get("retry-after");
|
|
8519
8579
|
if ((response.status === 429 || response.status === 503) && retryAfter && retryAfter.length <= 128 && (/^\d+$/.test(retryAfter) || Number.isFinite(Date.parse(retryAfter))))
|
|
8520
8580
|
rejected.headers.set("retry-after", retryAfter);
|
|
@@ -8570,10 +8630,11 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8570
8630
|
current.reason = "provider_idle_timeout";
|
|
8571
8631
|
const networkError = !(error instanceof Fault) && current.reason === "network_error";
|
|
8572
8632
|
release();
|
|
8573
|
-
|
|
8633
|
+
const origin = new URL(endpoint(input.baseUrl)).origin;
|
|
8634
|
+
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
8635
|
}
|
|
8575
|
-
}
|
|
8576
|
-
return {
|
|
8636
|
+
};
|
|
8637
|
+
return { bodyLimit, closing: () => closing, handle, close: () => stopped ??= (async () => {
|
|
8577
8638
|
closing = true;
|
|
8578
8639
|
const pending = [...active];
|
|
8579
8640
|
for (const request of pending)
|
|
@@ -8582,6 +8643,24 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8582
8643
|
await request.cancel?.();
|
|
8583
8644
|
await request.done;
|
|
8584
8645
|
}));
|
|
8646
|
+
})() };
|
|
8647
|
+
}
|
|
8648
|
+
function createInferenceGateway(input, timing = {}) {
|
|
8649
|
+
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
8650
|
+
const digest = (value) => createHash6("sha256").update(value).digest();
|
|
8651
|
+
const expected = digest(token);
|
|
8652
|
+
const handler = createInferenceHandler(input, timing);
|
|
8653
|
+
let stopped;
|
|
8654
|
+
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: handler.bodyLimit, idleTimeout: 255, async fetch(request, server2) {
|
|
8655
|
+
if (handler.closing())
|
|
8656
|
+
return Response.json({ error: { type: "switcher_model_policy", code: "closing", message: CLOSING_MESSAGE } }, { status: 503 });
|
|
8657
|
+
const credential = request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
|
|
8658
|
+
if (!timingSafeEqual3(expected, digest(credential)))
|
|
8659
|
+
return Response.json({ error: { type: "switcher_model_policy", code: "unauthorized", message: "Switcher inference gateway: unauthorized." } }, { status: 401 });
|
|
8660
|
+
return handler.handle(request, server2);
|
|
8661
|
+
} });
|
|
8662
|
+
return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
|
|
8663
|
+
await handler.close();
|
|
8585
8664
|
await server.stop(true);
|
|
8586
8665
|
})() };
|
|
8587
8666
|
}
|
|
@@ -11307,7 +11386,14 @@ async function prepareHarnessLaunch(input) {
|
|
|
11307
11386
|
throw new Error(`${input.harness} does not expose native model controls for: ${unsupported3.join(", ")}.`);
|
|
11308
11387
|
await mkdir10(input.stateDir, { recursive: true, mode: 448 });
|
|
11309
11388
|
const catalogPath = await jsonFile(input.stateDir, `switcher-model-policy-${randomUUID4()}.json`, { policy: compiledPolicy, models: input.models });
|
|
11310
|
-
const bridge =
|
|
11389
|
+
const bridge = input.gatewayHost ? await input.gatewayHost.open({ ...input, compiledPolicy, catalogPath }).catch(async (error) => {
|
|
11390
|
+
await rm2(catalogPath, { force: true });
|
|
11391
|
+
throw error;
|
|
11392
|
+
}) : createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
11393
|
+
const removeCatalog = async () => {
|
|
11394
|
+
if (!bridge.retainsState?.())
|
|
11395
|
+
await rm2(catalogPath, { force: true });
|
|
11396
|
+
};
|
|
11311
11397
|
try {
|
|
11312
11398
|
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
11399
|
const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy });
|
|
@@ -11316,12 +11402,12 @@ async function prepareHarnessLaunch(input) {
|
|
|
11316
11402
|
await prepared.cleanup?.();
|
|
11317
11403
|
} finally {
|
|
11318
11404
|
await bridge.cleanup();
|
|
11319
|
-
await
|
|
11405
|
+
await removeCatalog();
|
|
11320
11406
|
}
|
|
11321
11407
|
} };
|
|
11322
11408
|
} catch (error) {
|
|
11323
11409
|
await bridge.cleanup();
|
|
11324
|
-
await
|
|
11410
|
+
await removeCatalog();
|
|
11325
11411
|
throw error;
|
|
11326
11412
|
}
|
|
11327
11413
|
}
|
|
@@ -11353,8 +11439,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
|
11353
11439
|
}
|
|
11354
11440
|
|
|
11355
11441
|
// src/launcher.ts
|
|
11356
|
-
import { mkdir as
|
|
11357
|
-
import { join as
|
|
11442
|
+
import { mkdir as mkdir14, mkdtemp, rm as rm6, writeFile as writeFile18 } from "fs/promises";
|
|
11443
|
+
import { join as join24, resolve as resolve14 } from "path";
|
|
11358
11444
|
|
|
11359
11445
|
// src/provider-credential-onboarding.ts
|
|
11360
11446
|
import { z as z9 } from "zod";
|
|
@@ -12232,6 +12318,11 @@ async function runHarnessProcess(options) {
|
|
|
12232
12318
|
};
|
|
12233
12319
|
return events;
|
|
12234
12320
|
})();
|
|
12321
|
+
if (child.pid) {
|
|
12322
|
+
try {
|
|
12323
|
+
options.onSpawn?.(child.pid);
|
|
12324
|
+
} catch {}
|
|
12325
|
+
}
|
|
12235
12326
|
let interrupted = false;
|
|
12236
12327
|
let interruptionExitCode;
|
|
12237
12328
|
let killTimer;
|
|
@@ -14255,10 +14346,1213 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
|
|
|
14255
14346
|
}
|
|
14256
14347
|
}
|
|
14257
14348
|
|
|
14349
|
+
// src/gateway-client.ts
|
|
14350
|
+
import { spawn as spawn4 } from "child_process";
|
|
14351
|
+
import { closeSync as closeSync3, openSync as openSync3 } from "fs";
|
|
14352
|
+
|
|
14353
|
+
// src/gateway-service.ts
|
|
14354
|
+
import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
|
|
14355
|
+
import { constants as constants10 } from "fs";
|
|
14356
|
+
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";
|
|
14357
|
+
import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join22, resolve as resolve13 } from "path";
|
|
14358
|
+
import { z as z10 } from "zod";
|
|
14359
|
+
|
|
14360
|
+
// src/process-table.ts
|
|
14361
|
+
import { createHash as createHash15 } from "crypto";
|
|
14362
|
+
import { readdir as readdir6, readFile as readFile7 } from "fs/promises";
|
|
14363
|
+
var MAX_PROCESSES = 1e5;
|
|
14364
|
+
async function darwinTable() {
|
|
14365
|
+
const child = Bun.spawn(["/bin/ps", "-A", "-o", "pid=", "-o", "ppid=", "-o", "lstart="], {
|
|
14366
|
+
env: { PATH: "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC" },
|
|
14367
|
+
stdin: "ignore",
|
|
14368
|
+
stdout: "pipe",
|
|
14369
|
+
stderr: "ignore"
|
|
14370
|
+
});
|
|
14371
|
+
const [text, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
|
|
14372
|
+
if (code !== 0)
|
|
14373
|
+
throw new Error("The process table could not be read.");
|
|
14374
|
+
const table = new Map;
|
|
14375
|
+
for (const line of text.split(`
|
|
14376
|
+
`)) {
|
|
14377
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(\S.*?)\s*$/.exec(line);
|
|
14378
|
+
if (!match || table.size >= MAX_PROCESSES)
|
|
14379
|
+
continue;
|
|
14380
|
+
const pid = Number(match[1]);
|
|
14381
|
+
table.set(pid, { pid, ppid: Number(match[2]), start: match[3] });
|
|
14382
|
+
}
|
|
14383
|
+
return table;
|
|
14384
|
+
}
|
|
14385
|
+
async function linuxTable() {
|
|
14386
|
+
const boot = (await readFile7("/proc/sys/kernel/random/boot_id", "utf8").catch(() => "")).trim();
|
|
14387
|
+
const table = new Map;
|
|
14388
|
+
for (const name of await readdir6("/proc")) {
|
|
14389
|
+
if (!/^\d+$/.test(name) || table.size >= MAX_PROCESSES)
|
|
14390
|
+
continue;
|
|
14391
|
+
let stat6;
|
|
14392
|
+
try {
|
|
14393
|
+
stat6 = await readFile7(`/proc/${name}/stat`, "utf8");
|
|
14394
|
+
} catch {
|
|
14395
|
+
continue;
|
|
14396
|
+
}
|
|
14397
|
+
const fields = stat6.slice(stat6.lastIndexOf(")") + 2).split(" ");
|
|
14398
|
+
const pid = Number(name), ppid = Number(fields[1]), ticks = fields[19];
|
|
14399
|
+
if (!Number.isSafeInteger(ppid) || !ticks)
|
|
14400
|
+
continue;
|
|
14401
|
+
table.set(pid, { pid, ppid, start: `${boot}:${ticks}`, comm: stat6.slice(stat6.indexOf("(") + 1, stat6.lastIndexOf(")")) });
|
|
14402
|
+
}
|
|
14403
|
+
return table;
|
|
14404
|
+
}
|
|
14405
|
+
function readProcessTable() {
|
|
14406
|
+
if (process.platform === "darwin")
|
|
14407
|
+
return darwinTable();
|
|
14408
|
+
if (process.platform === "linux")
|
|
14409
|
+
return linuxTable();
|
|
14410
|
+
return Promise.reject(new Error("Process tracking is supported on macOS and Linux only."));
|
|
14411
|
+
}
|
|
14412
|
+
function descendants(table, roots, exclude = []) {
|
|
14413
|
+
const children = new Map;
|
|
14414
|
+
for (const entry of table.values())
|
|
14415
|
+
if (entry.pid !== entry.ppid)
|
|
14416
|
+
(children.get(entry.ppid) ?? children.set(entry.ppid, []).get(entry.ppid)).push(entry.pid);
|
|
14417
|
+
const blocked = new Set(exclude), seen = new Set, found = [];
|
|
14418
|
+
const queue = [...roots].filter((pid) => !blocked.has(pid));
|
|
14419
|
+
while (queue.length) {
|
|
14420
|
+
const pid = queue.shift();
|
|
14421
|
+
for (const child of children.get(pid) ?? []) {
|
|
14422
|
+
if (seen.has(child) || blocked.has(child))
|
|
14423
|
+
continue;
|
|
14424
|
+
seen.add(child);
|
|
14425
|
+
const entry = table.get(child);
|
|
14426
|
+
if (entry) {
|
|
14427
|
+
found.push(entry);
|
|
14428
|
+
queue.push(child);
|
|
14429
|
+
}
|
|
14430
|
+
}
|
|
14431
|
+
}
|
|
14432
|
+
return found;
|
|
14433
|
+
}
|
|
14434
|
+
function isOrphan(entry, table) {
|
|
14435
|
+
if (entry.ppid === 1)
|
|
14436
|
+
return true;
|
|
14437
|
+
return entry.ppid !== entry.pid && table.get(entry.ppid)?.comm === "systemd";
|
|
14438
|
+
}
|
|
14439
|
+
var TOKEN_ENTRY = /^[A-Za-z_][A-Za-z0-9_]*=([A-Za-z0-9_-]{43})$/;
|
|
14440
|
+
var holdsDigest = (entries, digest2) => {
|
|
14441
|
+
for (const entry of entries) {
|
|
14442
|
+
const match = TOKEN_ENTRY.exec(entry);
|
|
14443
|
+
if (match && createHash15("sha256").update(match[1]).digest("hex") === digest2)
|
|
14444
|
+
return true;
|
|
14445
|
+
}
|
|
14446
|
+
return false;
|
|
14447
|
+
};
|
|
14448
|
+
var PROBE_CHUNK = 200;
|
|
14449
|
+
async function darwinDigestHolders(pids, digest2) {
|
|
14450
|
+
const found = [];
|
|
14451
|
+
for (let index = 0;index < pids.length; index += PROBE_CHUNK) {
|
|
14452
|
+
const child = Bun.spawn(["/bin/ps", "-E", "-ww", "-o", "pid=", "-o", "command=", "-p", pids.slice(index, index + PROBE_CHUNK).join(",")], {
|
|
14453
|
+
env: { PATH: "/usr/bin:/bin", LC_ALL: "C" },
|
|
14454
|
+
stdin: "ignore",
|
|
14455
|
+
stdout: "pipe",
|
|
14456
|
+
stderr: "ignore"
|
|
14457
|
+
});
|
|
14458
|
+
const [text] = await Promise.all([new Response(child.stdout).text(), child.exited]);
|
|
14459
|
+
for (const line of text.split(`
|
|
14460
|
+
`)) {
|
|
14461
|
+
const match = /^\s*(\d+)\s(.*)$/.exec(line);
|
|
14462
|
+
if (match && holdsDigest(match[2].split(" "), digest2))
|
|
14463
|
+
found.push(Number(match[1]));
|
|
14464
|
+
}
|
|
14465
|
+
}
|
|
14466
|
+
return found;
|
|
14467
|
+
}
|
|
14468
|
+
async function linuxDigestHolders(pids, digest2) {
|
|
14469
|
+
const found = [];
|
|
14470
|
+
for (const pid of pids) {
|
|
14471
|
+
let environment;
|
|
14472
|
+
try {
|
|
14473
|
+
environment = await readFile7(`/proc/${pid}/environ`, "latin1");
|
|
14474
|
+
} catch {
|
|
14475
|
+
continue;
|
|
14476
|
+
}
|
|
14477
|
+
if (holdsDigest(environment.split("\x00"), digest2))
|
|
14478
|
+
found.push(pid);
|
|
14479
|
+
}
|
|
14480
|
+
return found;
|
|
14481
|
+
}
|
|
14482
|
+
function processesHoldingTokenDigest(pids, digest2) {
|
|
14483
|
+
if (!pids.length)
|
|
14484
|
+
return Promise.resolve([]);
|
|
14485
|
+
if (process.platform === "darwin")
|
|
14486
|
+
return darwinDigestHolders(pids, digest2);
|
|
14487
|
+
if (process.platform === "linux")
|
|
14488
|
+
return linuxDigestHolders(pids, digest2);
|
|
14489
|
+
return Promise.resolve([]);
|
|
14490
|
+
}
|
|
14491
|
+
|
|
14492
|
+
// src/gateway-service.ts
|
|
14493
|
+
var GATEWAY_PROTOCOL = 1;
|
|
14494
|
+
var SOCKET_PATH_LIMIT = 100;
|
|
14495
|
+
var MAX_HOLDERS = 4096;
|
|
14496
|
+
var MAX_ORPHAN_CANDIDATES = 1000;
|
|
14497
|
+
var MAX_EVENTS = 1000;
|
|
14498
|
+
var MAX_EVENT_BYTES = 512 * 1024;
|
|
14499
|
+
var DEFAULT_GRACE_MS = 10 * 60000;
|
|
14500
|
+
var DEFAULT_SCAN_MS = 1000;
|
|
14501
|
+
var PERSIST_INTERVAL_MS = 5000;
|
|
14502
|
+
var USE_PERSIST_INTERVAL_MS = 60000;
|
|
14503
|
+
function gatewayPaths(env = process.env) {
|
|
14504
|
+
const root = join22(switcherHome(env), "gateway");
|
|
14505
|
+
const preferred = join22(root, "control.sock");
|
|
14506
|
+
const name = `${createHash16("sha256").update(root).digest("hex").slice(0, 16)}.sock`;
|
|
14507
|
+
const runtime = process.platform === "linux" && env.XDG_RUNTIME_DIR && isAbsolute17(env.XDG_RUNTIME_DIR) ? join22(env.XDG_RUNTIME_DIR, "switcher", name) : undefined;
|
|
14508
|
+
const socket = Buffer.byteLength(preferred) <= SOCKET_PATH_LIMIT ? preferred : runtime && Buffer.byteLength(runtime) <= SOCKET_PATH_LIMIT ? runtime : join22("/tmp", `switcher-${process.getuid?.() ?? 0}`, name);
|
|
14509
|
+
return { root, socket, launches: join22(root, "launches"), config: join22(root, "config.json"), log: join22(root, "service.log") };
|
|
14510
|
+
}
|
|
14511
|
+
var UNTRUSTED_FIX = "Another account may have created it: remove it (or set HASNA_SWITCHER_HOME to a shorter path) and launch again.";
|
|
14512
|
+
async function assertPrivateSocketDirectory(directory) {
|
|
14513
|
+
const info2 = await lstat10(directory);
|
|
14514
|
+
if (!info2.isDirectory() || info2.isSymbolicLink() || (info2.mode & 63) !== 0 || info2.uid !== process.getuid?.())
|
|
14515
|
+
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}`);
|
|
14516
|
+
}
|
|
14517
|
+
async function assertTrustedControlSocket(socket) {
|
|
14518
|
+
const missing = () => new Fault(503, "gateway_unavailable", "The Switcher gateway service is not running. Run `switcher gateway status`.");
|
|
14519
|
+
try {
|
|
14520
|
+
await assertPrivateSocketDirectory(dirname9(socket));
|
|
14521
|
+
} catch (error) {
|
|
14522
|
+
if (error.code === "ENOENT")
|
|
14523
|
+
throw missing();
|
|
14524
|
+
throw error;
|
|
14525
|
+
}
|
|
14526
|
+
let info2;
|
|
14527
|
+
try {
|
|
14528
|
+
info2 = await lstat10(socket);
|
|
14529
|
+
} catch (error) {
|
|
14530
|
+
if (error.code === "ENOENT")
|
|
14531
|
+
throw missing();
|
|
14532
|
+
throw new Fault(503, "gateway_socket_untrusted", `The Switcher gateway socket ${socket} could not be checked.`);
|
|
14533
|
+
}
|
|
14534
|
+
if (!info2.isSocket() || info2.uid !== process.getuid?.())
|
|
14535
|
+
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}`);
|
|
14536
|
+
}
|
|
14537
|
+
function defaultGatewayPort(uid = process.getuid?.() ?? 0) {
|
|
14538
|
+
return 47000 + uid % 1000;
|
|
14539
|
+
}
|
|
14540
|
+
var passwdHome;
|
|
14541
|
+
function accountHome() {
|
|
14542
|
+
if (passwdHome !== undefined)
|
|
14543
|
+
return passwdHome ?? undefined;
|
|
14544
|
+
passwdHome = null;
|
|
14545
|
+
const uid = process.getuid?.();
|
|
14546
|
+
if (uid === undefined)
|
|
14547
|
+
return;
|
|
14548
|
+
try {
|
|
14549
|
+
const command = process.platform === "darwin" ? ["/usr/bin/id", "-P", String(uid)] : process.platform === "linux" ? ["getent", "passwd", String(uid)] : undefined;
|
|
14550
|
+
if (!command)
|
|
14551
|
+
return;
|
|
14552
|
+
const result = Bun.spawnSync(command, { env: { PATH: "/usr/bin:/bin" }, stdin: "ignore", stdout: "pipe", stderr: "ignore" });
|
|
14553
|
+
const fields = result.exitCode === 0 ? result.stdout.toString().trim().split(`
|
|
14554
|
+
`)[0].split(":") : [];
|
|
14555
|
+
const home = fields[process.platform === "darwin" ? 8 : 5];
|
|
14556
|
+
if (home && isAbsolute17(home))
|
|
14557
|
+
passwdHome = resolve13(home);
|
|
14558
|
+
} catch {}
|
|
14559
|
+
return passwdHome ?? undefined;
|
|
14560
|
+
}
|
|
14561
|
+
function isDefaultSwitcherHome(env = process.env, home = accountHome()) {
|
|
14562
|
+
if (!home)
|
|
14563
|
+
return false;
|
|
14564
|
+
return resolve13(env.HOME?.trim() || home) === resolve13(home) && switcherHome(env) === resolve13(home, ".hasna", "switcher");
|
|
14565
|
+
}
|
|
14566
|
+
function envNumber(env, name, fallback, min, max) {
|
|
14567
|
+
const raw = env[name]?.trim();
|
|
14568
|
+
if (!raw)
|
|
14569
|
+
return fallback;
|
|
14570
|
+
const value = Number(raw);
|
|
14571
|
+
if (!Number.isSafeInteger(value) || value < min || value > max)
|
|
14572
|
+
throw new Fault(400, "invalid_gateway_setting", `${name} must be an integer from ${min} to ${max}.`);
|
|
14573
|
+
return value;
|
|
14574
|
+
}
|
|
14575
|
+
function gatewaySettings(env = process.env) {
|
|
14576
|
+
const port = env.SWITCHER_GATEWAY_PORT?.trim() ? envNumber(env, "SWITCHER_GATEWAY_PORT", 0, 1024, 65535) : undefined;
|
|
14577
|
+
return {
|
|
14578
|
+
port,
|
|
14579
|
+
graceMs: envNumber(env, "SWITCHER_GATEWAY_GRACE_SECONDS", DEFAULT_GRACE_MS / 1000, 1, 7 * 24 * 3600) * 1000,
|
|
14580
|
+
scanMs: envNumber(env, "SWITCHER_GATEWAY_SCAN_MS", DEFAULT_SCAN_MS, 50, 60000),
|
|
14581
|
+
exitIdleMs: envNumber(env, "SWITCHER_GATEWAY_EXIT_IDLE_SECONDS", 60, 1, 24 * 3600) * 1000
|
|
14582
|
+
};
|
|
14583
|
+
}
|
|
14584
|
+
async function socketDirectory(paths) {
|
|
14585
|
+
const directory = dirname9(paths.socket);
|
|
14586
|
+
if (directory === paths.root)
|
|
14587
|
+
return;
|
|
14588
|
+
await mkdir12(directory, { mode: 448, recursive: true });
|
|
14589
|
+
await assertPrivateSocketDirectory(directory);
|
|
14590
|
+
}
|
|
14591
|
+
var sha256 = (value) => createHash16("sha256").update(value).digest("hex");
|
|
14592
|
+
var forbiddenKeys = new Set(["__proto__", "prototype", "constructor"]);
|
|
14593
|
+
function nullRecord(value, item2, limit) {
|
|
14594
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
14595
|
+
throw new Fault(400, "invalid_request", "Model policy maps must be objects.");
|
|
14596
|
+
const entries = Object.entries(value);
|
|
14597
|
+
if (entries.length > limit)
|
|
14598
|
+
throw new Fault(400, "invalid_request", "Model policy map is too large.");
|
|
14599
|
+
const result = Object.create(null);
|
|
14600
|
+
for (const [key, entry] of entries) {
|
|
14601
|
+
if (forbiddenKeys.has(key) || key.length > 300)
|
|
14602
|
+
throw new Fault(400, "invalid_request", "Model policy key is invalid.");
|
|
14603
|
+
result[key] = item2(entry);
|
|
14604
|
+
}
|
|
14605
|
+
return result;
|
|
14606
|
+
}
|
|
14607
|
+
var modelId = (value) => {
|
|
14608
|
+
if (typeof value !== "string" || !value || value.length > 300 || /[\x00-\x1f\x7f]/.test(value))
|
|
14609
|
+
throw new Fault(400, "invalid_request", "Model policy entry is invalid.");
|
|
14610
|
+
return value;
|
|
14611
|
+
};
|
|
14612
|
+
function compiledPolicy(value) {
|
|
14613
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
14614
|
+
throw new Fault(400, "invalid_request", "A compiled model policy is required.");
|
|
14615
|
+
const input = value;
|
|
14616
|
+
if (input.version !== 1 || typeof input.digest !== "string" || !/^[a-f0-9]{64}$/.test(input.digest) || !Array.isArray(input.allowedModels) || input.allowedModels.length > 20000)
|
|
14617
|
+
throw new Fault(400, "invalid_request", "The compiled model policy is invalid.");
|
|
14618
|
+
return {
|
|
14619
|
+
version: 1,
|
|
14620
|
+
model: modelId(input.model),
|
|
14621
|
+
digest: input.digest,
|
|
14622
|
+
roles: nullRecord(input.roles, modelId, 20),
|
|
14623
|
+
allowedModels: input.allowedModels.map(modelId),
|
|
14624
|
+
aliases: nullRecord(input.aliases, modelId, 200),
|
|
14625
|
+
fallbacks: nullRecord(input.fallbacks, (entry) => {
|
|
14626
|
+
if (!Array.isArray(entry) || entry.length > 20)
|
|
14627
|
+
throw new Fault(400, "invalid_request", "Fallback list is invalid.");
|
|
14628
|
+
return entry.map(modelId);
|
|
14629
|
+
}, 200)
|
|
14630
|
+
};
|
|
14631
|
+
}
|
|
14632
|
+
var gatewaySchema = z10.object({
|
|
14633
|
+
harness: harnessSchema,
|
|
14634
|
+
baseUrl: z10.string().max(2000).refine((value) => {
|
|
14635
|
+
try {
|
|
14636
|
+
return ["http:", "https:"].includes(new URL(value).protocol);
|
|
14637
|
+
} catch {
|
|
14638
|
+
return false;
|
|
14639
|
+
}
|
|
14640
|
+
}, "Use an http(s) provider URL."),
|
|
14641
|
+
protocol: protocolSchema,
|
|
14642
|
+
authStyle: z10.enum(["bearer", "x-api-key", "api-key"]).optional(),
|
|
14643
|
+
model: z10.string().min(1).max(300),
|
|
14644
|
+
models: z10.array(modelSchema.strip()).min(1).max(20000),
|
|
14645
|
+
compiledPolicy: z10.unknown(),
|
|
14646
|
+
providerId: z10.string().max(200).optional(),
|
|
14647
|
+
catalogPath: z10.string().max(4096).refine(isAbsolute17, "Use an absolute catalog path."),
|
|
14648
|
+
cwd: z10.string().max(4096).refine(isAbsolute17, "Use an absolute working directory.")
|
|
14649
|
+
}).strict();
|
|
14650
|
+
var credentialEnvSchema = z10.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
|
|
14651
|
+
var registrationSchema = z10.object({
|
|
14652
|
+
holderPid: z10.number().int().positive(),
|
|
14653
|
+
gateway: gatewaySchema,
|
|
14654
|
+
credential: z10.string().min(1).max(64000).refine((value) => !/[\x00-\x1f\x7f]/.test(value), "Credential contains control characters.").optional(),
|
|
14655
|
+
credentialEnv: credentialEnvSchema.optional(),
|
|
14656
|
+
stateDir: z10.string().max(4096).optional()
|
|
14657
|
+
}).strict();
|
|
14658
|
+
var holderSchema = z10.object({ pid: z10.number().int().positive(), start: z10.string().min(1).max(200) }).strict();
|
|
14659
|
+
var credentialSourceSchema = z10.discriminatedUnion("source", [
|
|
14660
|
+
z10.object({ source: z10.literal("none") }).strict(),
|
|
14661
|
+
z10.object({ source: z10.literal("ephemeral"), credentialEnv: credentialEnvSchema.optional() }).strict(),
|
|
14662
|
+
z10.object({ source: z10.literal("binding"), credentialEnv: credentialEnvSchema, bindingDigest: z10.string().regex(/^[a-f0-9]{64}$/) }).strict()
|
|
14663
|
+
]);
|
|
14664
|
+
var staticSchema = z10.object({
|
|
14665
|
+
schema: z10.literal(1),
|
|
14666
|
+
id: z10.string().uuid(),
|
|
14667
|
+
tokenDigest: z10.string().regex(/^[a-f0-9]{64}$/),
|
|
14668
|
+
createdAt: z10.number(),
|
|
14669
|
+
launcherPid: z10.number().int().positive(),
|
|
14670
|
+
gateway: gatewaySchema,
|
|
14671
|
+
credential: credentialSourceSchema,
|
|
14672
|
+
stateDir: z10.string().max(4096).optional()
|
|
14673
|
+
}).strict();
|
|
14674
|
+
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();
|
|
14675
|
+
var processKey = (entry) => `${entry.pid}@${entry.start}`;
|
|
14676
|
+
var SETTLED_MS = 120000;
|
|
14677
|
+
var SETTLED_SCAN_FACTOR = 5;
|
|
14678
|
+
var staticFields = (record3) => {
|
|
14679
|
+
const { lastUsedAt: _used, lastHolderAt: _holder, released: _released, holders: _holders, extendedAt: _extended, ...rest } = record3;
|
|
14680
|
+
return rest;
|
|
14681
|
+
};
|
|
14682
|
+
var holderFields = (record3) => ({ lastUsedAt: record3.lastUsedAt, lastHolderAt: record3.lastHolderAt, released: record3.released, holders: record3.holders, ...record3.extendedAt !== undefined ? { extendedAt: record3.extendedAt } : {} });
|
|
14683
|
+
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.";
|
|
14684
|
+
var loopbackHosts = (port) => new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
|
|
14685
|
+
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 });
|
|
14686
|
+
var presented = (request) => request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
|
|
14687
|
+
async function liveGateway(socket) {
|
|
14688
|
+
try {
|
|
14689
|
+
const response = await fetch("http://switcher-gateway/v1/status", { unix: socket, signal: AbortSignal.timeout(1500) });
|
|
14690
|
+
const body2 = await response.json();
|
|
14691
|
+
return response.ok && body2.service === "switcher-gateway";
|
|
14692
|
+
} catch {
|
|
14693
|
+
return false;
|
|
14694
|
+
}
|
|
14695
|
+
}
|
|
14696
|
+
async function readPrivateJson(path) {
|
|
14697
|
+
const file = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
|
|
14698
|
+
try {
|
|
14699
|
+
const info2 = await file.stat();
|
|
14700
|
+
if (!info2.isFile() || info2.size > 128 * 1024 * 1024 || (info2.mode & 63) !== 0 || info2.uid !== process.getuid?.())
|
|
14701
|
+
throw new Error("unsafe launch record");
|
|
14702
|
+
return JSON.parse(await file.readFile("utf8"));
|
|
14703
|
+
} finally {
|
|
14704
|
+
await file.close();
|
|
14705
|
+
}
|
|
14706
|
+
}
|
|
14707
|
+
async function readRecord(directory, id2) {
|
|
14708
|
+
const fixed = staticSchema.parse(await readPrivateJson(join22(directory, `${id2}.json`)));
|
|
14709
|
+
if (fixed.id !== id2)
|
|
14710
|
+
throw new Error("launch record id mismatch");
|
|
14711
|
+
const state = await readPrivateJson(join22(directory, `${id2}.holders.json`)).then((value) => holderStateSchema.parse(value), () => {
|
|
14712
|
+
return;
|
|
14713
|
+
});
|
|
14714
|
+
return { ...fixed, ...state ?? { lastUsedAt: fixed.createdAt, lastHolderAt: fixed.createdAt, released: false, holders: [] } };
|
|
14715
|
+
}
|
|
14716
|
+
async function writePrivate(path, text) {
|
|
14717
|
+
const temporary = `${path}.${randomUUID7()}.tmp`;
|
|
14718
|
+
const file = await open7(temporary, "wx", 384);
|
|
14719
|
+
try {
|
|
14720
|
+
await file.writeFile(text);
|
|
14721
|
+
await file.sync();
|
|
14722
|
+
} finally {
|
|
14723
|
+
await file.close();
|
|
14724
|
+
}
|
|
14725
|
+
await rename4(temporary, path);
|
|
14726
|
+
}
|
|
14727
|
+
async function launchStateDirectory(path) {
|
|
14728
|
+
if (path === undefined)
|
|
14729
|
+
return;
|
|
14730
|
+
if (!isAbsolute17(path) || resolve13(path) !== path || !/^launch-[A-Za-z0-9]{6}$/.test(basename4(path)))
|
|
14731
|
+
throw new Fault(400, "invalid_state_dir", "The launch state directory must be an absolute launch-XXXXXX directory.");
|
|
14732
|
+
const info2 = await lstat10(path).catch(() => {
|
|
14733
|
+
return;
|
|
14734
|
+
});
|
|
14735
|
+
if (!info2?.isDirectory() || info2.isSymbolicLink() || info2.uid !== process.getuid?.() || (info2.mode & 63) !== 0)
|
|
14736
|
+
throw new Fault(400, "invalid_state_dir", "The launch state directory must be a private directory owned by this user.");
|
|
14737
|
+
return path;
|
|
14738
|
+
}
|
|
14739
|
+
async function startGatewayService(options = {}) {
|
|
14740
|
+
if (process.platform === "win32")
|
|
14741
|
+
throw new Fault(422, "gateway_unsupported", "The persistent Switcher gateway supports macOS and Linux.");
|
|
14742
|
+
const env = options.env ?? process.env;
|
|
14743
|
+
const settings2 = gatewaySettings(env);
|
|
14744
|
+
const paths = gatewayPaths(env);
|
|
14745
|
+
const now = options.now ?? Date.now;
|
|
14746
|
+
const graceMs = options.graceMs ?? settings2.graceMs, scanMs = options.scanMs ?? settings2.scanMs;
|
|
14747
|
+
const processTable = options.processTable ?? readProcessTable;
|
|
14748
|
+
const environmentProbe = options.environmentProbe ?? processesHoldingTokenDigest;
|
|
14749
|
+
const log = options.log ?? ((line) => console.error(`switcher-gateway ${new Date().toISOString()} ${line}`));
|
|
14750
|
+
const resolver = new CredentialResolver(env);
|
|
14751
|
+
const resolveCredential2 = options.resolveCredential ?? ((provider) => resolver.resolve(provider));
|
|
14752
|
+
const bindings = new CredentialBindings(env);
|
|
14753
|
+
await privateDirectory(switcherHome(env));
|
|
14754
|
+
await privateDirectory(paths.root);
|
|
14755
|
+
await privateDirectory(paths.launches);
|
|
14756
|
+
await socketDirectory(paths);
|
|
14757
|
+
let persisted = {};
|
|
14758
|
+
try {
|
|
14759
|
+
const config = await Bun.file(paths.config).json();
|
|
14760
|
+
if (Number.isSafeInteger(config.port))
|
|
14761
|
+
persisted = { port: config.port };
|
|
14762
|
+
} catch {}
|
|
14763
|
+
const requestedPort = options.port ?? settings2.port ?? persisted.port ?? (isDefaultSwitcherHome(env) ? defaultGatewayPort() : 0);
|
|
14764
|
+
const launches = new Map, byDigest = new Map;
|
|
14765
|
+
let closing = false, stopping, resolveClosed, idleSince = now();
|
|
14766
|
+
const closed = new Promise((resolve14) => {
|
|
14767
|
+
resolveClosed = resolve14;
|
|
14768
|
+
});
|
|
14769
|
+
const persist = async (launch, force = false) => {
|
|
14770
|
+
if (!force && !launch.dirty)
|
|
14771
|
+
return;
|
|
14772
|
+
launch.dirty = false;
|
|
14773
|
+
launch.persistedAt = now();
|
|
14774
|
+
if (!launches.has(launch.record.id))
|
|
14775
|
+
return;
|
|
14776
|
+
await writePrivate(join22(paths.launches, `${launch.record.id}.holders.json`), JSON.stringify(holderFields(launch.record))).catch(() => {
|
|
14777
|
+
launch.dirty = true;
|
|
14778
|
+
});
|
|
14779
|
+
};
|
|
14780
|
+
const credentialFor = (launch) => async () => {
|
|
14781
|
+
if (launch.credential !== undefined)
|
|
14782
|
+
return launch.credential;
|
|
14783
|
+
const source = launch.record.credential;
|
|
14784
|
+
if (source.source === "none")
|
|
14785
|
+
return;
|
|
14786
|
+
if (source.source === "ephemeral") {
|
|
14787
|
+
const reference2 = source.credentialEnv ?? "SWITCHER_PROVIDER_<NAME>";
|
|
14788
|
+
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>\`.`);
|
|
14789
|
+
}
|
|
14790
|
+
return launch.pending ??= (async () => {
|
|
14791
|
+
try {
|
|
14792
|
+
const binding = await bindings.get(source.credentialEnv);
|
|
14793
|
+
if (!binding || sha256(JSON.stringify(binding)) !== source.bindingDigest)
|
|
14794
|
+
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}`);
|
|
14795
|
+
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 };
|
|
14796
|
+
let value;
|
|
14797
|
+
try {
|
|
14798
|
+
value = await resolveCredential2(provider);
|
|
14799
|
+
} catch (error) {
|
|
14800
|
+
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.`);
|
|
14801
|
+
}
|
|
14802
|
+
if (!value)
|
|
14803
|
+
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.`);
|
|
14804
|
+
launch.credential = value;
|
|
14805
|
+
return value;
|
|
14806
|
+
} finally {
|
|
14807
|
+
launch.pending = undefined;
|
|
14808
|
+
}
|
|
14809
|
+
})();
|
|
14810
|
+
};
|
|
14811
|
+
const handlerFor = (launch) => createInferenceHandler({
|
|
14812
|
+
...launch.record.gateway,
|
|
14813
|
+
compiledPolicy: compiledPolicy(launch.record.gateway.compiledPolicy),
|
|
14814
|
+
stateDir: launch.record.stateDir ?? paths.root,
|
|
14815
|
+
credential: undefined,
|
|
14816
|
+
onRoutingEvent: (event) => {
|
|
14817
|
+
if (launch.record.released)
|
|
14818
|
+
return;
|
|
14819
|
+
const bytes = Buffer.byteLength(JSON.stringify(event));
|
|
14820
|
+
if (launch.events.length < MAX_EVENTS && launch.eventBytes + bytes <= MAX_EVENT_BYTES) {
|
|
14821
|
+
launch.events.push(event);
|
|
14822
|
+
launch.eventBytes += bytes;
|
|
14823
|
+
} else
|
|
14824
|
+
launch.eventsDropped = Math.min(1e6, launch.eventsDropped + 1);
|
|
14825
|
+
}
|
|
14826
|
+
}, options.timing, { credential: () => credentialFor(launch)() });
|
|
14827
|
+
const adopt = (record3, credential) => {
|
|
14828
|
+
const launch = { record: record3, credential, events: [], eventBytes: 0, eventsDropped: 0, dirty: false, persistedAt: 0, usedPersistedAt: 0, recentAt: now() };
|
|
14829
|
+
launch.handler = handlerFor(launch);
|
|
14830
|
+
launches.set(record3.id, launch);
|
|
14831
|
+
byDigest.set(record3.tokenDigest, launch);
|
|
14832
|
+
return launch;
|
|
14833
|
+
};
|
|
14834
|
+
const remove = async (launch, reason, removeState) => {
|
|
14835
|
+
if (!launches.delete(launch.record.id))
|
|
14836
|
+
return;
|
|
14837
|
+
byDigest.delete(launch.record.tokenDigest);
|
|
14838
|
+
launch.credential = undefined;
|
|
14839
|
+
await launch.handler.close().catch(() => {
|
|
14840
|
+
return;
|
|
14841
|
+
});
|
|
14842
|
+
await rm5(join22(paths.launches, `${launch.record.id}.holders.json`), { force: true }).catch(() => {
|
|
14843
|
+
return;
|
|
14844
|
+
});
|
|
14845
|
+
await rm5(join22(paths.launches, `${launch.record.id}.json`), { force: true }).catch(() => {
|
|
14846
|
+
return;
|
|
14847
|
+
});
|
|
14848
|
+
if (removeState && launch.record.stateDir) {
|
|
14849
|
+
const directory = await launchStateDirectory(launch.record.stateDir).catch(() => {
|
|
14850
|
+
return;
|
|
14851
|
+
});
|
|
14852
|
+
if (directory)
|
|
14853
|
+
await rm5(directory, { recursive: true, force: true }).catch(() => {
|
|
14854
|
+
return;
|
|
14855
|
+
});
|
|
14856
|
+
}
|
|
14857
|
+
log(`launch ${launch.record.id.slice(0, 8)} ${reason}`);
|
|
14858
|
+
if (!launches.size)
|
|
14859
|
+
idleSince = now();
|
|
14860
|
+
};
|
|
14861
|
+
const liveHolders = (launch, table) => launch.record.holders.filter((holder) => table.get(holder.pid)?.start === holder.start);
|
|
14862
|
+
const track = (launch, table, at) => {
|
|
14863
|
+
const live = liveHolders(launch, table);
|
|
14864
|
+
const next = new Map(live.map((holder) => [holder.pid, holder]));
|
|
14865
|
+
for (const entry of descendants(table, live.map((holder) => holder.pid), [process.pid]))
|
|
14866
|
+
if (!next.has(entry.pid) && next.size < MAX_HOLDERS)
|
|
14867
|
+
next.set(entry.pid, { pid: entry.pid, start: entry.start });
|
|
14868
|
+
const key = (holders) => [...holders].map((holder) => `${holder.pid}@${holder.start}`).sort().join("|");
|
|
14869
|
+
const changed = key(next.values()) !== key(launch.record.holders);
|
|
14870
|
+
launch.record.holders = [...next.values()];
|
|
14871
|
+
if (next.size)
|
|
14872
|
+
launch.record.lastHolderAt = at;
|
|
14873
|
+
if (changed)
|
|
14874
|
+
launch.dirty = true;
|
|
14875
|
+
};
|
|
14876
|
+
const adoptOrphans = async (launch, table) => {
|
|
14877
|
+
const baseline = launch.orphanBaseline;
|
|
14878
|
+
if (!baseline)
|
|
14879
|
+
return;
|
|
14880
|
+
launch.orphanBaseline = undefined;
|
|
14881
|
+
const known = new Set(launch.record.holders.map(processKey));
|
|
14882
|
+
const candidates = [...table.values()].filter((entry) => entry.pid !== process.pid && isOrphan(entry, table) && !baseline.has(processKey(entry)) && !known.has(processKey(entry)));
|
|
14883
|
+
if (!candidates.length)
|
|
14884
|
+
return;
|
|
14885
|
+
let found;
|
|
14886
|
+
try {
|
|
14887
|
+
found = await environmentProbe(candidates.slice(-MAX_ORPHAN_CANDIDATES).map((entry) => entry.pid), launch.record.tokenDigest);
|
|
14888
|
+
} catch {
|
|
14889
|
+
return;
|
|
14890
|
+
}
|
|
14891
|
+
let adopted = 0;
|
|
14892
|
+
for (const pid of new Set(found)) {
|
|
14893
|
+
const entry = table.get(pid);
|
|
14894
|
+
if (!entry || known.has(processKey(entry)) || launch.record.holders.length >= MAX_HOLDERS)
|
|
14895
|
+
continue;
|
|
14896
|
+
launch.record.holders.push({ pid, start: entry.start });
|
|
14897
|
+
known.add(processKey(entry));
|
|
14898
|
+
adopted++;
|
|
14899
|
+
}
|
|
14900
|
+
if (!adopted)
|
|
14901
|
+
return;
|
|
14902
|
+
launch.dirty = true;
|
|
14903
|
+
log(`launch ${launch.record.id.slice(0, 8)} adopted ${adopted} detached process(es) started with its token`);
|
|
14904
|
+
};
|
|
14905
|
+
const launcherGone = (launch) => !launch.record.holders.some((holder) => holder.pid === launch.record.launcherPid);
|
|
14906
|
+
let scanning;
|
|
14907
|
+
const runScan = async () => {
|
|
14908
|
+
if (!launches.size)
|
|
14909
|
+
return;
|
|
14910
|
+
let table;
|
|
14911
|
+
try {
|
|
14912
|
+
table = await processTable();
|
|
14913
|
+
} catch {
|
|
14914
|
+
return;
|
|
14915
|
+
}
|
|
14916
|
+
const at = now();
|
|
14917
|
+
for (const launch of [...launches.values()]) {
|
|
14918
|
+
track(launch, table, at);
|
|
14919
|
+
if (launch.orphanBaseline && launcherGone(launch)) {
|
|
14920
|
+
await adoptOrphans(launch, table);
|
|
14921
|
+
track(launch, table, at);
|
|
14922
|
+
}
|
|
14923
|
+
if (!launch.record.holders.length && at - Math.max(launch.record.lastHolderAt, launch.record.lastUsedAt) > graceMs)
|
|
14924
|
+
await remove(launch, "expired: no process holds it", true);
|
|
14925
|
+
else if (launch.dirty && at - launch.persistedAt >= PERSIST_INTERVAL_MS)
|
|
14926
|
+
await persist(launch);
|
|
14927
|
+
}
|
|
14928
|
+
};
|
|
14929
|
+
const scan = () => scanning ??= runScan().finally(() => {
|
|
14930
|
+
scanning = undefined;
|
|
14931
|
+
});
|
|
14932
|
+
let inference;
|
|
14933
|
+
try {
|
|
14934
|
+
inference = Bun.serve({ hostname: "127.0.0.1", port: requestedPort, maxRequestBodySize: MAX_REQUEST_BODY_BYTES, idleTimeout: 255, async fetch(request, server) {
|
|
14935
|
+
const host2 = request.headers.get("host")?.toLowerCase();
|
|
14936
|
+
if (host2 !== undefined && !loopbackHosts(server.port).has(host2))
|
|
14937
|
+
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.`);
|
|
14938
|
+
const url2 = new URL(request.url);
|
|
14939
|
+
if (request.method === "GET" && url2.pathname === "/health")
|
|
14940
|
+
return Response.json({ status: "ok", service: "switcher-gateway", protocol: GATEWAY_PROTOCOL });
|
|
14941
|
+
if (closing)
|
|
14942
|
+
return errorBody(503, "switcher_gateway_stopping", `Switcher gateway is restarting. Retry in a few seconds; if this persists, run \`switcher gateway status\`.`);
|
|
14943
|
+
const token = presented(request);
|
|
14944
|
+
if (!token)
|
|
14945
|
+
return errorBody(401, "switcher_gateway_token_missing", `Switcher gateway: the request carries no launch token. ${LAUNCH_HINT}`);
|
|
14946
|
+
const launch = byDigest.get(sha256(token));
|
|
14947
|
+
if (!launch)
|
|
14948
|
+
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}`);
|
|
14949
|
+
const at = now();
|
|
14950
|
+
launch.record.lastUsedAt = at;
|
|
14951
|
+
if (at - launch.usedPersistedAt >= USE_PERSIST_INTERVAL_MS) {
|
|
14952
|
+
launch.usedPersistedAt = at;
|
|
14953
|
+
launch.dirty = true;
|
|
14954
|
+
}
|
|
14955
|
+
return launch.handler.handle(request, server);
|
|
14956
|
+
} });
|
|
14957
|
+
} catch (error) {
|
|
14958
|
+
if (await liveGateway(paths.socket))
|
|
14959
|
+
throw new Fault(409, "gateway_running", "A Switcher gateway is already running for this home.");
|
|
14960
|
+
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.`);
|
|
14961
|
+
}
|
|
14962
|
+
const port = inference.port;
|
|
14963
|
+
const url = `http://127.0.0.1:${port}`;
|
|
14964
|
+
if (await liveGateway(paths.socket)) {
|
|
14965
|
+
await inference.stop(true);
|
|
14966
|
+
throw new Fault(409, "gateway_running", "A Switcher gateway is already running for this home.");
|
|
14967
|
+
}
|
|
14968
|
+
await unlink3(paths.socket).catch((error) => {
|
|
14969
|
+
if (error.code !== "ENOENT")
|
|
14970
|
+
throw error;
|
|
14971
|
+
});
|
|
14972
|
+
if (persisted.port !== port)
|
|
14973
|
+
await writePrivate(paths.config, JSON.stringify({ port }) + `
|
|
14974
|
+
`);
|
|
14975
|
+
const json = async (request) => {
|
|
14976
|
+
try {
|
|
14977
|
+
return await request.json();
|
|
14978
|
+
} catch {
|
|
14979
|
+
throw new Fault(400, "invalid_json", "The control request must be JSON.");
|
|
14980
|
+
}
|
|
14981
|
+
};
|
|
14982
|
+
const launchFor = (id2) => {
|
|
14983
|
+
const launch = launches.get(id2);
|
|
14984
|
+
if (!launch)
|
|
14985
|
+
throw new Fault(404, "launch_not_found", "No such launch is registered with the gateway.");
|
|
14986
|
+
return launch;
|
|
14987
|
+
};
|
|
14988
|
+
const register = async (input) => {
|
|
14989
|
+
const table = await processTable();
|
|
14990
|
+
const holder = table.get(input.holderPid);
|
|
14991
|
+
if (!holder)
|
|
14992
|
+
throw new Fault(400, "holder_not_running", "The registering process is not running.");
|
|
14993
|
+
const stateDir = await launchStateDirectory(input.stateDir);
|
|
14994
|
+
const policy = compiledPolicy(input.gateway.compiledPolicy);
|
|
14995
|
+
if (policy.model !== input.gateway.model)
|
|
14996
|
+
throw new Fault(400, "invalid_request", "The compiled policy does not belong to the selected model.");
|
|
14997
|
+
let credential = { source: "none" };
|
|
14998
|
+
if (input.credential !== undefined) {
|
|
14999
|
+
credential = { source: "ephemeral", ...input.credentialEnv ? { credentialEnv: input.credentialEnv } : {} };
|
|
15000
|
+
if (input.credentialEnv) {
|
|
15001
|
+
const binding = await bindings.get(input.credentialEnv).catch(() => {
|
|
15002
|
+
return;
|
|
15003
|
+
});
|
|
15004
|
+
if (binding && binding.origins.includes(new URL(input.gateway.baseUrl).origin))
|
|
15005
|
+
credential = { source: "binding", credentialEnv: input.credentialEnv, bindingDigest: sha256(JSON.stringify(binding)) };
|
|
15006
|
+
}
|
|
15007
|
+
}
|
|
15008
|
+
const token = randomBytes2(32).toString("base64url"), at = now();
|
|
15009
|
+
const record3 = {
|
|
15010
|
+
schema: 1,
|
|
15011
|
+
id: randomUUID7(),
|
|
15012
|
+
tokenDigest: sha256(token),
|
|
15013
|
+
createdAt: at,
|
|
15014
|
+
lastUsedAt: at,
|
|
15015
|
+
lastHolderAt: at,
|
|
15016
|
+
launcherPid: holder.pid,
|
|
15017
|
+
released: false,
|
|
15018
|
+
holders: [{ pid: holder.pid, start: holder.start }],
|
|
15019
|
+
gateway: { ...input.gateway, compiledPolicy: policy },
|
|
15020
|
+
credential,
|
|
15021
|
+
...stateDir ? { stateDir } : {}
|
|
15022
|
+
};
|
|
15023
|
+
const launch = adopt(record3, input.credential);
|
|
15024
|
+
launch.orphanBaseline = new Set([...table.values()].filter((entry) => isOrphan(entry, table)).map(processKey));
|
|
15025
|
+
await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
|
|
15026
|
+
await persist(launch, true);
|
|
15027
|
+
log(`launch ${record3.id.slice(0, 8)} registered (${record3.gateway.harness}, ${record3.gateway.model})`);
|
|
15028
|
+
return { id: record3.id, token, baseUrl: `${url}/${record3.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}` };
|
|
15029
|
+
};
|
|
15030
|
+
const release = async (launch) => {
|
|
15031
|
+
const table = await processTable().catch(() => {
|
|
15032
|
+
return;
|
|
15033
|
+
});
|
|
15034
|
+
if (table) {
|
|
15035
|
+
track(launch, table, now());
|
|
15036
|
+
await adoptOrphans(launch, table);
|
|
15037
|
+
track(launch, table, now());
|
|
15038
|
+
}
|
|
15039
|
+
const others = table ? liveHolders(launch, table).filter((holder) => holder.pid !== launch.record.launcherPid) : launch.record.holders;
|
|
15040
|
+
const { events, eventsDropped } = launch;
|
|
15041
|
+
launch.events = [];
|
|
15042
|
+
launch.eventBytes = 0;
|
|
15043
|
+
if (!others.length) {
|
|
15044
|
+
await remove(launch, "revoked: launch ended", false);
|
|
15045
|
+
return { retained: false, holders: 0, events, eventsDropped };
|
|
15046
|
+
}
|
|
15047
|
+
launch.record.released = true;
|
|
15048
|
+
await persist(launch, true);
|
|
15049
|
+
log(`launch ${launch.record.id.slice(0, 8)} released; ${others.length} process(es) still hold it`);
|
|
15050
|
+
return { retained: true, holders: others.length, events, eventsDropped };
|
|
15051
|
+
};
|
|
15052
|
+
const control = async (request) => {
|
|
15053
|
+
const url2 = new URL(request.url), method = request.method, parts = url2.pathname.split("/").filter(Boolean);
|
|
15054
|
+
try {
|
|
15055
|
+
if (method === "GET" && url2.pathname === "/v1/status")
|
|
15056
|
+
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" });
|
|
15057
|
+
if (method === "GET" && url2.pathname === "/v1/launches")
|
|
15058
|
+
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 })) });
|
|
15059
|
+
if (method === "POST" && url2.pathname === "/v1/launches")
|
|
15060
|
+
return Response.json(await register(registrationSchema.parse(await json(request))), { status: 201 });
|
|
15061
|
+
if (method === "POST" && url2.pathname === "/v1/stop") {
|
|
15062
|
+
setTimeout(() => void close(), 10);
|
|
15063
|
+
return Response.json({ stopping: true });
|
|
15064
|
+
}
|
|
15065
|
+
if (parts.length >= 3 && parts[0] === "v1" && parts[1] === "launches") {
|
|
15066
|
+
const launch = launchFor(parts[2]);
|
|
15067
|
+
if (method === "DELETE" && parts.length === 3) {
|
|
15068
|
+
await remove(launch, "revoked by its launcher", false);
|
|
15069
|
+
return Response.json({ revoked: true });
|
|
15070
|
+
}
|
|
15071
|
+
if (method === "POST" && parts[3] === "holders" && parts.length === 4) {
|
|
15072
|
+
const { pid } = z10.object({ pid: z10.number().int().positive() }).strict().parse(await json(request));
|
|
15073
|
+
const table = await processTable();
|
|
15074
|
+
const entry = table.get(pid);
|
|
15075
|
+
if (entry && !launch.record.holders.some((holder) => holder.pid === pid && holder.start === entry.start) && launch.record.holders.length < MAX_HOLDERS)
|
|
15076
|
+
launch.record.holders.push({ pid, start: entry.start });
|
|
15077
|
+
track(launch, table, now());
|
|
15078
|
+
launch.recentAt = now();
|
|
15079
|
+
await persist(launch, true);
|
|
15080
|
+
return Response.json({ holders: launch.record.holders.length });
|
|
15081
|
+
}
|
|
15082
|
+
if (method === "POST" && parts[3] === "release" && parts.length === 4)
|
|
15083
|
+
return Response.json(await release(launch));
|
|
15084
|
+
}
|
|
15085
|
+
return errorBody(404, "unsupported_route", "Unsupported gateway control route.");
|
|
15086
|
+
} catch (error) {
|
|
15087
|
+
if (error instanceof z10.ZodError)
|
|
15088
|
+
return errorBody(400, "invalid_request", error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ").slice(0, 1000));
|
|
15089
|
+
if (error instanceof Fault)
|
|
15090
|
+
return errorBody(error.status, error.code, error.message);
|
|
15091
|
+
return errorBody(500, "gateway_error", "The gateway could not complete the control request.");
|
|
15092
|
+
}
|
|
15093
|
+
};
|
|
15094
|
+
const controlServer = Bun.serve({ unix: paths.socket, maxRequestBodySize: 256 * 1024 * 1024, fetch: control });
|
|
15095
|
+
await chmod3(paths.socket, 384);
|
|
15096
|
+
const restoredAt = now();
|
|
15097
|
+
for (const name of await readdir7(paths.launches)) {
|
|
15098
|
+
if (!/^[0-9a-f-]{36}\.json$/.test(name))
|
|
15099
|
+
continue;
|
|
15100
|
+
try {
|
|
15101
|
+
const record3 = await readRecord(paths.launches, name.slice(0, -5));
|
|
15102
|
+
const extend = record3.extendedAt === undefined || Math.max(record3.lastHolderAt, record3.lastUsedAt) > record3.extendedAt;
|
|
15103
|
+
if (extend) {
|
|
15104
|
+
record3.lastHolderAt = Math.max(record3.lastHolderAt, restoredAt);
|
|
15105
|
+
record3.extendedAt = restoredAt;
|
|
15106
|
+
}
|
|
15107
|
+
const launch = adopt(record3);
|
|
15108
|
+
if (extend)
|
|
15109
|
+
await persist(launch, true);
|
|
15110
|
+
} catch {
|
|
15111
|
+
log(`ignored unreadable launch record ${name.slice(0, 8)}`);
|
|
15112
|
+
}
|
|
15113
|
+
}
|
|
15114
|
+
log(`listening on ${url} (pid ${process.pid}, version ${VERSION}, ${launches.size} launch(es) restored)`);
|
|
15115
|
+
await scan();
|
|
15116
|
+
let tick = 0;
|
|
15117
|
+
const timer = setInterval(() => {
|
|
15118
|
+
tick++;
|
|
15119
|
+
const at = now(), settled = [...launches.values()].every((launch) => at - launch.recentAt > SETTLED_MS);
|
|
15120
|
+
(settled && tick % SETTLED_SCAN_FACTOR ? Promise.resolve() : scan()).then(() => {
|
|
15121
|
+
if (options.exitWhenIdleMs !== undefined && !launches.size && now() - idleSince >= options.exitWhenIdleMs) {
|
|
15122
|
+
log("exiting: no launches");
|
|
15123
|
+
close();
|
|
15124
|
+
}
|
|
15125
|
+
});
|
|
15126
|
+
}, scanMs);
|
|
15127
|
+
const close = () => stopping ??= (async () => {
|
|
15128
|
+
closing = true;
|
|
15129
|
+
clearInterval(timer);
|
|
15130
|
+
await scanning?.catch(() => {
|
|
15131
|
+
return;
|
|
15132
|
+
});
|
|
15133
|
+
for (const launch of launches.values())
|
|
15134
|
+
await persist(launch, true);
|
|
15135
|
+
await Promise.allSettled([...launches.values()].map((launch) => launch.handler.close()));
|
|
15136
|
+
await inference.stop(true);
|
|
15137
|
+
await controlServer.stop(true);
|
|
15138
|
+
await unlink3(paths.socket).catch(() => {
|
|
15139
|
+
return;
|
|
15140
|
+
});
|
|
15141
|
+
log("stopped");
|
|
15142
|
+
resolveClosed();
|
|
15143
|
+
})();
|
|
15144
|
+
return { url, port, socket: paths.socket, pid: process.pid, close, closed, scan };
|
|
15145
|
+
}
|
|
15146
|
+
|
|
15147
|
+
// src/gateway-supervisor.ts
|
|
15148
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
15149
|
+
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";
|
|
15150
|
+
import { dirname as dirname10, isAbsolute as isAbsolute18, join as join23 } from "path";
|
|
15151
|
+
var LAUNCHD_LABEL = "com.hasna.switcher.gateway";
|
|
15152
|
+
var SYSTEMD_UNIT = "switcher-gateway.service";
|
|
15153
|
+
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)$/;
|
|
15154
|
+
function serviceEnvironment(env = process.env) {
|
|
15155
|
+
return Object.fromEntries(Object.entries(env).filter((entry) => SERVICE_ENV.test(entry[0]) && typeof entry[1] === "string" && !/[\x00-\x1f\x7f]/.test(entry[1])));
|
|
15156
|
+
}
|
|
15157
|
+
function unitEnvironment(env = process.env) {
|
|
15158
|
+
const { TMPDIR: _temporary, ...rest } = serviceEnvironment(env);
|
|
15159
|
+
return rest;
|
|
15160
|
+
}
|
|
15161
|
+
var TEMPORARY_ROOTS = ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp", "/dev/shm"];
|
|
15162
|
+
async function assertSafeServiceCommand(command, temporaryRoots = TEMPORARY_ROOTS) {
|
|
15163
|
+
checkCommand(command);
|
|
15164
|
+
const uid = process.getuid?.();
|
|
15165
|
+
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\`.`);
|
|
15166
|
+
for (const path of command) {
|
|
15167
|
+
const real = await realpath7(path).catch(() => {
|
|
15168
|
+
throw refuse(path, "it does not exist");
|
|
15169
|
+
});
|
|
15170
|
+
for (const candidate of new Set([real, path])) {
|
|
15171
|
+
if (temporaryRoots.some((root) => candidate === root || candidate.startsWith(`${root}/`)))
|
|
15172
|
+
throw refuse(path, `${candidate} is under a temporary directory`);
|
|
15173
|
+
for (let current = candidate;; current = dirname10(current)) {
|
|
15174
|
+
const info2 = await lstat11(current).catch(() => {
|
|
15175
|
+
throw refuse(path, `${current} could not be checked`);
|
|
15176
|
+
});
|
|
15177
|
+
if (!info2.isSymbolicLink()) {
|
|
15178
|
+
if (info2.uid !== uid && info2.uid !== 0)
|
|
15179
|
+
throw refuse(path, `${current} is owned by another account`);
|
|
15180
|
+
if ((info2.mode & 18) !== 0)
|
|
15181
|
+
throw refuse(path, `${current} is writable by other accounts`);
|
|
15182
|
+
}
|
|
15183
|
+
if (current === dirname10(current))
|
|
15184
|
+
break;
|
|
15185
|
+
}
|
|
15186
|
+
}
|
|
15187
|
+
}
|
|
15188
|
+
}
|
|
15189
|
+
function supervisorFor(env = process.env, platform = process.platform, home = accountHome()) {
|
|
15190
|
+
const requested = env.SWITCHER_GATEWAY_SUPERVISOR?.trim() || "auto";
|
|
15191
|
+
if (!["auto", "none"].includes(requested))
|
|
15192
|
+
throw new Fault(400, "invalid_gateway_setting", "SWITCHER_GATEWAY_SUPERVISOR must be auto or none.");
|
|
15193
|
+
if (requested === "none" || !isDefaultSwitcherHome(env, home))
|
|
15194
|
+
return "none";
|
|
15195
|
+
return platform === "darwin" ? "launchd" : platform === "linux" ? "systemd" : "none";
|
|
15196
|
+
}
|
|
15197
|
+
function launchdLogPath(home) {
|
|
15198
|
+
return join23(home, "Library", "Logs", "Hasna", "switcher-gateway.log");
|
|
15199
|
+
}
|
|
15200
|
+
function requireHome(home) {
|
|
15201
|
+
if (!home)
|
|
15202
|
+
throw new Fault(422, "gateway_supervisor_unavailable", "The account home could not be read from the user database, so no login supervisor is used.");
|
|
15203
|
+
return home;
|
|
15204
|
+
}
|
|
15205
|
+
function unitPath(supervisor, env = process.env, home = requireHome(accountHome())) {
|
|
15206
|
+
if (supervisor === "launchd")
|
|
15207
|
+
return join23(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
|
|
15208
|
+
const config = env.XDG_CONFIG_HOME && isAbsolute18(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join23(home, ".config");
|
|
15209
|
+
return join23(config, "systemd", "user", SYSTEMD_UNIT);
|
|
15210
|
+
}
|
|
15211
|
+
function checkCommand(command) {
|
|
15212
|
+
if (command.length < 2 || !command.every((part) => isAbsolute18(part) && !/[\x00-\x1f\x7f"\\%$`]/.test(part)))
|
|
15213
|
+
throw new Fault(400, "invalid_gateway_command", "The gateway service command must be absolute paths without quotes, backslashes, $, % or control characters.");
|
|
15214
|
+
}
|
|
15215
|
+
var xml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
15216
|
+
function renderLaunchdPlist(command, env = process.env, home = requireHome(accountHome())) {
|
|
15217
|
+
checkCommand(command);
|
|
15218
|
+
const log = launchdLogPath(home);
|
|
15219
|
+
const variables = { ...unitEnvironment(env), SWITCHER_GATEWAY_SUPERVISED: "launchd" };
|
|
15220
|
+
const strings2 = (values2) => values2.map((value) => ` <string>${xml(value)}</string>`).join(`
|
|
15221
|
+
`);
|
|
15222
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
15223
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
15224
|
+
<plist version="1.0">
|
|
15225
|
+
<dict>
|
|
15226
|
+
<key>Label</key>
|
|
15227
|
+
<string>${LAUNCHD_LABEL}</string>
|
|
15228
|
+
<key>ProgramArguments</key>
|
|
15229
|
+
<array>
|
|
15230
|
+
${strings2([...command, "gateway", "run"])}
|
|
15231
|
+
</array>
|
|
15232
|
+
<key>EnvironmentVariables</key>
|
|
15233
|
+
<dict>
|
|
15234
|
+
${Object.entries(variables).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => ` <key>${xml(key)}</key>
|
|
15235
|
+
<string>${xml(value)}</string>`).join(`
|
|
15236
|
+
`)}
|
|
15237
|
+
</dict>
|
|
15238
|
+
<key>LimitLoadToSessionType</key>
|
|
15239
|
+
<array>
|
|
15240
|
+
<string>Aqua</string>
|
|
15241
|
+
<string>Background</string>
|
|
15242
|
+
</array>
|
|
15243
|
+
<key>RunAtLoad</key>
|
|
15244
|
+
<true/>
|
|
15245
|
+
<key>KeepAlive</key>
|
|
15246
|
+
<dict>
|
|
15247
|
+
<key>SuccessfulExit</key>
|
|
15248
|
+
<false/>
|
|
15249
|
+
</dict>
|
|
15250
|
+
<key>ThrottleInterval</key>
|
|
15251
|
+
<integer>5</integer>
|
|
15252
|
+
<key>Umask</key>
|
|
15253
|
+
<integer>63</integer>
|
|
15254
|
+
<key>StandardOutPath</key>
|
|
15255
|
+
<string>${xml(log)}</string>
|
|
15256
|
+
<key>StandardErrorPath</key>
|
|
15257
|
+
<string>${xml(log)}</string>
|
|
15258
|
+
</dict>
|
|
15259
|
+
</plist>
|
|
15260
|
+
`;
|
|
15261
|
+
}
|
|
15262
|
+
function renderSystemdUnit(command, env = process.env) {
|
|
15263
|
+
checkCommand(command);
|
|
15264
|
+
const variables = { ...unitEnvironment(env), SWITCHER_GATEWAY_SUPERVISED: "systemd" };
|
|
15265
|
+
const quote3 = (value) => `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/%/g, "%%")}"`;
|
|
15266
|
+
return `[Unit]
|
|
15267
|
+
Description=Switcher inference gateway
|
|
15268
|
+
After=network.target
|
|
15269
|
+
|
|
15270
|
+
[Service]
|
|
15271
|
+
ExecStart=${[...command, "gateway", "run"].map(quote3).join(" ")}
|
|
15272
|
+
${Object.entries(variables).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `Environment=${quote3(`${key}=${value}`)}`).join(`
|
|
15273
|
+
`)}
|
|
15274
|
+
Restart=on-failure
|
|
15275
|
+
RestartSec=5
|
|
15276
|
+
|
|
15277
|
+
[Install]
|
|
15278
|
+
WantedBy=default.target
|
|
15279
|
+
`;
|
|
15280
|
+
}
|
|
15281
|
+
var defaultRunner = async (argv) => {
|
|
15282
|
+
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 ?? "" } });
|
|
15283
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), 15000);
|
|
15284
|
+
try {
|
|
15285
|
+
const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
|
|
15286
|
+
return { code, stdout: stdout.slice(0, 4096), stderr: stderr.slice(0, 4096) };
|
|
15287
|
+
} finally {
|
|
15288
|
+
clearTimeout(timer);
|
|
15289
|
+
}
|
|
15290
|
+
};
|
|
15291
|
+
async function writeUnit(path, content) {
|
|
15292
|
+
const previous = await readFile8(path, "utf8").catch(() => {
|
|
15293
|
+
return;
|
|
15294
|
+
});
|
|
15295
|
+
if (previous === content)
|
|
15296
|
+
return false;
|
|
15297
|
+
await mkdir13(dirname10(path), { recursive: true, mode: 493 });
|
|
15298
|
+
const temporary = `${path}.${randomUUID8()}.tmp`;
|
|
15299
|
+
const file = await open8(temporary, "wx", 420);
|
|
15300
|
+
try {
|
|
15301
|
+
await file.writeFile(content);
|
|
15302
|
+
await file.sync();
|
|
15303
|
+
} finally {
|
|
15304
|
+
await file.close();
|
|
15305
|
+
}
|
|
15306
|
+
await rename5(temporary, path);
|
|
15307
|
+
return true;
|
|
15308
|
+
}
|
|
15309
|
+
async function installGatewayService(options) {
|
|
15310
|
+
const env = options.env ?? process.env, runner = options.runner ?? defaultRunner, home = options.home ?? accountHome();
|
|
15311
|
+
const supervisor = options.supervisor ?? supervisorFor(env, process.platform, home);
|
|
15312
|
+
if (supervisor === "none")
|
|
15313
|
+
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.");
|
|
15314
|
+
await (options.verifyCommand ?? assertSafeServiceCommand)(options.command);
|
|
15315
|
+
const path = unitPath(supervisor, env, requireHome(home));
|
|
15316
|
+
if (supervisor === "launchd") {
|
|
15317
|
+
const changed2 = await writeUnit(path, renderLaunchdPlist(options.command, env, requireHome(home)));
|
|
15318
|
+
const uid = process.getuid?.() ?? 0;
|
|
15319
|
+
for (const domain of [`gui/${uid}`, `user/${uid}`]) {
|
|
15320
|
+
const loaded = (await runner(["/bin/launchctl", "print", `${domain}/${LAUNCHD_LABEL}`])).code === 0;
|
|
15321
|
+
if (loaded && changed2)
|
|
15322
|
+
await runner(["/bin/launchctl", "bootout", `${domain}/${LAUNCHD_LABEL}`]);
|
|
15323
|
+
if (!loaded || changed2) {
|
|
15324
|
+
await runner(["/bin/launchctl", "enable", `${domain}/${LAUNCHD_LABEL}`]);
|
|
15325
|
+
if ((await runner(["/bin/launchctl", "bootstrap", domain, path])).code !== 0)
|
|
15326
|
+
continue;
|
|
15327
|
+
} else if ((await runner(["/bin/launchctl", "kickstart", `${domain}/${LAUNCHD_LABEL}`])).code !== 0)
|
|
15328
|
+
continue;
|
|
15329
|
+
return { supervisor, path, changed: changed2, domain };
|
|
15330
|
+
}
|
|
15331
|
+
throw new Fault(503, "gateway_supervisor_failed", `launchd did not accept ${path}. Check \`launchctl print gui/${uid}/${LAUNCHD_LABEL}\`.`);
|
|
15332
|
+
}
|
|
15333
|
+
const changed = await writeUnit(path, renderSystemdUnit(options.command, env));
|
|
15334
|
+
const systemctl = (...args) => runner(["/usr/bin/env", "systemctl", "--user", ...args]);
|
|
15335
|
+
if ((await systemctl("daemon-reload")).code !== 0)
|
|
15336
|
+
throw new Fault(503, "gateway_supervisor_failed", "systemd --user is unavailable in this session (systemctl --user daemon-reload failed).");
|
|
15337
|
+
const started = await systemctl(changed ? "restart" : "start", SYSTEMD_UNIT);
|
|
15338
|
+
await systemctl("enable", SYSTEMD_UNIT);
|
|
15339
|
+
if (started.code !== 0)
|
|
15340
|
+
throw new Fault(503, "gateway_supervisor_failed", `systemd --user could not start ${SYSTEMD_UNIT}. Check \`systemctl --user status ${SYSTEMD_UNIT}\`.`);
|
|
15341
|
+
return { supervisor, path, changed };
|
|
15342
|
+
}
|
|
15343
|
+
async function uninstallGatewayService(options = {}) {
|
|
15344
|
+
const env = options.env ?? process.env, runner = options.runner ?? defaultRunner, home = options.home ?? accountHome();
|
|
15345
|
+
const supervisor = options.supervisor ?? supervisorFor(env, process.platform, home);
|
|
15346
|
+
if (supervisor === "none")
|
|
15347
|
+
return { removed: false, supervisor };
|
|
15348
|
+
const path = unitPath(supervisor, env, requireHome(home));
|
|
15349
|
+
if (supervisor === "launchd") {
|
|
15350
|
+
const uid = process.getuid?.() ?? 0;
|
|
15351
|
+
for (const domain of [`gui/${uid}`, `user/${uid}`])
|
|
15352
|
+
await runner(["/bin/launchctl", "bootout", `${domain}/${LAUNCHD_LABEL}`]);
|
|
15353
|
+
} else
|
|
15354
|
+
await runner(["/usr/bin/env", "systemctl", "--user", "disable", "--now", SYSTEMD_UNIT]);
|
|
15355
|
+
const removed = await unlink4(path).then(() => true, () => false);
|
|
15356
|
+
if (supervisor === "systemd")
|
|
15357
|
+
await runner(["/usr/bin/env", "systemctl", "--user", "daemon-reload"]);
|
|
15358
|
+
return { removed, supervisor, path };
|
|
15359
|
+
}
|
|
15360
|
+
async function unitInstalled(env = process.env, home = accountHome()) {
|
|
15361
|
+
const supervisor = supervisorFor(env, process.platform, home);
|
|
15362
|
+
if (supervisor === "none" || !home)
|
|
15363
|
+
return { supervisor: "none", installed: false };
|
|
15364
|
+
const path = unitPath(supervisor, env, home);
|
|
15365
|
+
return { supervisor, path, ...supervisor === "launchd" ? { log: launchdLogPath(home) } : {}, installed: await Bun.file(path).exists() };
|
|
15366
|
+
}
|
|
15367
|
+
|
|
15368
|
+
// src/gateway-client.ts
|
|
15369
|
+
class GatewayControlClient {
|
|
15370
|
+
socket;
|
|
15371
|
+
timeoutMs;
|
|
15372
|
+
constructor(socket, timeoutMs = 1e4) {
|
|
15373
|
+
this.socket = socket;
|
|
15374
|
+
this.timeoutMs = timeoutMs;
|
|
15375
|
+
}
|
|
15376
|
+
async request(method, path, body2) {
|
|
15377
|
+
await assertTrustedControlSocket(this.socket);
|
|
15378
|
+
let response;
|
|
15379
|
+
try {
|
|
15380
|
+
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) });
|
|
15381
|
+
} catch {
|
|
15382
|
+
throw new Fault(503, "gateway_unavailable", "The Switcher gateway service is not running. Run `switcher gateway status`.");
|
|
15383
|
+
}
|
|
15384
|
+
const value = await response.json().catch(() => {
|
|
15385
|
+
return;
|
|
15386
|
+
});
|
|
15387
|
+
if (!response.ok)
|
|
15388
|
+
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}).`);
|
|
15389
|
+
return value;
|
|
15390
|
+
}
|
|
15391
|
+
status() {
|
|
15392
|
+
return this.request("GET", "/v1/status");
|
|
15393
|
+
}
|
|
15394
|
+
launches() {
|
|
15395
|
+
return this.request("GET", "/v1/launches");
|
|
15396
|
+
}
|
|
15397
|
+
register(body2) {
|
|
15398
|
+
return this.request("POST", "/v1/launches", body2);
|
|
15399
|
+
}
|
|
15400
|
+
attach(id2, pid) {
|
|
15401
|
+
return this.request("POST", `/v1/launches/${encodeURIComponent(id2)}/holders`, { pid });
|
|
15402
|
+
}
|
|
15403
|
+
release(id2) {
|
|
15404
|
+
return this.request("POST", `/v1/launches/${encodeURIComponent(id2)}/release`, {});
|
|
15405
|
+
}
|
|
15406
|
+
revoke(id2) {
|
|
15407
|
+
return this.request("DELETE", `/v1/launches/${encodeURIComponent(id2)}`);
|
|
15408
|
+
}
|
|
15409
|
+
stop() {
|
|
15410
|
+
return this.request("POST", "/v1/stop", {});
|
|
15411
|
+
}
|
|
15412
|
+
}
|
|
15413
|
+
var untrusted = (error) => error instanceof Fault && error.code === "gateway_socket_untrusted";
|
|
15414
|
+
async function gatewayStatus(env = process.env) {
|
|
15415
|
+
return new GatewayControlClient(gatewayPaths(env).socket, 2000).status().catch((error) => {
|
|
15416
|
+
if (untrusted(error))
|
|
15417
|
+
throw error;
|
|
15418
|
+
return;
|
|
15419
|
+
});
|
|
15420
|
+
}
|
|
15421
|
+
var gatewayOutdated = (status) => status.version !== VERSION || status.protocol !== GATEWAY_PROTOCOL;
|
|
15422
|
+
async function spawnDetached(command, env) {
|
|
15423
|
+
const paths = gatewayPaths(env);
|
|
15424
|
+
await privateDirectory(switcherHome(env));
|
|
15425
|
+
await privateDirectory(paths.root);
|
|
15426
|
+
const log = openSync3(paths.log, "a", 384);
|
|
15427
|
+
try {
|
|
15428
|
+
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 });
|
|
15429
|
+
child.on("error", () => {
|
|
15430
|
+
return;
|
|
15431
|
+
});
|
|
15432
|
+
child.unref();
|
|
15433
|
+
} finally {
|
|
15434
|
+
closeSync3(log);
|
|
15435
|
+
}
|
|
15436
|
+
}
|
|
15437
|
+
async function ensureGatewayService(options) {
|
|
15438
|
+
const env = options.env ?? process.env;
|
|
15439
|
+
if (process.platform === "win32")
|
|
15440
|
+
throw new Fault(422, "gateway_unsupported", "The persistent Switcher gateway supports macOS and Linux.");
|
|
15441
|
+
const warn = options.warn ?? ((message) => console.error(message));
|
|
15442
|
+
const client = new GatewayControlClient(gatewayPaths(env).socket);
|
|
15443
|
+
const check2 = async () => {
|
|
15444
|
+
const status = await new GatewayControlClient(client.socket, 2000).status().catch((error) => {
|
|
15445
|
+
if (untrusted(error))
|
|
15446
|
+
throw error;
|
|
15447
|
+
return;
|
|
15448
|
+
});
|
|
15449
|
+
if (status && status.protocol !== GATEWAY_PROTOCOL)
|
|
15450
|
+
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}.`);
|
|
15451
|
+
return status;
|
|
15452
|
+
};
|
|
15453
|
+
const existing = await check2();
|
|
15454
|
+
if (existing) {
|
|
15455
|
+
if (gatewayOutdated(existing))
|
|
15456
|
+
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).`);
|
|
15457
|
+
return { client, status: existing, started: "existing" };
|
|
15458
|
+
}
|
|
15459
|
+
const supervisor = options.supervise === false ? "none" : supervisorFor(env);
|
|
15460
|
+
let started = "detached";
|
|
15461
|
+
if (supervisor !== "none") {
|
|
15462
|
+
try {
|
|
15463
|
+
await installGatewayService({ command: options.command, env, supervisor, runner: options.runner });
|
|
15464
|
+
started = supervisor;
|
|
15465
|
+
} catch (error) {
|
|
15466
|
+
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.`);
|
|
15467
|
+
await spawnDetached(options.command, env);
|
|
15468
|
+
}
|
|
15469
|
+
} else
|
|
15470
|
+
await spawnDetached(options.command, env);
|
|
15471
|
+
const deadline = Date.now() + (options.waitMs ?? 1e4);
|
|
15472
|
+
for (;; ) {
|
|
15473
|
+
const status = await check2();
|
|
15474
|
+
if (status)
|
|
15475
|
+
return { client, status, started };
|
|
15476
|
+
if (Date.now() > deadline)
|
|
15477
|
+
throw new Fault(503, "gateway_unavailable", `The Switcher gateway did not start. See ${gatewayPaths(env).log}.`);
|
|
15478
|
+
await new Promise((resolve14) => setTimeout(resolve14, 100));
|
|
15479
|
+
}
|
|
15480
|
+
}
|
|
15481
|
+
function createServiceGatewayHost(client, context) {
|
|
15482
|
+
const leases = [];
|
|
15483
|
+
const attaching = [];
|
|
15484
|
+
let attachedPid;
|
|
15485
|
+
return {
|
|
15486
|
+
async open(input) {
|
|
15487
|
+
const gateway = {
|
|
15488
|
+
harness: input.harness,
|
|
15489
|
+
baseUrl: input.baseUrl,
|
|
15490
|
+
protocol: input.protocol,
|
|
15491
|
+
...input.authStyle ? { authStyle: input.authStyle } : {},
|
|
15492
|
+
model: input.model,
|
|
15493
|
+
models: input.models,
|
|
15494
|
+
compiledPolicy: input.compiledPolicy,
|
|
15495
|
+
...input.providerId ? { providerId: input.providerId } : {},
|
|
15496
|
+
catalogPath: input.catalogPath,
|
|
15497
|
+
cwd: input.cwd
|
|
15498
|
+
};
|
|
15499
|
+
let registration;
|
|
15500
|
+
try {
|
|
15501
|
+
registration = await client.register({
|
|
15502
|
+
holderPid: context.holderPid,
|
|
15503
|
+
gateway,
|
|
15504
|
+
...input.credential ? { credential: input.credential } : {},
|
|
15505
|
+
...context.credentialEnv ? { credentialEnv: context.credentialEnv } : {},
|
|
15506
|
+
...context.stateDir ? { stateDir: context.stateDir } : {}
|
|
15507
|
+
});
|
|
15508
|
+
} catch (error) {
|
|
15509
|
+
(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.`);
|
|
15510
|
+
return createInferenceGateway(input);
|
|
15511
|
+
}
|
|
15512
|
+
const lease = { id: registration.id, attached: attachedPid !== undefined, retained: false, done: false };
|
|
15513
|
+
leases.push(lease);
|
|
15514
|
+
if (attachedPid !== undefined)
|
|
15515
|
+
attaching.push(client.attach(lease.id, attachedPid).catch(() => {
|
|
15516
|
+
return;
|
|
15517
|
+
}));
|
|
15518
|
+
return { baseUrl: registration.baseUrl, token: registration.token, retainsState: () => lease.retained, cleanup: async () => {
|
|
15519
|
+
if (lease.done)
|
|
15520
|
+
return;
|
|
15521
|
+
lease.done = true;
|
|
15522
|
+
await Promise.allSettled(attaching);
|
|
15523
|
+
if (!lease.attached) {
|
|
15524
|
+
await client.revoke(lease.id).catch(() => {
|
|
15525
|
+
return;
|
|
15526
|
+
});
|
|
15527
|
+
return;
|
|
15528
|
+
}
|
|
15529
|
+
try {
|
|
15530
|
+
const result = await client.release(lease.id);
|
|
15531
|
+
lease.retained = result.retained;
|
|
15532
|
+
for (const event of result.events ?? [])
|
|
15533
|
+
context.onRoutingEvent?.(event);
|
|
15534
|
+
} catch (error) {
|
|
15535
|
+
lease.retained = !(error instanceof Fault && error.status === 404);
|
|
15536
|
+
}
|
|
15537
|
+
} };
|
|
15538
|
+
},
|
|
15539
|
+
attach(pid) {
|
|
15540
|
+
attachedPid = pid;
|
|
15541
|
+
for (const lease of leases) {
|
|
15542
|
+
lease.attached = true;
|
|
15543
|
+
attaching.push(client.attach(lease.id, pid).catch(() => {
|
|
15544
|
+
return;
|
|
15545
|
+
}));
|
|
15546
|
+
}
|
|
15547
|
+
},
|
|
15548
|
+
retainedState: () => leases.some((lease) => lease.retained)
|
|
15549
|
+
};
|
|
15550
|
+
}
|
|
15551
|
+
|
|
14258
15552
|
// src/launcher.ts
|
|
14259
15553
|
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
14260
15554
|
async function writeOriCodexCatalog(stateDir, models) {
|
|
14261
|
-
const path =
|
|
15555
|
+
const path = join24(stateDir, "ori-codex-models.json");
|
|
14262
15556
|
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
14263
15557
|
await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
14264
15558
|
`, { mode: 384, flag: "wx" });
|
|
@@ -14298,7 +15592,7 @@ async function oriRequestForPlan(plan, options = {}) {
|
|
|
14298
15592
|
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
15593
|
if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
14300
15594
|
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 ?
|
|
15595
|
+
const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve14(options.cwd) : undefined });
|
|
14302
15596
|
const native = requireOriHarness(contract, target);
|
|
14303
15597
|
if (!native.path)
|
|
14304
15598
|
throw new Error("Ori did not report the native harness executable path.");
|
|
@@ -14346,14 +15640,14 @@ async function prepareOriForPlan(plan, options) {
|
|
|
14346
15640
|
executable: detection.executable,
|
|
14347
15641
|
version: detection.version,
|
|
14348
15642
|
stateDir: options.stateDir,
|
|
14349
|
-
cwd:
|
|
15643
|
+
cwd: resolve14(options.cwd ?? process.cwd()),
|
|
14350
15644
|
args: options.args ?? [],
|
|
14351
15645
|
sharedState: options.sharedState
|
|
14352
15646
|
});
|
|
14353
15647
|
try {
|
|
14354
15648
|
const shim = prepareOriModelPolicy(request.target, native);
|
|
14355
|
-
const dir =
|
|
14356
|
-
await
|
|
15649
|
+
const dir = join24(options.stateDir, "ori-bin"), path = join24(dir, shim.name);
|
|
15650
|
+
await mkdir14(dir, { mode: 448 });
|
|
14357
15651
|
await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
|
|
14358
15652
|
return { contract, prepared: {
|
|
14359
15653
|
...ori,
|
|
@@ -14378,7 +15672,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14378
15672
|
assertHarnessArguments(profile.harness, options.args ?? []);
|
|
14379
15673
|
if (profile.harness === "gemini" || profile.harness === "antigravity")
|
|
14380
15674
|
validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
|
|
14381
|
-
await validateHarnessConfiguration(profile.harness,
|
|
15675
|
+
await validateHarnessConfiguration(profile.harness, resolve14(options.cwd ?? process.cwd()), options.args);
|
|
14382
15676
|
if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
|
|
14383
15677
|
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
15678
|
if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
@@ -14387,7 +15681,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14387
15681
|
await client.refreshModels(profile.providerId);
|
|
14388
15682
|
const plan = await client.launchPlan(profileId);
|
|
14389
15683
|
assertHarnessArguments(plan.profile.harness, options.args ?? []);
|
|
14390
|
-
await validateHarnessConfiguration(plan.profile.harness,
|
|
15684
|
+
await validateHarnessConfiguration(plan.profile.harness, resolve14(options.cwd ?? process.cwd()), options.args);
|
|
14391
15685
|
if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
|
|
14392
15686
|
throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
|
|
14393
15687
|
const backend = options.backend ?? "direct";
|
|
@@ -14409,9 +15703,9 @@ async function launch(client, profileId, options = {}) {
|
|
|
14409
15703
|
validateHarnessVersion("gemini", detection?.version);
|
|
14410
15704
|
if (backend === "direct" && plan.profile.harness === "aider")
|
|
14411
15705
|
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
14412
|
-
const root =
|
|
15706
|
+
const root = resolve14(options.stateDir ?? join24(switcherHome(), "state"));
|
|
14413
15707
|
await privateDirectory(root);
|
|
14414
|
-
const stateDir = await mkdtemp(
|
|
15708
|
+
const stateDir = await mkdtemp(join24(root, "launch-"));
|
|
14415
15709
|
let credential;
|
|
14416
15710
|
if (backend === "direct") {
|
|
14417
15711
|
try {
|
|
@@ -14419,7 +15713,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14419
15713
|
if (plan.provider.credentialEnv && !credential)
|
|
14420
15714
|
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
15715
|
} catch (error) {
|
|
14422
|
-
await
|
|
15716
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
14423
15717
|
throw error;
|
|
14424
15718
|
}
|
|
14425
15719
|
}
|
|
@@ -14441,6 +15735,15 @@ async function launch(client, profileId, options = {}) {
|
|
|
14441
15735
|
} else
|
|
14442
15736
|
routingEventsDropped = Math.min(1e6, routingEventsDropped + 1);
|
|
14443
15737
|
};
|
|
15738
|
+
let gatewayHost;
|
|
15739
|
+
if (options.gateway === "service" && backend === "direct" && !options.claudeDesktop && process.platform !== "win32") {
|
|
15740
|
+
try {
|
|
15741
|
+
const client2 = options.connectGateway ? await options.connectGateway() : (await ensureGatewayService({ command: options.gatewayCommand ?? [process.execPath, Bun.main], supervise: options.gatewaySupervise ?? false })).client;
|
|
15742
|
+
gatewayHost = createServiceGatewayHost(client2, { holderPid: process.pid, stateDir, credentialEnv: credential ? plan.provider.credentialEnv : undefined, onRoutingEvent });
|
|
15743
|
+
} catch (error) {
|
|
15744
|
+
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.`);
|
|
15745
|
+
}
|
|
15746
|
+
}
|
|
14444
15747
|
const finishRunOnce = async (candidate, body2, message) => {
|
|
14445
15748
|
if (runFinalized)
|
|
14446
15749
|
return;
|
|
@@ -14470,8 +15773,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
14470
15773
|
let nativeHome2;
|
|
14471
15774
|
if (sharedState && !options.desktop && !options.claudeDesktop) {
|
|
14472
15775
|
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) ?
|
|
15776
|
+
const configured = process.env[variable] ? resolve14(process.env[variable]) : undefined;
|
|
15777
|
+
nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join24(root, "native-claude", profileId) : configured ?? sharedState.home;
|
|
14475
15778
|
if (sharedState.tool === "claude")
|
|
14476
15779
|
await prepareClaudeUserSettings(nativeHome2);
|
|
14477
15780
|
await privateDirectory(nativeHome2);
|
|
@@ -14481,12 +15784,12 @@ async function launch(client, profileId, options = {}) {
|
|
|
14481
15784
|
if (options.shareNativeState === false && backend === "direct") {
|
|
14482
15785
|
const tool = plan.profile.harness;
|
|
14483
15786
|
if (options.desktop)
|
|
14484
|
-
await assertNativeStateIsolation(tool,
|
|
15787
|
+
await assertNativeStateIsolation(tool, join24(root, "desktop", desktopState, "codex"));
|
|
14485
15788
|
else if (options.claudeDesktop)
|
|
14486
|
-
await assertNativeStateIsolation(tool,
|
|
15789
|
+
await assertNativeStateIsolation(tool, join24(root, "desktop-claude", desktopState));
|
|
14487
15790
|
else {
|
|
14488
15791
|
const variable = tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
|
|
14489
|
-
nativeHome2 = process.env[variable] ?
|
|
15792
|
+
nativeHome2 = process.env[variable] ? resolve14(process.env[variable]) : join24(root, `native-${tool}`, profileId);
|
|
14490
15793
|
await assertNativeStateIsolation(tool, nativeHome2);
|
|
14491
15794
|
await privateDirectory(nativeHome2);
|
|
14492
15795
|
}
|
|
@@ -14503,10 +15806,10 @@ async function launch(client, profileId, options = {}) {
|
|
|
14503
15806
|
onRoutingEvent,
|
|
14504
15807
|
credential,
|
|
14505
15808
|
stateDir,
|
|
14506
|
-
cwd:
|
|
15809
|
+
cwd: resolve14(options.cwd ?? process.cwd()),
|
|
14507
15810
|
sharedState
|
|
14508
15811
|
};
|
|
14509
|
-
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop,
|
|
15812
|
+
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
15813
|
harness: plan.profile.harness,
|
|
14511
15814
|
baseUrl: plan.provider.baseUrl,
|
|
14512
15815
|
protocol: plan.provider.protocol,
|
|
@@ -14522,10 +15825,11 @@ async function launch(client, profileId, options = {}) {
|
|
|
14522
15825
|
executable: nativeExecutable ?? detection?.executable,
|
|
14523
15826
|
args: options.args ?? [],
|
|
14524
15827
|
stateDir,
|
|
14525
|
-
cwd:
|
|
15828
|
+
cwd: resolve14(options.cwd ?? process.cwd()),
|
|
14526
15829
|
version: detection?.version,
|
|
14527
15830
|
sharedState,
|
|
14528
|
-
|
|
15831
|
+
gatewayHost,
|
|
15832
|
+
...["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
15833
|
});
|
|
14530
15834
|
cleanup = prepared.cleanup;
|
|
14531
15835
|
prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
|
|
@@ -14542,7 +15846,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14542
15846
|
prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
|
|
14543
15847
|
}
|
|
14544
15848
|
if (options.desktop) {
|
|
14545
|
-
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir,
|
|
15849
|
+
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join24(root, "desktop", desktopState), sharedState);
|
|
14546
15850
|
cleanup = prepared.cleanup;
|
|
14547
15851
|
}
|
|
14548
15852
|
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
@@ -14619,7 +15923,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
14619
15923
|
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
|
|
14620
15924
|
throw preparationSignal;
|
|
14621
15925
|
}
|
|
14622
|
-
const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd:
|
|
15926
|
+
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
15927
|
await cleanup?.();
|
|
14624
15928
|
cleanup = undefined;
|
|
14625
15929
|
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 +15940,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
14636
15940
|
} finally {
|
|
14637
15941
|
if (lateCreateRunFinalization) {
|
|
14638
15942
|
let finalizationTimer;
|
|
14639
|
-
const finalizationTimeout = new Promise((
|
|
14640
|
-
finalizationTimer = setTimeout(
|
|
15943
|
+
const finalizationTimeout = new Promise((resolve15) => {
|
|
15944
|
+
finalizationTimer = setTimeout(resolve15, LATE_RUN_FINALIZATION_TIMEOUT_MS);
|
|
14641
15945
|
});
|
|
14642
15946
|
try {
|
|
14643
15947
|
await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
|
|
@@ -14650,13 +15954,14 @@ async function launch(client, profileId, options = {}) {
|
|
|
14650
15954
|
try {
|
|
14651
15955
|
await cleanup?.();
|
|
14652
15956
|
} finally {
|
|
14653
|
-
|
|
15957
|
+
if (!gatewayHost?.retainedState())
|
|
15958
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
14654
15959
|
}
|
|
14655
15960
|
}
|
|
14656
15961
|
}
|
|
14657
15962
|
|
|
14658
15963
|
// src/direct-launch.ts
|
|
14659
|
-
import { createHash as
|
|
15964
|
+
import { createHash as createHash17 } from "crypto";
|
|
14660
15965
|
import { createInterface as createInterface3 } from "readline/promises";
|
|
14661
15966
|
var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
|
|
14662
15967
|
async function resolveLaunchProvider(client, selector, options = {}) {
|
|
@@ -14737,7 +16042,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
14737
16042
|
const policy = modelPolicy ?? (harness === "codex" ? { version: 1, selection: "catalog" } : undefined);
|
|
14738
16043
|
const normalizedPolicy = policy === undefined ? undefined : parse2(modelPolicySchema, policy);
|
|
14739
16044
|
const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
|
|
14740
|
-
const hash3 =
|
|
16045
|
+
const hash3 = createHash17("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
|
|
14741
16046
|
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
|
|
14742
16047
|
let existing;
|
|
14743
16048
|
try {
|
|
@@ -14761,16 +16066,16 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
14761
16066
|
}
|
|
14762
16067
|
|
|
14763
16068
|
// src/native-state-import.ts
|
|
14764
|
-
import { createHash as
|
|
14765
|
-
import { constants as
|
|
14766
|
-
import { lstat as
|
|
14767
|
-
import { basename as
|
|
16069
|
+
import { createHash as createHash18 } from "crypto";
|
|
16070
|
+
import { constants as constants11 } from "fs";
|
|
16071
|
+
import { lstat as lstat12, open as open9, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
|
|
16072
|
+
import { basename as basename5, dirname as dirname11, isAbsolute as isAbsolute19, join as join25, relative as relative6, resolve as resolve15 } from "path";
|
|
14768
16073
|
var MAX_FILES = 1e5;
|
|
14769
16074
|
var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
|
|
14770
16075
|
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
16076
|
async function info2(path) {
|
|
14772
16077
|
try {
|
|
14773
|
-
return await
|
|
16078
|
+
return await lstat12(path);
|
|
14774
16079
|
} catch (error) {
|
|
14775
16080
|
if (error.code === "ENOENT")
|
|
14776
16081
|
return;
|
|
@@ -14781,12 +16086,12 @@ var identity = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeM
|
|
|
14781
16086
|
var same = (a, b) => JSON.stringify(identity(a)) === JSON.stringify(identity(b));
|
|
14782
16087
|
var inside3 = (parent, child) => {
|
|
14783
16088
|
const path = relative6(parent, child);
|
|
14784
|
-
return path !== ".." && !path.startsWith("../") && !
|
|
16089
|
+
return path !== ".." && !path.startsWith("../") && !isAbsolute19(path);
|
|
14785
16090
|
};
|
|
14786
16091
|
var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
|
|
14787
16092
|
async function sessionId(path, expected) {
|
|
14788
|
-
const nameId =
|
|
14789
|
-
const handle = await
|
|
16093
|
+
const nameId = basename5(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
|
|
16094
|
+
const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
|
|
14790
16095
|
try {
|
|
14791
16096
|
const before = await handle.stat();
|
|
14792
16097
|
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
|
|
@@ -14800,7 +16105,7 @@ async function sessionId(path, expected) {
|
|
|
14800
16105
|
length += read.bytesRead;
|
|
14801
16106
|
newline = buffer.indexOf(10, 0);
|
|
14802
16107
|
}
|
|
14803
|
-
const after = await handle.stat(), named = await
|
|
16108
|
+
const after = await handle.stat(), named = await lstat12(path);
|
|
14804
16109
|
if (!same(before, after) || !same(after, named) || after.nlink !== 1 || named.nlink !== 1 || named.isSymbolicLink())
|
|
14805
16110
|
throw refused();
|
|
14806
16111
|
if (newline < 0 && before.size > buffer.length)
|
|
@@ -14829,7 +16134,7 @@ async function checkSessionIdentities(plan) {
|
|
|
14829
16134
|
for (const file of plan.files) {
|
|
14830
16135
|
if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
|
|
14831
16136
|
continue;
|
|
14832
|
-
file.sessionId = await sessionId(
|
|
16137
|
+
file.sessionId = await sessionId(join25(plan.source, file.path), file.source);
|
|
14833
16138
|
if (!file.sessionId)
|
|
14834
16139
|
continue;
|
|
14835
16140
|
const previous = ids.get(file.sessionId);
|
|
@@ -14853,7 +16158,7 @@ async function checkSessionIdentities(plan) {
|
|
|
14853
16158
|
for await (const entry of await opendir2(directory)) {
|
|
14854
16159
|
if (++seen > MAX_FILES || entry.isSymbolicLink())
|
|
14855
16160
|
throw refused();
|
|
14856
|
-
const path =
|
|
16161
|
+
const path = join25(directory, entry.name);
|
|
14857
16162
|
if (entry.isDirectory()) {
|
|
14858
16163
|
await scan(path, depth + 1);
|
|
14859
16164
|
continue;
|
|
@@ -14870,19 +16175,19 @@ async function checkSessionIdentities(plan) {
|
|
|
14870
16175
|
file.existing = true;
|
|
14871
16176
|
}
|
|
14872
16177
|
}
|
|
14873
|
-
await scan(
|
|
14874
|
-
await scan(
|
|
16178
|
+
await scan(join25(plan.state.home, "sessions"));
|
|
16179
|
+
await scan(join25(plan.state.home, "archived_sessions"));
|
|
14875
16180
|
}
|
|
14876
16181
|
async function fingerprint2(path, copyTo) {
|
|
14877
|
-
const handle = await
|
|
16182
|
+
const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
|
|
14878
16183
|
let output, complete = false;
|
|
14879
16184
|
try {
|
|
14880
16185
|
const before = await handle.stat();
|
|
14881
16186
|
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
|
|
14882
16187
|
throw refused();
|
|
14883
16188
|
if (copyTo)
|
|
14884
|
-
output = await
|
|
14885
|
-
const hash3 =
|
|
16189
|
+
output = await open9(copyTo, "wx", 384);
|
|
16190
|
+
const hash3 = createHash18("sha256"), buffer = Buffer.alloc(64 * 1024);
|
|
14886
16191
|
let bytes = 0;
|
|
14887
16192
|
for (;; ) {
|
|
14888
16193
|
const read = await handle.read(buffer, 0, buffer.length, null);
|
|
@@ -14899,7 +16204,7 @@ async function fingerprint2(path, copyTo) {
|
|
|
14899
16204
|
offset += (await output.write(chunk, offset, chunk.length - offset)).bytesWritten;
|
|
14900
16205
|
}
|
|
14901
16206
|
}
|
|
14902
|
-
const after = await handle.stat(), named = await
|
|
16207
|
+
const after = await handle.stat(), named = await lstat12(path);
|
|
14903
16208
|
if (named.isSymbolicLink() || after.nlink !== 1 || named.nlink !== 1 || bytes !== before.size || !same(before, after) || !same(after, named))
|
|
14904
16209
|
throw refused();
|
|
14905
16210
|
await output?.sync();
|
|
@@ -14909,15 +16214,15 @@ async function fingerprint2(path, copyTo) {
|
|
|
14909
16214
|
await output?.close();
|
|
14910
16215
|
await handle.close();
|
|
14911
16216
|
if (copyTo && !complete)
|
|
14912
|
-
await
|
|
16217
|
+
await unlink5(copyTo).catch(() => {
|
|
14913
16218
|
return;
|
|
14914
16219
|
});
|
|
14915
16220
|
}
|
|
14916
16221
|
}
|
|
14917
16222
|
async function planNativeStateImport(state, source, selection) {
|
|
14918
|
-
if (!
|
|
16223
|
+
if (!isAbsolute19(source) || source.includes("\x00"))
|
|
14919
16224
|
throw refused();
|
|
14920
|
-
source =
|
|
16225
|
+
source = resolve15(source);
|
|
14921
16226
|
if (inside3(source, state.home) || inside3(state.home, source))
|
|
14922
16227
|
throw refused();
|
|
14923
16228
|
await assertNativeStateDirectory(source);
|
|
@@ -14931,9 +16236,9 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
14931
16236
|
async function visit(path, kind) {
|
|
14932
16237
|
if (++seen > MAX_FILES || path.split("/").length > 32)
|
|
14933
16238
|
throw refused();
|
|
14934
|
-
await ensureNativeStateDirectory(
|
|
14935
|
-
await ensureNativeStateDirectory(
|
|
14936
|
-
const from =
|
|
16239
|
+
await ensureNativeStateDirectory(dirname11(join25(source, path)), false);
|
|
16240
|
+
await ensureNativeStateDirectory(dirname11(join25(state.home, path)), false);
|
|
16241
|
+
const from = join25(source, path), to = join25(state.home, path), entry = await info2(from), target = await info2(to);
|
|
14937
16242
|
if (!entry)
|
|
14938
16243
|
return;
|
|
14939
16244
|
if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
|
|
@@ -14952,7 +16257,7 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
14952
16257
|
}
|
|
14953
16258
|
children.sort((a, b) => a.name.localeCompare(b.name));
|
|
14954
16259
|
for (const child of children)
|
|
14955
|
-
await visit(
|
|
16260
|
+
await visit(join25(path, child.name), child.kind);
|
|
14956
16261
|
} else {
|
|
14957
16262
|
const value = await fingerprint2(from);
|
|
14958
16263
|
plan.bytes += value.bytes;
|
|
@@ -14974,7 +16279,7 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
14974
16279
|
return plan;
|
|
14975
16280
|
}
|
|
14976
16281
|
function nativeStateImportDigest(plan) {
|
|
14977
|
-
return
|
|
16282
|
+
return createHash18("sha256").update(JSON.stringify({
|
|
14978
16283
|
tool: plan.state.tool,
|
|
14979
16284
|
source: plan.source,
|
|
14980
16285
|
destination: plan.state.home,
|
|
@@ -15006,14 +16311,14 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
15006
16311
|
throw refused();
|
|
15007
16312
|
const requiredDirectories = new Set([plan.state.home]);
|
|
15008
16313
|
for (const path of plan.directories) {
|
|
15009
|
-
for (let directory =
|
|
16314
|
+
for (let directory = join25(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname11(directory)) {
|
|
15010
16315
|
requiredDirectories.add(directory);
|
|
15011
16316
|
if (directory === plan.state.home)
|
|
15012
16317
|
break;
|
|
15013
16318
|
}
|
|
15014
16319
|
}
|
|
15015
16320
|
for (const file of plan.files.filter((file2) => !file2.existing)) {
|
|
15016
|
-
for (let directory =
|
|
16321
|
+
for (let directory = dirname11(join25(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname11(directory)) {
|
|
15017
16322
|
requiredDirectories.add(directory);
|
|
15018
16323
|
if (directory === plan.state.home)
|
|
15019
16324
|
break;
|
|
@@ -15034,9 +16339,9 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
15034
16339
|
for (const file of plan.files) {
|
|
15035
16340
|
if (file.existing)
|
|
15036
16341
|
continue;
|
|
15037
|
-
const target =
|
|
16342
|
+
const target = join25(plan.state.home, file.path), temporary = join25(dirname11(target), `.switcher-import-${crypto.randomUUID()}`);
|
|
15038
16343
|
staged.push({ temporary, target });
|
|
15039
|
-
const copied = await fingerprint2(
|
|
16344
|
+
const copied = await fingerprint2(join25(plan.source, file.path), temporary);
|
|
15040
16345
|
if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
|
|
15041
16346
|
throw refused();
|
|
15042
16347
|
}
|
|
@@ -15054,7 +16359,7 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
15054
16359
|
} finally {
|
|
15055
16360
|
for (const item2 of staged) {
|
|
15056
16361
|
try {
|
|
15057
|
-
await
|
|
16362
|
+
await unlink5(item2.temporary);
|
|
15058
16363
|
} catch (error) {
|
|
15059
16364
|
if (error.code !== "ENOENT")
|
|
15060
16365
|
cleanupFailed = true;
|
|
@@ -15089,6 +16394,7 @@ async function applyNativeStateImport(plan) {
|
|
|
15089
16394
|
}
|
|
15090
16395
|
|
|
15091
16396
|
// src/cli.ts
|
|
16397
|
+
import { realpathSync as realpathSync2 } from "fs";
|
|
15092
16398
|
var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
|
|
15093
16399
|
|
|
15094
16400
|
switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
|
|
@@ -15125,6 +16431,8 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
|
|
|
15125
16431
|
switcher credentials list|check|remove [PRESET_OR_REFERENCE]
|
|
15126
16432
|
switcher credentials repair-executable PRESET_OR_REFERENCE --sha256 EXPECTED
|
|
15127
16433
|
switcher credentials repair-executable --vault-cli PATH --sha256 EXPECTED
|
|
16434
|
+
switcher gateway status|install|uninstall|stop
|
|
16435
|
+
switcher gateway run [--exit-when-idle]
|
|
15128
16436
|
switcher doctor
|
|
15129
16437
|
switcher state import codex|claude --from LEGACY_NATIVE_HOME [--entry NAME]... [--dry-run | --apply --plan-digest SHA256]
|
|
15130
16438
|
|
|
@@ -15137,6 +16445,11 @@ Its local Codex conversations use the selected Responses-compatible provider.
|
|
|
15137
16445
|
claude-desktop launches Claude in its separate Claude-3p gateway profile with a
|
|
15138
16446
|
Messages-compatible provider. Quit that instance before switching providers.
|
|
15139
16447
|
Keep Switcher running while using the app; quit that app instance to end the launch.
|
|
16448
|
+
Launches register with one persistent per-user gateway on a stable 127.0.0.1 port,
|
|
16449
|
+
so background processes the harness leaves running (such as Claude Code's daemon)
|
|
16450
|
+
keep working after the launch exits. It runs under launchd (macOS) or systemd --user
|
|
16451
|
+
(Linux) for the default home and starts automatically. SWITCHER_GATEWAY=local uses
|
|
16452
|
+
the older per-launch gateway that stops with the launch.
|
|
15140
16453
|
--reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
|
|
15141
16454
|
--dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
|
|
15142
16455
|
PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
|
|
@@ -15261,7 +16574,8 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15261
16574
|
"vault-operator": { type: "string" },
|
|
15262
16575
|
"keychain-service": { type: "string" },
|
|
15263
16576
|
"keychain-account": { type: "string" },
|
|
15264
|
-
origin: { type: "string", multiple: true }
|
|
16577
|
+
origin: { type: "string", multiple: true },
|
|
16578
|
+
"exit-when-idle": { type: "boolean" }
|
|
15265
16579
|
} });
|
|
15266
16580
|
if (values2.help || !positionals.length) {
|
|
15267
16581
|
console.log(HELP);
|
|
@@ -15281,6 +16595,10 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15281
16595
|
output(nativeStateImportSummary(plan, Boolean(values2.apply)));
|
|
15282
16596
|
return;
|
|
15283
16597
|
}
|
|
16598
|
+
if (command === "gateway")
|
|
16599
|
+
return gatewayCommand(action2, positionals, values2, nativeArgs, output);
|
|
16600
|
+
if (values2["exit-when-idle"] !== undefined)
|
|
16601
|
+
throw new Fault(400, "conflicting_options", "--exit-when-idle belongs to switcher gateway run.");
|
|
15284
16602
|
if (values2.from !== undefined || values2.entry !== undefined || values2.apply !== undefined || values2["plan-digest"] !== undefined)
|
|
15285
16603
|
throw new Fault(400, "conflicting_options", "--from, --entry, --plan-digest, --dry-run and --apply belong to switcher state import.");
|
|
15286
16604
|
if (values2["share-native-state"] && values2["no-share-native-state"])
|
|
@@ -15542,9 +16860,9 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15542
16860
|
if (sharedNativeState)
|
|
15543
16861
|
await resolveNativeState(plan.profile.harness, process.env, { create: false });
|
|
15544
16862
|
if (shareNativeState === false) {
|
|
15545
|
-
const tool = plan.profile.harness, root =
|
|
16863
|
+
const tool = plan.profile.harness, root = resolve16(values2["state-dir"] ?? join26(switcherHome(), "state"));
|
|
15546
16864
|
const configured = process.env[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
|
|
15547
|
-
const home = desktop ?
|
|
16865
|
+
const home = desktop ? join26(root, "desktop", profileId, "codex") : claudeApp ? join26(root, "desktop-claude", profileId) : configured ? resolve16(configured) : join26(root, `native-${tool}`, profileId);
|
|
15548
16866
|
await assertNativeStateIsolation(tool, home);
|
|
15549
16867
|
}
|
|
15550
16868
|
if (backend === "ori") {
|
|
@@ -15556,7 +16874,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15556
16874
|
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
16875
|
return;
|
|
15558
16876
|
}
|
|
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)) });
|
|
16877
|
+
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
16878
|
return;
|
|
15561
16879
|
}
|
|
15562
16880
|
if (editingModel) {
|
|
@@ -15666,6 +16984,95 @@ async function main(args = process.argv.slice(2)) {
|
|
|
15666
16984
|
await runtime.close();
|
|
15667
16985
|
}
|
|
15668
16986
|
}
|
|
16987
|
+
function launchGatewayMode() {
|
|
16988
|
+
const mode = process.env.SWITCHER_GATEWAY?.trim() || "service";
|
|
16989
|
+
if (mode !== "local" && mode !== "service")
|
|
16990
|
+
throw new Fault(400, "invalid_gateway_setting", "SWITCHER_GATEWAY must be service or local.");
|
|
16991
|
+
return mode;
|
|
16992
|
+
}
|
|
16993
|
+
function gatewayServiceCommand() {
|
|
16994
|
+
const script = Bun.main;
|
|
16995
|
+
const linked = Bun.which("switcher");
|
|
16996
|
+
try {
|
|
16997
|
+
if (linked && realpathSync2(linked) === realpathSync2(script))
|
|
16998
|
+
return { command: [process.execPath, linked], linked: true };
|
|
16999
|
+
} catch {}
|
|
17000
|
+
return { command: [process.execPath, script], linked: false };
|
|
17001
|
+
}
|
|
17002
|
+
async function stopGateway(status, socket) {
|
|
17003
|
+
await new GatewayControlClient(socket).stop();
|
|
17004
|
+
for (let i = 0;i < 100; i++) {
|
|
17005
|
+
try {
|
|
17006
|
+
process.kill(status.pid, 0);
|
|
17007
|
+
} catch {
|
|
17008
|
+
return true;
|
|
17009
|
+
}
|
|
17010
|
+
await Bun.sleep(50);
|
|
17011
|
+
}
|
|
17012
|
+
return false;
|
|
17013
|
+
}
|
|
17014
|
+
async function gatewayCommand(action2, positionals, values2, nativeArgs, output) {
|
|
17015
|
+
const allowed = action2 === "run" ? ["exit-when-idle", "json"] : ["json"];
|
|
17016
|
+
if (positionals.length !== 2 || nativeArgs.length || Object.keys(values2).some((name) => !allowed.includes(name)))
|
|
17017
|
+
throw new Fault(400, "invalid_request", "Use switcher gateway status|install|uninstall|stop, or switcher gateway run [--exit-when-idle].");
|
|
17018
|
+
const paths = gatewayPaths();
|
|
17019
|
+
const describe = async () => {
|
|
17020
|
+
const status = await gatewayStatus();
|
|
17021
|
+
const unit = await unitInstalled().catch(() => ({ supervisor: "none", installed: false }));
|
|
17022
|
+
const log = unit.log ?? (unit.supervisor === "systemd" ? "journalctl --user -u switcher-gateway.service" : paths.log);
|
|
17023
|
+
return { running: Boolean(status), ...status ?? {}, socket: paths.socket, log, unit };
|
|
17024
|
+
};
|
|
17025
|
+
if (action2 === "run") {
|
|
17026
|
+
process.umask(63);
|
|
17027
|
+
const settings2 = gatewaySettings();
|
|
17028
|
+
let service;
|
|
17029
|
+
try {
|
|
17030
|
+
service = await startGatewayService({ exitWhenIdleMs: values2["exit-when-idle"] ? settings2.exitIdleMs : undefined, supervisor: process.env.SWITCHER_GATEWAY_SUPERVISED ?? "none" });
|
|
17031
|
+
} catch (error) {
|
|
17032
|
+
if (error instanceof Fault && error.code === "gateway_running") {
|
|
17033
|
+
console.error("switcher gateway: already running for this home.");
|
|
17034
|
+
return;
|
|
17035
|
+
}
|
|
17036
|
+
throw error;
|
|
17037
|
+
}
|
|
17038
|
+
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
|
|
17039
|
+
process.on(signal, () => void service.close());
|
|
17040
|
+
await service.closed;
|
|
17041
|
+
return;
|
|
17042
|
+
}
|
|
17043
|
+
if (action2 === "status") {
|
|
17044
|
+
const result = await describe();
|
|
17045
|
+
output(result);
|
|
17046
|
+
if (!result.running)
|
|
17047
|
+
process.exitCode = 1;
|
|
17048
|
+
return;
|
|
17049
|
+
}
|
|
17050
|
+
if (action2 === "install") {
|
|
17051
|
+
const running = await gatewayStatus();
|
|
17052
|
+
const replaced = running && gatewayOutdated(running) ? { replaced: { version: running.version, pid: running.pid, stopped: await stopGateway(running, paths.socket) } } : {};
|
|
17053
|
+
const { command } = gatewayServiceCommand();
|
|
17054
|
+
const installed = await installGatewayService({ command });
|
|
17055
|
+
const ensured = await ensureGatewayService({ command, waitMs: 15000 });
|
|
17056
|
+
output({ ...installed, ...replaced, ...await describe(), started: ensured.started });
|
|
17057
|
+
return;
|
|
17058
|
+
}
|
|
17059
|
+
if (action2 === "uninstall") {
|
|
17060
|
+
const removed = await uninstallGatewayService();
|
|
17061
|
+
output({ ...removed, ...await describe() });
|
|
17062
|
+
return;
|
|
17063
|
+
}
|
|
17064
|
+
if (action2 === "stop") {
|
|
17065
|
+
const status = await gatewayStatus();
|
|
17066
|
+
if (!status) {
|
|
17067
|
+
output({ stopped: false, running: false });
|
|
17068
|
+
return;
|
|
17069
|
+
}
|
|
17070
|
+
await stopGateway(status, paths.socket);
|
|
17071
|
+
output({ stopped: true, pid: status.pid });
|
|
17072
|
+
return;
|
|
17073
|
+
}
|
|
17074
|
+
throw new Fault(400, "invalid_request", "Use switcher gateway status|install|uninstall|stop, or switcher gateway run [--exit-when-idle].");
|
|
17075
|
+
}
|
|
15669
17076
|
if (import.meta.main) {
|
|
15670
17077
|
if (process.argv.slice(2).length === 1 && process.argv[2] === "--version")
|
|
15671
17078
|
console.log(VERSION);
|