@hasna/switcher 0.2.2 → 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 +14 -9
- package/dist/cli/index.js +992 -706
- package/dist/credentials.d.ts +18 -62
- package/dist/direct-launch.d.ts +2 -2
- package/dist/domain.d.ts +78 -4
- package/dist/generated/api.d.ts +109 -1
- package/dist/index.js +15 -11
- package/dist/mcp/index.js +1055 -95
- package/dist/mint/index.js +136 -0
- package/dist/mint-key.d.ts +34 -0
- package/dist/provider-credential-onboarding.d.ts +73 -0
- package/dist/sdk.d.ts +21 -1
- package/dist/sdk.js +15 -11
- package/dist/serve/index.js +350 -90
- 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 +135 -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 {};
|
|
@@ -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<{
|
|
@@ -448,6 +450,24 @@ export declare class SwitcherClient {
|
|
|
448
450
|
refreshedAt: string;
|
|
449
451
|
source: "remote" | "manual";
|
|
450
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
|
+
}>;
|
|
451
471
|
listModels(id: string, options?: {}): Promise<{
|
|
452
472
|
data: {
|
|
453
473
|
id: string;
|
package/dist/sdk.js
CHANGED
|
@@ -153,6 +153,7 @@ var runUpdateSchema = z3.object({
|
|
|
153
153
|
routingEvents: routingEventsSchema.optional(),
|
|
154
154
|
routingEventsDropped: z3.number().int().min(0).max(1e6).optional()
|
|
155
155
|
}).strict();
|
|
156
|
+
var catalogSchema = z3.object({ models: z3.array(modelSchema).max(1e4), refreshedAt: z3.string().datetime(), source: z3.enum(["remote", "manual"]) }).strict();
|
|
156
157
|
|
|
157
158
|
class Fault extends Error {
|
|
158
159
|
status;
|
|
@@ -315,8 +316,8 @@ function getProviderPreset(id) {
|
|
|
315
316
|
return structuredClone(entry);
|
|
316
317
|
}
|
|
317
318
|
function providerFromPreset(presetId, options = {}) {
|
|
318
|
-
const
|
|
319
|
-
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)));
|
|
320
321
|
if (!selected)
|
|
321
322
|
throw new Fault(422, "protocol_mismatch", "This provider preset has no native protocol compatible with the requested harness. Choose an explicitly compatible gateway.");
|
|
322
323
|
const baseUrl = options.baseUrl ?? selected.baseUrl;
|
|
@@ -324,7 +325,7 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
324
325
|
throw new Fault(400, "endpoint_required", "This preset requires an explicit --url for its inference endpoint.");
|
|
325
326
|
if (presetId === "azure-openai" && !/\/openai\/v1$/.test(endpoint(baseUrl)))
|
|
326
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.");
|
|
327
|
-
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)
|
|
328
329
|
throw new Fault(422, "credential_authority", "An endpoint on another origin requires an explicit --credential-env reference.");
|
|
329
330
|
const suffix = selected.protocol === "anthropic-messages" ? "messages" : selected.protocol === "openai-responses" ? "responses" : "chat";
|
|
330
331
|
if (presetId === "fireworks" && !options.catalogBaseUrl && !options.catalogAccountId)
|
|
@@ -333,11 +334,11 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
333
334
|
throw new Fault(400, "catalog_url_required", "This preset requires an explicit --catalog-url when enabling a catalog parser.");
|
|
334
335
|
const catalogBaseUrl = options.catalogBaseUrl ?? (presetId === "fireworks" && options.catalogAccountId ? `https://api.fireworks.ai/v1/accounts/${encodeURIComponent(options.catalogAccountId)}` : options.baseUrl ? undefined : selected.catalogBaseUrl);
|
|
335
336
|
return parse(providerInputSchema, {
|
|
336
|
-
id: options.id ?? `${
|
|
337
|
-
name:
|
|
337
|
+
id: options.id ?? `${preset.id}-${suffix}`,
|
|
338
|
+
name: preset.name,
|
|
338
339
|
baseUrl,
|
|
339
340
|
protocol: selected.protocol,
|
|
340
|
-
credentialEnv: options.credentialEnv ??
|
|
341
|
+
credentialEnv: options.credentialEnv ?? preset.credentialEnv,
|
|
341
342
|
authStyle: options.authStyle ?? selected.authStyle,
|
|
342
343
|
credentialCheck: selected.credentialCheck,
|
|
343
344
|
catalogBaseUrl,
|
|
@@ -624,6 +625,9 @@ class SwitcherClient {
|
|
|
624
625
|
refreshModels(id, idempotencyKey) {
|
|
625
626
|
return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey });
|
|
626
627
|
}
|
|
628
|
+
saveCatalog(id, providerVersion, catalog, idempotencyKey) {
|
|
629
|
+
return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey });
|
|
630
|
+
}
|
|
627
631
|
listModels(id, options = {}) {
|
|
628
632
|
return this.request("GET", `/v1/providers/${encodeURIComponent(id)}/models?${this.query(options)}`);
|
|
629
633
|
}
|
|
@@ -662,10 +666,10 @@ function clientFromEnv(env = process.env, options = {}) {
|
|
|
662
666
|
return SwitcherClient.fromEnvironment(env, options);
|
|
663
667
|
}
|
|
664
668
|
export {
|
|
665
|
-
|
|
666
|
-
detectClaudeDesktopApp,
|
|
667
|
-
detectChatGPTApp,
|
|
668
|
-
clientFromEnv,
|
|
669
|
+
SwitcherClient,
|
|
669
670
|
SwitcherError,
|
|
670
|
-
|
|
671
|
+
clientFromEnv,
|
|
672
|
+
detectChatGPTApp,
|
|
673
|
+
detectClaudeDesktopApp,
|
|
674
|
+
providerFromPreset
|
|
671
675
|
};
|