@hasna/switcher 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -432,9 +432,14 @@ async function detectChatGPTApp(appPath, system = host) {
432
432
  const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
433
433
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
434
434
  continue;
435
- const executable = join(path, "Contents/MacOS", name), codexExecutable = join(path, "Contents/Resources/codex");
436
- if (await system.executable(executable) && await system.executable(codexExecutable))
437
- return { path, executable, codexExecutable, bundleId, version: version2 };
435
+ const executable = join(path, "Contents/MacOS", name);
436
+ if (!await system.executable(executable))
437
+ continue;
438
+ for (const relative of ["Contents/Resources/codex", "Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex"]) {
439
+ const codexExecutable = join(path, relative);
440
+ if (await system.executable(codexExecutable))
441
+ return { path, executable, codexExecutable, bundleId, version: version2 };
442
+ }
438
443
  } catch {}
439
444
  }
440
445
  throw new Fault(404, "app_not_installed", "Install the current ChatGPT/Codex macOS app or use --app-path with its absolute .app path. Legacy ChatGPT Classic cannot run custom Codex providers.");
package/dist/mcp/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // src/mcp.ts
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
- import { z as z7 } from "zod";
7
+ import { z as z8 } from "zod";
8
8
 
9
9
  // src/runtime.ts
10
10
  import { randomBytes } from "crypto";
@@ -69,7 +69,7 @@ function canonicalPolicyJSON(value) {
69
69
  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);
70
70
  }
71
71
  // package.json
72
- var version = "0.2.9";
72
+ var version = "0.2.11";
73
73
 
74
74
  // src/version.ts
75
75
  var VERSION = version;
