@hasna/switcher 0.2.1 → 0.2.3
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/Dockerfile +38 -8
- package/README.md +43 -13
- package/dist/cli/index.js +2855 -2189
- package/dist/credentials.d.ts +52 -7
- package/dist/direct-launch.d.ts +1 -0
- package/dist/domain.d.ts +140 -4
- package/dist/generated/api.d.ts +141 -1
- package/dist/index.js +21 -12
- package/dist/launcher.d.ts +1 -0
- package/dist/mcp/index.js +1152 -96
- package/dist/mint/index.js +136 -0
- package/dist/mint-key.d.ts +34 -0
- package/dist/presets.d.ts +8 -0
- package/dist/provider-credential-onboarding.d.ts +73 -0
- package/dist/sdk.d.ts +57 -1
- package/dist/sdk.js +21 -12
- package/dist/serve/index.js +447 -91
- package/dist/server.d.ts +2 -1
- package/dist/service.d.ts +8 -1
- package/dist/store.d.ts +4 -0
- package/hasna.contract.json +20 -6
- package/openapi.json +227 -9
- package/package.json +6 -3
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/mint-key.ts
|
|
3
|
+
import { createHash } from "crypto";
|
|
4
|
+
import { dirname, join } from "path";
|
|
5
|
+
import { fileURLToPath } from "url";
|
|
6
|
+
import { access } from "fs/promises";
|
|
7
|
+
import { GetSecretValueCommand, PutSecretValueCommand, SecretsManagerClient } from "@aws-sdk/client-secrets-manager";
|
|
8
|
+
import { ApiKeyStore } from "@hasna/contracts/auth";
|
|
9
|
+
import pg from "pg";
|
|
10
|
+
var APP = "switcher";
|
|
11
|
+
var DEFAULT_SECRET_ID = "hasna/oss/switcher/api-key";
|
|
12
|
+
var MAX_OUTPUT = 1024 * 1024;
|
|
13
|
+
var required = (env, name) => {
|
|
14
|
+
const value = env[name]?.trim();
|
|
15
|
+
if (!value)
|
|
16
|
+
throw new Error(`Missing ${name}.`);
|
|
17
|
+
return value;
|
|
18
|
+
};
|
|
19
|
+
async function bounded(stream) {
|
|
20
|
+
if (!stream)
|
|
21
|
+
return "";
|
|
22
|
+
const reader = stream.getReader();
|
|
23
|
+
let size = 0;
|
|
24
|
+
const chunks = [];
|
|
25
|
+
try {
|
|
26
|
+
for (;; ) {
|
|
27
|
+
const item = await reader.read();
|
|
28
|
+
if (item.done)
|
|
29
|
+
break;
|
|
30
|
+
size += item.value.byteLength;
|
|
31
|
+
if (size > MAX_OUTPUT)
|
|
32
|
+
throw new Error("Mint subprocess output exceeded its bound.");
|
|
33
|
+
chunks.push(item.value);
|
|
34
|
+
}
|
|
35
|
+
} finally {
|
|
36
|
+
await reader.cancel().catch(() => {});
|
|
37
|
+
}
|
|
38
|
+
const data = new Uint8Array(size);
|
|
39
|
+
let offset = 0;
|
|
40
|
+
for (const chunk of chunks) {
|
|
41
|
+
data.set(chunk, offset);
|
|
42
|
+
offset += chunk.length;
|
|
43
|
+
}
|
|
44
|
+
return new TextDecoder().decode(data);
|
|
45
|
+
}
|
|
46
|
+
async function issueKey(request) {
|
|
47
|
+
const authEntry = fileURLToPath(import.meta.resolve("@hasna/contracts/auth"));
|
|
48
|
+
const cli = join(dirname(authEntry), "..", "cli", "index.js");
|
|
49
|
+
await access(cli);
|
|
50
|
+
const child = Bun.spawn([process.execPath, cli, "issue-key", "--app", APP, "--agent", request.agent, "--scopes", request.scopes, "--ttl-days", request.ttlDays, "--json"], {
|
|
51
|
+
env: { ...process.env, HASNA_SWITCHER_DATABASE_URL: request.databaseUrl, HASNA_SWITCHER_API_SIGNING_KEY: request.signingSecret },
|
|
52
|
+
stdin: "ignore",
|
|
53
|
+
stdout: "pipe",
|
|
54
|
+
stderr: "pipe"
|
|
55
|
+
});
|
|
56
|
+
const [code, stdout] = await Promise.all([child.exited, bounded(child.stdout), bounded(child.stderr).then(() => {
|
|
57
|
+
return;
|
|
58
|
+
})]).then(([exit, text]) => [exit, text]);
|
|
59
|
+
let result;
|
|
60
|
+
try {
|
|
61
|
+
result = JSON.parse(stdout);
|
|
62
|
+
} catch {
|
|
63
|
+
throw new Error("Credential issuer returned invalid output.");
|
|
64
|
+
}
|
|
65
|
+
const value = result;
|
|
66
|
+
if (code !== 0 || value.ok !== true || value.stored !== true || typeof value.token !== "string" || !value.token || typeof value.kid !== "string" || !value.kid)
|
|
67
|
+
throw new Error("Credential issuer failed.");
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
async function putSecret(request) {
|
|
71
|
+
const client = new SecretsManagerClient({ region: process.env.AWS_REGION ?? "us-east-1" });
|
|
72
|
+
const version = createHash("sha256").update(request.token).digest("hex");
|
|
73
|
+
try {
|
|
74
|
+
await client.send(new PutSecretValueCommand({ SecretId: request.secretId, SecretString: request.token, ClientRequestToken: version }));
|
|
75
|
+
} catch (error) {
|
|
76
|
+
try {
|
|
77
|
+
const observed = await client.send(new GetSecretValueCommand({ SecretId: request.secretId, VersionId: version }));
|
|
78
|
+
if (observed.SecretString === request.token)
|
|
79
|
+
return;
|
|
80
|
+
} catch {}
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function revoke(request) {
|
|
85
|
+
const pool = new pg.Pool({ connectionString: request.databaseUrl, max: 1, connectionTimeoutMillis: 1e4 });
|
|
86
|
+
try {
|
|
87
|
+
const store = new ApiKeyStore({
|
|
88
|
+
many: async (sql, params = []) => (await pool.query(sql, [...params])).rows,
|
|
89
|
+
get: async (sql, params = []) => (await pool.query(sql, [...params])).rows[0] ?? null,
|
|
90
|
+
execute: async (sql, params = []) => {
|
|
91
|
+
await pool.query(sql, [...params]);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
if (!await store.revoke(request.kid, "credential_delivery_failed", Date.now(), { app: APP }))
|
|
95
|
+
throw new Error("Issued key could not be revoked after delivery failure.");
|
|
96
|
+
} finally {
|
|
97
|
+
await pool.end();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
async function mintSwitcherFleetKey(options = {}) {
|
|
101
|
+
const env = options.env ?? process.env, write = options.write ?? ((line) => console.log(line));
|
|
102
|
+
const databaseUrl = required(env, "HASNA_SWITCHER_DATABASE_URL"), signingSecret = required(env, "HASNA_SWITCHER_API_SIGNING_KEY");
|
|
103
|
+
const secretId = (env.MINT_SECRET_ID ?? DEFAULT_SECRET_ID).trim();
|
|
104
|
+
if (secretId !== DEFAULT_SECRET_ID)
|
|
105
|
+
throw new Error("Refusing a non-Switcher client-key destination.");
|
|
106
|
+
const agent = (env.MINT_AGENT ?? "fleet").trim();
|
|
107
|
+
if (!/^[A-Za-z0-9._-]{1,100}$/.test(agent))
|
|
108
|
+
throw new Error("Invalid MINT_AGENT.");
|
|
109
|
+
const scopes = (env.MINT_SCOPES ?? "switcher:read,switcher:write").trim();
|
|
110
|
+
if (scopes !== "switcher:read,switcher:write")
|
|
111
|
+
throw new Error("Switcher fleet mint requires the exact read/write scopes.");
|
|
112
|
+
const ttlDays = (env.MINT_TTL_DAYS ?? "365").trim();
|
|
113
|
+
if (!/^[1-9]\d{0,3}$/.test(ttlDays))
|
|
114
|
+
throw new Error("Invalid MINT_TTL_DAYS.");
|
|
115
|
+
const issued = await (options.issueKey ?? issueKey)({ databaseUrl, signingSecret, agent, scopes, ttlDays });
|
|
116
|
+
try {
|
|
117
|
+
await (options.putSecret ?? putSecret)({ secretId, token: issued.token, kid: issued.kid });
|
|
118
|
+
} catch {
|
|
119
|
+
try {
|
|
120
|
+
await (options.revoke ?? revoke)({ databaseUrl, kid: issued.kid });
|
|
121
|
+
} catch {
|
|
122
|
+
throw new Error("Credential delivery failed and issued-key revocation could not be confirmed.");
|
|
123
|
+
}
|
|
124
|
+
throw new Error("Credential delivery failed; the issued key was revoked.");
|
|
125
|
+
}
|
|
126
|
+
write(JSON.stringify({ event: "fleet-key-minted", app: APP, kid: issued.kid, agent: issued.agent ?? agent, scopes: issued.scopes ?? scopes.split(","), expiresAt: issued.expiresAt ?? null, secretId }));
|
|
127
|
+
return { kid: issued.kid, secretId };
|
|
128
|
+
}
|
|
129
|
+
if (import.meta.main)
|
|
130
|
+
mintSwitcherFleetKey().catch((error) => {
|
|
131
|
+
console.error(error instanceof Error ? error.message : "Fleet key mint failed.");
|
|
132
|
+
process.exitCode = 1;
|
|
133
|
+
});
|
|
134
|
+
export {
|
|
135
|
+
mintSwitcherFleetKey
|
|
136
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
type MintResult = {
|
|
2
|
+
ok: true;
|
|
3
|
+
stored: true;
|
|
4
|
+
token: string;
|
|
5
|
+
kid: string;
|
|
6
|
+
agent?: string;
|
|
7
|
+
scopes?: string[];
|
|
8
|
+
expiresAt?: string | null;
|
|
9
|
+
};
|
|
10
|
+
type MintOptions = {
|
|
11
|
+
env?: NodeJS.ProcessEnv;
|
|
12
|
+
issueKey?: (request: {
|
|
13
|
+
databaseUrl: string;
|
|
14
|
+
signingSecret: string;
|
|
15
|
+
agent: string;
|
|
16
|
+
scopes: string;
|
|
17
|
+
ttlDays: string;
|
|
18
|
+
}) => Promise<MintResult>;
|
|
19
|
+
putSecret?: (request: {
|
|
20
|
+
secretId: string;
|
|
21
|
+
token: string;
|
|
22
|
+
kid: string;
|
|
23
|
+
}) => Promise<void>;
|
|
24
|
+
revoke?: (request: {
|
|
25
|
+
databaseUrl: string;
|
|
26
|
+
kid: string;
|
|
27
|
+
}) => Promise<void>;
|
|
28
|
+
write?: (line: string) => void;
|
|
29
|
+
};
|
|
30
|
+
export declare function mintSwitcherFleetKey(options?: MintOptions): Promise<{
|
|
31
|
+
kid: string;
|
|
32
|
+
secretId: string;
|
|
33
|
+
}>;
|
|
34
|
+
export {};
|
package/dist/presets.d.ts
CHANGED
|
@@ -12,6 +12,10 @@ export declare function getProviderPreset(id: string): {
|
|
|
12
12
|
modelsPath: string;
|
|
13
13
|
notes: string[];
|
|
14
14
|
baseUrl?: string | undefined;
|
|
15
|
+
credentialCheck?: {
|
|
16
|
+
path: string;
|
|
17
|
+
method: "GET" | "HEAD";
|
|
18
|
+
} | undefined;
|
|
15
19
|
catalogBaseUrl?: string | undefined;
|
|
16
20
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none" | undefined;
|
|
17
21
|
}[];
|
|
@@ -55,6 +59,10 @@ export declare function providerFromPreset(presetId: string, options?: PresetOpt
|
|
|
55
59
|
supportedGenerationMethods?: string[] | undefined;
|
|
56
60
|
}[];
|
|
57
61
|
credentialEnv?: string | undefined;
|
|
62
|
+
credentialCheck?: {
|
|
63
|
+
path: string;
|
|
64
|
+
method: "GET" | "HEAD";
|
|
65
|
+
} | undefined;
|
|
58
66
|
catalogBaseUrl?: string | undefined;
|
|
59
67
|
catalogFormat?: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none" | undefined;
|
|
60
68
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none" | undefined;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { type CatalogCredentialResolver } from "./catalog";
|
|
2
|
+
import { type Catalog, type Provider, type ProviderInput } from "./domain";
|
|
3
|
+
import { SwitcherClient } from "./sdk";
|
|
4
|
+
import { CredentialBindings, CredentialResolver, type VaultOperatorResolution } from "./credentials";
|
|
5
|
+
export type VaultCredentialReference = {
|
|
6
|
+
account: string;
|
|
7
|
+
key: string;
|
|
8
|
+
url?: string;
|
|
9
|
+
executable: string;
|
|
10
|
+
operator: {
|
|
11
|
+
kind: "contracts";
|
|
12
|
+
expectedSource?: string;
|
|
13
|
+
expectedTier?: VaultOperatorResolution["tier"];
|
|
14
|
+
} | {
|
|
15
|
+
kind: "env";
|
|
16
|
+
} | {
|
|
17
|
+
kind: "keychain";
|
|
18
|
+
account: string;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
type CredentialResolverLike = Pick<CredentialResolver, "resolve"> & {
|
|
22
|
+
bindings: Pick<CredentialBindings, "get" | "bind">;
|
|
23
|
+
};
|
|
24
|
+
export type ProviderAuthenticationResult = {
|
|
25
|
+
authenticated: boolean;
|
|
26
|
+
status?: number;
|
|
27
|
+
unsupported?: boolean;
|
|
28
|
+
};
|
|
29
|
+
export type EnsureProviderCredentialOptions = {
|
|
30
|
+
interactive?: boolean;
|
|
31
|
+
resolver?: CredentialResolverLike;
|
|
32
|
+
env?: NodeJS.ProcessEnv;
|
|
33
|
+
vaultExecutable?: string;
|
|
34
|
+
discoverVaultReferences?: (request: {
|
|
35
|
+
provider: ProviderInput;
|
|
36
|
+
credentialEnv: string;
|
|
37
|
+
}) => Promise<VaultCredentialReference[]>;
|
|
38
|
+
selectVaultReference?: (request: {
|
|
39
|
+
provider: ProviderInput;
|
|
40
|
+
matches: VaultCredentialReference[];
|
|
41
|
+
}) => Promise<VaultCredentialReference | undefined>;
|
|
42
|
+
verifyProviderAuthentication?: (request: {
|
|
43
|
+
provider: ProviderInput;
|
|
44
|
+
credential: string;
|
|
45
|
+
}) => Promise<ProviderAuthenticationResult>;
|
|
46
|
+
};
|
|
47
|
+
export type PreparedProviderCredential = {
|
|
48
|
+
source: "not-required" | "environment" | "binding";
|
|
49
|
+
configured: boolean;
|
|
50
|
+
verified: boolean;
|
|
51
|
+
providerFingerprint: string;
|
|
52
|
+
readonly resolveCredential: (provider: ProviderInput) => Promise<string | undefined>;
|
|
53
|
+
};
|
|
54
|
+
export declare const providerCredentialSetupCommand: (provider: ProviderInput) => string;
|
|
55
|
+
export declare function discoverVaultReferences(provider: ProviderInput, env?: NodeJS.ProcessEnv, vaultExecutable?: string): Promise<VaultCredentialReference[]>;
|
|
56
|
+
export declare function selectVaultReference({ provider, matches }: {
|
|
57
|
+
provider: ProviderInput;
|
|
58
|
+
matches: VaultCredentialReference[];
|
|
59
|
+
}): Promise<VaultCredentialReference | undefined>;
|
|
60
|
+
export declare function verifyProviderAuthentication({ provider, credential, fetch: fetchImpl }: {
|
|
61
|
+
provider: ProviderInput;
|
|
62
|
+
credential: string;
|
|
63
|
+
fetch?: typeof fetch;
|
|
64
|
+
}): Promise<ProviderAuthenticationResult>;
|
|
65
|
+
export declare function providerCredentialFingerprint(provider: ProviderInput): string;
|
|
66
|
+
export declare function ensureProviderCredential(provider: ProviderInput, options?: EnsureProviderCredentialOptions): Promise<PreparedProviderCredential>;
|
|
67
|
+
export type LaunchCatalogOptions = {
|
|
68
|
+
clientSide?: boolean;
|
|
69
|
+
credential?: string;
|
|
70
|
+
resolveCredential?: CatalogCredentialResolver;
|
|
71
|
+
};
|
|
72
|
+
export declare function launchCatalog(client: SwitcherClient, provider: Provider, dryRun?: boolean, options?: LaunchCatalogOptions): Promise<Catalog>;
|
|
73
|
+
export {};
|
package/dist/sdk.d.ts
CHANGED
|
@@ -55,7 +55,9 @@ export declare class SwitcherClient {
|
|
|
55
55
|
backend: "sqlite" | "postgresql";
|
|
56
56
|
}>;
|
|
57
57
|
ready(): Promise<{
|
|
58
|
-
|
|
58
|
+
status: "ready" | "unavailable";
|
|
59
|
+
version: string;
|
|
60
|
+
backend: "sqlite" | "postgresql";
|
|
59
61
|
reason?: string;
|
|
60
62
|
}>;
|
|
61
63
|
version(): Promise<{
|
|
@@ -73,6 +75,10 @@ export declare class SwitcherClient {
|
|
|
73
75
|
protocol: "anthropic-messages" | "openai-responses" | "openai-chat" | "gemini-generate-content";
|
|
74
76
|
baseUrl?: string;
|
|
75
77
|
authStyle: "bearer" | "x-api-key" | "api-key";
|
|
78
|
+
credentialCheck?: {
|
|
79
|
+
method: "GET" | "HEAD";
|
|
80
|
+
path: string;
|
|
81
|
+
};
|
|
76
82
|
catalogBaseUrl?: string;
|
|
77
83
|
catalogFormat: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none";
|
|
78
84
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none";
|
|
@@ -89,6 +95,10 @@ export declare class SwitcherClient {
|
|
|
89
95
|
protocol: "anthropic-messages" | "openai-responses" | "openai-chat" | "gemini-generate-content";
|
|
90
96
|
credentialEnv?: string;
|
|
91
97
|
authStyle: "bearer" | "x-api-key" | "api-key";
|
|
98
|
+
credentialCheck?: {
|
|
99
|
+
method: "GET" | "HEAD";
|
|
100
|
+
path: string;
|
|
101
|
+
};
|
|
92
102
|
catalogBaseUrl?: string;
|
|
93
103
|
catalogFormat?: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none";
|
|
94
104
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none";
|
|
@@ -133,6 +143,10 @@ export declare class SwitcherClient {
|
|
|
133
143
|
protocol: "anthropic-messages" | "openai-responses" | "openai-chat" | "gemini-generate-content";
|
|
134
144
|
credentialEnv?: string;
|
|
135
145
|
authStyle: "bearer" | "x-api-key" | "api-key";
|
|
146
|
+
credentialCheck?: {
|
|
147
|
+
method: "GET" | "HEAD";
|
|
148
|
+
path: string;
|
|
149
|
+
};
|
|
136
150
|
catalogBaseUrl?: string;
|
|
137
151
|
catalogFormat?: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none";
|
|
138
152
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none";
|
|
@@ -177,6 +191,10 @@ export declare class SwitcherClient {
|
|
|
177
191
|
protocol: "anthropic-messages" | "openai-responses" | "openai-chat" | "gemini-generate-content";
|
|
178
192
|
credentialEnv?: string;
|
|
179
193
|
authStyle: "bearer" | "x-api-key" | "api-key";
|
|
194
|
+
credentialCheck?: {
|
|
195
|
+
method: "GET" | "HEAD";
|
|
196
|
+
path: string;
|
|
197
|
+
};
|
|
180
198
|
catalogBaseUrl?: string;
|
|
181
199
|
catalogFormat?: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none";
|
|
182
200
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none";
|
|
@@ -221,6 +239,10 @@ export declare class SwitcherClient {
|
|
|
221
239
|
protocol: "anthropic-messages" | "openai-responses" | "openai-chat" | "gemini-generate-content";
|
|
222
240
|
credentialEnv?: string;
|
|
223
241
|
authStyle: "bearer" | "x-api-key" | "api-key";
|
|
242
|
+
credentialCheck?: {
|
|
243
|
+
method: "GET" | "HEAD";
|
|
244
|
+
path: string;
|
|
245
|
+
};
|
|
224
246
|
catalogBaseUrl?: string;
|
|
225
247
|
catalogFormat?: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none";
|
|
226
248
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none";
|
|
@@ -272,6 +294,10 @@ export declare class SwitcherClient {
|
|
|
272
294
|
protocol: "anthropic-messages" | "openai-responses" | "openai-chat" | "gemini-generate-content";
|
|
273
295
|
credentialEnv?: string;
|
|
274
296
|
authStyle: "bearer" | "x-api-key" | "api-key";
|
|
297
|
+
credentialCheck?: {
|
|
298
|
+
method: "GET" | "HEAD";
|
|
299
|
+
path: string;
|
|
300
|
+
};
|
|
275
301
|
catalogBaseUrl?: string;
|
|
276
302
|
catalogFormat?: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none";
|
|
277
303
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none";
|
|
@@ -317,6 +343,10 @@ export declare class SwitcherClient {
|
|
|
317
343
|
protocol: "anthropic-messages" | "openai-responses" | "openai-chat" | "gemini-generate-content";
|
|
318
344
|
credentialEnv?: string;
|
|
319
345
|
authStyle: "bearer" | "x-api-key" | "api-key";
|
|
346
|
+
credentialCheck?: {
|
|
347
|
+
method: "GET" | "HEAD";
|
|
348
|
+
path: string;
|
|
349
|
+
};
|
|
320
350
|
catalogBaseUrl?: string;
|
|
321
351
|
catalogFormat?: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none";
|
|
322
352
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none";
|
|
@@ -361,6 +391,10 @@ export declare class SwitcherClient {
|
|
|
361
391
|
protocol: "anthropic-messages" | "openai-responses" | "openai-chat" | "gemini-generate-content";
|
|
362
392
|
credentialEnv?: string;
|
|
363
393
|
authStyle: "bearer" | "x-api-key" | "api-key";
|
|
394
|
+
credentialCheck?: {
|
|
395
|
+
method: "GET" | "HEAD";
|
|
396
|
+
path: string;
|
|
397
|
+
};
|
|
364
398
|
catalogBaseUrl?: string;
|
|
365
399
|
catalogFormat?: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none";
|
|
366
400
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none";
|
|
@@ -416,6 +450,24 @@ export declare class SwitcherClient {
|
|
|
416
450
|
refreshedAt: string;
|
|
417
451
|
source: "remote" | "manual";
|
|
418
452
|
}>;
|
|
453
|
+
saveCatalog(id: string, providerVersion: number, catalog: Catalog, idempotencyKey?: string): Promise<{
|
|
454
|
+
models: {
|
|
455
|
+
id: string;
|
|
456
|
+
name: string;
|
|
457
|
+
description?: string;
|
|
458
|
+
available?: boolean;
|
|
459
|
+
expiresOn?: string;
|
|
460
|
+
contextWindow?: number;
|
|
461
|
+
maxOutputTokens?: number;
|
|
462
|
+
inputModalities?: string[];
|
|
463
|
+
outputModalities?: string[];
|
|
464
|
+
supportedParameters?: string[];
|
|
465
|
+
reasoningEfforts?: ("none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | "ultra")[];
|
|
466
|
+
supportedGenerationMethods?: string[];
|
|
467
|
+
}[];
|
|
468
|
+
refreshedAt: string;
|
|
469
|
+
source: "remote" | "manual";
|
|
470
|
+
}>;
|
|
419
471
|
listModels(id: string, options?: {}): Promise<{
|
|
420
472
|
data: {
|
|
421
473
|
id: string;
|
|
@@ -566,6 +618,10 @@ export declare class SwitcherClient {
|
|
|
566
618
|
protocol: "anthropic-messages" | "openai-responses" | "openai-chat" | "gemini-generate-content";
|
|
567
619
|
credentialEnv?: string;
|
|
568
620
|
authStyle: "bearer" | "x-api-key" | "api-key";
|
|
621
|
+
credentialCheck?: {
|
|
622
|
+
method: "GET" | "HEAD";
|
|
623
|
+
path: string;
|
|
624
|
+
};
|
|
569
625
|
catalogBaseUrl?: string;
|
|
570
626
|
catalogFormat?: "openai" | "ollama" | "mistral" | "together" | "fireworks" | "dashscope" | "gemini" | "none";
|
|
571
627
|
catalogAuthStyle?: "bearer" | "x-api-key" | "api-key" | "none";
|
package/dist/sdk.js
CHANGED
|
@@ -75,6 +75,8 @@ var urlSchema = z3.string().max(2000).superRefine((v, ctx) => {
|
|
|
75
75
|
ctx.addIssue({ code: "custom", message: "Invalid endpoint URL" });
|
|
76
76
|
}
|
|
77
77
|
}).transform(endpoint);
|
|
78
|
+
var credentialCheckPath = z3.string().min(1).max(200).regex(/^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$/).refine((value) => !value.startsWith("/") && !value.split("/").some((part) => part === "." || part === ".."), "credentialCheck.path must be relative without dot segments");
|
|
79
|
+
var credentialCheckSchema = z3.object({ method: z3.enum(["GET", "HEAD"]).default("GET"), path: credentialCheckPath }).strict();
|
|
78
80
|
var expiresOnSchema = z3.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
|
|
79
81
|
const day = new Date(`${value}T00:00:00.000Z`);
|
|
80
82
|
return Number.isFinite(day.getTime()) && day.toISOString().slice(0, 10) === value;
|
|
@@ -100,6 +102,7 @@ var providerInputSchema = z3.object({
|
|
|
100
102
|
protocol: protocolSchema,
|
|
101
103
|
credentialEnv: envRef.optional(),
|
|
102
104
|
authStyle: z3.enum(["bearer", "x-api-key", "api-key"]).default("bearer"),
|
|
105
|
+
credentialCheck: credentialCheckSchema.optional(),
|
|
103
106
|
catalogBaseUrl: urlSchema.optional(),
|
|
104
107
|
catalogFormat: z3.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]).optional(),
|
|
105
108
|
catalogAuthStyle: z3.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
|
|
@@ -118,6 +121,7 @@ var providerPresetSchema = z3.object({
|
|
|
118
121
|
protocol: protocolSchema,
|
|
119
122
|
baseUrl: urlSchema.optional(),
|
|
120
123
|
authStyle: z3.enum(["bearer", "x-api-key", "api-key"]),
|
|
124
|
+
credentialCheck: credentialCheckSchema.optional(),
|
|
121
125
|
catalogBaseUrl: urlSchema.optional(),
|
|
122
126
|
catalogFormat: z3.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]),
|
|
123
127
|
catalogAuthStyle: z3.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
|
|
@@ -149,6 +153,7 @@ var runUpdateSchema = z3.object({
|
|
|
149
153
|
routingEvents: routingEventsSchema.optional(),
|
|
150
154
|
routingEventsDropped: z3.number().int().min(0).max(1e6).optional()
|
|
151
155
|
}).strict();
|
|
156
|
+
var catalogSchema = z3.object({ models: z3.array(modelSchema).max(1e4), refreshedAt: z3.string().datetime(), source: z3.enum(["remote", "manual"]) }).strict();
|
|
152
157
|
|
|
153
158
|
class Fault extends Error {
|
|
154
159
|
status;
|
|
@@ -244,7 +249,7 @@ var providerPresets = [
|
|
|
244
249
|
route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
245
250
|
route("anthropic-messages", "https://api.deepseek.com/anthropic/v1", { catalogBaseUrl: "https://api.deepseek.com" })
|
|
246
251
|
], ["https://api-docs.deepseek.com/guides/anthropic_api", "https://api-docs.deepseek.com/api/list-models", "https://api-docs.deepseek.com/updates/", "https://api-docs.deepseek.com/guides/responses_api/"], "DEEPSEEK_API_KEY"),
|
|
247
|
-
preset("openrouter", "OpenRouter", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, "https://openrouter.ai/api/v1", { catalogAuthStyle: "none" })), ["https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties", "https://openrouter.ai/docs/guides/overview"], "OPENROUTER_API_KEY"),
|
|
252
|
+
preset("openrouter", "OpenRouter", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, "https://openrouter.ai/api/v1", { catalogAuthStyle: "none", credentialCheck: { method: "GET", path: "key" } })), ["https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties", "https://openrouter.ai/docs/guides/overview"], "OPENROUTER_API_KEY"),
|
|
248
253
|
preset("anthropic", "Anthropic", [route("anthropic-messages", "https://api.anthropic.com/v1", { authStyle: "x-api-key" })], ["https://platform.claude.com/docs/en/api/overview", "https://platform.claude.com/docs/en/api/models/list"], "ANTHROPIC_API_KEY"),
|
|
249
254
|
preset("gemini", "Google Gemini", [route("gemini-generate-content", "https://generativelanguage.googleapis.com/v1beta", {
|
|
250
255
|
authStyle: "x-api-key",
|
|
@@ -311,8 +316,8 @@ function getProviderPreset(id) {
|
|
|
311
316
|
return structuredClone(entry);
|
|
312
317
|
}
|
|
313
318
|
function providerFromPreset(presetId, options = {}) {
|
|
314
|
-
const
|
|
315
|
-
const selected =
|
|
319
|
+
const preset = getProviderPreset(presetId);
|
|
320
|
+
const selected = preset.protocols.find((p) => (!options.protocol || p.protocol === options.protocol) && (!options.harness || compatible(options.harness, p.protocol)));
|
|
316
321
|
if (!selected)
|
|
317
322
|
throw new Fault(422, "protocol_mismatch", "This provider preset has no native protocol compatible with the requested harness. Choose an explicitly compatible gateway.");
|
|
318
323
|
const baseUrl = options.baseUrl ?? selected.baseUrl;
|
|
@@ -320,7 +325,7 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
320
325
|
throw new Fault(400, "endpoint_required", "This preset requires an explicit --url for its inference endpoint.");
|
|
321
326
|
if (presetId === "azure-openai" && !/\/openai\/v1$/.test(endpoint(baseUrl)))
|
|
322
327
|
throw new Fault(400, "invalid_url", "Azure OpenAI v1 requires an explicit endpoint ending in /openai/v1; deployment and api-version URLs are unsupported.");
|
|
323
|
-
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin &&
|
|
328
|
+
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin && preset.credentialEnv && !options.credentialEnv)
|
|
324
329
|
throw new Fault(422, "credential_authority", "An endpoint on another origin requires an explicit --credential-env reference.");
|
|
325
330
|
const suffix = selected.protocol === "anthropic-messages" ? "messages" : selected.protocol === "openai-responses" ? "responses" : "chat";
|
|
326
331
|
if (presetId === "fireworks" && !options.catalogBaseUrl && !options.catalogAccountId)
|
|
@@ -329,12 +334,13 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
329
334
|
throw new Fault(400, "catalog_url_required", "This preset requires an explicit --catalog-url when enabling a catalog parser.");
|
|
330
335
|
const catalogBaseUrl = options.catalogBaseUrl ?? (presetId === "fireworks" && options.catalogAccountId ? `https://api.fireworks.ai/v1/accounts/${encodeURIComponent(options.catalogAccountId)}` : options.baseUrl ? undefined : selected.catalogBaseUrl);
|
|
331
336
|
return parse(providerInputSchema, {
|
|
332
|
-
id: options.id ?? `${
|
|
333
|
-
name:
|
|
337
|
+
id: options.id ?? `${preset.id}-${suffix}`,
|
|
338
|
+
name: preset.name,
|
|
334
339
|
baseUrl,
|
|
335
340
|
protocol: selected.protocol,
|
|
336
|
-
credentialEnv: options.credentialEnv ??
|
|
341
|
+
credentialEnv: options.credentialEnv ?? preset.credentialEnv,
|
|
337
342
|
authStyle: options.authStyle ?? selected.authStyle,
|
|
343
|
+
credentialCheck: selected.credentialCheck,
|
|
338
344
|
catalogBaseUrl,
|
|
339
345
|
catalogCredentialEnv: options.catalogCredentialEnv,
|
|
340
346
|
catalogAuthStyle: options.catalogAuthStyle ?? selected.catalogAuthStyle,
|
|
@@ -619,6 +625,9 @@ class SwitcherClient {
|
|
|
619
625
|
refreshModels(id, idempotencyKey) {
|
|
620
626
|
return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey });
|
|
621
627
|
}
|
|
628
|
+
saveCatalog(id, providerVersion, catalog, idempotencyKey) {
|
|
629
|
+
return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey });
|
|
630
|
+
}
|
|
622
631
|
listModels(id, options = {}) {
|
|
623
632
|
return this.request("GET", `/v1/providers/${encodeURIComponent(id)}/models?${this.query(options)}`);
|
|
624
633
|
}
|
|
@@ -657,10 +666,10 @@ function clientFromEnv(env = process.env, options = {}) {
|
|
|
657
666
|
return SwitcherClient.fromEnvironment(env, options);
|
|
658
667
|
}
|
|
659
668
|
export {
|
|
660
|
-
|
|
661
|
-
detectClaudeDesktopApp,
|
|
662
|
-
detectChatGPTApp,
|
|
663
|
-
clientFromEnv,
|
|
669
|
+
SwitcherClient,
|
|
664
670
|
SwitcherError,
|
|
665
|
-
|
|
671
|
+
clientFromEnv,
|
|
672
|
+
detectChatGPTApp,
|
|
673
|
+
detectClaudeDesktopApp,
|
|
674
|
+
providerFromPreset
|
|
666
675
|
};
|