@@ -1197,7 +1197,7 @@ var openapi_default = {
1197
1197
  openapi: "3.0.3",
1198
1198
  info: {
1199
1199
  title: "Switcher API",
1200
- version: "0.2.9",
1200
+ version: "0.2.11",
1201
1201
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
1202
1202
  },
1203
1203
  security: [
@@ -6216,18 +6216,70 @@ async function fetchVaultCredential(binding, env) {
6216
6216
  }
6217
6217
 
6218
6218
  // src/provider-credential-onboarding.ts
6219
- import { z as z6 } from "zod";
6219
+ import { z as z7 } from "zod";
6220
6220
  import { createHash as createHash5 } from "crypto";
6221
6221
  import { createInterface } from "readline/promises";
6222
+
6223
+ // src/opencode-authentication.ts
6224
+ import { z as z6 } from "zod";
6225
+ var endpoint2 = "https://opencode.ai/zen/v1/systemone";
6226
+ var body = JSON.stringify({
6227
+ model: "jev-1.13-free",
6228
+ state: "The fixed test number is 7.",
6229
+ questions: { match: { type: "noul", instructions: "Is the fixed test number 7?" } }
6230
+ });
6231
+ var responseSchema = z6.object({
6232
+ model: z6.enum(["jev-1.13", "jev-1.13.0", "jev-1.13-free"]),
6233
+ answers: z6.object({ match: z6.object({ type: z6.literal("noul"), noul: z6.number().finite().min(0).max(1) }) }),
6234
+ usage: z6.object({ input_tokens: z6.number().int().nonnegative(), output_tokens: z6.number().int().nonnegative() })
6235
+ });
6236
+ var authErrorSchema = z6.object({ error: z6.object({ type: z6.enum(["AuthError", "server_error"]) }) });
6237
+ var unavailable = () => new Fault(502, "provider_auth_unavailable", "OpenCode authentication could not be verified with its free check. The selected credential was preserved; no paid model was requested.");
6238
+ function supportsOpenCodeAuthentication(provider) {
6239
+ return provider.credentialEnv === "SWITCHER_PROVIDER_OPENCODE" && ["https://opencode.ai/zen/v1", "https://opencode.ai/zen/v1/"].includes(provider.baseUrl) && (["openai-chat", "openai-responses"].includes(provider.protocol) ? (provider.authStyle ?? "bearer") === "bearer" : provider.protocol === "anthropic-messages" && provider.authStyle === "x-api-key");
6240
+ }
6241
+ async function verifyOpenCodeAuthentication(credential, fetchImpl) {
6242
+ if (!credential || /[\s\x00-\x1f\x7f]/u.test(credential) || credential.toLowerCase() === "public")
6243
+ return { authenticated: false, status: 401 };
6244
+ const signal = AbortSignal.timeout(1e4);
6245
+ const request = async (value) => {
6246
+ try {
6247
+ const response = await fetchImpl(endpoint2, {
6248
+ method: "POST",
6249
+ redirect: "manual",
6250
+ cache: "no-store",
6251
+ signal,
6252
+ body,
6253
+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": "hasna-switcher/credential-check", authorization: `Bearer ${value}` }
6254
+ });
6255
+ return { status: response.status, data: await boundedJson(response, 16 * 1024) };
6256
+ } catch {
6257
+ throw unavailable();
6258
+ }
6259
+ };
6260
+ for (const invalid of ["hasna-switcher-invalid-credential", "oc_sk_invalid"]) {
6261
+ const control = await request(invalid);
6262
+ if (control.status !== 401 || !authErrorSchema.safeParse(control.data).success)
6263
+ throw unavailable();
6264
+ }
6265
+ const result = await request(credential);
6266
+ if ((result.status === 401 || result.status === 403) && authErrorSchema.safeParse(result.data).success)
6267
+ return { authenticated: false, status: result.status };
6268
+ if (result.status !== 200 || !responseSchema.safeParse(result.data).success)
6269
+ throw unavailable();
6270
+ return { authenticated: true, status: 200 };
6271
+ }
6272
+
6273
+ // src/provider-credential-onboarding.ts
6222
6274
  var absent = (error) => error instanceof SwitcherError && error.status === 404;
6223
6275
  var MAX_CREDENTIAL_MATCHES = 256;
6224
- var secretMetadataSchema = z6.object({
6276
+ var secretMetadataSchema = z7.object({
6225
6277
  key: vaultKeySchema,
6226
- type: z6.enum(["api_key", "password", "token", "credential", "other"]),
6227
- label: z6.string().max(1000).nullable().optional(),
6228
- expires_at: z6.string().max(200).nullable().optional(),
6229
- created_at: z6.string().max(200),
6230
- updated_at: z6.string().max(200)
6278
+ type: z7.enum(["api_key", "password", "token", "credential", "other"]),
6279
+ label: z7.string().max(1000).nullable().optional(),
6280
+ expires_at: z7.string().max(200).nullable().optional(),
6281
+ created_at: z7.string().max(200),
6282
+ updated_at: z7.string().max(200)
6231
6283
  }).strict();
6232
6284
  var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
6233
6285
  var credentialOrigins = (provider) => {
@@ -6336,6 +6388,8 @@ function authenticationProbe(provider) {
6336
6388
  return;
6337
6389
  }
6338
6390
  async function verifyProviderAuthentication({ provider, credential, fetch: fetchImpl = fetch }) {
6391
+ if (!provider.credentialCheck && supportsOpenCodeAuthentication(provider))
6392
+ return verifyOpenCodeAuthentication(credential, fetchImpl);
6339
6393
  const probe = authenticationProbe(provider);
6340
6394
  if (!probe)
6341
6395
  return { authenticated: false, unsupported: true };
@@ -6487,7 +6541,7 @@ var clientFromEnv2 = () => {
6487
6541
  throw new Fault(503, "unavailable", "Switcher API runtime is not open.");
6488
6542
  return runtime.client;
6489
6543
  };
6490
- var page = { limit: z7.number().int().min(1).max(1000).optional(), offset: z7.number().int().nonnegative().optional(), search: z7.string().optional() };
6544
+ var page = { limit: z8.number().int().min(1).max(1000).optional(), offset: z8.number().int().nonnegative().optional(), search: z8.string().optional() };
6491
6545
  function tool(name, description, schema, run) {
6492
6546
  server.tool(name, description, schema, async (input) => {
6493
6547
  try {
@@ -6498,18 +6552,18 @@ function tool(name, description, schema, run) {
6498
6552
  });
6499
6553
  }
6500
6554
  tool("providers_list", "List provider profiles.", page, (p) => clientFromEnv2().listProviders(p));
6501
- tool("providers_get", "Get a provider.", { id: z7.string() }, (p) => clientFromEnv2().getProvider(p.id));
6555
+ tool("providers_get", "Get a provider.", { id: z8.string() }, (p) => clientFromEnv2().getProvider(p.id));
6502
6556
  tool("providers_create", "Create a provider using credential environment references only.", providerInputSchema.innerType().shape, (p) => clientFromEnv2().createProvider(p));
6503
- tool("providers_update", "Replace a provider at its current version.", { provider: providerInputSchema, version: z7.number().int() }, (p) => clientFromEnv2().updateProvider(p.provider, p.version));
6504
- tool("providers_delete", "Delete an unreferenced provider.", { id: z7.string(), version: z7.number().int() }, (p) => clientFromEnv2().deleteProvider(p.id, p.version));
6505
- tool("models_list", "List catalog with capability information.", { id: z7.string(), ...page }, (p) => {
6557
+ tool("providers_update", "Replace a provider at its current version.", { provider: providerInputSchema, version: z8.number().int() }, (p) => clientFromEnv2().updateProvider(p.provider, p.version));
6558
+ tool("providers_delete", "Delete an unreferenced provider.", { id: z8.string(), version: z8.number().int() }, (p) => clientFromEnv2().deleteProvider(p.id, p.version));
6559
+ tool("models_list", "List catalog with capability information.", { id: z8.string(), ...page }, (p) => {
6506
6560
  const { id: id2, ...rest } = p;
6507
6561
  return clientFromEnv2().listModels(id2, rest);
6508
6562
  });
6509
- tool("models_add", "Add saved model metadata; discovery stays active unless the provider uses a manual catalog.", { providerId: z7.string(), model: modelSchema }, (p) => clientFromEnv2().addModel(p.providerId, p.model));
6510
- tool("models_update", "Replace all saved metadata for a configured model.", { providerId: z7.string(), model: modelSchema }, (p) => clientFromEnv2().updateModel(p.providerId, p.model));
6511
- tool("models_remove", "Remove saved model metadata; upstream catalog entries remain.", { providerId: z7.string(), modelId: modelSchema.shape.id }, (p) => clientFromEnv2().removeModel(p.providerId, p.modelId));
6512
- tool("models_refresh", "Discover provider models.", { id: z7.string() }, async (p) => {
6563
+ tool("models_add", "Add saved model metadata; discovery stays active unless the provider uses a manual catalog.", { providerId: z8.string(), model: modelSchema }, (p) => clientFromEnv2().addModel(p.providerId, p.model));
6564
+ tool("models_update", "Replace all saved metadata for a configured model.", { providerId: z8.string(), model: modelSchema }, (p) => clientFromEnv2().updateModel(p.providerId, p.model));
6565
+ tool("models_remove", "Remove saved model metadata; upstream catalog entries remain.", { providerId: z8.string(), modelId: modelSchema.shape.id }, (p) => clientFromEnv2().removeModel(p.providerId, p.modelId));
6566
+ tool("models_refresh", "Discover provider models.", { id: z8.string() }, async (p) => {
6513
6567
  const client = clientFromEnv2(), provider = await client.getProvider(p.id);
6514
6568
  if (runtime?.mode !== "remote")
6515
6569
  return client.refreshModels(provider.id);
@@ -6518,13 +6572,13 @@ tool("models_refresh", "Discover provider models.", { id: z7.string() }, async (
6518
6572
  return launchCatalog(client, provider, false, { clientSide: true, credential, resolveCredential: (candidate) => credentials.resolve(candidate) });
6519
6573
  });
6520
6574
  tool("profiles_list", "List harness launch profiles.", page, (p) => clientFromEnv2().listProfiles(p));
6521
- tool("profiles_get", "Get a harness profile.", { id: z7.string() }, (p) => clientFromEnv2().getProfile(p.id));
6575
+ tool("profiles_get", "Get a harness profile.", { id: z8.string() }, (p) => clientFromEnv2().getProfile(p.id));
6522
6576
  tool("profiles_create", "Create a harness launch profile.", profileInputSchema.shape, (p) => clientFromEnv2().createProfile(p));
6523
- tool("profiles_update", "Replace a harness profile at its version.", { profile: profileInputSchema, version: z7.number().int() }, (p) => clientFromEnv2().updateProfile(p.profile, p.version));
6524
- tool("profiles_delete", "Delete a profile without run history.", { id: z7.string(), version: z7.number().int() }, (p) => clientFromEnv2().deleteProfile(p.id, p.version));
6525
- tool("launch_plan", "Validate a local launch plan; does not execute a remote process.", { profileId: z7.string() }, (p) => clientFromEnv2().launchPlan(p.profileId));
6577
+ tool("profiles_update", "Replace a harness profile at its version.", { profile: profileInputSchema, version: z8.number().int() }, (p) => clientFromEnv2().updateProfile(p.profile, p.version));
6578
+ tool("profiles_delete", "Delete a profile without run history.", { id: z8.string(), version: z8.number().int() }, (p) => clientFromEnv2().deleteProfile(p.id, p.version));
6579
+ tool("launch_plan", "Validate a local launch plan; does not execute a remote process.", { profileId: z8.string() }, (p) => clientFromEnv2().launchPlan(p.profileId));
6526
6580
  tool("runs_list", "List launch metadata.", page, (p) => clientFromEnv2().listRuns(p));
6527
- tool("runs_get", "Get launch metadata.", { id: z7.string() }, (p) => clientFromEnv2().getRun(p.id));
6581
+ tool("runs_get", "Get launch metadata.", { id: z8.string() }, (p) => clientFromEnv2().getRun(p.id));
6528
6582
  if (process.argv.includes("--version"))
6529
6583
  console.log(VERSION);
6530
6584
  else if (process.argv.includes("--help"))
@@ -16,6 +16,9 @@ type Entry = {
16
16
  export declare const NATIVE_STATE_ENTRIES: Record<SharedNativeTool, readonly Entry[]>;
17
17
  export declare function assertNativeStateDirectory(path: string): Promise<void>;
18
18
  export declare function ensureNativeStateDirectory(path: string, create?: boolean): Promise<void>;
19
+ /** Disabling projection must not silently reuse a previously shared overlay.
20
+ * Keep existing links intact; a different isolated profile is an explicit choice. */
21
+ export declare function assertNativeStateIsolation(tool: SharedNativeTool, home: string, environment?: NodeJS.ProcessEnv): Promise<void>;
19
22
  export declare function withNativeStateLock<T>(state: NativeState, operation: () => Promise<T>): Promise<T>;
20
23
  /** A nested CLI keeps its authentication home. Refuse conflicting instruction
21
24
  * overlays rather than rewriting account config or exposing instructions in argv. */
@@ -0,0 +1,11 @@
1
+ import { type ProviderInput } from "./domain";
2
+ export declare function supportsOpenCodeAuthentication(provider: ProviderInput): boolean;
3
+ /** A valid supplied key is required even though this fixed synthetic request is free.
4
+ * Anonymous responses alone are not authentication evidence: first require rejection
5
+ * of invalid keys through both legacy and migrated routing. A legacy-shaped
6
+ * selected key may have been migrated, which cannot be inferred from its prefix.
7
+ */
8
+ export declare function verifyOpenCodeAuthentication(credential: string, fetchImpl: typeof fetch): Promise<{
9
+ authenticated: boolean;
10
+ status: number;
11
+ }>;
package/dist/sdk.js CHANGED
@@ -432,9 +432,14 @@ async function detectChatGPTApp(appPath, system = host) {
432
432
  const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
433
433
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
434
434
  continue;
435
- const executable = join(path, "Contents/MacOS", name), codexExecutable = join(path, "Contents/Resources/codex");
436
- if (await system.executable(executable) && await system.executable(codexExecutable))
437
- return { path, executable, codexExecutable, bundleId, version: version2 };
435
+ const executable = join(path, "Contents/MacOS", name);
436
+ if (!await system.executable(executable))
437
+ continue;
438
+ for (const relative of ["Contents/Resources/codex", "Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex"]) {
439
+ const codexExecutable = join(path, relative);
440
+ if (await system.executable(codexExecutable))
441
+ return { path, executable, codexExecutable, bundleId, version: version2 };
442
+ }
438
443
  } catch {}
439
444
  }
440
445
  throw new Fault(404, "app_not_installed", "Install the current ChatGPT/Codex macOS app or use --app-path with its absolute .app path. Legacy ChatGPT Classic cannot run custom Codex providers.");
@@ -68,7 +68,7 @@ function canonicalPolicyJSON(value) {
68
68
  return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
69
69
  }
70
70
  // package.json
71
- var version = "0.2.9";
71
+ var version = "0.2.11";
72
72
 
73
73
  // src/version.ts
74
74
  var VERSION = version;
@@ -922,7 +922,7 @@ var openapi_default = {
922
922
  openapi: "3.0.3",
923
923
  info: {
924
924
  title: "Switcher API",
925
- version: "0.2.9",
925
+ version: "0.2.11",
926
926
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
927
927
  },
928
928
  security: [
@@ -4,7 +4,7 @@
4
4
  "name": "switcher",
5
5
  "class": "cli-with-store",
6
6
  "contractVersion": "v1",
7
- "kitVersion": "1.3.0",
7
+ "kitVersion": "1.3.3",
8
8
  "description": "Universal provider and model switcher with API-first local and hosted operation. CLI, MCP and SDK resolve one authenticated HTTP authority through @hasna/contracts and fail closed when hosted configuration is missing or invalid. HASNA_SWITCHER_LOCAL=1 deliberately selects an owned loopback API backed by SQLite; hosted https://api.hasna.com/switcher uses PostgreSQL and signed revocable API keys. Provider credentials remain local to the launcher and are never stored or returned by the service.",
9
9
  "bins": [
10
10
  "switcher",
package/openapi.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "openapi": "3.0.3",
3
3
  "info": {
4
4
  "title": "Switcher API",
5
- "version": "0.2.9",
5
+ "version": "0.2.11",
6
6
  "description": "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
7
7
  },
8
8
  "security": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/switcher",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
4
4
  "type": "module",
5
5
  "description": "Universal provider and model switcher for coding harnesses with an API, SDK and self-hosted storage",
6
6
  "license": "Apache-2.0",
@@ -72,7 +72,7 @@
72
72
  "@types/pg": "8.23.1"
73
73
  },
74
74
  "dependencies": {
75
- "@hasna/contracts": "1.3.0",
75
+ "@hasna/contracts": "1.3.3",
76
76
  "@modelcontextprotocol/sdk": "^1.29.0",
77
77
  "jsonc-parser": "3.3.1",
78
78
  "yaml": "2.9.0",