@byok-sdk/keys 0.3.10 → 0.4.1
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/bin/pi-provider-launcher.js +124 -6
- package/dist/bin/pi-provider-launcher.js.map +1 -1
- package/dist/errors.d.ts +4 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +126 -7
- package/dist/index.js.map +1 -1
- package/dist/provider-catalog.d.ts +73 -0
- package/dist/provider-profile.d.ts +32 -4
- package/dist/sqlite-profile-store.d.ts +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/url.ts","../src/provider-profile.ts","../src/headers.ts","../src/http.ts","../src/openai-client.ts","../src/anthropic-client.ts","../src/command-runner.ts","../src/secret-name.ts","../src/secret-store.ts","../src/macos-keychain.ts","../src/windows-credential-manager.ts","../src/secret-scope.ts","../src/profile-store.ts","../src/sqlite-support.ts","../src/sqlite-profile-store.ts","../src/truth-profile-store.ts","../src/registry.ts","../src/pi-provider-projection.ts"],"names":["createHash","path"],"mappings":";;;;;;;;;AAYO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvB,IAAA;AAAA,EACA,UAAA;AAAA,EAEhB,WAAA,CACE,IAAA,EACA,OAAA,EACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,aAAa,OAAA,EAAS,UAAA;AAAA,EAC7B;AACF;AAyBO,IAAM,qBAAA,GAAwB;AAAA,EACnC,gCAAA,EAAkC,kCAAA;AAAA,EAClC,8BAAA,EAAgC,gCAAA;AAAA,EAChC,iCAAA,EAAmC,mCAAA;AAAA,EACnC,8BAAA,EAAgC,gCAAA;AAAA,EAChC,+BAAA,E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AAA,CAAQ,QAAA;AAAA,QACjB,GAAA,EACE,OAAA,CAAQ,OAAA,KAAY,WAAA,GAChB,oBAAA,GACA,oBAAA;AAAA,QACN,GAAI,OAAA,CAAQ,SAAA,KAAc,MAAA,GACtB,KACA,EAAE,MAAA,EAAQ,CAAA,CAAA,EAAI,oBAAoB,CAAA,CAAA,EAAG;AAAA,QACzC,GAAI,QAAQ,SAAA,KAAc,QAAA,GAAW,EAAE,UAAA,EAAY,IAAA,KAAS,EAAC;AAAA,QAC7D,MAAA,EAAQ;AAAA,UACN;AAAA,YACE,IAAI,OAAA,CAAQ,KAAA;AAAA,YACZ,MAAM,OAAA,CAAQ,YAAA;AAAA,YACd,KAAA,EAAO;AAAA,cACL,MAAA;AAAA,cACA,GAAI,QAAQ,YAAA,CAAa,QAAA,CAAS,aAAa,CAAA,GAAI,CAAC,OAAO,CAAA,GAAI;AAAC;AAClE;AACF;AACF;AACF;AACF,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Single error class for `@byok-sdk/keys`.\n *\n * The ported source (`aip-main-open@c6a5385`, `apps/local-agent/src/providers.ts`)\n * raised two different classes — `LocalExecutionError` and\n * `ResearchExecutionError` — that differed only in which subsystem owned the\n * throw site; both carried a `code` string and consumers branched on that code.\n * The narrative/research subsystem stays behind in aip-main-open, so this\n * package keeps one class and preserves the `code` strings verbatim. K4's swap\n * converts aip's two `instanceof` sites to structured code detection, so the\n * strings — not the class identity — are the compatibility surface.\n */\nexport class ByokKeysError extends Error {\n public readonly code: string;\n public readonly httpStatus?: number;\n\n constructor(\n code: string,\n message: string,\n options?: ErrorOptions & { httpStatus?: number },\n ) {\n super(message, options);\n this.name = 'ByokKeysError';\n this.code = code;\n this.httpStatus = options?.httpStatus;\n }\n}\n\n/**\n * Error codes this package can throw, ported verbatim from the source. Kept as\n * a named record so consumers (and K4's aip-main-open swap) can branch on\n * `error.code` without retyping string literals.\n *\n * Four codes have no source counterpart, and each guards a check the source did\n * not make: `KEYCHAIN_SECRET_DECODE_FAILED` (the source returned an undecodable\n * stored value as-is), `SECRET_ENVELOPE_INVALID` (it reported a malformed\n * envelope as an absent secret), and `SECRET_NAME_INVALID` /\n * `SECRET_VALUE_INVALID` (the runtime replacements for the closed\n * `KeychainSecretName` union). Everything else matches the source string for\n * string.\n *\n * `SECRET_NAMESPACE_INVALID` is a separate case. The source does record it:\n * `normalizeSecretNamespace` (`index.ts:748-757`) throws the verbatim string\n * `'SECRET_NAMESPACE_INVALID'` at `index.ts:752`, and this package ports both\n * that string and its pattern unchanged. It is still not a compatibility\n * surface K4 must match, but for a different reason than the string: neither\n * side has a branch consumer. In the source the only callers are the two OS\n * stores' `scope()` methods, which just compose a service prefix; here the code\n * is only ever asserted in tests. Matching it costs nothing and constrains\n * nothing.\n */\nexport const BYOK_KEYS_ERROR_CODES = {\n CREDENTIAL_MANAGER_DELETE_FAILED: 'CREDENTIAL_MANAGER_DELETE_FAILED',\n CREDENTIAL_MANAGER_READ_FAILED: 'CREDENTIAL_MANAGER_READ_FAILED',\n CREDENTIAL_MANAGER_SECRET_INVALID: 'CREDENTIAL_MANAGER_SECRET_INVALID',\n CREDENTIAL_MANAGER_UNAVAILABLE: 'CREDENTIAL_MANAGER_UNAVAILABLE',\n CREDENTIAL_MANAGER_WRITE_FAILED: 'CREDENTIAL_MANAGER_WRITE_FAILED',\n KEYCHAIN_ARGUMENT_INVALID: 'KEYCHAIN_ARGUMENT_INVALID',\n KEYCHAIN_DELETE_FAILED: 'KEYCHAIN_DELETE_FAILED',\n KEYCHAIN_READ_FAILED: 'KEYCHAIN_READ_FAILED',\n KEYCHAIN_SECRET_DECODE_FAILED: 'KEYCHAIN_SECRET_DECODE_FAILED',\n KEYCHAIN_SECRET_INVALID: 'KEYCHAIN_SECRET_INVALID',\n KEYCHAIN_UNAVAILABLE: 'KEYCHAIN_UNAVAILABLE',\n KEYCHAIN_WRITE_FAILED: 'KEYCHAIN_WRITE_FAILED',\n LOCAL_ACCOUNT_SCOPE_INVALID: 'LOCAL_ACCOUNT_SCOPE_INVALID',\n MODEL_PROVIDER_AUTH_FAILED: 'MODEL_PROVIDER_AUTH_FAILED',\n MODEL_PROVIDER_BALANCE_INSUFFICIENT: 'MODEL_PROVIDER_BALANCE_INSUFFICIENT',\n MODEL_PROVIDER_HTTP_ERROR: 'MODEL_PROVIDER_HTTP_ERROR',\n MODEL_PROVIDER_MODEL_NOT_FOUND: 'MODEL_PROVIDER_MODEL_NOT_FOUND',\n MODEL_PROVIDER_RATE_LIMITED: 'MODEL_PROVIDER_RATE_LIMITED',\n MODEL_RESPONSE_INVALID: 'MODEL_RESPONSE_INVALID',\n PROVIDER_NOT_CONFIGURED: 'PROVIDER_NOT_CONFIGURED',\n PROVIDER_PROFILE_INVALID: 'PROVIDER_PROFILE_INVALID',\n PROVIDER_PROFILE_CONFLICT: 'PROVIDER_PROFILE_CONFLICT',\n PROVIDER_REQUEST_TIMEOUT: 'PROVIDER_REQUEST_TIMEOUT',\n PROVIDER_RESPONSE_INVALID: 'PROVIDER_RESPONSE_INVALID',\n PROVIDER_RESPONSE_TOO_LARGE: 'PROVIDER_RESPONSE_TOO_LARGE',\n PROVIDER_SECRET_EMPTY: 'PROVIDER_SECRET_EMPTY',\n PROVIDER_SECRET_MISSING: 'PROVIDER_SECRET_MISSING',\n PROVIDER_SECRET_NOT_ALLOWED: 'PROVIDER_SECRET_NOT_ALLOWED',\n PROVIDER_SECRET_ROLLBACK_FAILED: 'PROVIDER_SECRET_ROLLBACK_FAILED',\n PROVIDER_STORE_UNAVAILABLE: 'PROVIDER_STORE_UNAVAILABLE',\n PROVIDER_TRUTH_INVALID: 'PROVIDER_TRUTH_INVALID',\n PROVIDER_URL_INVALID: 'PROVIDER_URL_INVALID',\n SECRET_ENVELOPE_INVALID: 'SECRET_ENVELOPE_INVALID',\n SECRET_NAME_INVALID: 'SECRET_NAME_INVALID',\n SECRET_NAMESPACE_INVALID: 'SECRET_NAMESPACE_INVALID',\n SECRET_VALUE_INVALID: 'SECRET_VALUE_INVALID',\n} as const;\n\nexport type ByokKeysErrorCode =\n (typeof BYOK_KEYS_ERROR_CODES)[keyof typeof BYOK_KEYS_ERROR_CODES];\n","import { ByokKeysError } from './errors';\n\n/**\n * Normalize a provider base URL, fail-closed.\n *\n * Ported from `aip-main-open@c6a5385` `providers.ts:1558-1588` plus the two\n * host predicates at `:2216-2242`. Rules, unchanged:\n * - must be an absolute URL;\n * - no embedded credentials, no fragment, no query string;\n * - HTTPS only, except that HTTP is allowed for loopback hosts;\n * - private-network literals are rejected unless they are loopback;\n * - one trailing slash is stripped.\n */\nexport function normalizeProviderUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider base URL must be absolute',\n );\n }\n if (\n url.username ||\n url.password ||\n url.hash ||\n url.search ||\n (url.protocol !== 'https:' &&\n !(url.protocol === 'http:' && isLoopbackHost(url.hostname)))\n ) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider URL requires HTTPS; HTTP is allowed only for localhost',\n );\n }\n if (isPrivateNetworkLiteral(url.hostname) && !isLoopbackHost(url.hostname)) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Private-network provider IPs are not allowed',\n );\n }\n return url.toString().replace(/\\/$/u, '');\n}\n\n/** Whether an already-parseable provider URL points at a loopback host. */\nexport function isLoopbackProviderUrl(value: string): boolean {\n return isLoopbackHost(new URL(value).hostname);\n}\n\nexport function isLoopbackHost(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n return value === 'localhost' || value === '127.0.0.1' || value === '::1';\n}\n\n/**\n * Conservative private-network literal check. Any IPv6 literal counts as\n * private (the `:` branch), matching the source: the guard cannot cheaply\n * classify IPv6 ranges, so it refuses all of them and lets hostnames through.\n */\nexport function isPrivateNetworkLiteral(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n if (value.includes(':')) return true;\n const parts = value.split('.').map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n return (\n parts[0] === 10 ||\n parts[0] === 127 ||\n (parts[0] === 169 && parts[1] === 254) ||\n (parts[0] === 172 && (parts[1] ?? 0) >= 16 && (parts[1] ?? 0) <= 31) ||\n (parts[0] === 192 && parts[1] === 168)\n );\n}\n","import { z } from 'zod';\nimport { createHash } from 'node:crypto';\n\nimport { ByokKeysError } from './errors';\nimport { normalizeProviderUrl } from './url';\n\n/**\n * Opaque, portable identity of one locally configured provider profile.\n *\n * This is the profile's primary key: it is a local logical id, never a path,\n * and several profiles may share one {@link MODEL_PROVIDER_KINDS} kind (two\n * independent `custom` endpoints, for example). It replaces the former\n * `MODEL_PROVIDER_IDS` primary key, which conflated instance identity with\n * provider kind and therefore allowed exactly one profile per kind.\n *\n * `@byok-sdk/protocol` declares the same lexical rule for the wire form in\n * `provider-profile-binding.ts`. The two definitions are deliberately parallel\n * rather than shared: the release graph (`scripts/release/check-package-graph.mjs`)\n * forbids `@byok-sdk/keys` from depending on any dispatch package, so the\n * device-local authority cannot import the wire authority. This mirrors how\n * `packages/protocol/src/blob.ts`'s `CONTENT_HASH_RE` restates\n * `packages/core/src/blob.ts`'s content-hash format across the same boundary.\n */\nexport const PROVIDER_PROFILE_REF_PATTERN =\n /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/u;\n\nexport const ProviderProfileRefSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(\n PROVIDER_PROFILE_REF_PATTERN,\n 'provider profile refs must be lowercase portable identifiers',\n );\n\nexport type ProviderProfileRef = z.infer<typeof ProviderProfileRefSchema>;\n\n/**\n * Provider kinds this package knows how to address — the surviving half of the\n * former `MODEL_PROVIDER_IDS`. A kind says *what dialect family and vendor\n * shape* a profile is; {@link ProviderProfileRefSchema} says *which* profile.\n * Ported from `aip-main-open@c6a5385` `providers.ts:30-36`\n * (`LOCAL_MODEL_PROVIDER_IDS`).\n */\nexport const MODEL_PROVIDER_KINDS = [\n 'openai',\n 'deepseek',\n 'anthropic',\n 'custom',\n] as const;\n\nexport type ModelProviderKind = (typeof MODEL_PROVIDER_KINDS)[number];\n\n/**\n * Bounded model capabilities a profile may declare. A capability is explicit\n * local configuration, never inferred from the model name or the base URL.\n */\nexport const PROVIDER_MODEL_CAPABILITIES = ['image-input'] as const;\n\nexport const ProviderModelCapabilitySchema = z.enum(PROVIDER_MODEL_CAPABILITIES);\n\nexport type ProviderModelCapability = z.infer<\n typeof ProviderModelCapabilitySchema\n>;\n\n/** Auth modes a provider profile can request (`providers.ts:29`). */\nexport const PROVIDER_AUTH_MODES = ['bearer', 'x_api_key', 'none'] as const;\n\nexport type ProviderAuthMode = (typeof PROVIDER_AUTH_MODES)[number];\n\n/**\n * Wire dialects. The source's `market_data` / `mcp_http` branch stays in\n * aip-main-open — this package ports the model branch only\n * (`providers.ts:38-61`, second union member).\n */\nexport const MODEL_PROVIDER_ADAPTERS = ['openai_compatible', 'anthropic'] as const;\n\nexport type ModelProviderAdapter = (typeof MODEL_PROVIDER_ADAPTERS)[number];\n\n/**\n * Marker attached to schema issues so {@link parseModelProviderProfile} can\n * reproduce the source's distinct error codes: the URL guard reports\n * `PROVIDER_URL_INVALID`, everything else reports `PROVIDER_PROFILE_INVALID`.\n */\ninterface ProfileIssueParams {\n byokCode: string;\n}\n\nfunction boundedString(field: string, maximumLength: number) {\n return z\n .string()\n .superRefine((value, ctx) => {\n if (\n value.trim().length === 0 ||\n value.length > maximumLength ||\n /[\\u0000\\r\\n]/u.test(value)\n ) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} is invalid`,\n });\n }\n })\n .transform((value) => value.trim());\n}\n\nfunction isoTimestamp(field: string) {\n return boundedString(field, 64).superRefine((value, ctx) => {\n if (!Number.isFinite(Date.parse(value))) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} must be an ISO timestamp`,\n });\n }\n });\n}\n\nconst providerBaseUrl = z\n .string()\n .superRefine((value, ctx) => {\n try {\n normalizeProviderUrl(value);\n } catch (error) {\n ctx.addIssue({\n code: 'custom',\n message:\n error instanceof Error ? error.message : 'Provider base URL is invalid',\n params: {\n byokCode:\n error instanceof ByokKeysError ? error.code : 'PROVIDER_URL_INVALID',\n } satisfies ProfileIssueParams,\n });\n }\n })\n .transform((value) => normalizeProviderUrl(value));\n\n/**\n * A model provider profile: everything needed to address a provider except the\n * secret itself, which lives in the OS credential store.\n *\n * The adapter/auth-mode legality rules are the ones `normalizeProviderProfile`\n * enforced imperatively at `providers.ts:1522-1543`, moved into the schema so\n * there is one validation authority rather than a schema plus a normalizer.\n */\nexport const ModelProviderProfileSchema = z\n .object({\n adapter: z.enum(MODEL_PROVIDER_ADAPTERS),\n auth_mode: z.enum(PROVIDER_AUTH_MODES),\n base_url: providerBaseUrl,\n capabilities: z.array(ProviderModelCapabilitySchema).max(8),\n created_at: isoTimestamp('created_at'),\n display_name: boundedString('display_name', 100),\n enabled: z.boolean(),\n kind: z.literal('model'),\n model: boundedString('model', 160),\n profile_ref: ProviderProfileRefSchema,\n provider_kind: z.enum(MODEL_PROVIDER_KINDS),\n updated_at: isoTimestamp('updated_at'),\n })\n .superRefine((profile, ctx) => {\n if (new Set(profile.capabilities).size !== profile.capabilities.length) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider capabilities cannot repeat',\n path: ['capabilities'],\n });\n }\n if (profile.adapter === 'anthropic' && profile.auth_mode !== 'x_api_key') {\n ctx.addIssue({\n code: 'custom',\n message: 'Anthropic requires x_api_key authentication',\n path: ['auth_mode'],\n });\n }\n if (\n profile.adapter === 'openai_compatible' &&\n profile.auth_mode === 'x_api_key'\n ) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'OpenAI-compatible providers support bearer or no authentication',\n path: ['auth_mode'],\n });\n }\n if (Date.parse(profile.updated_at) < Date.parse(profile.created_at)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider updated_at cannot precede created_at',\n path: ['updated_at'],\n });\n }\n });\n\n/** Validated, normalized profile. */\nexport type ModelProviderProfile = z.infer<typeof ModelProviderProfileSchema>;\n\n/** Pre-normalization shape callers may hand in. */\nexport type ModelProviderProfileInput = z.input<typeof ModelProviderProfileSchema>;\n\nexport interface ExactProviderProfileBinding {\n profileRef: ProviderProfileRef;\n profileRevision: string;\n profileHash: string;\n modelId: string;\n requiredCapabilities: readonly ProviderModelCapability[];\n}\n\n/**\n * Derive the credential-free wire identity from the normalized local record.\n * `updated_at` is the persisted monotonic revision authority; the hash covers\n * the complete normalized non-secret record with capability order\n * canonicalized. Secret values are not accepted by this type and therefore\n * cannot enter the digest or any mismatch message.\n */\nexport function exactProviderProfileBinding(\n profileInput: ModelProviderProfile,\n requiredCapabilities: readonly ProviderModelCapability[] = profileInput.capabilities,\n): ExactProviderProfileBinding {\n const profile = parseModelProviderProfile(profileInput);\n const revision = Date.parse(profile.updated_at);\n if (!Number.isSafeInteger(revision) || revision < 0) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider updated_at cannot be represented as a canonical revision',\n );\n }\n const normalizedCapabilities = [...profile.capabilities].sort();\n const canonical = JSON.stringify({\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n capabilities: normalizedCapabilities,\n kind: profile.kind,\n model: profile.model,\n profile_ref: profile.profile_ref,\n provider_kind: profile.provider_kind,\n });\n return {\n profileRef: profile.profile_ref,\n profileRevision: String(revision),\n profileHash: `sha256:${createHash('sha256').update(canonical).digest('hex')}`,\n modelId: profile.model,\n requiredCapabilities: [...requiredCapabilities],\n };\n}\n\n/** Fail closed unless every offered binding field matches local authority. */\nexport function assertExactProviderProfileBinding(\n profile: ModelProviderProfile,\n expected: ExactProviderProfileBinding,\n): void {\n if (new Set(expected.requiredCapabilities).size !== expected.requiredCapabilities.length) {\n throw new Error('provider profile required capabilities must be unique');\n }\n const actual = exactProviderProfileBinding(profile, expected.requiredCapabilities);\n if (actual.profileRef !== expected.profileRef) throw new Error('provider profile ref mismatch');\n if (actual.profileRevision !== expected.profileRevision) throw new Error('provider profile revision mismatch');\n if (actual.profileHash !== expected.profileHash) throw new Error('provider profile hash mismatch');\n if (actual.modelId !== expected.modelId) throw new Error('provider profile model mismatch');\n const supported = new Set(profile.capabilities);\n const unsupported = expected.requiredCapabilities.find((capability) => !supported.has(capability));\n if (unsupported !== undefined) throw new Error(`provider profile does not support required capability ${unsupported}`);\n}\n\n/**\n * Parse and normalize a profile, or throw {@link ByokKeysError}. Replaces the\n * source's `normalizeProviderProfile` (`providers.ts:1489-1556`) for the model\n * branch, preserving its error codes.\n */\nexport function parseModelProviderProfile(value: unknown): ModelProviderProfile {\n const result = ModelProviderProfileSchema.safeParse(value);\n if (result.success) return result.data;\n const issue = result.error.issues[0];\n const params = (issue as { params?: Partial<ProfileIssueParams> } | undefined)\n ?.params;\n throw new ByokKeysError(\n params?.byokCode ?? 'PROVIDER_PROFILE_INVALID',\n issue?.message ?? 'Provider profile is invalid',\n { cause: result.error },\n );\n}\n","import { ByokKeysError } from './errors';\nimport type { ProviderAuthMode } from './provider-profile';\n\n/** The subset of a profile the header builder reads. */\nexport interface ProviderAuthProfile {\n auth_mode: ProviderAuthMode;\n kind: string;\n}\n\n/**\n * Fail-closed secret check. Ported from `aip-main-open@c6a5385`\n * `providers.ts:1657-1671`: a profile that declares `bearer` or `x_api_key`\n * must have a secret, or the request is refused rather than sent unauthenticated.\n */\nexport function requiredProviderSecret(\n profile: ProviderAuthProfile,\n secret: string | undefined,\n): string | undefined {\n if (\n (profile.auth_mode === 'bearer' || profile.auth_mode === 'x_api_key') &&\n !secret\n ) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_MISSING',\n `${profile.kind} provider requires a secret in the operating-system credential store`,\n );\n }\n return secret;\n}\n\n/**\n * Build the outbound request headers for a provider call. Key-for-key\n * equivalent to `providers.ts:1680-1697`:\n * - always `accept` and `content-type`;\n * - `bearer` adds `authorization: Bearer <secret>`;\n * - `x_api_key` adds `x-api-key: <secret>` and `anthropic-version: 2023-06-01`;\n * - `none` adds nothing.\n */\nexport function providerHeaders(\n profile: ProviderAuthProfile,\n secret: string | undefined,\n): Record<string, string> {\n return {\n accept: 'application/json',\n 'content-type': 'application/json',\n ...(profile.auth_mode === 'bearer'\n ? { authorization: `Bearer ${requiredProviderSecret(profile, secret)}` }\n : {}),\n ...(profile.auth_mode === 'x_api_key'\n ? {\n 'anthropic-version': '2023-06-01',\n 'x-api-key': requiredProviderSecret(profile, secret) as string,\n }\n : {}),\n };\n}\n","import { ByokKeysError } from './errors';\nimport { normalizeProviderUrl } from './url';\n\n/** Injectable `fetch`. Defaults to `globalThis.fetch` at every call site. */\nexport type ProviderFetch = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>;\n\n/** Response body ceiling, ported from `providers.ts:106`. */\nexport const PROVIDER_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;\n\n/** Per-request timeout, ported from `providers.ts:107`. */\nexport const PROVIDER_TIMEOUT_MS = 15_000;\n\n/**\n * Issue a provider request under the source's guards\n * (`providers.ts:1711-1743`): the URL is re-validated immediately before the\n * call, the caller's abort signal is chained, and an internal timeout aborts\n * with a distinguishable reason so a timeout maps to\n * `PROVIDER_REQUEST_TIMEOUT` rather than a bare `AbortError`.\n */\nexport async function fetchWithProviderGuards(\n fetchImpl: ProviderFetch,\n url: string,\n init: RequestInit,\n signal: AbortSignal,\n): Promise<Response> {\n normalizeProviderUrl(url);\n const controller = new AbortController();\n const onAbort = () => controller.abort(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n if (signal.aborted) onAbort();\n const timeout = setTimeout(\n () => controller.abort('provider_timeout'),\n PROVIDER_TIMEOUT_MS,\n );\n try {\n return await fetchImpl(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (\n !signal.aborted &&\n controller.signal.aborted &&\n controller.signal.reason === 'provider_timeout'\n ) {\n throw new ByokKeysError(\n 'PROVIDER_REQUEST_TIMEOUT',\n 'Provider request timed out',\n );\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n signal.removeEventListener('abort', onAbort);\n }\n}\n\n/**\n * Read a JSON body with a size ceiling (`providers.ts:1825-1851`). The\n * `content-length` check is an early exit; the decoded-byte check is the one\n * that actually holds, since `content-length` is attacker-controlled.\n */\nexport async function parseBoundedJsonResponse(\n response: Response,\n): Promise<unknown> {\n const contentLength = Number(response.headers.get('content-length'));\n if (\n Number.isFinite(contentLength) &&\n contentLength > PROVIDER_RESPONSE_MAX_BYTES\n ) {\n throw new ByokKeysError(\n 'PROVIDER_RESPONSE_TOO_LARGE',\n 'Provider response exceeds the local safety limit',\n );\n }\n const text = await response.text();\n if (new TextEncoder().encode(text).byteLength > PROVIDER_RESPONSE_MAX_BYTES) {\n throw new ByokKeysError(\n 'PROVIDER_RESPONSE_TOO_LARGE',\n 'Provider response exceeds the local safety limit',\n );\n }\n try {\n return JSON.parse(text);\n } catch {\n throw new ByokKeysError(\n 'PROVIDER_RESPONSE_INVALID',\n 'Provider returned invalid JSON',\n );\n }\n}\n\n/**\n * Parse a model-provider response, mapping non-2xx to a classified error\n * (`providers.ts:1748-1769`). The source's `context` parameter only chose\n * between two error classes; this package has one, so the parameter is gone.\n */\nexport async function readModelProviderResponse(\n response: Response,\n): Promise<unknown> {\n let payload: unknown;\n try {\n payload = await parseBoundedJsonResponse(response);\n } catch (error) {\n if (\n !response.ok &&\n error instanceof ByokKeysError &&\n error.code === 'PROVIDER_RESPONSE_INVALID'\n ) {\n throw modelProviderHttpError(response.status, undefined);\n }\n throw error;\n }\n if (!response.ok) {\n throw modelProviderHttpError(response.status, payload);\n }\n return payload;\n}\n\nfunction modelProviderHttpError(\n status: number,\n payload: unknown,\n): ByokKeysError {\n return new ByokKeysError(\n classifyModelProviderHttpError(status, payload),\n `Model provider request failed with HTTP ${status}`,\n { httpStatus: status },\n );\n}\n\n/**\n * Map an HTTP status plus error body onto a stable code\n * (`providers.ts:1783-1815`). Providers disagree on status codes for billing\n * and key problems, so the body text is inspected as well — the pattern lists\n * are verbatim from the source, including the Chinese-language variants the\n * source's providers actually return.\n */\nexport function classifyModelProviderHttpError(\n status: number,\n payload: unknown,\n): string {\n const detail = safeProviderErrorText(payload);\n if (\n status === 402 ||\n /(?:insufficient[_ -]?(?:quota|balance|credit)|quota[_ -]?exceeded|billing|payment required|余额不足|额度不足|欠费|充值)/iu.test(\n detail,\n )\n ) {\n return 'MODEL_PROVIDER_BALANCE_INSUFFICIENT';\n }\n if (\n status === 401 ||\n status === 403 ||\n /(?:invalid[_ -]?api[_ -]?key|authentication|unauthori[sz]ed|forbidden|鉴权失败|密钥无效|令牌无效)/iu.test(\n detail,\n )\n ) {\n return 'MODEL_PROVIDER_AUTH_FAILED';\n }\n if (\n status === 404 ||\n /(?:model[_ -]?not[_ -]?found|model does not exist|unknown model|模型不存在|无权访问模型)/iu.test(\n detail,\n )\n ) {\n return 'MODEL_PROVIDER_MODEL_NOT_FOUND';\n }\n if (status === 429) return 'MODEL_PROVIDER_RATE_LIMITED';\n return 'MODEL_PROVIDER_HTTP_ERROR';\n}\n\nfunction safeProviderErrorText(payload: unknown): string {\n try {\n return JSON.stringify(payload ?? '')\n .slice(0, 8_000)\n .toLowerCase();\n } catch {\n return '';\n }\n}\n\n/** Join a normalized base URL with an API path, idempotently (`providers.ts:1949-1953`). */\nexport function modelApiUrl(baseUrl: string, suffix: string): string {\n const normalized = normalizeProviderUrl(baseUrl);\n if (normalized.endsWith(`/${suffix}`)) return normalized;\n return `${normalized}/${suffix}`;\n}\n\n/**\n * Flatten a message content field to text (`providers.ts:1955-1971`). Both\n * dialects return either a string or an array of typed blocks.\n */\nexport function modelMessageText(value: unknown): string {\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) {\n return value\n .map(objectValue)\n .filter(\n (item): item is Record<string, unknown> =>\n item !== undefined && typeof item.text === 'string',\n )\n .map((item) => item.text as string)\n .join('');\n }\n throw new ByokKeysError(\n 'MODEL_RESPONSE_INVALID',\n 'Model response did not contain text',\n );\n}\n\nexport function objectValue(\n value: unknown,\n): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** `providers.ts:2301-2308` — an empty completion does not prove a live key. */\nexport function assertLiveModelResponse(value: string): void {\n if (value.trim().length === 0) {\n throw new ByokKeysError(\n 'MODEL_RESPONSE_INVALID',\n 'Model provider returned an empty completion during connection validation',\n );\n }\n}\n","import {\n assertLiveModelResponse,\n fetchWithProviderGuards,\n modelApiUrl,\n modelMessageText,\n objectValue,\n readModelProviderResponse,\n type ProviderFetch,\n} from './http';\nimport { providerHeaders, requiredProviderSecret } from './headers';\nimport { ByokKeysError } from './errors';\nimport {\n parseModelProviderProfile,\n type ModelProviderProfile,\n} from './provider-profile';\nimport { isLoopbackProviderUrl } from './url';\n\n/** One chat message. `content` is `unknown` so multimodal block arrays pass through. */\nexport interface ChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: unknown;\n}\n\n/**\n * A chat/completions request minus `model`, which the client fills from the\n * profile — the profile is the single source of truth for which model this\n * configured provider addresses.\n */\nexport interface ChatCompletionRequest {\n messages: readonly ChatMessage[];\n max_tokens?: number;\n temperature?: number;\n response_format?: { type: string };\n}\n\nexport interface ModelProviderClientOptions {\n fetchImpl?: ProviderFetch;\n profile: unknown;\n secret?: string;\n}\n\n/**\n * Transport for OpenAI-compatible chat/completions providers, ported from\n * `aip-main-open@c6a5385` `providers.ts:478-829`.\n *\n * Only the request construction, response parsing, and error mapping travel;\n * every narrative/finance method of the source class stays in aip-main-open\n * per `docs/researches/HANDOFF-byok-keys.md` §4.5. The domain-specific\n * prompts, temperatures, and token budgets that were baked into those methods\n * become caller-supplied request fields.\n */\nexport class OpenAiCompatibleChatClient {\n readonly model: string;\n /** False only when the provider is loopback, i.e. no data leaves the machine. */\n readonly remoteDataTransfer: boolean;\n readonly #fetch: ProviderFetch;\n readonly #profile: ModelProviderProfile;\n readonly #secret: string | undefined;\n\n constructor(options: ModelProviderClientOptions) {\n this.#fetch = options.fetchImpl ?? ((input, init) => fetch(input, init));\n this.#profile = parseModelProviderProfile(options.profile);\n this.#secret = requiredProviderSecret(this.#profile, options.secret);\n this.model = this.#profile.model;\n this.remoteDataTransfer = !isLoopbackProviderUrl(this.#profile.base_url);\n }\n\n /** POST `<base_url>/chat/completions`; returns the parsed response object. */\n async createChatCompletion(\n request: ChatCompletionRequest,\n signal: AbortSignal = new AbortController().signal,\n ): Promise<Record<string, unknown>> {\n const response = await fetchWithProviderGuards(\n this.#fetch,\n modelApiUrl(this.#profile.base_url, 'chat/completions'),\n {\n body: JSON.stringify({ ...request, model: this.#profile.model }),\n headers: providerHeaders(this.#profile, this.#secret),\n method: 'POST',\n redirect: 'error',\n },\n signal,\n );\n const payload = objectValue(await readModelProviderResponse(response));\n if (payload === undefined) {\n throw new ByokKeysError(\n 'MODEL_RESPONSE_INVALID',\n 'Model provider returned an invalid response',\n );\n }\n return payload;\n }\n\n /**\n * Round-trip the configured key against the provider\n * (`providers.ts:797-828`). An empty completion fails, so a provider that\n * accepts anything cannot be mistaken for a working configuration.\n */\n async testConnection(\n signal: AbortSignal = new AbortController().signal,\n ): Promise<void> {\n const payload = await this.createChatCompletion(\n {\n max_tokens: 32,\n messages: [\n {\n content:\n 'Return one JSON object with exactly this shape: {\"ok\":true}.',\n role: 'user',\n },\n ],\n response_format: { type: 'json_object' },\n temperature: 0,\n },\n signal,\n );\n assertLiveModelResponse(chatCompletionText(payload));\n }\n}\n\n/**\n * Pull the assistant text out of a chat/completions payload\n * (`providers.ts:597-599` and siblings, which repeated this shape in every\n * narrative method).\n */\nexport function chatCompletionText(payload: Record<string, unknown>): string {\n const choices = Array.isArray(payload.choices) ? payload.choices : [];\n const message = objectValue(objectValue(choices[0])?.message);\n return modelMessageText(message?.content);\n}\n","import {\n assertLiveModelResponse,\n fetchWithProviderGuards,\n modelApiUrl,\n modelMessageText,\n objectValue,\n readModelProviderResponse,\n type ProviderFetch,\n} from './http';\nimport { providerHeaders, requiredProviderSecret } from './headers';\nimport { ByokKeysError } from './errors';\nimport {\n parseModelProviderProfile,\n type ModelProviderProfile,\n} from './provider-profile';\nimport type { ModelProviderClientOptions } from './openai-client';\nimport { isLoopbackProviderUrl } from './url';\n\n/** One Anthropic message. `content` is `unknown` so block arrays pass through. */\nexport interface AnthropicMessage {\n role: 'user' | 'assistant';\n content: unknown;\n}\n\n/**\n * A Messages API request minus `model`, which the client fills from the\n * profile. `max_tokens` is required because the API requires it.\n */\nexport interface AnthropicMessageRequest {\n messages: readonly AnthropicMessage[];\n max_tokens: number;\n system?: string;\n temperature?: number;\n}\n\n/**\n * Transport for the Anthropic Messages API, ported from\n * `aip-main-open@c6a5385` `providers.ts:831-1067`.\n *\n * As with the OpenAI-compatible client, only `#createMessage`'s generic\n * request/parse/error path travels; the narrative methods that wrapped it stay\n * in aip-main-open per `docs/researches/HANDOFF-byok-keys.md` §4.5.\n */\nexport class AnthropicMessagesClient {\n readonly model: string;\n /** False only when the provider is loopback, i.e. no data leaves the machine. */\n readonly remoteDataTransfer: boolean;\n readonly #fetch: ProviderFetch;\n readonly #profile: ModelProviderProfile;\n readonly #secret: string;\n\n constructor(options: ModelProviderClientOptions) {\n this.#fetch = options.fetchImpl ?? ((input, init) => fetch(input, init));\n this.#profile = parseModelProviderProfile(options.profile);\n if (this.#profile.adapter !== 'anthropic') {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Anthropic provider requires the anthropic adapter',\n );\n }\n this.#secret = requiredProviderSecret(\n this.#profile,\n options.secret,\n ) as string;\n this.model = this.#profile.model;\n this.remoteDataTransfer = !isLoopbackProviderUrl(this.#profile.base_url);\n }\n\n /** POST `<base_url>/messages`; returns the parsed response object. */\n async createMessage(\n request: AnthropicMessageRequest,\n signal: AbortSignal = new AbortController().signal,\n ): Promise<Record<string, unknown>> {\n const response = await fetchWithProviderGuards(\n this.#fetch,\n modelApiUrl(this.#profile.base_url, 'messages'),\n {\n body: JSON.stringify({ ...request, model: this.#profile.model }),\n headers: providerHeaders(this.#profile, this.#secret),\n method: 'POST',\n redirect: 'error',\n },\n signal,\n );\n const payload = objectValue(await readModelProviderResponse(response));\n if (payload === undefined) {\n throw new ByokKeysError(\n 'MODEL_RESPONSE_INVALID',\n 'Anthropic provider returned an invalid response',\n );\n }\n return payload;\n }\n\n /** Round-trip the configured key against the provider (`providers.ts:1037-1054`). */\n async testConnection(\n signal: AbortSignal = new AbortController().signal,\n ): Promise<void> {\n const payload = await this.createMessage(\n {\n max_tokens: 32,\n messages: [\n {\n content:\n 'Return one JSON object with exactly this shape: {\"ok\":true}.',\n role: 'user',\n },\n ],\n temperature: 0,\n },\n signal,\n );\n assertLiveModelResponse(anthropicMessageText(payload));\n }\n}\n\n/** Pull the assistant text out of a Messages API payload (`providers.ts:1084`). */\nexport function anthropicMessageText(payload: Record<string, unknown>): string {\n return modelMessageText(payload.content);\n}\n","import { spawn } from 'node:child_process';\n\n/** A finished child process, ported from `aip-main-open@c6a5385` `index.ts:284-288`. */\nexport interface CommandResult {\n exitCode: number;\n stderr: string;\n stdout: string;\n}\n\n/**\n * The injection seam both OS backends are written against. Unit tests supply a\n * fake so no test ever reads or writes a real credential store; production code\n * gets {@link runCommand}.\n */\nexport type CommandRunner = (\n executable: string,\n args: string[],\n stdin?: string,\n) => Promise<CommandResult>;\n\n/**\n * Spawn `executable`, feed it `stdin`, and collect its output\n * (`index.ts:2498-2527`).\n *\n * It never rejects: a missing executable resolves as exit code 127 so the\n * backends' `available()` probes can treat \"no such binary\" the same way they\n * treat \"binary said no\". Stdin is always closed, otherwise a child that reads\n * to EOF would hang forever.\n */\nexport async function runCommand(\n executable: string,\n args: string[],\n stdin?: string,\n): Promise<CommandResult> {\n return new Promise((resolveResult) => {\n const child = spawn(executable, args, {\n env: process.env,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n child.stdout.setEncoding('utf8');\n child.stderr.setEncoding('utf8');\n child.stdout.on('data', (chunk: string) => {\n stdout += chunk;\n });\n child.stderr.on('data', (chunk: string) => {\n stderr += chunk;\n });\n child.on('error', () => {\n resolveResult({\n exitCode: 127,\n stderr: 'command unavailable',\n stdout: '',\n });\n });\n child.on('close', (code) => {\n resolveResult({ exitCode: code ?? 1, stderr, stdout });\n });\n if (stdin === undefined) child.stdin.end();\n else child.stdin.end(stdin);\n });\n}\n","import { ByokKeysError } from './errors';\n\n/**\n * Legal secret-entry names, 3 to 96 characters.\n *\n * The source (`aip-main-open@c6a5385`, `apps/local-agent/src/index.ts:258-268`)\n * closed this set at compile time with the `KeychainSecretName` union, so it\n * needed no runtime check. `SecretStore<TName extends string>` is open by\n * design — aip's closed union stays in aip — so the closure moves to runtime.\n *\n * The exclusion that matters is `.`: every backend composes its storage key as\n * `` `${servicePrefix}.${name}` `` and a scoped store appends\n * `.scope.<namespace>` to that prefix. A name containing a dot could therefore\n * spell out another scope's service string and read that scope's secret. The\n * validator throws rather than sanitizing — a caller that mistyped a name must\n * see the error, not silently address a different entry.\n */\nexport const SECRET_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{2,95}$/u;\n\n/**\n * Legal scope namespaces, 8 to 96 characters. Ported verbatim from the source's\n * `normalizeSecretNamespace` (`index.ts:748-757`); the 8-character floor keeps\n * a namespace from colliding with a short accidental value.\n */\nexport const SECRET_NAMESPACE_PATTERN = /^[a-z0-9][a-z0-9_-]{7,95}$/u;\n\n/** Fail closed unless `name` matches {@link SECRET_NAME_PATTERN}. */\nexport function assertSecretName<TName extends string>(name: TName): TName {\n if (!SECRET_NAME_PATTERN.test(name)) {\n throw new ByokKeysError(\n 'SECRET_NAME_INVALID',\n 'Secret name must be 3 to 96 characters of [a-z0-9_-] starting with a letter or digit',\n );\n }\n return name;\n}\n\n/**\n * Trim and validate a scope namespace, or throw. Trimming is the source's\n * behavior and is safe because the pattern rejects every interior whitespace\n * character anyway.\n */\nexport function assertSecretNamespace(value: string): string {\n const normalized = value.trim();\n if (!SECRET_NAMESPACE_PATTERN.test(normalized)) {\n throw new ByokKeysError(\n 'SECRET_NAMESPACE_INVALID',\n 'Secret namespace must be 8 to 96 characters of [a-z0-9_-] starting with a letter or digit',\n );\n }\n return normalized;\n}\n","import { ByokKeysError } from './errors';\nimport {\n ProviderProfileRefSchema,\n type ProviderProfileRef,\n} from './provider-profile';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\n\n/**\n * Storage contract for a single secret entry in an operating-system credential\n * store.\n *\n * Ported from `aip-main-open@c6a5385` `apps/local-agent/src/index.ts:261-269`\n * with two deliberate changes:\n *\n * 1. `TName` is a generic parameter rather than aip's closed\n * `KeychainSecretName` union. aip's union names device keys, refresh tokens,\n * and market-data entries that this package has no business knowing about,\n * so it stays in aip and consumers pin their own union. The compile-time\n * closure it provided is replaced at runtime by {@link assertSecretName},\n * which every implementation must apply on every name it receives.\n * 2. `scope()` is required, not optional. The source made it optional and its\n * `scopeLocalAgentSecretStore` silently substituted an envelope\n * implementation when a store did not provide one. Scope-envelope prefixing\n * has no installed base, so this package removes the implicit substitution:\n * every store scopes itself, and {@link EnvelopeScopedSecretStore} is a\n * decorator a caller applies on purpose.\n */\nexport interface SecretStore<TName extends string = string> {\n /** Human-readable backend name, safe to show a user. Never contains a secret. */\n readonly providerLabel: string;\n /** Whether this backend can be used on the current machine. Must not throw. */\n available(): Promise<boolean>;\n /** Remove `name`; `false` when it was already absent. */\n delete(name: TName): Promise<boolean>;\n /** Read `name`, or `undefined` when it is absent. */\n get(name: TName): Promise<string | undefined>;\n /** Whether `name` currently holds a secret. */\n has(name: TName): Promise<boolean>;\n /** A view of this store isolated under `namespace`. */\n scope(namespace: string): SecretStore<TName>;\n /** Write `secret` at `name`, replacing any existing value. */\n set(name: TName, secret: string): Promise<void>;\n}\n\n/**\n * Default service prefix for this package's own entries. `servicePrefix` is a\n * constructor option on both OS backends, so K4's aip-main-open swap passes its\n * `com.aiphabee.local-agent` value and keeps existing installs byte-compatible.\n */\nexport const DEFAULT_SECRET_SERVICE_PREFIX = 'com.byok.keys';\n\n/**\n * Credential-store entry name for one provider profile.\n *\n * The former fixed `MODEL_PROVIDER_SECRET_NAMES` table could name exactly one\n * entry per provider kind, so two independent `custom` endpoints would have\n * shared — and overwritten — a single credential. The name is now derived from\n * the profile's own {@link ProviderProfileRef}, keeping the shape\n * `providers.ts:1624-1632` established (`model-<id>-api-key`, no vendor\n * branding; the branding lives in the service prefix).\n */\nexport type ModelProviderSecretName = `model-${string}-api-key`;\n\n/**\n * Resolve a provider profile ref to the credential-store entry holding its API\n * key. The ref is validated here as well as by the profile schema: this\n * function composes a storage address, so an unvalidated ref would be an\n * address-injection surface rather than merely an invalid record.\n */\nexport function modelProviderSecretName(\n profileRef: ProviderProfileRef,\n): ModelProviderSecretName {\n const parsed = ProviderProfileRefSchema.safeParse(profileRef);\n if (!parsed.success) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider profile ref must be a lowercase portable identifier',\n { cause: parsed.error },\n );\n }\n return assertSecretName(`model-${parsed.data}-api-key` as const);\n}\n\n/**\n * The secret-shape invariant both OS backends share. Their size ceilings differ\n * in both magnitude and unit (macOS counts 16384 characters, Windows counts\n * 2560 UTF-8 bytes) and each reports its own error code, so those checks stay\n * in the backends; only the empty/control-character rule is common.\n */\nexport function assertSharedSecretValue(secret: string): void {\n if (secret.length === 0 || /[\\u0000\\r\\n]/u.test(secret)) {\n throw new ByokKeysError(\n 'SECRET_VALUE_INVALID',\n 'Secret must be a non-empty string without null or newline characters',\n );\n }\n}\n\n/**\n * Decode base64 to UTF-8 text, or return `undefined` — never a repaired\n * approximation.\n *\n * Both decode paths in Node are lenient in ways that matter here: `Buffer.from`\n * silently drops characters outside the base64 alphabet (so `\"a!G@k=\"` would\n * decode to `\"hi\"`), and `Buffer#toString('utf8')` substitutes U+FFFD for\n * invalid byte sequences. A credential store that \"successfully\" returns a\n * silently-mangled secret is worse than one that fails, so the alphabet, the\n * canonical padding, and the UTF-8 round trip are all checked explicitly.\n */\nexport function decodeStrictBase64Utf8(encoded: string): string | undefined {\n if (encoded.length % 4 !== 0) return undefined;\n if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(encoded)) return undefined;\n const bytes = Buffer.from(encoded, 'base64');\n if (bytes.toString('base64') !== encoded) return undefined;\n const text = bytes.toString('utf8');\n if (!Buffer.from(text, 'utf8').equals(bytes)) return undefined;\n return text;\n}\n\n/**\n * A {@link SecretStore} held in process memory, for tests and for embedders\n * that supply their own persistence.\n *\n * It keys entries by the same `` `${servicePrefix}.${name}` `` string the OS\n * backends use, and `scope()` extends that prefix exactly as they do, so a test\n * written against this store exercises the same isolation arithmetic as\n * production. It applies the name validator and the shared secret-shape rule;\n * the platform size ceilings deliberately are not simulated, since they differ\n * per backend.\n */\nexport class InMemorySecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'in-memory';\n readonly #entries: Map<string, string>;\n readonly #servicePrefix: string;\n\n constructor(\n options: {\n /** Shared backing map; a scoped view keeps the parent's map. */\n entries?: Map<string, string>;\n servicePrefix?: string;\n } = {},\n ) {\n this.#entries = options.entries ?? new Map();\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n }\n\n available(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n async delete(name: TName): Promise<boolean> {\n return this.#entries.delete(this.#service(name));\n }\n\n async get(name: TName): Promise<string | undefined> {\n return this.#entries.get(this.#service(name));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new InMemorySecretStore<TName>({\n entries: this.#entries,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n assertSharedSecretValue(secret);\n this.#entries.set(service, secret);\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n","import path from 'node:path';\n\nimport { type CommandRunner, runCommand } from './command-runner';\nimport { ByokKeysError } from './errors';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\nimport {\n DEFAULT_SECRET_SERVICE_PREFIX,\n type SecretStore,\n decodeStrictBase64Utf8,\n} from './secret-store';\n\n/**\n * Marker written in front of every stored value so a read can tell a value this\n * package wrote from anything else already sitting at the same service name.\n * Injectable, so K4's aip-main-open swap passes `aiphabee-b64-v1:` and stays\n * byte-compatible with existing installs (source: `index.ts:246`).\n */\nexport const DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX = 'byok-b64-v1:';\n\n/** `security` exits 44 for \"the item does not exist\". */\nconst SECURITY_ITEM_NOT_FOUND = 44;\n\nexport interface MacOsKeychainSecretStoreOptions {\n /** Keychain account field; entries are addressed by (account, service). */\n account?: string;\n /**\n * Return a stored value that lacks {@link MacOsKeychainSecretStoreOptions.storagePrefix}\n * instead of throwing. Defaults to `false`.\n *\n * The source returned such values unconditionally\n * (`decodeMacOsKeychainSecret`, `index.ts:536-545`), which meant any\n * unrelated item at the same service name was handed back as if this package\n * had written it. Reading is fail-closed here, and the tolerant behavior is\n * demoted to something a caller must ask for by name — it exists only for a\n * migration that has read an unprefixed value it already knows it wrote.\n */\n allowUnprefixedRead?: boolean;\n commandRunner?: CommandRunner;\n /** Explicit macOS keychain file; omitted means the user default keychain. */\n keychainPath?: string;\n platform?: NodeJS.Platform;\n servicePrefix?: string;\n storagePrefix?: string;\n}\n\n/**\n * macOS Keychain backend, driving `/usr/bin/security`\n * (`aip-main-open@c6a5385` `apps/local-agent/src/index.ts:412-533`).\n *\n * There is deliberately no plaintext fallback: on a non-darwin platform every\n * operation throws `KEYCHAIN_UNAVAILABLE` rather than degrading to a file.\n */\nexport class MacOsKeychainSecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'macOS Keychain';\n readonly #account: string;\n readonly #allowUnprefixedRead: boolean;\n readonly #commandRunner: CommandRunner;\n readonly #keychainPath: string | undefined;\n readonly #platform: NodeJS.Platform;\n readonly #servicePrefix: string;\n readonly #storagePrefix: string;\n\n constructor(options: MacOsKeychainSecretStoreOptions = {}) {\n this.#account = options.account ?? 'local-device';\n this.#allowUnprefixedRead = options.allowUnprefixedRead ?? false;\n this.#commandRunner = options.commandRunner ?? runCommand;\n this.#keychainPath = assertKeychainPath(options.keychainPath);\n this.#platform = options.platform ?? process.platform;\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n this.#storagePrefix =\n options.storagePrefix ?? DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX;\n }\n\n async available(): Promise<boolean> {\n if (this.#platform !== 'darwin') return false;\n const result = await this.#commandRunner('/usr/bin/security', [\n ...(this.#keychainPath === undefined\n ? ['default-keychain', '-d', 'user']\n : ['show-keychain-info', this.#keychainPath]),\n ]);\n return result.exitCode === 0;\n }\n\n async delete(name: TName): Promise<boolean> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'delete-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n ...(this.#keychainPath === undefined ? [] : [this.#keychainPath]),\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return false;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_DELETE_FAILED',\n 'macOS Keychain could not delete the requested secret',\n );\n }\n return true;\n }\n\n async get(name: TName): Promise<string | undefined> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'find-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n '-w',\n ...(this.#keychainPath === undefined ? [] : [this.#keychainPath]),\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return undefined;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_READ_FAILED',\n 'macOS Keychain could not read the requested secret',\n );\n }\n return this.#decode(result.stdout.replace(/\\r?\\n$/u, ''));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new MacOsKeychainSecretStore<TName>({\n account: this.#account,\n allowUnprefixedRead: this.#allowUnprefixedRead,\n commandRunner: this.#commandRunner,\n keychainPath: this.#keychainPath,\n platform: this.#platform,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n storagePrefix: this.#storagePrefix,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n this.#assertMacOs();\n if (\n secret.length === 0 ||\n secret.length > 16_384 ||\n /[\\u0000\\r\\n]/u.test(secret)\n ) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_INVALID',\n 'Secret must contain 1 to 16384 non-newline characters',\n );\n }\n // `security add-generic-password -w` opens /dev/tty when no password\n // argument is supplied, even if the child has a piped stdin. Interactive\n // mode accepts the complete command through stdin, keeping the encoded\n // secret out of argv/process listings and avoiding an unattended prompt.\n const storedSecret = `${this.#storagePrefix}${Buffer.from(secret, 'utf8').toString('base64')}`;\n const command = [\n 'add-generic-password',\n '-U',\n '-a',\n quoteSecurityInteractiveArgument(this.#account),\n '-s',\n quoteSecurityInteractiveArgument(service),\n '-w',\n quoteSecurityInteractiveArgument(storedSecret),\n ...(this.#keychainPath === undefined\n ? []\n : [quoteSecurityInteractiveArgument(this.#keychainPath)]),\n ].join(' ');\n const result = await this.#commandRunner(\n '/usr/bin/security',\n ['-i'],\n `${command}\\n`,\n );\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_WRITE_FAILED',\n 'macOS Keychain could not store the requested secret',\n );\n }\n }\n\n #assertMacOs(): void {\n if (this.#platform !== 'darwin') {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n 'macOS Keychain is required; plaintext fallback is disabled',\n );\n }\n }\n\n /**\n * Fail-closed inverse of the storage encoding. The error message never\n * echoes the undecodable value — it may still be somebody's live credential.\n */\n #decode(storedSecret: string): string {\n if (!storedSecret.startsWith(this.#storagePrefix)) {\n if (this.#allowUnprefixedRead) return storedSecret;\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a value without this store\\'s storage prefix',\n );\n }\n const decoded = decodeStrictBase64Utf8(\n storedSecret.slice(this.#storagePrefix.length),\n );\n if (decoded === undefined || decoded.length === 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a secret that is not valid base64-encoded UTF-8',\n );\n }\n return decoded;\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n\n/**\n * Quote a value for `security -i`'s interactive parser (`index.ts:547-557`).\n * Null and newline characters cannot be quoted safely — a newline would end the\n * command line and let the remainder be parsed as a second command — so they are\n * rejected rather than escaped.\n */\nfunction quoteSecurityInteractiveArgument(value: string): string {\n if (/[\\u0000\\r\\n]/u.test(value)) {\n throw new ByokKeysError(\n 'KEYCHAIN_ARGUMENT_INVALID',\n 'macOS Keychain arguments cannot contain null or newline characters',\n );\n }\n return `\"${value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')}\"`;\n}\n\nfunction assertKeychainPath(keychainPath: string | undefined): string | undefined {\n if (keychainPath === undefined) return undefined;\n if (\n keychainPath.length === 0 ||\n !path.posix.isAbsolute(keychainPath) ||\n /[\\u0000\\r\\n]/u.test(keychainPath)\n ) {\n throw new ByokKeysError(\n 'KEYCHAIN_ARGUMENT_INVALID',\n 'macOS keychain path must be a non-empty absolute single-line path',\n );\n }\n return keychainPath;\n}\n","import { type CommandResult, type CommandRunner, runCommand } from './command-runner';\nimport { ByokKeysError } from './errors';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\nimport {\n DEFAULT_SECRET_SERVICE_PREFIX,\n type SecretStore,\n decodeStrictBase64Utf8,\n} from './secret-store';\n\n/** The script exits 44 for \"no such credential\", matching `security`'s code. */\nconst CREDENTIAL_NOT_FOUND = 44;\n\n/**\n * PowerShell bridge to the Win32 credential API, ported from\n * `aip-main-open@c6a5385` `apps/local-agent/src/index.ts:294-408`.\n *\n * It is passed as `-EncodedCommand` (UTF-16LE base64) so no part of it can be\n * mangled by shell quoting, and the request — including the secret — travels on\n * stdin rather than argv, keeping credentials out of process listings. The\n * generated C# type lives in namespace `Byok`; the source used its own vendor\n * name, and the identifier has no wire or storage surface, so renaming it costs\n * nothing at K4.\n */\nconst WINDOWS_CREDENTIAL_MANAGER_SCRIPT_BASE64 = Buffer.from(\n String.raw`\nAdd-Type -TypeDefinition @\"\nusing System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Runtime.InteropServices.ComTypes;\n\nnamespace Byok {\n public static class CredentialManager {\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n private struct Credential {\n public UInt32 Flags;\n public UInt32 Type;\n [MarshalAs(UnmanagedType.LPWStr)] public string TargetName;\n [MarshalAs(UnmanagedType.LPWStr)] public string Comment;\n public FILETIME LastWritten;\n public UInt32 CredentialBlobSize;\n public IntPtr CredentialBlob;\n public UInt32 Persist;\n public UInt32 AttributeCount;\n public IntPtr Attributes;\n [MarshalAs(UnmanagedType.LPWStr)] public string TargetAlias;\n [MarshalAs(UnmanagedType.LPWStr)] public string UserName;\n }\n\n [DllImport(\"Advapi32.dll\", EntryPoint = \"CredWriteW\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern bool CredWrite([In] ref Credential credential, UInt32 flags);\n\n [DllImport(\"Advapi32.dll\", EntryPoint = \"CredReadW\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern bool CredRead(string target, UInt32 type, UInt32 flags, out IntPtr credential);\n\n [DllImport(\"Advapi32.dll\", EntryPoint = \"CredDeleteW\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern bool CredDelete(string target, UInt32 type, UInt32 flags);\n\n [DllImport(\"Advapi32.dll\", SetLastError = false)]\n private static extern void CredFree(IntPtr buffer);\n\n public static void Write(string target, string username, byte[] secret) {\n IntPtr blob = IntPtr.Zero;\n try {\n blob = Marshal.AllocHGlobal(secret.Length);\n Marshal.Copy(secret, 0, blob, secret.Length);\n Credential credential = new Credential {\n Type = 1,\n TargetName = target,\n CredentialBlobSize = (UInt32)secret.Length,\n CredentialBlob = blob,\n Persist = 2,\n UserName = username\n };\n if (!CredWrite(ref credential, 0)) {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n } finally {\n if (blob != IntPtr.Zero) {\n Marshal.Copy(new byte[secret.Length], 0, blob, secret.Length);\n Marshal.FreeHGlobal(blob);\n }\n }\n }\n\n public static byte[] Read(string target) {\n IntPtr pointer;\n if (!CredRead(target, 1, 0, out pointer)) {\n int error = Marshal.GetLastWin32Error();\n if (error == 1168) return null;\n throw new Win32Exception(error);\n }\n try {\n Credential credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));\n byte[] secret = new byte[credential.CredentialBlobSize];\n if (secret.Length > 0) Marshal.Copy(credential.CredentialBlob, secret, 0, secret.Length);\n return secret;\n } finally {\n CredFree(pointer);\n }\n }\n\n public static bool Delete(string target) {\n if (CredDelete(target, 1, 0)) return true;\n int error = Marshal.GetLastWin32Error();\n if (error == 1168) return false;\n throw new Win32Exception(error);\n }\n }\n}\n\"@\n\ntry {\n $request = ([Console]::In.ReadToEnd() | ConvertFrom-Json)\n if ($request.operation -eq \"set\") {\n [Byok.CredentialManager]::Write(\n [string]$request.target,\n [string]$request.username,\n [Convert]::FromBase64String([string]$request.secret_base64)\n )\n exit 0\n }\n if ($request.operation -eq \"get\") {\n $secret = [Byok.CredentialManager]::Read([string]$request.target)\n if ($null -eq $secret) { exit 44 }\n [Console]::Out.Write([Convert]::ToBase64String($secret))\n exit 0\n }\n if ($request.operation -eq \"delete\") {\n if ([Byok.CredentialManager]::Delete([string]$request.target)) { exit 0 }\n exit 44\n }\n exit 2\n} catch {\n [Console]::Error.Write(\"credential operation failed\")\n exit 1\n}\n`,\n 'utf16le',\n).toString('base64');\n\nexport interface WindowsCredentialManagerSecretStoreOptions {\n account?: string;\n commandRunner?: CommandRunner;\n platform?: NodeJS.Platform;\n servicePrefix?: string;\n}\n\n/**\n * Windows Credential Manager backend (`index.ts:568-712`).\n *\n * As on macOS there is no plaintext fallback — off win32 every operation throws\n * `CREDENTIAL_MANAGER_UNAVAILABLE`.\n */\nexport class WindowsCredentialManagerSecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'Windows Credential Manager';\n readonly #account: string;\n readonly #commandRunner: CommandRunner;\n readonly #platform: NodeJS.Platform;\n readonly #servicePrefix: string;\n\n constructor(options: WindowsCredentialManagerSecretStoreOptions = {}) {\n this.#account = options.account ?? 'local-device';\n this.#commandRunner = options.commandRunner ?? runCommand;\n this.#platform = options.platform ?? process.platform;\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n }\n\n async available(): Promise<boolean> {\n if (this.#platform !== 'win32') return false;\n const result = await this.#commandRunner('powershell.exe', [\n '-NoLogo',\n '-NoProfile',\n '-NonInteractive',\n '-Command',\n '$PSVersionTable.PSVersion.Major',\n ]);\n return result.exitCode === 0;\n }\n\n /**\n * Delete, then read back. The source verifies rather than trusting the\n * delete's exit code (`index.ts:651-679`): a credential that survives a\n * \"successful\" delete is a security failure, so it is reported as one instead\n * of being returned as `true`.\n */\n async delete(name: TName): Promise<boolean> {\n const target = this.#service(name);\n this.#assertWindows();\n const result = await this.#invoke({\n operation: 'delete',\n target,\n username: this.#account,\n });\n if (result.exitCode === CREDENTIAL_NOT_FOUND) return false;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_DELETE_FAILED',\n 'Windows Credential Manager could not delete the requested secret',\n );\n }\n const verification = await this.#invoke({\n operation: 'get',\n target,\n username: this.#account,\n });\n if (verification.exitCode === CREDENTIAL_NOT_FOUND) return true;\n if (verification.exitCode !== 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_DELETE_FAILED',\n 'Windows Credential Manager could not verify secret deletion',\n );\n }\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_DELETE_FAILED',\n 'Windows Credential Manager reported deletion but the secret remains',\n );\n }\n\n async get(name: TName): Promise<string | undefined> {\n const target = this.#service(name);\n this.#assertWindows();\n const result = await this.#invoke({\n operation: 'get',\n target,\n username: this.#account,\n });\n if (result.exitCode === CREDENTIAL_NOT_FOUND) return undefined;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_READ_FAILED',\n 'Windows Credential Manager could not read the requested secret',\n );\n }\n // The source wrapped this decode in try/catch, but `Buffer.from` never\n // throws on bad input -- it silently drops the offending characters, so\n // that branch was unreachable. The strict decoder makes it real.\n const secret = decodeStrictBase64Utf8(result.stdout.trim());\n if (secret === undefined || secret.length === 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_READ_FAILED',\n 'Windows Credential Manager returned an invalid secret',\n );\n }\n return secret;\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new WindowsCredentialManagerSecretStore<TName>({\n account: this.#account,\n commandRunner: this.#commandRunner,\n platform: this.#platform,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const target = this.#service(name);\n this.#assertWindows();\n assertWindowsCredentialSecret(secret);\n const result = await this.#invoke({\n operation: 'set',\n secret_base64: Buffer.from(secret, 'utf8').toString('base64'),\n target,\n username: this.#account,\n });\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_WRITE_FAILED',\n 'Windows Credential Manager could not store the requested secret',\n );\n }\n }\n\n #assertWindows(): void {\n if (this.#platform !== 'win32') {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_UNAVAILABLE',\n 'Windows Credential Manager is required; plaintext fallback is disabled',\n );\n }\n }\n\n async #invoke(request: {\n operation: 'delete' | 'get' | 'set';\n secret_base64?: string;\n target: string;\n username: string;\n }): Promise<CommandResult> {\n return this.#commandRunner(\n 'powershell.exe',\n [\n '-NoLogo',\n '-NoProfile',\n '-NonInteractive',\n '-EncodedCommand',\n WINDOWS_CREDENTIAL_MANAGER_SCRIPT_BASE64,\n ],\n JSON.stringify(request),\n );\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n\n/**\n * `index.ts:2529-2543`. The ceiling is measured in UTF-8 bytes because that is\n * what `CredentialBlobSize` counts; a character-based check would let a\n * multi-byte secret overrun it.\n */\nfunction assertWindowsCredentialSecret(secret: string): void {\n const bytes = Buffer.byteLength(secret, 'utf8');\n if (secret.length === 0 || bytes > 2_560 || /[\\u0000\\r\\n]/u.test(secret)) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_SECRET_INVALID',\n 'Secret must contain 1 to 2560 UTF-8 bytes without newline characters',\n );\n }\n}\n","import { createHash } from 'node:crypto';\n\nimport { ByokKeysError } from './errors';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\nimport { type SecretStore, assertSharedSecretValue } from './secret-store';\n\n/**\n * Tenant identity a secret store is partitioned by. Ported from\n * `aip-main-open@c6a5385` `apps/local-agent/src/local-data-scope.ts:19-22`\n * (`LocalAccountDataScope`).\n */\nexport interface SecretScope {\n account_id: string;\n workspace_id: string;\n}\n\n/**\n * Envelope marker, injectable so K4 can pass the source's\n * `aiphabee-scoped-secrets-v1:` value (`local-data-scope.ts:30`).\n */\nexport const DEFAULT_SECRET_ENVELOPE_PREFIX = 'byok-scoped-secrets-v1:';\n\n/**\n * Derive the opaque namespace a scope's secrets live under\n * (`local-data-scope.ts:32-37`). Hashing means the namespace never leaks a\n * tenant identifier into a keychain service name a user can browse.\n */\nexport function secretScopeId(scope: SecretScope): string {\n const normalized = normalizeSecretScope(scope);\n return `acct_${createHash('sha256')\n .update(`${normalized.account_id}\\n${normalized.workspace_id}`, 'utf8')\n .digest('hex')}`;\n}\n\n/**\n * Partition `store` by `scope` (`local-data-scope.ts:100-106`).\n *\n * The source read `store.scope?.(id) ?? new EnvelopeScopedSecretStore(...)`:\n * when a store happened not to implement `scope`, it silently switched to a\n * different storage layout. `SecretStore.scope` is required in this package, so\n * that implicit substitution is gone — a caller who wants envelope semantics\n * constructs {@link EnvelopeScopedSecretStore} on purpose.\n */\nexport function scopeSecretStore<TName extends string>(\n store: SecretStore<TName>,\n scope: SecretScope,\n): SecretStore<TName> {\n return store.scope(secretScopeId(scope));\n}\n\n/**\n * Partition a store by keeping every scope's secret in one underlying entry,\n * as a JSON map of scope id to secret.\n *\n * This is the layout to reach for when the backend cannot cheaply namespace its\n * own key space. It costs a read-modify-write on every mutation and offers no\n * cross-process locking, so prefer a backend's native `scope()` when it has\n * one; this decorator exists for the backends that do not.\n *\n * Reads are fail-closed in a way the source's were not\n * (`local-data-scope.ts:163-194`): the source mapped any unparseable stored\n * value to `undefined`, which made a foreign value look like an absent secret\n * and let the next `set()` overwrite it. Here a stored value that is not a\n * well-formed envelope raises `SECRET_ENVELOPE_INVALID`.\n */\nexport class EnvelopeScopedSecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel: string;\n readonly #envelopePrefix: string;\n readonly #scopeId: string;\n readonly #store: SecretStore<TName>;\n\n constructor(\n store: SecretStore<TName>,\n scopeId: string,\n options: { envelopePrefix?: string } = {},\n ) {\n this.#store = store;\n this.#scopeId = assertScopeSlotKey(scopeId);\n this.#envelopePrefix =\n options.envelopePrefix ?? DEFAULT_SECRET_ENVELOPE_PREFIX;\n this.providerLabel = store.providerLabel;\n }\n\n available(): Promise<boolean> {\n return this.#store.available();\n }\n\n async delete(name: TName): Promise<boolean> {\n const envelope = await this.#readEnvelope(name);\n if (envelope === undefined || !Object.hasOwn(envelope, this.#scopeId)) {\n return false;\n }\n delete envelope[this.#scopeId];\n if (Object.keys(envelope).length === 0) return this.#store.delete(name);\n await this.#store.set(name, this.#serialize(envelope));\n return true;\n }\n\n async get(name: TName): Promise<string | undefined> {\n return (await this.#readEnvelope(name))?.[this.#scopeId];\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new EnvelopeScopedSecretStore<TName>(\n this.#store,\n `${this.#scopeId}.${assertSecretNamespace(namespace)}`,\n { envelopePrefix: this.#envelopePrefix },\n );\n }\n\n async set(name: TName, secret: string): Promise<void> {\n assertSharedSecretValue(secret);\n const envelope =\n (await this.#readEnvelope(name)) ??\n (Object.create(null) as Record<string, string>);\n envelope[this.#scopeId] = secret;\n await this.#store.set(name, this.#serialize(envelope));\n }\n\n /**\n * `undefined` means the entry is absent; a malformed entry throws.\n *\n * The returned map has a null prototype. A slot key is attacker-adjacent\n * data — `constructor` is a legal namespace (`toString` and `__proto__` are\n * rejected by the pattern, but this defense does not depend on the pattern's\n * shape) — so a plain object would answer `envelope[scopeId]` from\n * `Object.prototype` and hand a Function back as a scope's secret.\n */\n async #readEnvelope(\n name: TName,\n ): Promise<Record<string, string> | undefined> {\n const stored = await this.#store.get(assertSecretName(name));\n if (stored === undefined) return undefined;\n if (!stored.startsWith(this.#envelopePrefix)) throw envelopeInvalid();\n const decoded = decodeBase64Url(stored.slice(this.#envelopePrefix.length));\n if (decoded === undefined) throw envelopeInvalid();\n let parsed: unknown;\n try {\n parsed = JSON.parse(decoded);\n } catch {\n throw envelopeInvalid();\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Array.isArray(parsed) ||\n Object.values(parsed).some((value) => typeof value !== 'string')\n ) {\n throw envelopeInvalid();\n }\n return Object.assign(\n Object.create(null) as Record<string, string>,\n parsed as Record<string, string>,\n );\n }\n\n #serialize(value: Record<string, string>): string {\n return `${this.#envelopePrefix}${Buffer.from(\n JSON.stringify(value),\n 'utf8',\n ).toString('base64url')}`;\n }\n}\n\n/**\n * Validate an envelope slot key: one or more namespaces joined by `.`, as\n * {@link EnvelopeScopedSecretStore.scope} composes them. Each segment must pass\n * {@link assertSecretNamespace} on its own, so a nested key cannot smuggle in a\n * segment the validator would otherwise reject.\n *\n * Unlike a backend service string, a `.` is safe here: the key addresses a JSON\n * object property, not a `` `${servicePrefix}.${name}` `` lookup, so it cannot\n * be confused with a different entry.\n *\n * Addressing a JSON object property carries its own hazard, though: the\n * namespace pattern admits `constructor` (`toString` and `__proto__` it\n * rejects), so a slot lookup on a plain object would resolve through\n * `Object.prototype` and report a never-written scope as present.\n * {@link EnvelopeScopedSecretStore} closes that by keeping every envelope\n * null-prototyped and testing slot presence with `Object.hasOwn` — a defense\n * that does not depend on the pattern's shape, which is why `constructor`\n * stays a legal namespace rather than being banned.\n */\nfunction assertScopeSlotKey(value: string): string {\n return value\n .trim()\n .split('.')\n .map((segment) => assertSecretNamespace(segment))\n .join('.');\n}\n\nfunction envelopeInvalid(): ByokKeysError {\n return new ByokKeysError(\n 'SECRET_ENVELOPE_INVALID',\n 'The stored value is not a well-formed scoped-secret envelope',\n );\n}\n\n/** Strict base64url decode; `undefined` rather than a repaired approximation. */\nfunction decodeBase64Url(encoded: string): string | undefined {\n if (!/^[A-Za-z0-9_-]*$/u.test(encoded)) return undefined;\n const bytes = Buffer.from(encoded, 'base64url');\n if (bytes.toString('base64url') !== encoded) return undefined;\n const text = bytes.toString('utf8');\n if (!Buffer.from(text, 'utf8').equals(bytes)) return undefined;\n return text;\n}\n\n/**\n * `local-data-scope.ts:108-121`, plus one tightening: control characters are\n * rejected. The scope id hashes `` `${account_id}\\n${workspace_id}` ``, so an\n * account id containing a newline would collide with a different scope\n * (`\"a\\nb\" + \"c\"` and `\"a\" + \"b\\nc\"` both serialize to `\"a\\nb\\nc\"`). Rejecting\n * them closes the collision without changing the hash of any legal input.\n */\nfunction normalizeSecretScope(scope: SecretScope): SecretScope {\n const accountId = scope.account_id.trim();\n const workspaceId = scope.workspace_id.trim();\n if (\n !accountId ||\n !workspaceId ||\n accountId.length > 160 ||\n workspaceId.length > 160 ||\n /[\\u0000\\r\\n]/u.test(accountId) ||\n /[\\u0000\\r\\n]/u.test(workspaceId)\n ) {\n throw new ByokKeysError(\n 'LOCAL_ACCOUNT_SCOPE_INVALID',\n 'The local account data scope is invalid',\n );\n }\n return { account_id: accountId, workspace_id: workspaceId };\n}\n","import { ByokKeysError } from './errors';\nimport {\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\n\n/**\n * Storage contract for provider profiles — everything needed to address a\n * provider except the API key, which lives in a {@link SecretStore}.\n *\n * Shaped after `@byok-sdk/server`'s `TaskStore` (`packages/server/src/task-store.ts`)\n * as a *pattern*, not a dependency: `keys` must not import `server`, and\n * `server` must not import `keys` (the plan's Security Boundary keeps the\n * agent-dispatch packages free of any credential-adjacent code).\n *\n * Two invariants every implementation MUST enforce, not just\n * {@link InMemoryProviderProfileStore}:\n *\n * 1. **At most one enabled profile.** The source expressed this as a partial\n * unique index (`providers.ts:140-144`); saving an enabled profile disables\n * every other one. {@link resolveDefaultModelProvider} relies on it to\n * answer \"which provider is the default\" with a single row.\n * 2. **Validate on write.** `save` runs {@link parseModelProviderProfile}, so an\n * invalid profile is refused at the boundary rather than discovered later by\n * a reader.\n */\nexport interface ProviderProfileStore {\n /** Release the underlying resource. Safe to call more than once. */\n close(): Promise<void>;\n /** Remove `profileRef`; `false` when it was not configured. */\n delete(profileRef: ProviderProfileRef): Promise<boolean>;\n /** Read one profile, configured or not enabled alike. */\n get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined>;\n /** The single enabled profile, or `undefined` when none is enabled. */\n getEnabled(): Promise<ModelProviderProfile | undefined>;\n /** Every configured profile, ordered by profile ref. */\n list(): Promise<ModelProviderProfile[]>;\n /** Insert or update `profile`, enforcing both invariants above. */\n save(profile: ModelProviderProfile): Promise<ModelProviderProfile>;\n /**\n * Make `profileRef` the enabled profile. Throws `PROVIDER_NOT_CONFIGURED`\n * when it has no profile — a fail-closed port of `providers.ts:1243-1250`.\n */\n setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile>;\n}\n\n/** Shared by both implementations so their error text cannot drift apart. */\nexport function providerNotConfigured(\n profileRef: ProviderProfileRef,\n): ByokKeysError {\n return new ByokKeysError(\n 'PROVIDER_NOT_CONFIGURED',\n `${profileRef} model provider is not configured`,\n );\n}\n\n/**\n * Profile store held in process memory: the default, and the one every test\n * that does not specifically exercise SQLite should use.\n *\n * Mirrors `InMemoryTaskStore`'s role in `@byok-sdk/server` — a real implementation\n * of the contract, not a stub, so behaviour proven here is the behaviour the\n * SQLite store must match (`profile-store.test.ts` runs one suite against both).\n */\nexport class InMemoryProviderProfileStore implements ProviderProfileStore {\n readonly #profiles = new Map<ProviderProfileRef, ModelProviderProfile>();\n\n async close(): Promise<void> {\n this.#profiles.clear();\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n return this.#profiles.delete(profileRef);\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n return this.#profiles.get(profileRef);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n return [...this.#profiles.values()].find((profile) => profile.enabled);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n return [...this.#profiles.values()].sort((left, right) =>\n left.profile_ref.localeCompare(right.profile_ref),\n );\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const validated = parseModelProviderProfile({\n ...profile,\n created_at:\n this.#profiles.get(profile.profile_ref)?.created_at ??\n profile.created_at,\n });\n if (validated.enabled) {\n for (const [profileRef, existing] of this.#profiles) {\n if (profileRef !== validated.profile_ref && existing.enabled) {\n this.#profiles.set(profileRef, { ...existing, enabled: false });\n }\n }\n }\n this.#profiles.set(validated.profile_ref, validated);\n return validated;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const existing = this.#profiles.get(profileRef);\n if (existing === undefined) throw providerNotConfigured(profileRef);\n return this.save({ ...existing, enabled: true });\n }\n}\n","import { chmodSync, existsSync, mkdirSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname } from 'node:path';\nimport type { DatabaseSync, DatabaseSyncOptions } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\n\nexport type SqliteOpenStep = 'after-open' | 'after-wal' | 'after-synchronous';\n\n/** Test-only seam for proving that post-open initialization failures release the native handle. */\nexport interface SqliteOpenFaultSeam {\n onStep?(step: SqliteOpenStep): void;\n close?(database: DatabaseSync): void;\n}\n\n/** Release an opened handle before propagating an initialization failure. */\nexport function closeSqliteDatabaseAfterInitializationFailure(\n database: DatabaseSync,\n initializationError: unknown,\n message: string,\n close: (database: DatabaseSync) => void = (handle) => handle.close(),\n): never {\n try {\n close(database);\n } catch (closeError) {\n throw new AggregateError([initializationError, closeError], message);\n }\n throw initializationError;\n}\n\n/** Owner-only directory mode, matching `providers.ts:1236`. */\nconst SECURE_DIR_MODE = 0o700;\n\n/** Owner-only file mode, matching `providers.ts:158`. */\nconst SECURE_FILE_MODE = 0o600;\n\nconst DEFAULT_BUSY_TIMEOUT_MS = 5_000;\n\ninterface SqliteModule {\n DatabaseSync: new (\n path: string,\n options?: DatabaseSyncOptions,\n ) => DatabaseSync;\n}\n\n/**\n * Load `node:sqlite`, or fail with a `ByokKeysError` that says why.\n *\n * `node:sqlite` shipped in Node.js 22.5.0 and stays marked experimental (an\n * `ExperimentalWarning` on stderr is expected and harmless). Following\n * `@byok-sdk/server`'s `sqlite-support.ts`, the SQLite-backed store here depends on\n * nothing else — no `better-sqlite3`, no native module — because zero native\n * dependencies is what keeps this package trivially packageable. The tradeoff\n * is that {@link SqliteProviderProfileStore} does not work below Node 22.5, and\n * this error says so instead of letting a cryptic `Cannot find module` surface\n * from deep inside a query.\n */\nexport function loadSqliteModule(): SqliteModule {\n try {\n return createRequire(import.meta.url)('node:sqlite') as SqliteModule;\n } catch (error) {\n throw new ByokKeysError(\n 'PROVIDER_STORE_UNAVAILABLE',\n 'node:sqlite is unavailable in this Node.js runtime. SqliteProviderProfileStore ' +\n 'requires Node.js 22.5+ with the built-in `node:sqlite` module (no native ' +\n 'dependency is used or allowed here). Upgrade Node.js, or use ' +\n 'InMemoryProviderProfileStore instead.',\n { cause: error },\n );\n }\n}\n\n/**\n * Whether `node:sqlite` can ACTUALLY be loaded right now.\n *\n * Same predicate as `@byok-sdk/server`'s `sqlite-support.ts`, and it exists for the\n * same reason: this package's `engines.node` is `>=20` and CI runs the matrix\n * on 20 and 22, but `node:sqlite` shipped in 22.5 and stayed behind\n * `--experimental-sqlite` for part of the 22.x line. A version-number\n * comparison would therefore be wrong in both directions, so this attempts the\n * real require via {@link loadSqliteModule} and reports whether it succeeded.\n *\n * Callers use it to skip a SQLite-backed path rather than fail it — the\n * package's own SQLite-backed suites gate on it — and anything else should call\n * it before assuming a {@link SqliteProviderProfileStore} can be constructed.\n */\nexport function isSqliteAvailable(): boolean {\n try {\n loadSqliteModule();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Open a database, creating its parent directory owner-only first. `:memory:`\n * skips every filesystem step, which is how the shared contract suite exercises\n * the SQLite code path without leaving anything on disk.\n */\nexport function openSqliteDatabase(\n path: string,\n options?: DatabaseSyncOptions,\n faults?: SqliteOpenFaultSeam,\n): DatabaseSync {\n const { DatabaseSync } = loadSqliteModule();\n const readOnly = options?.readOnly === true;\n if (path !== ':memory:' && !readOnly) {\n mkdirSync(dirname(path), { mode: SECURE_DIR_MODE, recursive: true });\n }\n const database = new DatabaseSync(path, {\n timeout: DEFAULT_BUSY_TIMEOUT_MS,\n ...options,\n });\n try {\n faults?.onStep?.('after-open');\n if (path !== ':memory:' && !readOnly) {\n database.exec('PRAGMA journal_mode = WAL');\n faults?.onStep?.('after-wal');\n database.exec('PRAGMA synchronous = FULL');\n faults?.onStep?.('after-synchronous');\n }\n return database;\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n database,\n error,\n 'provider profile SQLite open initialization failed and its native handle could not be closed',\n faults?.close,\n );\n }\n}\n\n/**\n * Restrict `databasePath` and its WAL/SHM siblings to owner-only read/write.\n *\n * The profile table holds no secret — that is the whole point of splitting the\n * key into the OS credential store — but it does hold every provider endpoint\n * this machine talks to, and the source locked the file down\n * (`providers.ts:158`), so the port keeps that. Call after the schema exists,\n * so the lazily-created WAL/SHM files are already there; a sibling that does\n * not exist is skipped rather than treated as an error. No-op for `:memory:`.\n */\nexport function secureSqliteFilePermissions(databasePath: string): void {\n if (databasePath === ':memory:') return;\n for (const candidate of [\n databasePath,\n `${databasePath}-wal`,\n `${databasePath}-shm`,\n ]) {\n if (existsSync(candidate)) {\n chmodSync(candidate, SECURE_FILE_MODE);\n }\n }\n}\n","import type { DatabaseSync } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\nimport {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n MODEL_PROVIDER_KINDS,\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\nimport {\n closeSqliteDatabaseAfterInitializationFailure,\n openSqliteDatabase,\n secureSqliteFilePermissions,\n} from './sqlite-support';\n\nexport interface SqliteProviderProfileStoreOptions {\n /**\n * Database file path. `:memory:` exercises the SQLite code path without a\n * temp file, but defeats the point of this store (restart-safety) exactly as\n * it does for `@byok-sdk/server`'s `SqliteTaskStore`.\n */\n path: string;\n /** Open an existing profile database without creating or mutating it. */\n readOnly?: boolean;\n}\n\n/**\n * Ported from `providers.ts:109-140`, narrowed to the model branch. The\n * source's table also carried `market_data` / `mcp_http` rows and a `tool_name`\n * column; that branch stays in aip-main-open per\n * `docs/researches/HANDOFF-byok-keys.md` §4.5, so the CHECK constraints here\n * are the model half only.\n */\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS provider_profile (\n profile_ref TEXT PRIMARY KEY,\n provider_kind TEXT NOT NULL CHECK (provider_kind IN ('openai', 'deepseek', 'anthropic', 'custom')),\n kind TEXT NOT NULL CHECK (kind = 'model'),\n adapter TEXT NOT NULL CHECK (adapter IN ('openai_compatible', 'anthropic')),\n display_name TEXT NOT NULL,\n base_url TEXT NOT NULL,\n auth_mode TEXT NOT NULL CHECK (auth_mode IN ('bearer', 'x_api_key', 'none')),\n model TEXT NOT NULL,\n capabilities TEXT NOT NULL,\n enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\n`;\n\n/**\n * The \"at most one enabled profile\" invariant, enforced by the database itself\n * rather than only by {@link SqliteProviderProfileStore.save}\n * (`providers.ts:140-144`). A partial unique index means a bug in the write\n * path surfaces as a constraint violation instead of silently producing two\n * defaults.\n */\nconst ENABLED_INDEX = `\nCREATE UNIQUE INDEX IF NOT EXISTS provider_profile_one_enabled\nON provider_profile(kind)\nWHERE enabled = 1;\n`;\n\ninterface ProfileRow {\n adapter: string;\n auth_mode: string;\n base_url: string;\n capabilities: string;\n created_at: string;\n display_name: string;\n enabled: number;\n kind: string;\n model: string;\n profile_ref: string;\n provider_kind: string;\n updated_at: string;\n}\n\n/**\n * SQLite-backed {@link ProviderProfileStore}, following `@byok-sdk/server`'s\n * `SqliteTaskStore` shape. Holds no secret: the API key lives in the injected\n * `SecretStore`, and `registry.golden.test.ts` asserts the plaintext key never\n * appears in this file's bytes.\n */\nexport class SqliteProviderProfileStore implements ProviderProfileStore {\n readonly #database: DatabaseSync;\n #closed = false;\n\n constructor(options: SqliteProviderProfileStoreOptions) {\n this.#database = openSqliteDatabase(options.path, {\n readOnly: options.readOnly ?? false,\n });\n if (!options.readOnly) {\n try {\n this.#database.exec(SCHEMA);\n this.#database.exec(ENABLED_INDEX);\n secureSqliteFilePermissions(options.path);\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n this.#database,\n error,\n 'SqliteProviderProfileStore initialization failed and its native handle could not be closed',\n );\n }\n }\n }\n\n /**\n * Idempotent, as {@link ProviderProfileStore.close} requires: `node:sqlite`\n * throws \"database is not open\" on a second `close()`, and a store is\n * routinely closed both by the code that finished with it and by a test's\n * teardown.\n */\n async close(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n this.#database.close();\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n const result = this.#database\n .prepare('DELETE FROM provider_profile WHERE profile_ref = ?')\n .run(profileRef);\n return Number(result.changes) === 1;\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE profile_ref = ?')\n .get(profileRef) as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE enabled = 1')\n .get() as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n const rows = this.#database\n .prepare('SELECT * FROM provider_profile ORDER BY profile_ref ASC')\n .all() as unknown as ProfileRow[];\n return rows.map(parseRow);\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const existing = await this.get(profile.profile_ref);\n const validated = parseModelProviderProfile({\n ...profile,\n created_at: existing?.created_at ?? profile.created_at,\n });\n this.#transaction(() => {\n if (validated.enabled) {\n this.#database\n .prepare(\n 'UPDATE provider_profile SET enabled = 0 WHERE profile_ref <> ?',\n )\n .run(validated.profile_ref);\n }\n this.#database\n .prepare(\n `INSERT INTO provider_profile (\n profile_ref, provider_kind, kind, adapter, display_name, base_url,\n auth_mode, model, capabilities, enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(profile_ref) DO UPDATE SET\n provider_kind = excluded.provider_kind,\n adapter = excluded.adapter,\n display_name = excluded.display_name,\n base_url = excluded.base_url,\n auth_mode = excluded.auth_mode,\n model = excluded.model,\n capabilities = excluded.capabilities,\n enabled = excluded.enabled,\n updated_at = excluded.updated_at`,\n )\n .run(\n validated.profile_ref,\n validated.provider_kind,\n validated.kind,\n validated.adapter,\n validated.display_name,\n validated.base_url,\n validated.auth_mode,\n validated.model,\n JSON.stringify(validated.capabilities),\n validated.enabled ? 1 : 0,\n validated.created_at,\n validated.updated_at,\n );\n });\n return (await this.get(validated.profile_ref)) as ModelProviderProfile;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const existing = await this.get(profileRef);\n if (existing === undefined) throw providerNotConfigured(profileRef);\n return this.save({ ...existing, enabled: true });\n }\n\n /** `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`, per `providers.ts:1252-1263`. */\n #transaction(body: () => void): void {\n this.#database.exec('BEGIN IMMEDIATE');\n try {\n body();\n this.#database.exec('COMMIT');\n } catch (error) {\n this.#database.exec('ROLLBACK');\n throw error;\n }\n }\n}\n\n/**\n * Rows go back through the same zod schema the write path used, so a row that\n * a different process wrote — or an older schema left behind — is rejected\n * rather than trusted. `enabled` is an INTEGER in SQLite and a real boolean in\n * the schema, and `capabilities` is a JSON array in a TEXT column, so both are\n * decoded explicitly and a row that fails to decode is refused rather than\n * quietly downgraded to an empty capability set.\n */\nfunction parseRow(row: ProfileRow): ModelProviderProfile {\n let capabilities: unknown;\n try {\n capabilities = JSON.parse(row.capabilities);\n } catch (cause) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider profile capabilities column is not valid JSON',\n { cause },\n );\n }\n return parseModelProviderProfile({\n ...row,\n capabilities,\n enabled: row.enabled === 1,\n });\n}\n\n/** Exported for the store's own tests to enumerate the CHECK-constrained kinds. */\nexport const SQLITE_PROFILE_PROVIDER_KINDS = MODEL_PROVIDER_KINDS;\n","import { createHash } from 'node:crypto';\n\nimport {\n contentHash,\n isCoreConflictError,\n type TenantId,\n type TruthRecord,\n type TruthStore,\n} from '@byok-sdk/core';\n\nimport { ByokKeysError } from './errors';\nimport {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\n\nexport const PROVIDER_PROFILE_TRUTH_RECORD_KEY =\n 'byok-sdk.keys/model-provider-registry-v1';\n\nconst PROFILE_KEYS = [\n 'adapter',\n 'auth_mode',\n 'base_url',\n 'capabilities',\n 'created_at',\n 'display_name',\n 'enabled',\n 'kind',\n 'model',\n 'profile_ref',\n 'provider_kind',\n 'updated_at',\n] as const;\n\n/**\n * Upper bound on how many profiles one tenant's registry snapshot may carry.\n *\n * The former bound was `MODEL_PROVIDER_IDS.length`, which only held because the\n * primary key was a four-value enum. Profile refs are open, so the CAS body\n * needs an explicit ceiling of its own; a registry is device-local operator\n * configuration, and 32 endpoints is far past any real local setup while\n * keeping the single-record snapshot small.\n */\nexport const MAX_PROVIDER_PROFILES = 32;\n\ninterface ProviderRegistrySnapshotV1 {\n readonly schema_version: 1;\n readonly profiles: readonly ModelProviderProfile[];\n}\n\ninterface LoadedRegistry {\n readonly profiles: readonly ModelProviderProfile[];\n readonly rev: number;\n}\n\nexport interface TruthStoreProviderProfileStoreOptions {\n tenant: TenantId;\n truthStore: TruthStore;\n}\n\n/**\n * Tenant-bound profile persistence over the core TruthStore snapshot contract.\n *\n * The complete, closed provider registry is one CAS unit. That is what makes a\n * delete and the \"at most one enabled profile\" transition atomic without\n * adding a second transaction authority. The body is metadata only; provider\n * credentials remain exclusively in the independently injected SecretStore.\n */\nexport class TruthStoreProviderProfileStore implements ProviderProfileStore {\n readonly #tenant: TenantId;\n readonly #truth: TruthStore;\n\n constructor(options: TruthStoreProviderProfileStoreOptions) {\n this.#tenant = options.tenant;\n this.#truth = options.truthStore;\n }\n\n async close(): Promise<void> {\n // The host owns the injected TruthStore lifecycle.\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n const current = await this.#load();\n if (!current.profiles.some((profile) => profile.profile_ref === profileRef)) {\n return false;\n }\n await this.#write(\n current.profiles.filter((profile) => profile.profile_ref !== profileRef),\n current.rev,\n );\n return true;\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n return (await this.#load()).profiles.find(\n (profile) => profile.profile_ref === profileRef,\n );\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n return (await this.#load()).profiles.find((profile) => profile.enabled);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n return [...(await this.#load()).profiles];\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const current = await this.#load();\n const existing = current.profiles.find(\n (candidate) => candidate.profile_ref === profile.profile_ref,\n );\n const validated = parseModelProviderProfile({\n ...profile,\n created_at: existing?.created_at ?? profile.created_at,\n });\n const next = current.profiles\n .filter((candidate) => candidate.profile_ref !== validated.profile_ref)\n .map((candidate) =>\n validated.enabled && candidate.enabled\n ? { ...candidate, enabled: false }\n : candidate,\n );\n next.push(validated);\n await this.#write(next, current.rev);\n return validated;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const current = await this.#load();\n const selected = current.profiles.find(\n (profile) => profile.profile_ref === profileRef,\n );\n if (selected === undefined) throw providerNotConfigured(profileRef);\n const next = current.profiles.map((profile) => ({\n ...profile,\n enabled: profile.profile_ref === profileRef,\n }));\n await this.#write(next, current.rev);\n return { ...selected, enabled: true };\n }\n\n async #load(): Promise<LoadedRegistry> {\n const record = await this.#truth.getRecord(this.#tenant, {\n kind: 'profile',\n recordKey: PROVIDER_PROFILE_TRUTH_RECORD_KEY,\n });\n if (record === undefined) return { profiles: [], rev: 0 };\n return decodeRegistryRecord(record, this.#tenant);\n }\n\n async #write(\n profiles: readonly ModelProviderProfile[],\n expectedRev: number,\n ): Promise<void> {\n const encoded = encodeRegistry(profiles);\n let written: TruthRecord;\n try {\n written = await this.#truth.writeSnapshot(this.#tenant, {\n kind: 'profile',\n recordKey: PROVIDER_PROFILE_TRUTH_RECORD_KEY,\n expectedRev,\n contentHash: hashBody(encoded),\n byteSize: BigInt(new TextEncoder().encode(encoded).byteLength),\n body: { kind: 'inline', body: encoded },\n label: 'BYOK model provider registry',\n });\n } catch (cause) {\n if (isCoreConflictError(cause, 'truth_revision_conflict')) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_CONFLICT',\n 'Provider profiles changed since this operation read them',\n { cause },\n );\n }\n throw cause;\n }\n if (written.body.kind !== 'inline' || written.body.body !== encoded) {\n throw invalidTruth('TruthStore did not confirm the requested provider profile snapshot');\n }\n const confirmed = decodeRegistryRecord(written, this.#tenant);\n if (confirmed.rev !== expectedRev + 1) {\n throw invalidTruth('TruthStore confirmed an unexpected provider profile revision');\n }\n }\n}\n\nfunction encodeRegistry(profiles: readonly ModelProviderProfile[]): string {\n const normalized = profiles\n .map((profile) => parseModelProviderProfile(profile))\n .sort((left, right) => left.profile_ref.localeCompare(right.profile_ref));\n assertRegistryInvariants(normalized);\n const snapshot: ProviderRegistrySnapshotV1 = {\n schema_version: 1,\n profiles: normalized.map((profile) => ({\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n capabilities: profile.capabilities,\n created_at: profile.created_at,\n display_name: profile.display_name,\n enabled: profile.enabled,\n kind: profile.kind,\n model: profile.model,\n profile_ref: profile.profile_ref,\n provider_kind: profile.provider_kind,\n updated_at: profile.updated_at,\n })),\n };\n return JSON.stringify(snapshot);\n}\n\nfunction decodeRegistryRecord(\n record: TruthRecord,\n tenant: TenantId,\n): LoadedRegistry {\n if (\n record.tenantId !== tenant ||\n record.kind !== 'profile' ||\n record.recordKey !== PROVIDER_PROFILE_TRUTH_RECORD_KEY ||\n !Number.isSafeInteger(record.rev) ||\n record.rev < 1\n ) {\n throw invalidTruth('TruthStore returned mismatched provider profile authority');\n }\n if (record.body.kind !== 'inline') {\n throw invalidTruth('Provider profiles must use an inline TruthStore body');\n }\n const bytes = new TextEncoder().encode(record.body.body);\n if (record.byteSize !== BigInt(bytes.byteLength)) {\n throw invalidTruth('Provider profile TruthStore byte size does not match its body');\n }\n if (record.contentHash !== hashBody(record.body.body)) {\n throw invalidTruth('Provider profile TruthStore hash does not match its body');\n }\n\n let raw: unknown;\n try {\n raw = JSON.parse(record.body.body);\n } catch (cause) {\n throw invalidTruth('Provider profile TruthStore body is not valid JSON', cause);\n }\n if (!isPlainRecord(raw) || !hasExactKeys(raw, ['profiles', 'schema_version'])) {\n throw invalidTruth('Provider profile TruthStore body has an unknown top-level field');\n }\n if (raw.schema_version !== 1 || !Array.isArray(raw.profiles)) {\n throw invalidTruth('Provider profile TruthStore body has an unsupported schema');\n }\n if (raw.profiles.length > MAX_PROVIDER_PROFILES) {\n throw invalidTruth('Provider profile TruthStore body exceeds the provider registry bound');\n }\n let profiles: ModelProviderProfile[];\n try {\n profiles = raw.profiles.map((candidate) => {\n if (!isPlainRecord(candidate) || !hasExactKeys(candidate, PROFILE_KEYS)) {\n throw invalidTruth('Provider profile TruthStore body contains an unknown profile field');\n }\n return parseModelProviderProfile(candidate);\n });\n } catch (cause) {\n if (cause instanceof ByokKeysError && cause.code === 'PROVIDER_TRUTH_INVALID') {\n throw cause;\n }\n throw invalidTruth('Provider profile TruthStore body contains an invalid profile', cause);\n }\n assertRegistryInvariants(profiles);\n if (record.body.body !== encodeRegistry(profiles)) {\n throw invalidTruth('Provider profile TruthStore body is not in canonical form');\n }\n return { profiles, rev: record.rev };\n}\n\nfunction assertRegistryInvariants(\n profiles: readonly ModelProviderProfile[],\n): void {\n const seen = new Set<ProviderProfileRef>();\n let enabled = 0;\n for (const profile of profiles) {\n if (seen.has(profile.profile_ref)) {\n throw invalidTruth(`Provider profile ${profile.profile_ref} appears more than once`);\n }\n seen.add(profile.profile_ref);\n if (profile.enabled) enabled += 1;\n }\n if (enabled > 1) {\n throw invalidTruth('Provider profile TruthStore body enables more than one provider');\n }\n}\n\nfunction hashBody(body: string) {\n const digest = createHash('sha256').update(body, 'utf8').digest('hex');\n return contentHash(`sha256:${digest}`);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasExactKeys(\n value: Record<string, unknown>,\n expected: readonly string[],\n): boolean {\n const keys = Object.keys(value).sort();\n const wanted = [...expected].sort();\n return keys.length === wanted.length && keys.every((key, index) => key === wanted[index]);\n}\n\nfunction invalidTruth(message: string, cause?: unknown): ByokKeysError {\n return new ByokKeysError('PROVIDER_TRUTH_INVALID', message, {\n ...(cause === undefined ? {} : { cause }),\n });\n}\n","import { AnthropicMessagesClient } from './anthropic-client';\nimport { ByokKeysError } from './errors';\nimport type { ProviderFetch } from './http';\nimport { OpenAiCompatibleChatClient } from './openai-client';\nimport type { ProviderProfileStore } from './profile-store';\nimport {\n type ModelProviderAdapter,\n type ModelProviderKind,\n type ModelProviderProfile,\n type ProviderAuthMode,\n type ProviderModelCapability,\n type ProviderProfileRef,\n exactProviderProfileBinding,\n parseModelProviderProfile,\n} from './provider-profile';\nimport {\n type ModelProviderSecretName,\n type SecretStore,\n modelProviderSecretName,\n} from './secret-store';\n\n/** A transport client for whichever dialect the resolved profile declares. */\nexport type ModelProviderClient =\n | AnthropicMessagesClient\n | OpenAiCompatibleChatClient;\n\n/**\n * What a caller supplies to {@link ProviderRegistry.configure}: the profile\n * minus the fields the registry owns (`kind`, both timestamps) and minus the\n * secret, which travels as a separate argument so it cannot be mistaken for\n * persisted data.\n */\nexport interface ProviderConfiguration {\n adapter: ModelProviderAdapter;\n auth_mode: ProviderAuthMode;\n base_url: string;\n /**\n * Bounded model capabilities this exact profile supports. Declared, never\n * inferred: an omitted capability means the endpoint does not offer it.\n */\n capabilities: readonly ProviderModelCapability[];\n display_name: string;\n /** Defaults to `true`: configuring a provider makes it the default. */\n enabled?: boolean;\n model: string;\n /** This profile's own local identity; several profiles may share one kind. */\n profile_ref: ProviderProfileRef;\n provider_kind: ModelProviderKind;\n}\n\n/**\n * The registry's outward projection of a profile.\n *\n * It reports **whether** a secret exists (`secret_configured`) and never the\n * secret itself — the property `registry.golden.test.ts` asserts, mirroring\n * `docs/researches/HANDOFF-byok-keys.md` §4.3's \"status JSON contains no\n * plaintext key\".\n */\nexport interface ProviderStatus {\n adapter: ModelProviderAdapter;\n auth_mode: ProviderAuthMode;\n base_url: string;\n capabilities: readonly ProviderModelCapability[];\n created_at: string;\n display_name: string;\n enabled: boolean;\n model: string;\n profile_ref: ProviderProfileRef;\n /** Canonical credential-free revision used by exact task admission. */\n profile_revision: string;\n /** SHA-256 of the normalized non-secret local record. */\n profile_hash: string;\n provider_kind: ModelProviderKind;\n /** Whether the credential store currently holds this profile's key. */\n secret_configured: boolean;\n updated_at: string;\n}\n\nexport interface ProviderRegistryOptions {\n fetchImpl?: ProviderFetch;\n /** Injected clock, so tests get deterministic timestamps. */\n now?: () => Date;\n profileStore: ProviderProfileStore;\n secretStore: SecretStore<ModelProviderSecretName>;\n}\n\n/**\n * The configure/resolve boundary, ported from `providers.ts:1180-1229`\n * (`configure`) and `providers.ts:1331-1354` (`resolveDefaultModelProvider`).\n *\n * Both halves of a provider's configuration are written here and nowhere else:\n * the non-secret profile goes to the injected {@link ProviderProfileStore}, the\n * API key goes to the injected {@link SecretStore}. Splitting them is the whole\n * point of the package, so the registry is the only place that knows both.\n *\n * Two departures from the source, both required by\n * `docs/researches/HANDOFF-byok-keys.md` §4.5:\n *\n * - `resolveDefaultModelProvider` returns a transport client or `undefined`,\n * and throws on a broken configuration. The source returned an\n * `UnavailableNarrativeProvider` null-object carrying an error code, which is\n * a narrative-domain symbol that stays in aip-main-open — and a degradation\n * fallback this package's fail-closed rule does not permit. A caller that\n * wants aip's behaviour catches `ByokKeysError` and reads `.code`, which is\n * the same information the null-object carried.\n * - The source's `#migrateLegacyModelSecret` is not ported (legacy secret\n * migration is out of scope per the plan).\n */\nexport class ProviderRegistry {\n readonly #fetch: ProviderFetch | undefined;\n readonly #now: () => Date;\n readonly #profiles: ProviderProfileStore;\n readonly #secrets: SecretStore<ModelProviderSecretName>;\n\n constructor(options: ProviderRegistryOptions) {\n this.#fetch = options.fetchImpl;\n this.#now = options.now ?? (() => new Date());\n this.#profiles = options.profileStore;\n this.#secrets = options.secretStore;\n }\n\n async close(): Promise<void> {\n await this.#profiles.close();\n }\n\n /**\n * Persist a provider's profile and, when supplied, its secret\n * (`providers.ts:1180-1229`).\n *\n * Order matters and is the source's: write the secret first, then require\n * that an authenticating profile actually has one, and only then save the\n * profile. A profile is therefore never persisted in a state that claims\n * authentication it cannot perform.\n */\n async configure(\n configuration: ProviderConfiguration,\n secret?: string,\n ): Promise<ProviderStatus> {\n const previous = await this.#profiles.get(configuration.profile_ref);\n const observedNow = this.#now().getTime();\n const previousRevision = previous === undefined ? undefined : Date.parse(previous.updated_at);\n const revision = previousRevision === undefined\n ? observedNow\n : Math.max(observedNow, previousRevision + 1);\n if (!Number.isSafeInteger(revision) || revision < 0) {\n throw new ByokKeysError('PROVIDER_PROFILE_INVALID', 'Provider clock cannot produce a monotonic profile revision');\n }\n const timestamp = new Date(revision).toISOString();\n const profile = parseModelProviderProfile({\n ...configuration,\n capabilities: [...configuration.capabilities],\n created_at: previous?.created_at ?? timestamp,\n enabled: configuration.enabled ?? true,\n kind: 'model',\n updated_at: timestamp,\n });\n const secretName = modelProviderSecretName(configuration.profile_ref);\n let previousSecret: string | undefined;\n let secretWritten = false;\n\n if (configuration.auth_mode === 'none' && secret !== undefined) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_NOT_ALLOWED',\n 'A provider without authentication cannot accept a secret',\n );\n }\n if (secret !== undefined) {\n if (secret.length === 0) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_EMPTY',\n 'Provider secret cannot be empty',\n );\n }\n previousSecret = await this.#secrets.get(secretName);\n await this.#secrets.set(secretName, secret);\n secretWritten = true;\n }\n if (\n configuration.auth_mode !== 'none' &&\n !(await this.#secrets.has(secretName))\n ) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_MISSING',\n 'Provider authentication requires a secret in the operating-system credential store',\n );\n }\n\n let saved: ModelProviderProfile;\n try {\n saved = await this.#profiles.save(profile);\n } catch (cause) {\n if (secretWritten) {\n try {\n if (previousSecret === undefined) {\n await this.#secrets.delete(secretName);\n } else {\n await this.#secrets.set(secretName, previousSecret);\n }\n } catch (rollbackCause) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_ROLLBACK_FAILED',\n 'Provider profile write failed and the previous secret could not be restored',\n { cause: new AggregateError([cause, rollbackCause]) },\n );\n }\n }\n throw cause;\n }\n if (saved.auth_mode === 'none') {\n await this.#secrets.delete(secretName);\n }\n return this.#status(saved);\n }\n\n /** Remove a profile and its secret together. */\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n const removed = await this.#profiles.delete(profileRef);\n await this.#secrets.delete(modelProviderSecretName(profileRef));\n return removed;\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ProviderStatus | undefined> {\n const profile = await this.#profiles.get(profileRef);\n return profile === undefined ? undefined : this.#status(profile);\n }\n\n async list(): Promise<ProviderStatus[]> {\n return Promise.all(\n (await this.#profiles.list()).map((profile) => this.#status(profile)),\n );\n }\n\n /**\n * Build a client for the one enabled provider (`providers.ts:1331-1354`).\n *\n * `undefined` means \"nothing is configured\", which is a legitimate state a\n * caller must handle. A configured-but-broken provider throws instead — a\n * missing secret or an unusable profile is a fault, not an absence.\n */\n async resolveDefaultModelProvider(): Promise<ModelProviderClient | undefined> {\n const profile = await this.#profiles.getEnabled();\n if (profile === undefined) return undefined;\n const secret = await this.#secrets.get(\n modelProviderSecretName(profile.profile_ref),\n );\n const options = { fetchImpl: this.#fetch, profile, secret };\n return profile.adapter === 'anthropic'\n ? new AnthropicMessagesClient(options)\n : new OpenAiCompatibleChatClient(options);\n }\n\n /** Switch which configured profile is the default. */\n async setDefaultModelProvider(\n profileRef: ProviderProfileRef,\n ): Promise<ProviderStatus> {\n return this.#status(await this.#profiles.setEnabled(profileRef));\n }\n\n async #status(profile: ModelProviderProfile): Promise<ProviderStatus> {\n const binding = exactProviderProfileBinding(profile, []);\n return {\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n capabilities: profile.capabilities,\n created_at: profile.created_at,\n display_name: profile.display_name,\n enabled: profile.enabled,\n model: profile.model,\n profile_ref: profile.profile_ref,\n profile_revision: binding.profileRevision,\n profile_hash: binding.profileHash,\n provider_kind: profile.provider_kind,\n secret_configured: await this.#secrets.has(\n modelProviderSecretName(profile.profile_ref),\n ),\n updated_at: profile.updated_at,\n };\n }\n}\n","import type { ModelProviderProfile } from './provider-profile';\n\nexport const PI_PROJECTED_KEY_ENV = 'PI_PROVIDER_API_KEY';\n\n/** Keep projected providers disjoint from Pi built-ins so composition can never fall back to one. */\nexport function piProjectionProviderId(profileRef: string): string {\n return `byok-sdk-${profileRef}`;\n}\n\n/**\n * Credential-blind Pi configuration derived from one validated local profile.\n *\n * The projected provider is namespaced by the profile's own ref, not by its\n * provider kind, so two independently configured endpoints of the same kind\n * project to two distinct Pi providers instead of colliding on one. Model\n * `input` modalities are projected from the profile's declared capabilities —\n * declared local configuration is the only authority; nothing is inferred from\n * the model name or base URL.\n */\nexport function buildPiProviderProjection(profile: ModelProviderProfile): object {\n const projectedProviderId = piProjectionProviderId(profile.profile_ref);\n return {\n providers: {\n [projectedProviderId]: {\n baseUrl: profile.base_url,\n api:\n profile.adapter === 'anthropic'\n ? 'anthropic-messages'\n : 'openai-completions',\n ...(profile.auth_mode === 'none'\n ? {}\n : { apiKey: `$${PI_PROJECTED_KEY_ENV}` }),\n ...(profile.auth_mode === 'bearer' ? { authHeader: true } : {}),\n models: [\n {\n id: profile.model,\n name: profile.display_name,\n input: [\n 'text',\n ...(profile.capabilities.includes('image-input') ? ['image'] : []),\n ],\n },\n ],\n },\n },\n };\n}\n\n/**\n * Validate the credential-blind RPC argv the client may delegate, then bind\n * the Pi child to the namespaced projection and exact configured model.\n */\nexport function buildPiProviderArgs(\n profile: ModelProviderProfile,\n delegatedArgs: readonly string[],\n): string[] {\n let modeCount = 0;\n for (let index = 0; index < delegatedArgs.length; index += 1) {\n const flag = delegatedArgs[index];\n if (flag === '--no-tools') continue;\n if (flag === '--mode') {\n modeCount += 1;\n const value = delegatedArgs[index + 1];\n if (value !== 'rpc') throw new Error('Pi launcher requires --mode rpc');\n index += 1;\n continue;\n }\n if (flag === '--session' || flag === '--tools' || flag === '--exclude-tools') {\n const value = delegatedArgs[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`${flag} requires a value`);\n }\n index += 1;\n continue;\n }\n throw new Error(`Pi launcher does not allow delegated argument ${flag ?? '<missing>'}`);\n }\n if (modeCount !== 1) throw new Error('Pi launcher requires exactly one --mode rpc');\n\n return [\n ...delegatedArgs,\n '--provider',\n piProjectionProviderId(profile.profile_ref),\n '--model',\n profile.model,\n ];\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/provider-catalog.ts","../src/url.ts","../src/provider-profile.ts","../src/headers.ts","../src/http.ts","../src/openai-client.ts","../src/anthropic-client.ts","../src/command-runner.ts","../src/secret-name.ts","../src/secret-store.ts","../src/macos-keychain.ts","../src/windows-credential-manager.ts","../src/secret-scope.ts","../src/profile-store.ts","../src/sqlite-support.ts","../src/sqlite-profile-store.ts","../src/truth-profile-store.ts","../src/registry.ts","../src/pi-provider-projection.ts"],"names":["createHash","path"],"mappings":";;;;;;;;;AAYO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvB,IAAA;AAAA,EACA,UAAA;AAAA,EAEhB,WAAA,CACE,IAAA,EACA,OAAA,EACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,aAAa,OAAA,EAAS,UAAA;AAAA,EAC7B;AACF;AA0BO,IAAM,qBAAA,GAAwB;AAAA,EACnC,gCAAA,EAAkC,kCAAA;AAAA,EAClC,8BAAA,EAAgC,gCAAA;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A,CAAQ,KAAA;AAAA,YACZ,MAAM,OAAA,CAAQ,YAAA;AAAA,YACd,KAAA,EAAO;AAAA,cACL,MAAA;AAAA,cACA,GAAI,QAAQ,YAAA,CAAa,QAAA,CAAS,aAAa,CAAA,GAAI,CAAC,OAAO,CAAA,GAAI;AAAC;AAClE;AACF;AACF;AACF;AACF,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Single error class for `@byok-sdk/keys`.\n *\n * The ported source (`aip-main-open@c6a5385`, `apps/local-agent/src/providers.ts`)\n * raised two different classes — `LocalExecutionError` and\n * `ResearchExecutionError` — that differed only in which subsystem owned the\n * throw site; both carried a `code` string and consumers branched on that code.\n * The narrative/research subsystem stays behind in aip-main-open, so this\n * package keeps one class and preserves the `code` strings verbatim. K4's swap\n * converts aip's two `instanceof` sites to structured code detection, so the\n * strings — not the class identity — are the compatibility surface.\n */\nexport class ByokKeysError extends Error {\n public readonly code: string;\n public readonly httpStatus?: number;\n\n constructor(\n code: string,\n message: string,\n options?: ErrorOptions & { httpStatus?: number },\n ) {\n super(message, options);\n this.name = 'ByokKeysError';\n this.code = code;\n this.httpStatus = options?.httpStatus;\n }\n}\n\n/**\n * Error codes this package can throw, ported verbatim from the source. Kept as\n * a named record so consumers (and K4's aip-main-open swap) can branch on\n * `error.code` without retyping string literals.\n *\n * Four codes have no source counterpart, and each guards a check the source did\n * not make: `KEYCHAIN_SECRET_DECODE_FAILED` (the source returned an undecodable\n * stored value as-is), `SECRET_ENVELOPE_INVALID` (it reported a malformed\n * envelope as an absent secret), and `SECRET_NAME_INVALID` /\n * `SECRET_VALUE_INVALID` (the runtime replacements for the closed\n * `KeychainSecretName` union). `PROVIDER_STORE_SCHEMA_STALE` joins them: it\n * guards a persisted `provider_profile` DDL that differs from the one this\n * package generates. Everything else matches the source string for string.\n *\n * `SECRET_NAMESPACE_INVALID` is a separate case. The source does record it:\n * `normalizeSecretNamespace` (`index.ts:748-757`) throws the verbatim string\n * `'SECRET_NAMESPACE_INVALID'` at `index.ts:752`, and this package ports both\n * that string and its pattern unchanged. It is still not a compatibility\n * surface K4 must match, but for a different reason than the string: neither\n * side has a branch consumer. In the source the only callers are the two OS\n * stores' `scope()` methods, which just compose a service prefix; here the code\n * is only ever asserted in tests. Matching it costs nothing and constrains\n * nothing.\n */\nexport const BYOK_KEYS_ERROR_CODES = {\n CREDENTIAL_MANAGER_DELETE_FAILED: 'CREDENTIAL_MANAGER_DELETE_FAILED',\n CREDENTIAL_MANAGER_READ_FAILED: 'CREDENTIAL_MANAGER_READ_FAILED',\n CREDENTIAL_MANAGER_SECRET_INVALID: 'CREDENTIAL_MANAGER_SECRET_INVALID',\n CREDENTIAL_MANAGER_UNAVAILABLE: 'CREDENTIAL_MANAGER_UNAVAILABLE',\n CREDENTIAL_MANAGER_WRITE_FAILED: 'CREDENTIAL_MANAGER_WRITE_FAILED',\n KEYCHAIN_ARGUMENT_INVALID: 'KEYCHAIN_ARGUMENT_INVALID',\n KEYCHAIN_DELETE_FAILED: 'KEYCHAIN_DELETE_FAILED',\n KEYCHAIN_READ_FAILED: 'KEYCHAIN_READ_FAILED',\n KEYCHAIN_SECRET_DECODE_FAILED: 'KEYCHAIN_SECRET_DECODE_FAILED',\n KEYCHAIN_SECRET_INVALID: 'KEYCHAIN_SECRET_INVALID',\n KEYCHAIN_UNAVAILABLE: 'KEYCHAIN_UNAVAILABLE',\n KEYCHAIN_WRITE_FAILED: 'KEYCHAIN_WRITE_FAILED',\n LOCAL_ACCOUNT_SCOPE_INVALID: 'LOCAL_ACCOUNT_SCOPE_INVALID',\n MODEL_PROVIDER_AUTH_FAILED: 'MODEL_PROVIDER_AUTH_FAILED',\n MODEL_PROVIDER_BALANCE_INSUFFICIENT: 'MODEL_PROVIDER_BALANCE_INSUFFICIENT',\n MODEL_PROVIDER_HTTP_ERROR: 'MODEL_PROVIDER_HTTP_ERROR',\n MODEL_PROVIDER_MODEL_NOT_FOUND: 'MODEL_PROVIDER_MODEL_NOT_FOUND',\n MODEL_PROVIDER_RATE_LIMITED: 'MODEL_PROVIDER_RATE_LIMITED',\n MODEL_RESPONSE_INVALID: 'MODEL_RESPONSE_INVALID',\n PROVIDER_NOT_CONFIGURED: 'PROVIDER_NOT_CONFIGURED',\n PROVIDER_PROFILE_INVALID: 'PROVIDER_PROFILE_INVALID',\n PROVIDER_PROFILE_CONFLICT: 'PROVIDER_PROFILE_CONFLICT',\n PROVIDER_REQUEST_TIMEOUT: 'PROVIDER_REQUEST_TIMEOUT',\n PROVIDER_RESPONSE_INVALID: 'PROVIDER_RESPONSE_INVALID',\n PROVIDER_RESPONSE_TOO_LARGE: 'PROVIDER_RESPONSE_TOO_LARGE',\n PROVIDER_SECRET_EMPTY: 'PROVIDER_SECRET_EMPTY',\n PROVIDER_SECRET_MISSING: 'PROVIDER_SECRET_MISSING',\n PROVIDER_SECRET_NOT_ALLOWED: 'PROVIDER_SECRET_NOT_ALLOWED',\n PROVIDER_SECRET_ROLLBACK_FAILED: 'PROVIDER_SECRET_ROLLBACK_FAILED',\n PROVIDER_STORE_SCHEMA_STALE: 'PROVIDER_STORE_SCHEMA_STALE',\n PROVIDER_STORE_UNAVAILABLE: 'PROVIDER_STORE_UNAVAILABLE',\n PROVIDER_TRUTH_INVALID: 'PROVIDER_TRUTH_INVALID',\n PROVIDER_URL_INVALID: 'PROVIDER_URL_INVALID',\n SECRET_ENVELOPE_INVALID: 'SECRET_ENVELOPE_INVALID',\n SECRET_NAME_INVALID: 'SECRET_NAME_INVALID',\n SECRET_NAMESPACE_INVALID: 'SECRET_NAMESPACE_INVALID',\n SECRET_VALUE_INVALID: 'SECRET_VALUE_INVALID',\n} as const;\n\nexport type ByokKeysErrorCode =\n (typeof BYOK_KEYS_ERROR_CODES)[keyof typeof BYOK_KEYS_ERROR_CODES];\n","import type { ModelProviderAdapter, ProviderAuthMode } from './provider-profile';\n\n/**\n * One vendor the SDK can address without the consumer typing its endpoint.\n *\n * Ported from the provider catalog deepseek-harness resolves its routes from:\n * pi-ai 0.84.2 `dist/providers/*.js` (the version the SDK's pinned\n * `@earendil-works/pi-coding-agent` 0.84.2 resolves) plus the harness's own\n * `packages/llm/llm-deepseek/src/index.ts` `PUBLIC_BASE_URL`, which agrees\n * with pi-ai's `deepseek` entry. Selection and the URL mapping rule are\n * recorded in `docs/researches/2026-09-06_deepseek-harness-provider-catalog-port.md`.\n *\n * Every field is declared configuration a consumer may copy into a\n * `ModelProviderProfile`; nothing here is read at request time, and a\n * profile still carries its own `base_url` so a self-hosted gateway for a\n * vendor stays expressible. `api_key_env` is the credential name the vendor's\n * own tooling reads; this package never reads it, and `@byok-sdk/client`'s\n * credential deny list must contain every value listed here.\n */\nexport interface ModelProviderVendor {\n readonly display_name: string;\n /**\n * Endpoint base in this package's suffix convention: an\n * `openai_compatible` client appends `chat/completions`, an `anthropic`\n * client appends `messages`. pi-ai's anthropic-dialect entries therefore\n * gain a `/v1` segment here; its OpenAI-dialect entries are verbatim.\n */\n readonly base_url: string;\n readonly adapter: ModelProviderAdapter;\n readonly auth_mode: Exclude<ProviderAuthMode, 'none'>;\n readonly api_key_env: string;\n}\n\nfunction openAiCompatible(\n display_name: string,\n base_url: string,\n api_key_env: string,\n): ModelProviderVendor {\n return {\n display_name,\n base_url,\n adapter: 'openai_compatible',\n auth_mode: 'bearer',\n api_key_env,\n };\n}\n\nfunction anthropicMessages(\n display_name: string,\n base_url: string,\n api_key_env: string,\n): ModelProviderVendor {\n return {\n display_name,\n base_url,\n adapter: 'anthropic',\n auth_mode: 'x_api_key',\n api_key_env,\n };\n}\n\n/**\n * Vendor id → declared endpoint facts. Ids are pi-ai's provider ids so a\n * profile's `provider_kind` names the same route deepseek-harness would.\n * Ordered by dialect, then alphabetically; order carries no meaning.\n */\nexport const MODEL_PROVIDER_VENDORS = {\n 'ant-ling': openAiCompatible('Ant Ling', 'https://api.ant-ling.com/v1', 'ANT_LING_API_KEY'),\n baseten: openAiCompatible('Baseten', 'https://inference.baseten.co/v1', 'BASETEN_API_KEY'),\n cerebras: openAiCompatible('Cerebras', 'https://api.cerebras.ai/v1', 'CEREBRAS_API_KEY'),\n deepseek: openAiCompatible('DeepSeek', 'https://api.deepseek.com', 'DEEPSEEK_API_KEY'),\n groq: openAiCompatible('Groq', 'https://api.groq.com/openai/v1', 'GROQ_API_KEY'),\n huggingface: openAiCompatible('Hugging Face', 'https://router.huggingface.co/v1', 'HF_TOKEN'),\n moonshotai: openAiCompatible('Moonshot AI', 'https://api.moonshot.ai/v1', 'MOONSHOT_API_KEY'),\n 'moonshotai-cn': openAiCompatible('Moonshot AI CN', 'https://api.moonshot.cn/v1', 'MOONSHOT_API_KEY'),\n nvidia: openAiCompatible('NVIDIA', 'https://integrate.api.nvidia.com/v1', 'NVIDIA_API_KEY'),\n openai: openAiCompatible('OpenAI', 'https://api.openai.com/v1', 'OPENAI_API_KEY'),\n openrouter: openAiCompatible('OpenRouter', 'https://openrouter.ai/api/v1', 'OPENROUTER_API_KEY'),\n 'qwen-token-plan': openAiCompatible(\n 'Qwen Token Plan',\n 'https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1',\n 'QWEN_TOKEN_PLAN_API_KEY',\n ),\n 'qwen-token-plan-cn': openAiCompatible(\n 'Qwen Token Plan CN',\n 'https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',\n 'QWEN_TOKEN_PLAN_CN_API_KEY',\n ),\n together: openAiCompatible('Together', 'https://api.together.ai/v1', 'TOGETHER_API_KEY'),\n xai: openAiCompatible('xAI', 'https://api.x.ai/v1', 'XAI_API_KEY'),\n xiaomi: openAiCompatible('Xiaomi', 'https://api.xiaomimimo.com/v1', 'XIAOMI_API_KEY'),\n 'xiaomi-token-plan-ams': openAiCompatible(\n 'Xiaomi Token Plan AMS',\n 'https://token-plan-ams.xiaomimimo.com/v1',\n 'XIAOMI_TOKEN_PLAN_AMS_API_KEY',\n ),\n 'xiaomi-token-plan-cn': openAiCompatible(\n 'Xiaomi Token Plan CN',\n 'https://token-plan-cn.xiaomimimo.com/v1',\n 'XIAOMI_TOKEN_PLAN_CN_API_KEY',\n ),\n 'xiaomi-token-plan-sgp': openAiCompatible(\n 'Xiaomi Token Plan SGP',\n 'https://token-plan-sgp.xiaomimimo.com/v1',\n 'XIAOMI_TOKEN_PLAN_SGP_API_KEY',\n ),\n zai: openAiCompatible('Z.AI', 'https://api.z.ai/api/coding/paas/v4', 'ZAI_API_KEY'),\n 'zai-coding-cn': openAiCompatible(\n 'Z.AI Coding CN',\n 'https://open.bigmodel.cn/api/coding/paas/v4',\n 'ZAI_CODING_CN_API_KEY',\n ),\n anthropic: anthropicMessages('Anthropic', 'https://api.anthropic.com/v1', 'ANTHROPIC_API_KEY'),\n fireworks: anthropicMessages('Fireworks', 'https://api.fireworks.ai/inference/v1', 'FIREWORKS_API_KEY'),\n 'kimi-coding': anthropicMessages('Kimi For Coding', 'https://api.kimi.com/coding/v1', 'KIMI_API_KEY'),\n minimax: anthropicMessages('MiniMax', 'https://api.minimax.io/anthropic/v1', 'MINIMAX_API_KEY'),\n 'minimax-cn': anthropicMessages('MiniMax CN', 'https://api.minimaxi.com/anthropic/v1', 'MINIMAX_CN_API_KEY'),\n 'vercel-ai-gateway': anthropicMessages(\n 'Vercel AI Gateway',\n 'https://ai-gateway.vercel.sh/v1',\n 'AI_GATEWAY_API_KEY',\n ),\n} as const satisfies Record<string, ModelProviderVendor>;\n\nexport type ModelProviderVendorId = keyof typeof MODEL_PROVIDER_VENDORS;\n\n/** Catalog vendor ids; `MODEL_PROVIDER_KINDS` is this list plus `custom`. */\nexport const MODEL_PROVIDER_VENDOR_IDS = Object.keys(\n MODEL_PROVIDER_VENDORS,\n) as readonly ModelProviderVendorId[];\n\n/**\n * The catalog entry for a provider kind, or `undefined` for `custom`, which\n * by definition declares everything itself.\n */\nexport function modelProviderVendor(\n kind: string,\n): ModelProviderVendor | undefined {\n return Object.hasOwn(MODEL_PROVIDER_VENDORS, kind)\n ? MODEL_PROVIDER_VENDORS[kind as ModelProviderVendorId]\n : undefined;\n}\n","import { ByokKeysError } from './errors';\n\n/**\n * Normalize a provider base URL, fail-closed.\n *\n * Ported from `aip-main-open@c6a5385` `providers.ts:1558-1588` plus the two\n * host predicates at `:2216-2242`. Rules, unchanged:\n * - must be an absolute URL;\n * - no embedded credentials, no fragment, no query string;\n * - HTTPS only, except that HTTP is allowed for loopback hosts;\n * - private-network literals are rejected unless they are loopback;\n * - one trailing slash is stripped.\n */\nexport function normalizeProviderUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider base URL must be absolute',\n );\n }\n if (\n url.username ||\n url.password ||\n url.hash ||\n url.search ||\n (url.protocol !== 'https:' &&\n !(url.protocol === 'http:' && isLoopbackHost(url.hostname)))\n ) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider URL requires HTTPS; HTTP is allowed only for localhost',\n );\n }\n if (isPrivateNetworkLiteral(url.hostname) && !isLoopbackHost(url.hostname)) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Private-network provider IPs are not allowed',\n );\n }\n return url.toString().replace(/\\/$/u, '');\n}\n\n/** Whether an already-parseable provider URL points at a loopback host. */\nexport function isLoopbackProviderUrl(value: string): boolean {\n return isLoopbackHost(new URL(value).hostname);\n}\n\nexport function isLoopbackHost(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n return value === 'localhost' || value === '127.0.0.1' || value === '::1';\n}\n\n/**\n * Conservative private-network literal check. Any IPv6 literal counts as\n * private (the `:` branch), matching the source: the guard cannot cheaply\n * classify IPv6 ranges, so it refuses all of them and lets hostnames through.\n */\nexport function isPrivateNetworkLiteral(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n if (value.includes(':')) return true;\n const parts = value.split('.').map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n return (\n parts[0] === 10 ||\n parts[0] === 127 ||\n (parts[0] === 169 && parts[1] === 254) ||\n (parts[0] === 172 && (parts[1] ?? 0) >= 16 && (parts[1] ?? 0) <= 31) ||\n (parts[0] === 192 && parts[1] === 168)\n );\n}\n","import { z } from 'zod';\nimport { createHash } from 'node:crypto';\n\nimport { ByokKeysError } from './errors';\nimport {\n MODEL_PROVIDER_VENDOR_IDS,\n modelProviderVendor,\n type ModelProviderVendorId,\n} from './provider-catalog';\nimport { normalizeProviderUrl } from './url';\n\n/**\n * Opaque, portable identity of one locally configured provider profile.\n *\n * This is the profile's primary key: it is a local logical id, never a path,\n * and several profiles may share one {@link MODEL_PROVIDER_KINDS} kind (two\n * independent `custom` endpoints, for example). It replaces the former\n * `MODEL_PROVIDER_IDS` primary key, which conflated instance identity with\n * provider kind and therefore allowed exactly one profile per kind.\n *\n * `@byok-sdk/protocol` declares the same lexical rule for the wire form in\n * `provider-profile-binding.ts`. The two definitions are deliberately parallel\n * rather than shared: the release graph (`scripts/release/check-package-graph.mjs`)\n * forbids `@byok-sdk/keys` from depending on any dispatch package, so the\n * device-local authority cannot import the wire authority. This mirrors how\n * `packages/protocol/src/blob.ts`'s `CONTENT_HASH_RE` restates\n * `packages/core/src/blob.ts`'s content-hash format across the same boundary.\n */\nexport const PROVIDER_PROFILE_REF_PATTERN =\n /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/u;\n\nexport const ProviderProfileRefSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(\n PROVIDER_PROFILE_REF_PATTERN,\n 'provider profile refs must be lowercase portable identifiers',\n );\n\nexport type ProviderProfileRef = z.infer<typeof ProviderProfileRefSchema>;\n\n/**\n * Provider kinds this package knows how to address — the surviving half of the\n * former `MODEL_PROVIDER_IDS`. A kind says *what dialect family and vendor\n * shape* a profile is; {@link ProviderProfileRefSchema} says *which* profile.\n * Originally ported from `aip-main-open@c6a5385` `providers.ts:30-36`\n * (`LOCAL_MODEL_PROVIDER_IDS`); the list is now derived: every id in\n * {@link MODEL_PROVIDER_VENDORS}, plus `custom` for an endpoint the catalog\n * does not name. `provider-catalog.ts` is the single authority, and\n * `sqlite-profile-store.ts` generates its CHECK constraint from this list.\n */\nexport type ModelProviderKind = ModelProviderVendorId | 'custom';\n\nexport const MODEL_PROVIDER_KINDS = [\n ...MODEL_PROVIDER_VENDOR_IDS,\n 'custom',\n] as readonly ModelProviderKind[] as readonly [\n ModelProviderKind,\n ...ModelProviderKind[],\n];\n\n/**\n * Bounded model capabilities a profile may declare. A capability is explicit\n * local configuration, never inferred from the model name or the base URL.\n */\nexport const PROVIDER_MODEL_CAPABILITIES = ['image-input'] as const;\n\nexport const ProviderModelCapabilitySchema = z.enum(PROVIDER_MODEL_CAPABILITIES);\n\nexport type ProviderModelCapability = z.infer<\n typeof ProviderModelCapabilitySchema\n>;\n\n/** Auth modes a provider profile can request (`providers.ts:29`). */\nexport const PROVIDER_AUTH_MODES = ['bearer', 'x_api_key', 'none'] as const;\n\nexport type ProviderAuthMode = (typeof PROVIDER_AUTH_MODES)[number];\n\n/**\n * Wire dialects. The source's `market_data` / `mcp_http` branch stays in\n * aip-main-open — this package ports the model branch only\n * (`providers.ts:38-61`, second union member).\n */\nexport const MODEL_PROVIDER_ADAPTERS = ['openai_compatible', 'anthropic'] as const;\n\nexport type ModelProviderAdapter = (typeof MODEL_PROVIDER_ADAPTERS)[number];\n\n/**\n * Marker attached to schema issues so {@link parseModelProviderProfile} can\n * reproduce the source's distinct error codes: the URL guard reports\n * `PROVIDER_URL_INVALID`, everything else reports `PROVIDER_PROFILE_INVALID`.\n */\ninterface ProfileIssueParams {\n byokCode: string;\n}\n\nfunction boundedString(field: string, maximumLength: number) {\n return z\n .string()\n .superRefine((value, ctx) => {\n if (\n value.trim().length === 0 ||\n value.length > maximumLength ||\n /[\\u0000\\r\\n]/u.test(value)\n ) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} is invalid`,\n });\n }\n })\n .transform((value) => value.trim());\n}\n\nfunction isoTimestamp(field: string) {\n return boundedString(field, 64).superRefine((value, ctx) => {\n if (!Number.isFinite(Date.parse(value))) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} must be an ISO timestamp`,\n });\n }\n });\n}\n\nconst providerBaseUrl = z\n .string()\n .superRefine((value, ctx) => {\n try {\n normalizeProviderUrl(value);\n } catch (error) {\n ctx.addIssue({\n code: 'custom',\n message:\n error instanceof Error ? error.message : 'Provider base URL is invalid',\n params: {\n byokCode:\n error instanceof ByokKeysError ? error.code : 'PROVIDER_URL_INVALID',\n } satisfies ProfileIssueParams,\n });\n }\n })\n .transform((value) => normalizeProviderUrl(value));\n\n/**\n * A model provider profile: everything needed to address a provider except the\n * secret itself, which lives in the OS credential store.\n *\n * The adapter/auth-mode legality rules are the ones `normalizeProviderProfile`\n * enforced imperatively at `providers.ts:1522-1543`, moved into the schema so\n * there is one validation authority rather than a schema plus a normalizer.\n */\nexport const ModelProviderProfileSchema = z\n .object({\n adapter: z.enum(MODEL_PROVIDER_ADAPTERS),\n auth_mode: z.enum(PROVIDER_AUTH_MODES),\n base_url: providerBaseUrl,\n capabilities: z.array(ProviderModelCapabilitySchema).max(8),\n created_at: isoTimestamp('created_at'),\n display_name: boundedString('display_name', 100),\n enabled: z.boolean(),\n kind: z.literal('model'),\n model: boundedString('model', 160),\n profile_ref: ProviderProfileRefSchema,\n provider_kind: z.enum(MODEL_PROVIDER_KINDS),\n updated_at: isoTimestamp('updated_at'),\n })\n .superRefine((profile, ctx) => {\n if (new Set(profile.capabilities).size !== profile.capabilities.length) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider capabilities cannot repeat',\n path: ['capabilities'],\n });\n }\n if (profile.adapter === 'anthropic' && profile.auth_mode !== 'x_api_key') {\n ctx.addIssue({\n code: 'custom',\n message: 'Anthropic requires x_api_key authentication',\n path: ['auth_mode'],\n });\n }\n if (\n profile.adapter === 'openai_compatible' &&\n profile.auth_mode === 'x_api_key'\n ) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'OpenAI-compatible providers support bearer or no authentication',\n path: ['auth_mode'],\n });\n }\n const vendor = modelProviderVendor(profile.provider_kind);\n if (vendor !== undefined && vendor.adapter !== profile.adapter) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider kind ${profile.provider_kind} speaks the ${vendor.adapter} adapter`,\n path: ['adapter'],\n });\n }\n if (Date.parse(profile.updated_at) < Date.parse(profile.created_at)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider updated_at cannot precede created_at',\n path: ['updated_at'],\n });\n }\n });\n\n/** Validated, normalized profile. */\nexport type ModelProviderProfile = z.infer<typeof ModelProviderProfileSchema>;\n\n/** Pre-normalization shape callers may hand in. */\nexport type ModelProviderProfileInput = z.input<typeof ModelProviderProfileSchema>;\n\nexport interface ExactProviderProfileBinding {\n profileRef: ProviderProfileRef;\n profileRevision: string;\n profileHash: string;\n modelId: string;\n requiredCapabilities: readonly ProviderModelCapability[];\n}\n\n/**\n * Derive the credential-free wire identity from the normalized local record.\n * `updated_at` is the persisted monotonic revision authority; the hash covers\n * the complete normalized non-secret record with capability order\n * canonicalized. Secret values are not accepted by this type and therefore\n * cannot enter the digest or any mismatch message.\n */\nexport function exactProviderProfileBinding(\n profileInput: ModelProviderProfile,\n requiredCapabilities: readonly ProviderModelCapability[] = profileInput.capabilities,\n): ExactProviderProfileBinding {\n const profile = parseModelProviderProfile(profileInput);\n const revision = Date.parse(profile.updated_at);\n if (!Number.isSafeInteger(revision) || revision < 0) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider updated_at cannot be represented as a canonical revision',\n );\n }\n const normalizedCapabilities = [...profile.capabilities].sort();\n const canonical = JSON.stringify({\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n capabilities: normalizedCapabilities,\n kind: profile.kind,\n model: profile.model,\n profile_ref: profile.profile_ref,\n provider_kind: profile.provider_kind,\n });\n return {\n profileRef: profile.profile_ref,\n profileRevision: String(revision),\n profileHash: `sha256:${createHash('sha256').update(canonical).digest('hex')}`,\n modelId: profile.model,\n requiredCapabilities: [...requiredCapabilities],\n };\n}\n\n/** Fail closed unless every offered binding field matches local authority. */\nexport function assertExactProviderProfileBinding(\n profile: ModelProviderProfile,\n expected: ExactProviderProfileBinding,\n): void {\n if (new Set(expected.requiredCapabilities).size !== expected.requiredCapabilities.length) {\n throw new Error('provider profile required capabilities must be unique');\n }\n const actual = exactProviderProfileBinding(profile, expected.requiredCapabilities);\n if (actual.profileRef !== expected.profileRef) throw new Error('provider profile ref mismatch');\n if (actual.profileRevision !== expected.profileRevision) throw new Error('provider profile revision mismatch');\n if (actual.profileHash !== expected.profileHash) throw new Error('provider profile hash mismatch');\n if (actual.modelId !== expected.modelId) throw new Error('provider profile model mismatch');\n const supported = new Set(profile.capabilities);\n const unsupported = expected.requiredCapabilities.find((capability) => !supported.has(capability));\n if (unsupported !== undefined) throw new Error(`provider profile does not support required capability ${unsupported}`);\n}\n\n/**\n * Parse and normalize a profile, or throw {@link ByokKeysError}. Replaces the\n * source's `normalizeProviderProfile` (`providers.ts:1489-1556`) for the model\n * branch, preserving its error codes.\n */\nexport function parseModelProviderProfile(value: unknown): ModelProviderProfile {\n const result = ModelProviderProfileSchema.safeParse(value);\n if (result.success) return result.data;\n const issue = result.error.issues[0];\n const params = (issue as { params?: Partial<ProfileIssueParams> } | undefined)\n ?.params;\n throw new ByokKeysError(\n params?.byokCode ?? 'PROVIDER_PROFILE_INVALID',\n issue?.message ?? 'Provider profile is invalid',\n { cause: result.error },\n );\n}\n","import { ByokKeysError } from './errors';\nimport type { ProviderAuthMode } from './provider-profile';\n\n/** The subset of a profile the header builder reads. */\nexport interface ProviderAuthProfile {\n auth_mode: ProviderAuthMode;\n kind: string;\n}\n\n/**\n * Fail-closed secret check. Ported from `aip-main-open@c6a5385`\n * `providers.ts:1657-1671`: a profile that declares `bearer` or `x_api_key`\n * must have a secret, or the request is refused rather than sent unauthenticated.\n */\nexport function requiredProviderSecret(\n profile: ProviderAuthProfile,\n secret: string | undefined,\n): string | undefined {\n if (\n (profile.auth_mode === 'bearer' || profile.auth_mode === 'x_api_key') &&\n !secret\n ) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_MISSING',\n `${profile.kind} provider requires a secret in the operating-system credential store`,\n );\n }\n return secret;\n}\n\n/**\n * Build the outbound request headers for a provider call. Key-for-key\n * equivalent to `providers.ts:1680-1697`:\n * - always `accept` and `content-type`;\n * - `bearer` adds `authorization: Bearer <secret>`;\n * - `x_api_key` adds `x-api-key: <secret>` and `anthropic-version: 2023-06-01`;\n * - `none` adds nothing.\n */\nexport function providerHeaders(\n profile: ProviderAuthProfile,\n secret: string | undefined,\n): Record<string, string> {\n return {\n accept: 'application/json',\n 'content-type': 'application/json',\n ...(profile.auth_mode === 'bearer'\n ? { authorization: `Bearer ${requiredProviderSecret(profile, secret)}` }\n : {}),\n ...(profile.auth_mode === 'x_api_key'\n ? {\n 'anthropic-version': '2023-06-01',\n 'x-api-key': requiredProviderSecret(profile, secret) as string,\n }\n : {}),\n };\n}\n","import { ByokKeysError } from './errors';\nimport { normalizeProviderUrl } from './url';\n\n/** Injectable `fetch`. Defaults to `globalThis.fetch` at every call site. */\nexport type ProviderFetch = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>;\n\n/** Response body ceiling, ported from `providers.ts:106`. */\nexport const PROVIDER_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;\n\n/** Per-request timeout, ported from `providers.ts:107`. */\nexport const PROVIDER_TIMEOUT_MS = 15_000;\n\n/**\n * Issue a provider request under the source's guards\n * (`providers.ts:1711-1743`): the URL is re-validated immediately before the\n * call, the caller's abort signal is chained, and an internal timeout aborts\n * with a distinguishable reason so a timeout maps to\n * `PROVIDER_REQUEST_TIMEOUT` rather than a bare `AbortError`.\n */\nexport async function fetchWithProviderGuards(\n fetchImpl: ProviderFetch,\n url: string,\n init: RequestInit,\n signal: AbortSignal,\n): Promise<Response> {\n normalizeProviderUrl(url);\n const controller = new AbortController();\n const onAbort = () => controller.abort(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n if (signal.aborted) onAbort();\n const timeout = setTimeout(\n () => controller.abort('provider_timeout'),\n PROVIDER_TIMEOUT_MS,\n );\n try {\n return await fetchImpl(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (\n !signal.aborted &&\n controller.signal.aborted &&\n controller.signal.reason === 'provider_timeout'\n ) {\n throw new ByokKeysError(\n 'PROVIDER_REQUEST_TIMEOUT',\n 'Provider request timed out',\n );\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n signal.removeEventListener('abort', onAbort);\n }\n}\n\n/**\n * Read a JSON body with a size ceiling (`providers.ts:1825-1851`). The\n * `content-length` check is an early exit; the decoded-byte check is the one\n * that actually holds, since `content-length` is attacker-controlled.\n */\nexport async function parseBoundedJsonResponse(\n response: Response,\n): Promise<unknown> {\n const contentLength = Number(response.headers.get('content-length'));\n if (\n Number.isFinite(contentLength) &&\n contentLength > PROVIDER_RESPONSE_MAX_BYTES\n ) {\n throw new ByokKeysError(\n 'PROVIDER_RESPONSE_TOO_LARGE',\n 'Provider response exceeds the local safety limit',\n );\n }\n const text = await response.text();\n if (new TextEncoder().encode(text).byteLength > PROVIDER_RESPONSE_MAX_BYTES) {\n throw new ByokKeysError(\n 'PROVIDER_RESPONSE_TOO_LARGE',\n 'Provider response exceeds the local safety limit',\n );\n }\n try {\n return JSON.parse(text);\n } catch {\n throw new ByokKeysError(\n 'PROVIDER_RESPONSE_INVALID',\n 'Provider returned invalid JSON',\n );\n }\n}\n\n/**\n * Parse a model-provider response, mapping non-2xx to a classified error\n * (`providers.ts:1748-1769`). The source's `context` parameter only chose\n * between two error classes; this package has one, so the parameter is gone.\n */\nexport async function readModelProviderResponse(\n response: Response,\n): Promise<unknown> {\n let payload: unknown;\n try {\n payload = await parseBoundedJsonResponse(response);\n } catch (error) {\n if (\n !response.ok &&\n error instanceof ByokKeysError &&\n error.code === 'PROVIDER_RESPONSE_INVALID'\n ) {\n throw modelProviderHttpError(response.status, undefined);\n }\n throw error;\n }\n if (!response.ok) {\n throw modelProviderHttpError(response.status, payload);\n }\n return payload;\n}\n\nfunction modelProviderHttpError(\n status: number,\n payload: unknown,\n): ByokKeysError {\n return new ByokKeysError(\n classifyModelProviderHttpError(status, payload),\n `Model provider request failed with HTTP ${status}`,\n { httpStatus: status },\n );\n}\n\n/**\n * Map an HTTP status plus error body onto a stable code\n * (`providers.ts:1783-1815`). Providers disagree on status codes for billing\n * and key problems, so the body text is inspected as well — the pattern lists\n * are verbatim from the source, including the Chinese-language variants the\n * source's providers actually return.\n */\nexport function classifyModelProviderHttpError(\n status: number,\n payload: unknown,\n): string {\n const detail = safeProviderErrorText(payload);\n if (\n status === 402 ||\n /(?:insufficient[_ -]?(?:quota|balance|credit)|quota[_ -]?exceeded|billing|payment required|余额不足|额度不足|欠费|充值)/iu.test(\n detail,\n )\n ) {\n return 'MODEL_PROVIDER_BALANCE_INSUFFICIENT';\n }\n if (\n status === 401 ||\n status === 403 ||\n /(?:invalid[_ -]?api[_ -]?key|authentication|unauthori[sz]ed|forbidden|鉴权失败|密钥无效|令牌无效)/iu.test(\n detail,\n )\n ) {\n return 'MODEL_PROVIDER_AUTH_FAILED';\n }\n if (\n status === 404 ||\n /(?:model[_ -]?not[_ -]?found|model does not exist|unknown model|模型不存在|无权访问模型)/iu.test(\n detail,\n )\n ) {\n return 'MODEL_PROVIDER_MODEL_NOT_FOUND';\n }\n if (status === 429) return 'MODEL_PROVIDER_RATE_LIMITED';\n return 'MODEL_PROVIDER_HTTP_ERROR';\n}\n\nfunction safeProviderErrorText(payload: unknown): string {\n try {\n return JSON.stringify(payload ?? '')\n .slice(0, 8_000)\n .toLowerCase();\n } catch {\n return '';\n }\n}\n\n/** Join a normalized base URL with an API path, idempotently (`providers.ts:1949-1953`). */\nexport function modelApiUrl(baseUrl: string, suffix: string): string {\n const normalized = normalizeProviderUrl(baseUrl);\n if (normalized.endsWith(`/${suffix}`)) return normalized;\n return `${normalized}/${suffix}`;\n}\n\n/**\n * Flatten a message content field to text (`providers.ts:1955-1971`). Both\n * dialects return either a string or an array of typed blocks.\n */\nexport function modelMessageText(value: unknown): string {\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) {\n return value\n .map(objectValue)\n .filter(\n (item): item is Record<string, unknown> =>\n item !== undefined && typeof item.text === 'string',\n )\n .map((item) => item.text as string)\n .join('');\n }\n throw new ByokKeysError(\n 'MODEL_RESPONSE_INVALID',\n 'Model response did not contain text',\n );\n}\n\nexport function objectValue(\n value: unknown,\n): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** `providers.ts:2301-2308` — an empty completion does not prove a live key. */\nexport function assertLiveModelResponse(value: string): void {\n if (value.trim().length === 0) {\n throw new ByokKeysError(\n 'MODEL_RESPONSE_INVALID',\n 'Model provider returned an empty completion during connection validation',\n );\n }\n}\n","import {\n assertLiveModelResponse,\n fetchWithProviderGuards,\n modelApiUrl,\n modelMessageText,\n objectValue,\n readModelProviderResponse,\n type ProviderFetch,\n} from './http';\nimport { providerHeaders, requiredProviderSecret } from './headers';\nimport { ByokKeysError } from './errors';\nimport {\n parseModelProviderProfile,\n type ModelProviderProfile,\n} from './provider-profile';\nimport { isLoopbackProviderUrl } from './url';\n\n/** One chat message. `content` is `unknown` so multimodal block arrays pass through. */\nexport interface ChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: unknown;\n}\n\n/**\n * A chat/completions request minus `model`, which the client fills from the\n * profile — the profile is the single source of truth for which model this\n * configured provider addresses.\n */\nexport interface ChatCompletionRequest {\n messages: readonly ChatMessage[];\n max_tokens?: number;\n temperature?: number;\n response_format?: { type: string };\n}\n\nexport interface ModelProviderClientOptions {\n fetchImpl?: ProviderFetch;\n profile: unknown;\n secret?: string;\n}\n\n/**\n * Transport for OpenAI-compatible chat/completions providers, ported from\n * `aip-main-open@c6a5385` `providers.ts:478-829`.\n *\n * Only the request construction, response parsing, and error mapping travel;\n * every narrative/finance method of the source class stays in aip-main-open\n * per `docs/researches/HANDOFF-byok-keys.md` §4.5. The domain-specific\n * prompts, temperatures, and token budgets that were baked into those methods\n * become caller-supplied request fields.\n */\nexport class OpenAiCompatibleChatClient {\n readonly model: string;\n /** False only when the provider is loopback, i.e. no data leaves the machine. */\n readonly remoteDataTransfer: boolean;\n readonly #fetch: ProviderFetch;\n readonly #profile: ModelProviderProfile;\n readonly #secret: string | undefined;\n\n constructor(options: ModelProviderClientOptions) {\n this.#fetch = options.fetchImpl ?? ((input, init) => fetch(input, init));\n this.#profile = parseModelProviderProfile(options.profile);\n this.#secret = requiredProviderSecret(this.#profile, options.secret);\n this.model = this.#profile.model;\n this.remoteDataTransfer = !isLoopbackProviderUrl(this.#profile.base_url);\n }\n\n /** POST `<base_url>/chat/completions`; returns the parsed response object. */\n async createChatCompletion(\n request: ChatCompletionRequest,\n signal: AbortSignal = new AbortController().signal,\n ): Promise<Record<string, unknown>> {\n const response = await fetchWithProviderGuards(\n this.#fetch,\n modelApiUrl(this.#profile.base_url, 'chat/completions'),\n {\n body: JSON.stringify({ ...request, model: this.#profile.model }),\n headers: providerHeaders(this.#profile, this.#secret),\n method: 'POST',\n redirect: 'error',\n },\n signal,\n );\n const payload = objectValue(await readModelProviderResponse(response));\n if (payload === undefined) {\n throw new ByokKeysError(\n 'MODEL_RESPONSE_INVALID',\n 'Model provider returned an invalid response',\n );\n }\n return payload;\n }\n\n /**\n * Round-trip the configured key against the provider\n * (`providers.ts:797-828`). An empty completion fails, so a provider that\n * accepts anything cannot be mistaken for a working configuration.\n */\n async testConnection(\n signal: AbortSignal = new AbortController().signal,\n ): Promise<void> {\n const payload = await this.createChatCompletion(\n {\n max_tokens: 32,\n messages: [\n {\n content:\n 'Return one JSON object with exactly this shape: {\"ok\":true}.',\n role: 'user',\n },\n ],\n response_format: { type: 'json_object' },\n temperature: 0,\n },\n signal,\n );\n assertLiveModelResponse(chatCompletionText(payload));\n }\n}\n\n/**\n * Pull the assistant text out of a chat/completions payload\n * (`providers.ts:597-599` and siblings, which repeated this shape in every\n * narrative method).\n */\nexport function chatCompletionText(payload: Record<string, unknown>): string {\n const choices = Array.isArray(payload.choices) ? payload.choices : [];\n const message = objectValue(objectValue(choices[0])?.message);\n return modelMessageText(message?.content);\n}\n","import {\n assertLiveModelResponse,\n fetchWithProviderGuards,\n modelApiUrl,\n modelMessageText,\n objectValue,\n readModelProviderResponse,\n type ProviderFetch,\n} from './http';\nimport { providerHeaders, requiredProviderSecret } from './headers';\nimport { ByokKeysError } from './errors';\nimport {\n parseModelProviderProfile,\n type ModelProviderProfile,\n} from './provider-profile';\nimport type { ModelProviderClientOptions } from './openai-client';\nimport { isLoopbackProviderUrl } from './url';\n\n/** One Anthropic message. `content` is `unknown` so block arrays pass through. */\nexport interface AnthropicMessage {\n role: 'user' | 'assistant';\n content: unknown;\n}\n\n/**\n * A Messages API request minus `model`, which the client fills from the\n * profile. `max_tokens` is required because the API requires it.\n */\nexport interface AnthropicMessageRequest {\n messages: readonly AnthropicMessage[];\n max_tokens: number;\n system?: string;\n temperature?: number;\n}\n\n/**\n * Transport for the Anthropic Messages API, ported from\n * `aip-main-open@c6a5385` `providers.ts:831-1067`.\n *\n * As with the OpenAI-compatible client, only `#createMessage`'s generic\n * request/parse/error path travels; the narrative methods that wrapped it stay\n * in aip-main-open per `docs/researches/HANDOFF-byok-keys.md` §4.5.\n */\nexport class AnthropicMessagesClient {\n readonly model: string;\n /** False only when the provider is loopback, i.e. no data leaves the machine. */\n readonly remoteDataTransfer: boolean;\n readonly #fetch: ProviderFetch;\n readonly #profile: ModelProviderProfile;\n readonly #secret: string;\n\n constructor(options: ModelProviderClientOptions) {\n this.#fetch = options.fetchImpl ?? ((input, init) => fetch(input, init));\n this.#profile = parseModelProviderProfile(options.profile);\n if (this.#profile.adapter !== 'anthropic') {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Anthropic provider requires the anthropic adapter',\n );\n }\n this.#secret = requiredProviderSecret(\n this.#profile,\n options.secret,\n ) as string;\n this.model = this.#profile.model;\n this.remoteDataTransfer = !isLoopbackProviderUrl(this.#profile.base_url);\n }\n\n /** POST `<base_url>/messages`; returns the parsed response object. */\n async createMessage(\n request: AnthropicMessageRequest,\n signal: AbortSignal = new AbortController().signal,\n ): Promise<Record<string, unknown>> {\n const response = await fetchWithProviderGuards(\n this.#fetch,\n modelApiUrl(this.#profile.base_url, 'messages'),\n {\n body: JSON.stringify({ ...request, model: this.#profile.model }),\n headers: providerHeaders(this.#profile, this.#secret),\n method: 'POST',\n redirect: 'error',\n },\n signal,\n );\n const payload = objectValue(await readModelProviderResponse(response));\n if (payload === undefined) {\n throw new ByokKeysError(\n 'MODEL_RESPONSE_INVALID',\n 'Anthropic provider returned an invalid response',\n );\n }\n return payload;\n }\n\n /** Round-trip the configured key against the provider (`providers.ts:1037-1054`). */\n async testConnection(\n signal: AbortSignal = new AbortController().signal,\n ): Promise<void> {\n const payload = await this.createMessage(\n {\n max_tokens: 32,\n messages: [\n {\n content:\n 'Return one JSON object with exactly this shape: {\"ok\":true}.',\n role: 'user',\n },\n ],\n temperature: 0,\n },\n signal,\n );\n assertLiveModelResponse(anthropicMessageText(payload));\n }\n}\n\n/** Pull the assistant text out of a Messages API payload (`providers.ts:1084`). */\nexport function anthropicMessageText(payload: Record<string, unknown>): string {\n return modelMessageText(payload.content);\n}\n","import { spawn } from 'node:child_process';\n\n/** A finished child process, ported from `aip-main-open@c6a5385` `index.ts:284-288`. */\nexport interface CommandResult {\n exitCode: number;\n stderr: string;\n stdout: string;\n}\n\n/**\n * The injection seam both OS backends are written against. Unit tests supply a\n * fake so no test ever reads or writes a real credential store; production code\n * gets {@link runCommand}.\n */\nexport type CommandRunner = (\n executable: string,\n args: string[],\n stdin?: string,\n) => Promise<CommandResult>;\n\n/**\n * Spawn `executable`, feed it `stdin`, and collect its output\n * (`index.ts:2498-2527`).\n *\n * It never rejects: a missing executable resolves as exit code 127 so the\n * backends' `available()` probes can treat \"no such binary\" the same way they\n * treat \"binary said no\". Stdin is always closed, otherwise a child that reads\n * to EOF would hang forever.\n */\nexport async function runCommand(\n executable: string,\n args: string[],\n stdin?: string,\n): Promise<CommandResult> {\n return new Promise((resolveResult) => {\n const child = spawn(executable, args, {\n env: process.env,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n child.stdout.setEncoding('utf8');\n child.stderr.setEncoding('utf8');\n child.stdout.on('data', (chunk: string) => {\n stdout += chunk;\n });\n child.stderr.on('data', (chunk: string) => {\n stderr += chunk;\n });\n child.on('error', () => {\n resolveResult({\n exitCode: 127,\n stderr: 'command unavailable',\n stdout: '',\n });\n });\n child.on('close', (code) => {\n resolveResult({ exitCode: code ?? 1, stderr, stdout });\n });\n if (stdin === undefined) child.stdin.end();\n else child.stdin.end(stdin);\n });\n}\n","import { ByokKeysError } from './errors';\n\n/**\n * Legal secret-entry names, 3 to 96 characters.\n *\n * The source (`aip-main-open@c6a5385`, `apps/local-agent/src/index.ts:258-268`)\n * closed this set at compile time with the `KeychainSecretName` union, so it\n * needed no runtime check. `SecretStore<TName extends string>` is open by\n * design — aip's closed union stays in aip — so the closure moves to runtime.\n *\n * The exclusion that matters is `.`: every backend composes its storage key as\n * `` `${servicePrefix}.${name}` `` and a scoped store appends\n * `.scope.<namespace>` to that prefix. A name containing a dot could therefore\n * spell out another scope's service string and read that scope's secret. The\n * validator throws rather than sanitizing — a caller that mistyped a name must\n * see the error, not silently address a different entry.\n */\nexport const SECRET_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{2,95}$/u;\n\n/**\n * Legal scope namespaces, 8 to 96 characters. Ported verbatim from the source's\n * `normalizeSecretNamespace` (`index.ts:748-757`); the 8-character floor keeps\n * a namespace from colliding with a short accidental value.\n */\nexport const SECRET_NAMESPACE_PATTERN = /^[a-z0-9][a-z0-9_-]{7,95}$/u;\n\n/** Fail closed unless `name` matches {@link SECRET_NAME_PATTERN}. */\nexport function assertSecretName<TName extends string>(name: TName): TName {\n if (!SECRET_NAME_PATTERN.test(name)) {\n throw new ByokKeysError(\n 'SECRET_NAME_INVALID',\n 'Secret name must be 3 to 96 characters of [a-z0-9_-] starting with a letter or digit',\n );\n }\n return name;\n}\n\n/**\n * Trim and validate a scope namespace, or throw. Trimming is the source's\n * behavior and is safe because the pattern rejects every interior whitespace\n * character anyway.\n */\nexport function assertSecretNamespace(value: string): string {\n const normalized = value.trim();\n if (!SECRET_NAMESPACE_PATTERN.test(normalized)) {\n throw new ByokKeysError(\n 'SECRET_NAMESPACE_INVALID',\n 'Secret namespace must be 8 to 96 characters of [a-z0-9_-] starting with a letter or digit',\n );\n }\n return normalized;\n}\n","import { ByokKeysError } from './errors';\nimport {\n ProviderProfileRefSchema,\n type ProviderProfileRef,\n} from './provider-profile';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\n\n/**\n * Storage contract for a single secret entry in an operating-system credential\n * store.\n *\n * Ported from `aip-main-open@c6a5385` `apps/local-agent/src/index.ts:261-269`\n * with two deliberate changes:\n *\n * 1. `TName` is a generic parameter rather than aip's closed\n * `KeychainSecretName` union. aip's union names device keys, refresh tokens,\n * and market-data entries that this package has no business knowing about,\n * so it stays in aip and consumers pin their own union. The compile-time\n * closure it provided is replaced at runtime by {@link assertSecretName},\n * which every implementation must apply on every name it receives.\n * 2. `scope()` is required, not optional. The source made it optional and its\n * `scopeLocalAgentSecretStore` silently substituted an envelope\n * implementation when a store did not provide one. Scope-envelope prefixing\n * has no installed base, so this package removes the implicit substitution:\n * every store scopes itself, and {@link EnvelopeScopedSecretStore} is a\n * decorator a caller applies on purpose.\n */\nexport interface SecretStore<TName extends string = string> {\n /** Human-readable backend name, safe to show a user. Never contains a secret. */\n readonly providerLabel: string;\n /** Whether this backend can be used on the current machine. Must not throw. */\n available(): Promise<boolean>;\n /** Remove `name`; `false` when it was already absent. */\n delete(name: TName): Promise<boolean>;\n /** Read `name`, or `undefined` when it is absent. */\n get(name: TName): Promise<string | undefined>;\n /** Whether `name` currently holds a secret. */\n has(name: TName): Promise<boolean>;\n /** A view of this store isolated under `namespace`. */\n scope(namespace: string): SecretStore<TName>;\n /** Write `secret` at `name`, replacing any existing value. */\n set(name: TName, secret: string): Promise<void>;\n}\n\n/**\n * Default service prefix for this package's own entries. `servicePrefix` is a\n * constructor option on both OS backends, so K4's aip-main-open swap passes its\n * `com.aiphabee.local-agent` value and keeps existing installs byte-compatible.\n */\nexport const DEFAULT_SECRET_SERVICE_PREFIX = 'com.byok.keys';\n\n/**\n * Credential-store entry name for one provider profile.\n *\n * The former fixed `MODEL_PROVIDER_SECRET_NAMES` table could name exactly one\n * entry per provider kind, so two independent `custom` endpoints would have\n * shared — and overwritten — a single credential. The name is now derived from\n * the profile's own {@link ProviderProfileRef}, keeping the shape\n * `providers.ts:1624-1632` established (`model-<id>-api-key`, no vendor\n * branding; the branding lives in the service prefix).\n */\nexport type ModelProviderSecretName = `model-${string}-api-key`;\n\n/**\n * Resolve a provider profile ref to the credential-store entry holding its API\n * key. The ref is validated here as well as by the profile schema: this\n * function composes a storage address, so an unvalidated ref would be an\n * address-injection surface rather than merely an invalid record.\n */\nexport function modelProviderSecretName(\n profileRef: ProviderProfileRef,\n): ModelProviderSecretName {\n const parsed = ProviderProfileRefSchema.safeParse(profileRef);\n if (!parsed.success) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider profile ref must be a lowercase portable identifier',\n { cause: parsed.error },\n );\n }\n return assertSecretName(`model-${parsed.data}-api-key` as const);\n}\n\n/**\n * The secret-shape invariant both OS backends share. Their size ceilings differ\n * in both magnitude and unit (macOS counts 16384 characters, Windows counts\n * 2560 UTF-8 bytes) and each reports its own error code, so those checks stay\n * in the backends; only the empty/control-character rule is common.\n */\nexport function assertSharedSecretValue(secret: string): void {\n if (secret.length === 0 || /[\\u0000\\r\\n]/u.test(secret)) {\n throw new ByokKeysError(\n 'SECRET_VALUE_INVALID',\n 'Secret must be a non-empty string without null or newline characters',\n );\n }\n}\n\n/**\n * Decode base64 to UTF-8 text, or return `undefined` — never a repaired\n * approximation.\n *\n * Both decode paths in Node are lenient in ways that matter here: `Buffer.from`\n * silently drops characters outside the base64 alphabet (so `\"a!G@k=\"` would\n * decode to `\"hi\"`), and `Buffer#toString('utf8')` substitutes U+FFFD for\n * invalid byte sequences. A credential store that \"successfully\" returns a\n * silently-mangled secret is worse than one that fails, so the alphabet, the\n * canonical padding, and the UTF-8 round trip are all checked explicitly.\n */\nexport function decodeStrictBase64Utf8(encoded: string): string | undefined {\n if (encoded.length % 4 !== 0) return undefined;\n if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(encoded)) return undefined;\n const bytes = Buffer.from(encoded, 'base64');\n if (bytes.toString('base64') !== encoded) return undefined;\n const text = bytes.toString('utf8');\n if (!Buffer.from(text, 'utf8').equals(bytes)) return undefined;\n return text;\n}\n\n/**\n * A {@link SecretStore} held in process memory, for tests and for embedders\n * that supply their own persistence.\n *\n * It keys entries by the same `` `${servicePrefix}.${name}` `` string the OS\n * backends use, and `scope()` extends that prefix exactly as they do, so a test\n * written against this store exercises the same isolation arithmetic as\n * production. It applies the name validator and the shared secret-shape rule;\n * the platform size ceilings deliberately are not simulated, since they differ\n * per backend.\n */\nexport class InMemorySecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'in-memory';\n readonly #entries: Map<string, string>;\n readonly #servicePrefix: string;\n\n constructor(\n options: {\n /** Shared backing map; a scoped view keeps the parent's map. */\n entries?: Map<string, string>;\n servicePrefix?: string;\n } = {},\n ) {\n this.#entries = options.entries ?? new Map();\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n }\n\n available(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n async delete(name: TName): Promise<boolean> {\n return this.#entries.delete(this.#service(name));\n }\n\n async get(name: TName): Promise<string | undefined> {\n return this.#entries.get(this.#service(name));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new InMemorySecretStore<TName>({\n entries: this.#entries,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n assertSharedSecretValue(secret);\n this.#entries.set(service, secret);\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n","import path from 'node:path';\n\nimport { type CommandRunner, runCommand } from './command-runner';\nimport { ByokKeysError } from './errors';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\nimport {\n DEFAULT_SECRET_SERVICE_PREFIX,\n type SecretStore,\n decodeStrictBase64Utf8,\n} from './secret-store';\n\n/**\n * Marker written in front of every stored value so a read can tell a value this\n * package wrote from anything else already sitting at the same service name.\n * Injectable, so K4's aip-main-open swap passes `aiphabee-b64-v1:` and stays\n * byte-compatible with existing installs (source: `index.ts:246`).\n */\nexport const DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX = 'byok-b64-v1:';\n\n/** `security` exits 44 for \"the item does not exist\". */\nconst SECURITY_ITEM_NOT_FOUND = 44;\n\nexport interface MacOsKeychainSecretStoreOptions {\n /** Keychain account field; entries are addressed by (account, service). */\n account?: string;\n /**\n * Return a stored value that lacks {@link MacOsKeychainSecretStoreOptions.storagePrefix}\n * instead of throwing. Defaults to `false`.\n *\n * The source returned such values unconditionally\n * (`decodeMacOsKeychainSecret`, `index.ts:536-545`), which meant any\n * unrelated item at the same service name was handed back as if this package\n * had written it. Reading is fail-closed here, and the tolerant behavior is\n * demoted to something a caller must ask for by name — it exists only for a\n * migration that has read an unprefixed value it already knows it wrote.\n */\n allowUnprefixedRead?: boolean;\n commandRunner?: CommandRunner;\n /** Explicit macOS keychain file; omitted means the user default keychain. */\n keychainPath?: string;\n platform?: NodeJS.Platform;\n servicePrefix?: string;\n storagePrefix?: string;\n}\n\n/**\n * macOS Keychain backend, driving `/usr/bin/security`\n * (`aip-main-open@c6a5385` `apps/local-agent/src/index.ts:412-533`).\n *\n * There is deliberately no plaintext fallback: on a non-darwin platform every\n * operation throws `KEYCHAIN_UNAVAILABLE` rather than degrading to a file.\n */\nexport class MacOsKeychainSecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'macOS Keychain';\n readonly #account: string;\n readonly #allowUnprefixedRead: boolean;\n readonly #commandRunner: CommandRunner;\n readonly #keychainPath: string | undefined;\n readonly #platform: NodeJS.Platform;\n readonly #servicePrefix: string;\n readonly #storagePrefix: string;\n\n constructor(options: MacOsKeychainSecretStoreOptions = {}) {\n this.#account = options.account ?? 'local-device';\n this.#allowUnprefixedRead = options.allowUnprefixedRead ?? false;\n this.#commandRunner = options.commandRunner ?? runCommand;\n this.#keychainPath = assertKeychainPath(options.keychainPath);\n this.#platform = options.platform ?? process.platform;\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n this.#storagePrefix =\n options.storagePrefix ?? DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX;\n }\n\n async available(): Promise<boolean> {\n if (this.#platform !== 'darwin') return false;\n const result = await this.#commandRunner('/usr/bin/security', [\n ...(this.#keychainPath === undefined\n ? ['default-keychain', '-d', 'user']\n : ['show-keychain-info', this.#keychainPath]),\n ]);\n return result.exitCode === 0;\n }\n\n async delete(name: TName): Promise<boolean> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'delete-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n ...(this.#keychainPath === undefined ? [] : [this.#keychainPath]),\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return false;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_DELETE_FAILED',\n 'macOS Keychain could not delete the requested secret',\n );\n }\n return true;\n }\n\n async get(name: TName): Promise<string | undefined> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'find-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n '-w',\n ...(this.#keychainPath === undefined ? [] : [this.#keychainPath]),\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return undefined;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_READ_FAILED',\n 'macOS Keychain could not read the requested secret',\n );\n }\n return this.#decode(result.stdout.replace(/\\r?\\n$/u, ''));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new MacOsKeychainSecretStore<TName>({\n account: this.#account,\n allowUnprefixedRead: this.#allowUnprefixedRead,\n commandRunner: this.#commandRunner,\n keychainPath: this.#keychainPath,\n platform: this.#platform,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n storagePrefix: this.#storagePrefix,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n this.#assertMacOs();\n if (\n secret.length === 0 ||\n secret.length > 16_384 ||\n /[\\u0000\\r\\n]/u.test(secret)\n ) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_INVALID',\n 'Secret must contain 1 to 16384 non-newline characters',\n );\n }\n // `security add-generic-password -w` opens /dev/tty when no password\n // argument is supplied, even if the child has a piped stdin. Interactive\n // mode accepts the complete command through stdin, keeping the encoded\n // secret out of argv/process listings and avoiding an unattended prompt.\n const storedSecret = `${this.#storagePrefix}${Buffer.from(secret, 'utf8').toString('base64')}`;\n const command = [\n 'add-generic-password',\n '-U',\n '-a',\n quoteSecurityInteractiveArgument(this.#account),\n '-s',\n quoteSecurityInteractiveArgument(service),\n '-w',\n quoteSecurityInteractiveArgument(storedSecret),\n ...(this.#keychainPath === undefined\n ? []\n : [quoteSecurityInteractiveArgument(this.#keychainPath)]),\n ].join(' ');\n const result = await this.#commandRunner(\n '/usr/bin/security',\n ['-i'],\n `${command}\\n`,\n );\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_WRITE_FAILED',\n 'macOS Keychain could not store the requested secret',\n );\n }\n }\n\n #assertMacOs(): void {\n if (this.#platform !== 'darwin') {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n 'macOS Keychain is required; plaintext fallback is disabled',\n );\n }\n }\n\n /**\n * Fail-closed inverse of the storage encoding. The error message never\n * echoes the undecodable value — it may still be somebody's live credential.\n */\n #decode(storedSecret: string): string {\n if (!storedSecret.startsWith(this.#storagePrefix)) {\n if (this.#allowUnprefixedRead) return storedSecret;\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a value without this store\\'s storage prefix',\n );\n }\n const decoded = decodeStrictBase64Utf8(\n storedSecret.slice(this.#storagePrefix.length),\n );\n if (decoded === undefined || decoded.length === 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a secret that is not valid base64-encoded UTF-8',\n );\n }\n return decoded;\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n\n/**\n * Quote a value for `security -i`'s interactive parser (`index.ts:547-557`).\n * Null and newline characters cannot be quoted safely — a newline would end the\n * command line and let the remainder be parsed as a second command — so they are\n * rejected rather than escaped.\n */\nfunction quoteSecurityInteractiveArgument(value: string): string {\n if (/[\\u0000\\r\\n]/u.test(value)) {\n throw new ByokKeysError(\n 'KEYCHAIN_ARGUMENT_INVALID',\n 'macOS Keychain arguments cannot contain null or newline characters',\n );\n }\n return `\"${value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')}\"`;\n}\n\nfunction assertKeychainPath(keychainPath: string | undefined): string | undefined {\n if (keychainPath === undefined) return undefined;\n if (\n keychainPath.length === 0 ||\n !path.posix.isAbsolute(keychainPath) ||\n /[\\u0000\\r\\n]/u.test(keychainPath)\n ) {\n throw new ByokKeysError(\n 'KEYCHAIN_ARGUMENT_INVALID',\n 'macOS keychain path must be a non-empty absolute single-line path',\n );\n }\n return keychainPath;\n}\n","import { type CommandResult, type CommandRunner, runCommand } from './command-runner';\nimport { ByokKeysError } from './errors';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\nimport {\n DEFAULT_SECRET_SERVICE_PREFIX,\n type SecretStore,\n decodeStrictBase64Utf8,\n} from './secret-store';\n\n/** The script exits 44 for \"no such credential\", matching `security`'s code. */\nconst CREDENTIAL_NOT_FOUND = 44;\n\n/**\n * PowerShell bridge to the Win32 credential API, ported from\n * `aip-main-open@c6a5385` `apps/local-agent/src/index.ts:294-408`.\n *\n * It is passed as `-EncodedCommand` (UTF-16LE base64) so no part of it can be\n * mangled by shell quoting, and the request — including the secret — travels on\n * stdin rather than argv, keeping credentials out of process listings. The\n * generated C# type lives in namespace `Byok`; the source used its own vendor\n * name, and the identifier has no wire or storage surface, so renaming it costs\n * nothing at K4.\n */\nconst WINDOWS_CREDENTIAL_MANAGER_SCRIPT_BASE64 = Buffer.from(\n String.raw`\nAdd-Type -TypeDefinition @\"\nusing System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Runtime.InteropServices.ComTypes;\n\nnamespace Byok {\n public static class CredentialManager {\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n private struct Credential {\n public UInt32 Flags;\n public UInt32 Type;\n [MarshalAs(UnmanagedType.LPWStr)] public string TargetName;\n [MarshalAs(UnmanagedType.LPWStr)] public string Comment;\n public FILETIME LastWritten;\n public UInt32 CredentialBlobSize;\n public IntPtr CredentialBlob;\n public UInt32 Persist;\n public UInt32 AttributeCount;\n public IntPtr Attributes;\n [MarshalAs(UnmanagedType.LPWStr)] public string TargetAlias;\n [MarshalAs(UnmanagedType.LPWStr)] public string UserName;\n }\n\n [DllImport(\"Advapi32.dll\", EntryPoint = \"CredWriteW\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern bool CredWrite([In] ref Credential credential, UInt32 flags);\n\n [DllImport(\"Advapi32.dll\", EntryPoint = \"CredReadW\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern bool CredRead(string target, UInt32 type, UInt32 flags, out IntPtr credential);\n\n [DllImport(\"Advapi32.dll\", EntryPoint = \"CredDeleteW\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern bool CredDelete(string target, UInt32 type, UInt32 flags);\n\n [DllImport(\"Advapi32.dll\", SetLastError = false)]\n private static extern void CredFree(IntPtr buffer);\n\n public static void Write(string target, string username, byte[] secret) {\n IntPtr blob = IntPtr.Zero;\n try {\n blob = Marshal.AllocHGlobal(secret.Length);\n Marshal.Copy(secret, 0, blob, secret.Length);\n Credential credential = new Credential {\n Type = 1,\n TargetName = target,\n CredentialBlobSize = (UInt32)secret.Length,\n CredentialBlob = blob,\n Persist = 2,\n UserName = username\n };\n if (!CredWrite(ref credential, 0)) {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n } finally {\n if (blob != IntPtr.Zero) {\n Marshal.Copy(new byte[secret.Length], 0, blob, secret.Length);\n Marshal.FreeHGlobal(blob);\n }\n }\n }\n\n public static byte[] Read(string target) {\n IntPtr pointer;\n if (!CredRead(target, 1, 0, out pointer)) {\n int error = Marshal.GetLastWin32Error();\n if (error == 1168) return null;\n throw new Win32Exception(error);\n }\n try {\n Credential credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));\n byte[] secret = new byte[credential.CredentialBlobSize];\n if (secret.Length > 0) Marshal.Copy(credential.CredentialBlob, secret, 0, secret.Length);\n return secret;\n } finally {\n CredFree(pointer);\n }\n }\n\n public static bool Delete(string target) {\n if (CredDelete(target, 1, 0)) return true;\n int error = Marshal.GetLastWin32Error();\n if (error == 1168) return false;\n throw new Win32Exception(error);\n }\n }\n}\n\"@\n\ntry {\n $request = ([Console]::In.ReadToEnd() | ConvertFrom-Json)\n if ($request.operation -eq \"set\") {\n [Byok.CredentialManager]::Write(\n [string]$request.target,\n [string]$request.username,\n [Convert]::FromBase64String([string]$request.secret_base64)\n )\n exit 0\n }\n if ($request.operation -eq \"get\") {\n $secret = [Byok.CredentialManager]::Read([string]$request.target)\n if ($null -eq $secret) { exit 44 }\n [Console]::Out.Write([Convert]::ToBase64String($secret))\n exit 0\n }\n if ($request.operation -eq \"delete\") {\n if ([Byok.CredentialManager]::Delete([string]$request.target)) { exit 0 }\n exit 44\n }\n exit 2\n} catch {\n [Console]::Error.Write(\"credential operation failed\")\n exit 1\n}\n`,\n 'utf16le',\n).toString('base64');\n\nexport interface WindowsCredentialManagerSecretStoreOptions {\n account?: string;\n commandRunner?: CommandRunner;\n platform?: NodeJS.Platform;\n servicePrefix?: string;\n}\n\n/**\n * Windows Credential Manager backend (`index.ts:568-712`).\n *\n * As on macOS there is no plaintext fallback — off win32 every operation throws\n * `CREDENTIAL_MANAGER_UNAVAILABLE`.\n */\nexport class WindowsCredentialManagerSecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'Windows Credential Manager';\n readonly #account: string;\n readonly #commandRunner: CommandRunner;\n readonly #platform: NodeJS.Platform;\n readonly #servicePrefix: string;\n\n constructor(options: WindowsCredentialManagerSecretStoreOptions = {}) {\n this.#account = options.account ?? 'local-device';\n this.#commandRunner = options.commandRunner ?? runCommand;\n this.#platform = options.platform ?? process.platform;\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n }\n\n async available(): Promise<boolean> {\n if (this.#platform !== 'win32') return false;\n const result = await this.#commandRunner('powershell.exe', [\n '-NoLogo',\n '-NoProfile',\n '-NonInteractive',\n '-Command',\n '$PSVersionTable.PSVersion.Major',\n ]);\n return result.exitCode === 0;\n }\n\n /**\n * Delete, then read back. The source verifies rather than trusting the\n * delete's exit code (`index.ts:651-679`): a credential that survives a\n * \"successful\" delete is a security failure, so it is reported as one instead\n * of being returned as `true`.\n */\n async delete(name: TName): Promise<boolean> {\n const target = this.#service(name);\n this.#assertWindows();\n const result = await this.#invoke({\n operation: 'delete',\n target,\n username: this.#account,\n });\n if (result.exitCode === CREDENTIAL_NOT_FOUND) return false;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_DELETE_FAILED',\n 'Windows Credential Manager could not delete the requested secret',\n );\n }\n const verification = await this.#invoke({\n operation: 'get',\n target,\n username: this.#account,\n });\n if (verification.exitCode === CREDENTIAL_NOT_FOUND) return true;\n if (verification.exitCode !== 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_DELETE_FAILED',\n 'Windows Credential Manager could not verify secret deletion',\n );\n }\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_DELETE_FAILED',\n 'Windows Credential Manager reported deletion but the secret remains',\n );\n }\n\n async get(name: TName): Promise<string | undefined> {\n const target = this.#service(name);\n this.#assertWindows();\n const result = await this.#invoke({\n operation: 'get',\n target,\n username: this.#account,\n });\n if (result.exitCode === CREDENTIAL_NOT_FOUND) return undefined;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_READ_FAILED',\n 'Windows Credential Manager could not read the requested secret',\n );\n }\n // The source wrapped this decode in try/catch, but `Buffer.from` never\n // throws on bad input -- it silently drops the offending characters, so\n // that branch was unreachable. The strict decoder makes it real.\n const secret = decodeStrictBase64Utf8(result.stdout.trim());\n if (secret === undefined || secret.length === 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_READ_FAILED',\n 'Windows Credential Manager returned an invalid secret',\n );\n }\n return secret;\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new WindowsCredentialManagerSecretStore<TName>({\n account: this.#account,\n commandRunner: this.#commandRunner,\n platform: this.#platform,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const target = this.#service(name);\n this.#assertWindows();\n assertWindowsCredentialSecret(secret);\n const result = await this.#invoke({\n operation: 'set',\n secret_base64: Buffer.from(secret, 'utf8').toString('base64'),\n target,\n username: this.#account,\n });\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_WRITE_FAILED',\n 'Windows Credential Manager could not store the requested secret',\n );\n }\n }\n\n #assertWindows(): void {\n if (this.#platform !== 'win32') {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_UNAVAILABLE',\n 'Windows Credential Manager is required; plaintext fallback is disabled',\n );\n }\n }\n\n async #invoke(request: {\n operation: 'delete' | 'get' | 'set';\n secret_base64?: string;\n target: string;\n username: string;\n }): Promise<CommandResult> {\n return this.#commandRunner(\n 'powershell.exe',\n [\n '-NoLogo',\n '-NoProfile',\n '-NonInteractive',\n '-EncodedCommand',\n WINDOWS_CREDENTIAL_MANAGER_SCRIPT_BASE64,\n ],\n JSON.stringify(request),\n );\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n\n/**\n * `index.ts:2529-2543`. The ceiling is measured in UTF-8 bytes because that is\n * what `CredentialBlobSize` counts; a character-based check would let a\n * multi-byte secret overrun it.\n */\nfunction assertWindowsCredentialSecret(secret: string): void {\n const bytes = Buffer.byteLength(secret, 'utf8');\n if (secret.length === 0 || bytes > 2_560 || /[\\u0000\\r\\n]/u.test(secret)) {\n throw new ByokKeysError(\n 'CREDENTIAL_MANAGER_SECRET_INVALID',\n 'Secret must contain 1 to 2560 UTF-8 bytes without newline characters',\n );\n }\n}\n","import { createHash } from 'node:crypto';\n\nimport { ByokKeysError } from './errors';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\nimport { type SecretStore, assertSharedSecretValue } from './secret-store';\n\n/**\n * Tenant identity a secret store is partitioned by. Ported from\n * `aip-main-open@c6a5385` `apps/local-agent/src/local-data-scope.ts:19-22`\n * (`LocalAccountDataScope`).\n */\nexport interface SecretScope {\n account_id: string;\n workspace_id: string;\n}\n\n/**\n * Envelope marker, injectable so K4 can pass the source's\n * `aiphabee-scoped-secrets-v1:` value (`local-data-scope.ts:30`).\n */\nexport const DEFAULT_SECRET_ENVELOPE_PREFIX = 'byok-scoped-secrets-v1:';\n\n/**\n * Derive the opaque namespace a scope's secrets live under\n * (`local-data-scope.ts:32-37`). Hashing means the namespace never leaks a\n * tenant identifier into a keychain service name a user can browse.\n */\nexport function secretScopeId(scope: SecretScope): string {\n const normalized = normalizeSecretScope(scope);\n return `acct_${createHash('sha256')\n .update(`${normalized.account_id}\\n${normalized.workspace_id}`, 'utf8')\n .digest('hex')}`;\n}\n\n/**\n * Partition `store` by `scope` (`local-data-scope.ts:100-106`).\n *\n * The source read `store.scope?.(id) ?? new EnvelopeScopedSecretStore(...)`:\n * when a store happened not to implement `scope`, it silently switched to a\n * different storage layout. `SecretStore.scope` is required in this package, so\n * that implicit substitution is gone — a caller who wants envelope semantics\n * constructs {@link EnvelopeScopedSecretStore} on purpose.\n */\nexport function scopeSecretStore<TName extends string>(\n store: SecretStore<TName>,\n scope: SecretScope,\n): SecretStore<TName> {\n return store.scope(secretScopeId(scope));\n}\n\n/**\n * Partition a store by keeping every scope's secret in one underlying entry,\n * as a JSON map of scope id to secret.\n *\n * This is the layout to reach for when the backend cannot cheaply namespace its\n * own key space. It costs a read-modify-write on every mutation and offers no\n * cross-process locking, so prefer a backend's native `scope()` when it has\n * one; this decorator exists for the backends that do not.\n *\n * Reads are fail-closed in a way the source's were not\n * (`local-data-scope.ts:163-194`): the source mapped any unparseable stored\n * value to `undefined`, which made a foreign value look like an absent secret\n * and let the next `set()` overwrite it. Here a stored value that is not a\n * well-formed envelope raises `SECRET_ENVELOPE_INVALID`.\n */\nexport class EnvelopeScopedSecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel: string;\n readonly #envelopePrefix: string;\n readonly #scopeId: string;\n readonly #store: SecretStore<TName>;\n\n constructor(\n store: SecretStore<TName>,\n scopeId: string,\n options: { envelopePrefix?: string } = {},\n ) {\n this.#store = store;\n this.#scopeId = assertScopeSlotKey(scopeId);\n this.#envelopePrefix =\n options.envelopePrefix ?? DEFAULT_SECRET_ENVELOPE_PREFIX;\n this.providerLabel = store.providerLabel;\n }\n\n available(): Promise<boolean> {\n return this.#store.available();\n }\n\n async delete(name: TName): Promise<boolean> {\n const envelope = await this.#readEnvelope(name);\n if (envelope === undefined || !Object.hasOwn(envelope, this.#scopeId)) {\n return false;\n }\n delete envelope[this.#scopeId];\n if (Object.keys(envelope).length === 0) return this.#store.delete(name);\n await this.#store.set(name, this.#serialize(envelope));\n return true;\n }\n\n async get(name: TName): Promise<string | undefined> {\n return (await this.#readEnvelope(name))?.[this.#scopeId];\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new EnvelopeScopedSecretStore<TName>(\n this.#store,\n `${this.#scopeId}.${assertSecretNamespace(namespace)}`,\n { envelopePrefix: this.#envelopePrefix },\n );\n }\n\n async set(name: TName, secret: string): Promise<void> {\n assertSharedSecretValue(secret);\n const envelope =\n (await this.#readEnvelope(name)) ??\n (Object.create(null) as Record<string, string>);\n envelope[this.#scopeId] = secret;\n await this.#store.set(name, this.#serialize(envelope));\n }\n\n /**\n * `undefined` means the entry is absent; a malformed entry throws.\n *\n * The returned map has a null prototype. A slot key is attacker-adjacent\n * data — `constructor` is a legal namespace (`toString` and `__proto__` are\n * rejected by the pattern, but this defense does not depend on the pattern's\n * shape) — so a plain object would answer `envelope[scopeId]` from\n * `Object.prototype` and hand a Function back as a scope's secret.\n */\n async #readEnvelope(\n name: TName,\n ): Promise<Record<string, string> | undefined> {\n const stored = await this.#store.get(assertSecretName(name));\n if (stored === undefined) return undefined;\n if (!stored.startsWith(this.#envelopePrefix)) throw envelopeInvalid();\n const decoded = decodeBase64Url(stored.slice(this.#envelopePrefix.length));\n if (decoded === undefined) throw envelopeInvalid();\n let parsed: unknown;\n try {\n parsed = JSON.parse(decoded);\n } catch {\n throw envelopeInvalid();\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Array.isArray(parsed) ||\n Object.values(parsed).some((value) => typeof value !== 'string')\n ) {\n throw envelopeInvalid();\n }\n return Object.assign(\n Object.create(null) as Record<string, string>,\n parsed as Record<string, string>,\n );\n }\n\n #serialize(value: Record<string, string>): string {\n return `${this.#envelopePrefix}${Buffer.from(\n JSON.stringify(value),\n 'utf8',\n ).toString('base64url')}`;\n }\n}\n\n/**\n * Validate an envelope slot key: one or more namespaces joined by `.`, as\n * {@link EnvelopeScopedSecretStore.scope} composes them. Each segment must pass\n * {@link assertSecretNamespace} on its own, so a nested key cannot smuggle in a\n * segment the validator would otherwise reject.\n *\n * Unlike a backend service string, a `.` is safe here: the key addresses a JSON\n * object property, not a `` `${servicePrefix}.${name}` `` lookup, so it cannot\n * be confused with a different entry.\n *\n * Addressing a JSON object property carries its own hazard, though: the\n * namespace pattern admits `constructor` (`toString` and `__proto__` it\n * rejects), so a slot lookup on a plain object would resolve through\n * `Object.prototype` and report a never-written scope as present.\n * {@link EnvelopeScopedSecretStore} closes that by keeping every envelope\n * null-prototyped and testing slot presence with `Object.hasOwn` — a defense\n * that does not depend on the pattern's shape, which is why `constructor`\n * stays a legal namespace rather than being banned.\n */\nfunction assertScopeSlotKey(value: string): string {\n return value\n .trim()\n .split('.')\n .map((segment) => assertSecretNamespace(segment))\n .join('.');\n}\n\nfunction envelopeInvalid(): ByokKeysError {\n return new ByokKeysError(\n 'SECRET_ENVELOPE_INVALID',\n 'The stored value is not a well-formed scoped-secret envelope',\n );\n}\n\n/** Strict base64url decode; `undefined` rather than a repaired approximation. */\nfunction decodeBase64Url(encoded: string): string | undefined {\n if (!/^[A-Za-z0-9_-]*$/u.test(encoded)) return undefined;\n const bytes = Buffer.from(encoded, 'base64url');\n if (bytes.toString('base64url') !== encoded) return undefined;\n const text = bytes.toString('utf8');\n if (!Buffer.from(text, 'utf8').equals(bytes)) return undefined;\n return text;\n}\n\n/**\n * `local-data-scope.ts:108-121`, plus one tightening: control characters are\n * rejected. The scope id hashes `` `${account_id}\\n${workspace_id}` ``, so an\n * account id containing a newline would collide with a different scope\n * (`\"a\\nb\" + \"c\"` and `\"a\" + \"b\\nc\"` both serialize to `\"a\\nb\\nc\"`). Rejecting\n * them closes the collision without changing the hash of any legal input.\n */\nfunction normalizeSecretScope(scope: SecretScope): SecretScope {\n const accountId = scope.account_id.trim();\n const workspaceId = scope.workspace_id.trim();\n if (\n !accountId ||\n !workspaceId ||\n accountId.length > 160 ||\n workspaceId.length > 160 ||\n /[\\u0000\\r\\n]/u.test(accountId) ||\n /[\\u0000\\r\\n]/u.test(workspaceId)\n ) {\n throw new ByokKeysError(\n 'LOCAL_ACCOUNT_SCOPE_INVALID',\n 'The local account data scope is invalid',\n );\n }\n return { account_id: accountId, workspace_id: workspaceId };\n}\n","import { ByokKeysError } from './errors';\nimport {\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\n\n/**\n * Storage contract for provider profiles — everything needed to address a\n * provider except the API key, which lives in a {@link SecretStore}.\n *\n * Shaped after `@byok-sdk/server`'s `TaskStore` (`packages/server/src/task-store.ts`)\n * as a *pattern*, not a dependency: `keys` must not import `server`, and\n * `server` must not import `keys` (the plan's Security Boundary keeps the\n * agent-dispatch packages free of any credential-adjacent code).\n *\n * Two invariants every implementation MUST enforce, not just\n * {@link InMemoryProviderProfileStore}:\n *\n * 1. **At most one enabled profile.** The source expressed this as a partial\n * unique index (`providers.ts:140-144`); saving an enabled profile disables\n * every other one. {@link resolveDefaultModelProvider} relies on it to\n * answer \"which provider is the default\" with a single row.\n * 2. **Validate on write.** `save` runs {@link parseModelProviderProfile}, so an\n * invalid profile is refused at the boundary rather than discovered later by\n * a reader.\n */\nexport interface ProviderProfileStore {\n /** Release the underlying resource. Safe to call more than once. */\n close(): Promise<void>;\n /** Remove `profileRef`; `false` when it was not configured. */\n delete(profileRef: ProviderProfileRef): Promise<boolean>;\n /** Read one profile, configured or not enabled alike. */\n get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined>;\n /** The single enabled profile, or `undefined` when none is enabled. */\n getEnabled(): Promise<ModelProviderProfile | undefined>;\n /** Every configured profile, ordered by profile ref. */\n list(): Promise<ModelProviderProfile[]>;\n /** Insert or update `profile`, enforcing both invariants above. */\n save(profile: ModelProviderProfile): Promise<ModelProviderProfile>;\n /**\n * Make `profileRef` the enabled profile. Throws `PROVIDER_NOT_CONFIGURED`\n * when it has no profile — a fail-closed port of `providers.ts:1243-1250`.\n */\n setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile>;\n}\n\n/** Shared by both implementations so their error text cannot drift apart. */\nexport function providerNotConfigured(\n profileRef: ProviderProfileRef,\n): ByokKeysError {\n return new ByokKeysError(\n 'PROVIDER_NOT_CONFIGURED',\n `${profileRef} model provider is not configured`,\n );\n}\n\n/**\n * Profile store held in process memory: the default, and the one every test\n * that does not specifically exercise SQLite should use.\n *\n * Mirrors `InMemoryTaskStore`'s role in `@byok-sdk/server` — a real implementation\n * of the contract, not a stub, so behaviour proven here is the behaviour the\n * SQLite store must match (`profile-store.test.ts` runs one suite against both).\n */\nexport class InMemoryProviderProfileStore implements ProviderProfileStore {\n readonly #profiles = new Map<ProviderProfileRef, ModelProviderProfile>();\n\n async close(): Promise<void> {\n this.#profiles.clear();\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n return this.#profiles.delete(profileRef);\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n return this.#profiles.get(profileRef);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n return [...this.#profiles.values()].find((profile) => profile.enabled);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n return [...this.#profiles.values()].sort((left, right) =>\n left.profile_ref.localeCompare(right.profile_ref),\n );\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const validated = parseModelProviderProfile({\n ...profile,\n created_at:\n this.#profiles.get(profile.profile_ref)?.created_at ??\n profile.created_at,\n });\n if (validated.enabled) {\n for (const [profileRef, existing] of this.#profiles) {\n if (profileRef !== validated.profile_ref && existing.enabled) {\n this.#profiles.set(profileRef, { ...existing, enabled: false });\n }\n }\n }\n this.#profiles.set(validated.profile_ref, validated);\n return validated;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const existing = this.#profiles.get(profileRef);\n if (existing === undefined) throw providerNotConfigured(profileRef);\n return this.save({ ...existing, enabled: true });\n }\n}\n","import { chmodSync, existsSync, mkdirSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname } from 'node:path';\nimport type { DatabaseSync, DatabaseSyncOptions } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\n\nexport type SqliteOpenStep = 'after-open' | 'after-wal' | 'after-synchronous';\n\n/** Test-only seam for proving that post-open initialization failures release the native handle. */\nexport interface SqliteOpenFaultSeam {\n onStep?(step: SqliteOpenStep): void;\n close?(database: DatabaseSync): void;\n}\n\n/** Release an opened handle before propagating an initialization failure. */\nexport function closeSqliteDatabaseAfterInitializationFailure(\n database: DatabaseSync,\n initializationError: unknown,\n message: string,\n close: (database: DatabaseSync) => void = (handle) => handle.close(),\n): never {\n try {\n close(database);\n } catch (closeError) {\n throw new AggregateError([initializationError, closeError], message);\n }\n throw initializationError;\n}\n\n/** Owner-only directory mode, matching `providers.ts:1236`. */\nconst SECURE_DIR_MODE = 0o700;\n\n/** Owner-only file mode, matching `providers.ts:158`. */\nconst SECURE_FILE_MODE = 0o600;\n\nconst DEFAULT_BUSY_TIMEOUT_MS = 5_000;\n\ninterface SqliteModule {\n DatabaseSync: new (\n path: string,\n options?: DatabaseSyncOptions,\n ) => DatabaseSync;\n}\n\n/**\n * Load `node:sqlite`, or fail with a `ByokKeysError` that says why.\n *\n * `node:sqlite` shipped in Node.js 22.5.0 and stays marked experimental (an\n * `ExperimentalWarning` on stderr is expected and harmless). Following\n * `@byok-sdk/server`'s `sqlite-support.ts`, the SQLite-backed store here depends on\n * nothing else — no `better-sqlite3`, no native module — because zero native\n * dependencies is what keeps this package trivially packageable. The tradeoff\n * is that {@link SqliteProviderProfileStore} does not work below Node 22.5, and\n * this error says so instead of letting a cryptic `Cannot find module` surface\n * from deep inside a query.\n */\nexport function loadSqliteModule(): SqliteModule {\n try {\n return createRequire(import.meta.url)('node:sqlite') as SqliteModule;\n } catch (error) {\n throw new ByokKeysError(\n 'PROVIDER_STORE_UNAVAILABLE',\n 'node:sqlite is unavailable in this Node.js runtime. SqliteProviderProfileStore ' +\n 'requires Node.js 22.5+ with the built-in `node:sqlite` module (no native ' +\n 'dependency is used or allowed here). Upgrade Node.js, or use ' +\n 'InMemoryProviderProfileStore instead.',\n { cause: error },\n );\n }\n}\n\n/**\n * Whether `node:sqlite` can ACTUALLY be loaded right now.\n *\n * Same predicate as `@byok-sdk/server`'s `sqlite-support.ts`, and it exists for the\n * same reason: this package's `engines.node` is `>=20` and CI runs the matrix\n * on 20 and 22, but `node:sqlite` shipped in 22.5 and stayed behind\n * `--experimental-sqlite` for part of the 22.x line. A version-number\n * comparison would therefore be wrong in both directions, so this attempts the\n * real require via {@link loadSqliteModule} and reports whether it succeeded.\n *\n * Callers use it to skip a SQLite-backed path rather than fail it — the\n * package's own SQLite-backed suites gate on it — and anything else should call\n * it before assuming a {@link SqliteProviderProfileStore} can be constructed.\n */\nexport function isSqliteAvailable(): boolean {\n try {\n loadSqliteModule();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Open a database, creating its parent directory owner-only first. `:memory:`\n * skips every filesystem step, which is how the shared contract suite exercises\n * the SQLite code path without leaving anything on disk.\n */\nexport function openSqliteDatabase(\n path: string,\n options?: DatabaseSyncOptions,\n faults?: SqliteOpenFaultSeam,\n): DatabaseSync {\n const { DatabaseSync } = loadSqliteModule();\n const readOnly = options?.readOnly === true;\n if (path !== ':memory:' && !readOnly) {\n mkdirSync(dirname(path), { mode: SECURE_DIR_MODE, recursive: true });\n }\n const database = new DatabaseSync(path, {\n timeout: DEFAULT_BUSY_TIMEOUT_MS,\n ...options,\n });\n try {\n faults?.onStep?.('after-open');\n if (path !== ':memory:' && !readOnly) {\n database.exec('PRAGMA journal_mode = WAL');\n faults?.onStep?.('after-wal');\n database.exec('PRAGMA synchronous = FULL');\n faults?.onStep?.('after-synchronous');\n }\n return database;\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n database,\n error,\n 'provider profile SQLite open initialization failed and its native handle could not be closed',\n faults?.close,\n );\n }\n}\n\n/**\n * Restrict `databasePath` and its WAL/SHM siblings to owner-only read/write.\n *\n * The profile table holds no secret — that is the whole point of splitting the\n * key into the OS credential store — but it does hold every provider endpoint\n * this machine talks to, and the source locked the file down\n * (`providers.ts:158`), so the port keeps that. Call after the schema exists,\n * so the lazily-created WAL/SHM files are already there; a sibling that does\n * not exist is skipped rather than treated as an error. No-op for `:memory:`.\n */\nexport function secureSqliteFilePermissions(databasePath: string): void {\n if (databasePath === ':memory:') return;\n for (const candidate of [\n databasePath,\n `${databasePath}-wal`,\n `${databasePath}-shm`,\n ]) {\n if (existsSync(candidate)) {\n chmodSync(candidate, SECURE_FILE_MODE);\n }\n }\n}\n","import type { DatabaseSync } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\nimport {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n MODEL_PROVIDER_ADAPTERS,\n MODEL_PROVIDER_KINDS,\n PROVIDER_AUTH_MODES,\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\nimport {\n closeSqliteDatabaseAfterInitializationFailure,\n openSqliteDatabase,\n secureSqliteFilePermissions,\n} from './sqlite-support';\n\nexport interface SqliteProviderProfileStoreOptions {\n /**\n * Database file path. `:memory:` exercises the SQLite code path without a\n * temp file, but defeats the point of this store (restart-safety) exactly as\n * it does for `@byok-sdk/server`'s `SqliteTaskStore`.\n */\n path: string;\n /** Open an existing profile database without creating or mutating it. */\n readOnly?: boolean;\n}\n\n/** SQL string-literal list for a CHECK constraint's `IN (...)` set. */\nfunction sqlList(values: readonly string[]): string {\n return values.map((value) => `'${value}'`).join(', ');\n}\n\n/**\n * Ported from `providers.ts:109-140`, narrowed to the model branch. The\n * source's table also carried `market_data` / `mcp_http` rows and a `tool_name`\n * column; that branch stays in aip-main-open per\n * `docs/researches/HANDOFF-byok-keys.md` §4.5, so the CHECK constraints here\n * are the model half only.\n *\n * The three enumerated CHECK lists are generated from the schema authorities in\n * `provider-profile.ts` rather than restated here: `MODEL_PROVIDER_KINDS` (in\n * turn derived from `provider-catalog.ts`), `MODEL_PROVIDER_ADAPTERS`, and\n * `PROVIDER_AUTH_MODES`. A widened enum therefore cannot silently disagree with\n * a persisted table, and {@link assertProviderProfileSchemaIsCurrent} fails\n * closed on a database whose stored DDL was generated by a different version.\n */\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS provider_profile (\n profile_ref TEXT PRIMARY KEY,\n provider_kind TEXT NOT NULL CHECK (provider_kind IN (${sqlList(MODEL_PROVIDER_KINDS)})),\n kind TEXT NOT NULL CHECK (kind = 'model'),\n adapter TEXT NOT NULL CHECK (adapter IN (${sqlList(MODEL_PROVIDER_ADAPTERS)})),\n display_name TEXT NOT NULL,\n base_url TEXT NOT NULL,\n auth_mode TEXT NOT NULL CHECK (auth_mode IN (${sqlList(PROVIDER_AUTH_MODES)})),\n model TEXT NOT NULL,\n capabilities TEXT NOT NULL,\n enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\n`;\n\n/**\n * Compare a `CREATE TABLE` statement by shape rather than by byte: SQLite\n * stores the original statement text in `sqlite_master.sql` with `IF NOT\n * EXISTS` removed and the trailing semicolon dropped, so both sides are\n * stripped of those and their whitespace runs collapsed before comparison.\n */\nfunction normalizeTableDdl(sql: string): string {\n return sql\n .replace(/\\bIF\\s+NOT\\s+EXISTS\\b/giu, '')\n .replace(/\\s+/gu, ' ')\n .trim()\n .replace(/;$/u, '')\n .trim();\n}\n\n/**\n * Fail closed when the opened database's `provider_profile` table was created\n * by a different `@byok-sdk/keys` schema.\n *\n * `CREATE TABLE IF NOT EXISTS` is a no-op against an existing table, so a store\n * written by a version with a narrower `provider_kind` CHECK would otherwise\n * keep opening and only reject the new kind at `save` time, from inside a\n * transaction, as an opaque constraint violation. There is deliberately no\n * in-place migration: the local profile database holds declared configuration\n * the operator can retype, and a silent ALTER would be exactly the steady-state\n * compatibility path this package refuses. A database that does not carry the\n * table yet passes.\n */\nfunction assertProviderProfileSchemaIsCurrent(\n database: DatabaseSync,\n path: string,\n): void {\n const row = database\n .prepare(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'provider_profile'\",\n )\n .get() as { sql?: string | null } | undefined;\n const stored = row?.sql;\n if (typeof stored !== 'string') return;\n if (normalizeTableDdl(stored) === normalizeTableDdl(SCHEMA)) return;\n throw new ByokKeysError(\n 'PROVIDER_STORE_SCHEMA_STALE',\n `Provider profile store at ${path} was created by a different @byok-sdk/keys schema; recreate the store file to continue`,\n );\n}\n\n/**\n * The \"at most one enabled profile\" invariant, enforced by the database itself\n * rather than only by {@link SqliteProviderProfileStore.save}\n * (`providers.ts:140-144`). A partial unique index means a bug in the write\n * path surfaces as a constraint violation instead of silently producing two\n * defaults.\n */\nconst ENABLED_INDEX = `\nCREATE UNIQUE INDEX IF NOT EXISTS provider_profile_one_enabled\nON provider_profile(kind)\nWHERE enabled = 1;\n`;\n\ninterface ProfileRow {\n adapter: string;\n auth_mode: string;\n base_url: string;\n capabilities: string;\n created_at: string;\n display_name: string;\n enabled: number;\n kind: string;\n model: string;\n profile_ref: string;\n provider_kind: string;\n updated_at: string;\n}\n\n/**\n * SQLite-backed {@link ProviderProfileStore}, following `@byok-sdk/server`'s\n * `SqliteTaskStore` shape. Holds no secret: the API key lives in the injected\n * `SecretStore`, and `registry.golden.test.ts` asserts the plaintext key never\n * appears in this file's bytes.\n */\nexport class SqliteProviderProfileStore implements ProviderProfileStore {\n readonly #database: DatabaseSync;\n #closed = false;\n\n constructor(options: SqliteProviderProfileStoreOptions) {\n this.#database = openSqliteDatabase(options.path, {\n readOnly: options.readOnly ?? false,\n });\n if (!options.readOnly) {\n try {\n this.#database.exec(SCHEMA);\n this.#database.exec(ENABLED_INDEX);\n assertProviderProfileSchemaIsCurrent(this.#database, options.path);\n secureSqliteFilePermissions(options.path);\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n this.#database,\n error,\n 'SqliteProviderProfileStore initialization failed and its native handle could not be closed',\n );\n }\n } else {\n try {\n assertProviderProfileSchemaIsCurrent(this.#database, options.path);\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n this.#database,\n error,\n 'SqliteProviderProfileStore read-only schema check failed and its native handle could not be closed',\n );\n }\n }\n }\n\n /**\n * Idempotent, as {@link ProviderProfileStore.close} requires: `node:sqlite`\n * throws \"database is not open\" on a second `close()`, and a store is\n * routinely closed both by the code that finished with it and by a test's\n * teardown.\n */\n async close(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n this.#database.close();\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n const result = this.#database\n .prepare('DELETE FROM provider_profile WHERE profile_ref = ?')\n .run(profileRef);\n return Number(result.changes) === 1;\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE profile_ref = ?')\n .get(profileRef) as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE enabled = 1')\n .get() as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n const rows = this.#database\n .prepare('SELECT * FROM provider_profile ORDER BY profile_ref ASC')\n .all() as unknown as ProfileRow[];\n return rows.map(parseRow);\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const existing = await this.get(profile.profile_ref);\n const validated = parseModelProviderProfile({\n ...profile,\n created_at: existing?.created_at ?? profile.created_at,\n });\n this.#transaction(() => {\n if (validated.enabled) {\n this.#database\n .prepare(\n 'UPDATE provider_profile SET enabled = 0 WHERE profile_ref <> ?',\n )\n .run(validated.profile_ref);\n }\n this.#database\n .prepare(\n `INSERT INTO provider_profile (\n profile_ref, provider_kind, kind, adapter, display_name, base_url,\n auth_mode, model, capabilities, enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(profile_ref) DO UPDATE SET\n provider_kind = excluded.provider_kind,\n adapter = excluded.adapter,\n display_name = excluded.display_name,\n base_url = excluded.base_url,\n auth_mode = excluded.auth_mode,\n model = excluded.model,\n capabilities = excluded.capabilities,\n enabled = excluded.enabled,\n updated_at = excluded.updated_at`,\n )\n .run(\n validated.profile_ref,\n validated.provider_kind,\n validated.kind,\n validated.adapter,\n validated.display_name,\n validated.base_url,\n validated.auth_mode,\n validated.model,\n JSON.stringify(validated.capabilities),\n validated.enabled ? 1 : 0,\n validated.created_at,\n validated.updated_at,\n );\n });\n return (await this.get(validated.profile_ref)) as ModelProviderProfile;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const existing = await this.get(profileRef);\n if (existing === undefined) throw providerNotConfigured(profileRef);\n return this.save({ ...existing, enabled: true });\n }\n\n /** `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`, per `providers.ts:1252-1263`. */\n #transaction(body: () => void): void {\n this.#database.exec('BEGIN IMMEDIATE');\n try {\n body();\n this.#database.exec('COMMIT');\n } catch (error) {\n this.#database.exec('ROLLBACK');\n throw error;\n }\n }\n}\n\n/**\n * Rows go back through the same zod schema the write path used, so a row that\n * a different process wrote — or an older schema left behind — is rejected\n * rather than trusted. `enabled` is an INTEGER in SQLite and a real boolean in\n * the schema, and `capabilities` is a JSON array in a TEXT column, so both are\n * decoded explicitly and a row that fails to decode is refused rather than\n * quietly downgraded to an empty capability set.\n */\nfunction parseRow(row: ProfileRow): ModelProviderProfile {\n let capabilities: unknown;\n try {\n capabilities = JSON.parse(row.capabilities);\n } catch (cause) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider profile capabilities column is not valid JSON',\n { cause },\n );\n }\n return parseModelProviderProfile({\n ...row,\n capabilities,\n enabled: row.enabled === 1,\n });\n}\n\n/** Exported for the store's own tests to enumerate the CHECK-constrained kinds. */\nexport const SQLITE_PROFILE_PROVIDER_KINDS = MODEL_PROVIDER_KINDS;\n","import { createHash } from 'node:crypto';\n\nimport {\n contentHash,\n isCoreConflictError,\n type TenantId,\n type TruthRecord,\n type TruthStore,\n} from '@byok-sdk/core';\n\nimport { ByokKeysError } from './errors';\nimport {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\n\nexport const PROVIDER_PROFILE_TRUTH_RECORD_KEY =\n 'byok-sdk.keys/model-provider-registry-v1';\n\nconst PROFILE_KEYS = [\n 'adapter',\n 'auth_mode',\n 'base_url',\n 'capabilities',\n 'created_at',\n 'display_name',\n 'enabled',\n 'kind',\n 'model',\n 'profile_ref',\n 'provider_kind',\n 'updated_at',\n] as const;\n\n/**\n * Upper bound on how many profiles one tenant's registry snapshot may carry.\n *\n * The former bound was `MODEL_PROVIDER_IDS.length`, which only held because the\n * primary key was a four-value enum. Profile refs are open, so the CAS body\n * needs an explicit ceiling of its own; a registry is device-local operator\n * configuration, and 32 endpoints is far past any real local setup while\n * keeping the single-record snapshot small.\n */\nexport const MAX_PROVIDER_PROFILES = 32;\n\ninterface ProviderRegistrySnapshotV1 {\n readonly schema_version: 1;\n readonly profiles: readonly ModelProviderProfile[];\n}\n\ninterface LoadedRegistry {\n readonly profiles: readonly ModelProviderProfile[];\n readonly rev: number;\n}\n\nexport interface TruthStoreProviderProfileStoreOptions {\n tenant: TenantId;\n truthStore: TruthStore;\n}\n\n/**\n * Tenant-bound profile persistence over the core TruthStore snapshot contract.\n *\n * The complete, closed provider registry is one CAS unit. That is what makes a\n * delete and the \"at most one enabled profile\" transition atomic without\n * adding a second transaction authority. The body is metadata only; provider\n * credentials remain exclusively in the independently injected SecretStore.\n */\nexport class TruthStoreProviderProfileStore implements ProviderProfileStore {\n readonly #tenant: TenantId;\n readonly #truth: TruthStore;\n\n constructor(options: TruthStoreProviderProfileStoreOptions) {\n this.#tenant = options.tenant;\n this.#truth = options.truthStore;\n }\n\n async close(): Promise<void> {\n // The host owns the injected TruthStore lifecycle.\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n const current = await this.#load();\n if (!current.profiles.some((profile) => profile.profile_ref === profileRef)) {\n return false;\n }\n await this.#write(\n current.profiles.filter((profile) => profile.profile_ref !== profileRef),\n current.rev,\n );\n return true;\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n return (await this.#load()).profiles.find(\n (profile) => profile.profile_ref === profileRef,\n );\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n return (await this.#load()).profiles.find((profile) => profile.enabled);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n return [...(await this.#load()).profiles];\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const current = await this.#load();\n const existing = current.profiles.find(\n (candidate) => candidate.profile_ref === profile.profile_ref,\n );\n const validated = parseModelProviderProfile({\n ...profile,\n created_at: existing?.created_at ?? profile.created_at,\n });\n const next = current.profiles\n .filter((candidate) => candidate.profile_ref !== validated.profile_ref)\n .map((candidate) =>\n validated.enabled && candidate.enabled\n ? { ...candidate, enabled: false }\n : candidate,\n );\n next.push(validated);\n await this.#write(next, current.rev);\n return validated;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const current = await this.#load();\n const selected = current.profiles.find(\n (profile) => profile.profile_ref === profileRef,\n );\n if (selected === undefined) throw providerNotConfigured(profileRef);\n const next = current.profiles.map((profile) => ({\n ...profile,\n enabled: profile.profile_ref === profileRef,\n }));\n await this.#write(next, current.rev);\n return { ...selected, enabled: true };\n }\n\n async #load(): Promise<LoadedRegistry> {\n const record = await this.#truth.getRecord(this.#tenant, {\n kind: 'profile',\n recordKey: PROVIDER_PROFILE_TRUTH_RECORD_KEY,\n });\n if (record === undefined) return { profiles: [], rev: 0 };\n return decodeRegistryRecord(record, this.#tenant);\n }\n\n async #write(\n profiles: readonly ModelProviderProfile[],\n expectedRev: number,\n ): Promise<void> {\n const encoded = encodeRegistry(profiles);\n let written: TruthRecord;\n try {\n written = await this.#truth.writeSnapshot(this.#tenant, {\n kind: 'profile',\n recordKey: PROVIDER_PROFILE_TRUTH_RECORD_KEY,\n expectedRev,\n contentHash: hashBody(encoded),\n byteSize: BigInt(new TextEncoder().encode(encoded).byteLength),\n body: { kind: 'inline', body: encoded },\n label: 'BYOK model provider registry',\n });\n } catch (cause) {\n if (isCoreConflictError(cause, 'truth_revision_conflict')) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_CONFLICT',\n 'Provider profiles changed since this operation read them',\n { cause },\n );\n }\n throw cause;\n }\n if (written.body.kind !== 'inline' || written.body.body !== encoded) {\n throw invalidTruth('TruthStore did not confirm the requested provider profile snapshot');\n }\n const confirmed = decodeRegistryRecord(written, this.#tenant);\n if (confirmed.rev !== expectedRev + 1) {\n throw invalidTruth('TruthStore confirmed an unexpected provider profile revision');\n }\n }\n}\n\nfunction encodeRegistry(profiles: readonly ModelProviderProfile[]): string {\n const normalized = profiles\n .map((profile) => parseModelProviderProfile(profile))\n .sort((left, right) => left.profile_ref.localeCompare(right.profile_ref));\n assertRegistryInvariants(normalized);\n const snapshot: ProviderRegistrySnapshotV1 = {\n schema_version: 1,\n profiles: normalized.map((profile) => ({\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n capabilities: profile.capabilities,\n created_at: profile.created_at,\n display_name: profile.display_name,\n enabled: profile.enabled,\n kind: profile.kind,\n model: profile.model,\n profile_ref: profile.profile_ref,\n provider_kind: profile.provider_kind,\n updated_at: profile.updated_at,\n })),\n };\n return JSON.stringify(snapshot);\n}\n\nfunction decodeRegistryRecord(\n record: TruthRecord,\n tenant: TenantId,\n): LoadedRegistry {\n if (\n record.tenantId !== tenant ||\n record.kind !== 'profile' ||\n record.recordKey !== PROVIDER_PROFILE_TRUTH_RECORD_KEY ||\n !Number.isSafeInteger(record.rev) ||\n record.rev < 1\n ) {\n throw invalidTruth('TruthStore returned mismatched provider profile authority');\n }\n if (record.body.kind !== 'inline') {\n throw invalidTruth('Provider profiles must use an inline TruthStore body');\n }\n const bytes = new TextEncoder().encode(record.body.body);\n if (record.byteSize !== BigInt(bytes.byteLength)) {\n throw invalidTruth('Provider profile TruthStore byte size does not match its body');\n }\n if (record.contentHash !== hashBody(record.body.body)) {\n throw invalidTruth('Provider profile TruthStore hash does not match its body');\n }\n\n let raw: unknown;\n try {\n raw = JSON.parse(record.body.body);\n } catch (cause) {\n throw invalidTruth('Provider profile TruthStore body is not valid JSON', cause);\n }\n if (!isPlainRecord(raw) || !hasExactKeys(raw, ['profiles', 'schema_version'])) {\n throw invalidTruth('Provider profile TruthStore body has an unknown top-level field');\n }\n if (raw.schema_version !== 1 || !Array.isArray(raw.profiles)) {\n throw invalidTruth('Provider profile TruthStore body has an unsupported schema');\n }\n if (raw.profiles.length > MAX_PROVIDER_PROFILES) {\n throw invalidTruth('Provider profile TruthStore body exceeds the provider registry bound');\n }\n let profiles: ModelProviderProfile[];\n try {\n profiles = raw.profiles.map((candidate) => {\n if (!isPlainRecord(candidate) || !hasExactKeys(candidate, PROFILE_KEYS)) {\n throw invalidTruth('Provider profile TruthStore body contains an unknown profile field');\n }\n return parseModelProviderProfile(candidate);\n });\n } catch (cause) {\n if (cause instanceof ByokKeysError && cause.code === 'PROVIDER_TRUTH_INVALID') {\n throw cause;\n }\n throw invalidTruth('Provider profile TruthStore body contains an invalid profile', cause);\n }\n assertRegistryInvariants(profiles);\n if (record.body.body !== encodeRegistry(profiles)) {\n throw invalidTruth('Provider profile TruthStore body is not in canonical form');\n }\n return { profiles, rev: record.rev };\n}\n\nfunction assertRegistryInvariants(\n profiles: readonly ModelProviderProfile[],\n): void {\n const seen = new Set<ProviderProfileRef>();\n let enabled = 0;\n for (const profile of profiles) {\n if (seen.has(profile.profile_ref)) {\n throw invalidTruth(`Provider profile ${profile.profile_ref} appears more than once`);\n }\n seen.add(profile.profile_ref);\n if (profile.enabled) enabled += 1;\n }\n if (enabled > 1) {\n throw invalidTruth('Provider profile TruthStore body enables more than one provider');\n }\n}\n\nfunction hashBody(body: string) {\n const digest = createHash('sha256').update(body, 'utf8').digest('hex');\n return contentHash(`sha256:${digest}`);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasExactKeys(\n value: Record<string, unknown>,\n expected: readonly string[],\n): boolean {\n const keys = Object.keys(value).sort();\n const wanted = [...expected].sort();\n return keys.length === wanted.length && keys.every((key, index) => key === wanted[index]);\n}\n\nfunction invalidTruth(message: string, cause?: unknown): ByokKeysError {\n return new ByokKeysError('PROVIDER_TRUTH_INVALID', message, {\n ...(cause === undefined ? {} : { cause }),\n });\n}\n","import { AnthropicMessagesClient } from './anthropic-client';\nimport { ByokKeysError } from './errors';\nimport type { ProviderFetch } from './http';\nimport { OpenAiCompatibleChatClient } from './openai-client';\nimport type { ProviderProfileStore } from './profile-store';\nimport {\n type ModelProviderAdapter,\n type ModelProviderKind,\n type ModelProviderProfile,\n type ProviderAuthMode,\n type ProviderModelCapability,\n type ProviderProfileRef,\n exactProviderProfileBinding,\n parseModelProviderProfile,\n} from './provider-profile';\nimport {\n type ModelProviderSecretName,\n type SecretStore,\n modelProviderSecretName,\n} from './secret-store';\n\n/** A transport client for whichever dialect the resolved profile declares. */\nexport type ModelProviderClient =\n | AnthropicMessagesClient\n | OpenAiCompatibleChatClient;\n\n/**\n * What a caller supplies to {@link ProviderRegistry.configure}: the profile\n * minus the fields the registry owns (`kind`, both timestamps) and minus the\n * secret, which travels as a separate argument so it cannot be mistaken for\n * persisted data.\n */\nexport interface ProviderConfiguration {\n adapter: ModelProviderAdapter;\n auth_mode: ProviderAuthMode;\n base_url: string;\n /**\n * Bounded model capabilities this exact profile supports. Declared, never\n * inferred: an omitted capability means the endpoint does not offer it.\n */\n capabilities: readonly ProviderModelCapability[];\n display_name: string;\n /** Defaults to `true`: configuring a provider makes it the default. */\n enabled?: boolean;\n model: string;\n /** This profile's own local identity; several profiles may share one kind. */\n profile_ref: ProviderProfileRef;\n provider_kind: ModelProviderKind;\n}\n\n/**\n * The registry's outward projection of a profile.\n *\n * It reports **whether** a secret exists (`secret_configured`) and never the\n * secret itself — the property `registry.golden.test.ts` asserts, mirroring\n * `docs/researches/HANDOFF-byok-keys.md` §4.3's \"status JSON contains no\n * plaintext key\".\n */\nexport interface ProviderStatus {\n adapter: ModelProviderAdapter;\n auth_mode: ProviderAuthMode;\n base_url: string;\n capabilities: readonly ProviderModelCapability[];\n created_at: string;\n display_name: string;\n enabled: boolean;\n model: string;\n profile_ref: ProviderProfileRef;\n /** Canonical credential-free revision used by exact task admission. */\n profile_revision: string;\n /** SHA-256 of the normalized non-secret local record. */\n profile_hash: string;\n provider_kind: ModelProviderKind;\n /** Whether the credential store currently holds this profile's key. */\n secret_configured: boolean;\n updated_at: string;\n}\n\nexport interface ProviderRegistryOptions {\n fetchImpl?: ProviderFetch;\n /** Injected clock, so tests get deterministic timestamps. */\n now?: () => Date;\n profileStore: ProviderProfileStore;\n secretStore: SecretStore<ModelProviderSecretName>;\n}\n\n/**\n * The configure/resolve boundary, ported from `providers.ts:1180-1229`\n * (`configure`) and `providers.ts:1331-1354` (`resolveDefaultModelProvider`).\n *\n * Both halves of a provider's configuration are written here and nowhere else:\n * the non-secret profile goes to the injected {@link ProviderProfileStore}, the\n * API key goes to the injected {@link SecretStore}. Splitting them is the whole\n * point of the package, so the registry is the only place that knows both.\n *\n * Two departures from the source, both required by\n * `docs/researches/HANDOFF-byok-keys.md` §4.5:\n *\n * - `resolveDefaultModelProvider` returns a transport client or `undefined`,\n * and throws on a broken configuration. The source returned an\n * `UnavailableNarrativeProvider` null-object carrying an error code, which is\n * a narrative-domain symbol that stays in aip-main-open — and a degradation\n * fallback this package's fail-closed rule does not permit. A caller that\n * wants aip's behaviour catches `ByokKeysError` and reads `.code`, which is\n * the same information the null-object carried.\n * - The source's `#migrateLegacyModelSecret` is not ported (legacy secret\n * migration is out of scope per the plan).\n */\nexport class ProviderRegistry {\n readonly #fetch: ProviderFetch | undefined;\n readonly #now: () => Date;\n readonly #profiles: ProviderProfileStore;\n readonly #secrets: SecretStore<ModelProviderSecretName>;\n\n constructor(options: ProviderRegistryOptions) {\n this.#fetch = options.fetchImpl;\n this.#now = options.now ?? (() => new Date());\n this.#profiles = options.profileStore;\n this.#secrets = options.secretStore;\n }\n\n async close(): Promise<void> {\n await this.#profiles.close();\n }\n\n /**\n * Persist a provider's profile and, when supplied, its secret\n * (`providers.ts:1180-1229`).\n *\n * Order matters and is the source's: write the secret first, then require\n * that an authenticating profile actually has one, and only then save the\n * profile. A profile is therefore never persisted in a state that claims\n * authentication it cannot perform.\n */\n async configure(\n configuration: ProviderConfiguration,\n secret?: string,\n ): Promise<ProviderStatus> {\n const previous = await this.#profiles.get(configuration.profile_ref);\n const observedNow = this.#now().getTime();\n const previousRevision = previous === undefined ? undefined : Date.parse(previous.updated_at);\n const revision = previousRevision === undefined\n ? observedNow\n : Math.max(observedNow, previousRevision + 1);\n if (!Number.isSafeInteger(revision) || revision < 0) {\n throw new ByokKeysError('PROVIDER_PROFILE_INVALID', 'Provider clock cannot produce a monotonic profile revision');\n }\n const timestamp = new Date(revision).toISOString();\n const profile = parseModelProviderProfile({\n ...configuration,\n capabilities: [...configuration.capabilities],\n created_at: previous?.created_at ?? timestamp,\n enabled: configuration.enabled ?? true,\n kind: 'model',\n updated_at: timestamp,\n });\n const secretName = modelProviderSecretName(configuration.profile_ref);\n let previousSecret: string | undefined;\n let secretWritten = false;\n\n if (configuration.auth_mode === 'none' && secret !== undefined) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_NOT_ALLOWED',\n 'A provider without authentication cannot accept a secret',\n );\n }\n if (secret !== undefined) {\n if (secret.length === 0) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_EMPTY',\n 'Provider secret cannot be empty',\n );\n }\n previousSecret = await this.#secrets.get(secretName);\n await this.#secrets.set(secretName, secret);\n secretWritten = true;\n }\n if (\n configuration.auth_mode !== 'none' &&\n !(await this.#secrets.has(secretName))\n ) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_MISSING',\n 'Provider authentication requires a secret in the operating-system credential store',\n );\n }\n\n let saved: ModelProviderProfile;\n try {\n saved = await this.#profiles.save(profile);\n } catch (cause) {\n if (secretWritten) {\n try {\n if (previousSecret === undefined) {\n await this.#secrets.delete(secretName);\n } else {\n await this.#secrets.set(secretName, previousSecret);\n }\n } catch (rollbackCause) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_ROLLBACK_FAILED',\n 'Provider profile write failed and the previous secret could not be restored',\n { cause: new AggregateError([cause, rollbackCause]) },\n );\n }\n }\n throw cause;\n }\n if (saved.auth_mode === 'none') {\n await this.#secrets.delete(secretName);\n }\n return this.#status(saved);\n }\n\n /** Remove a profile and its secret together. */\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n const removed = await this.#profiles.delete(profileRef);\n await this.#secrets.delete(modelProviderSecretName(profileRef));\n return removed;\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ProviderStatus | undefined> {\n const profile = await this.#profiles.get(profileRef);\n return profile === undefined ? undefined : this.#status(profile);\n }\n\n async list(): Promise<ProviderStatus[]> {\n return Promise.all(\n (await this.#profiles.list()).map((profile) => this.#status(profile)),\n );\n }\n\n /**\n * Build a client for the one enabled provider (`providers.ts:1331-1354`).\n *\n * `undefined` means \"nothing is configured\", which is a legitimate state a\n * caller must handle. A configured-but-broken provider throws instead — a\n * missing secret or an unusable profile is a fault, not an absence.\n */\n async resolveDefaultModelProvider(): Promise<ModelProviderClient | undefined> {\n const profile = await this.#profiles.getEnabled();\n if (profile === undefined) return undefined;\n const secret = await this.#secrets.get(\n modelProviderSecretName(profile.profile_ref),\n );\n const options = { fetchImpl: this.#fetch, profile, secret };\n return profile.adapter === 'anthropic'\n ? new AnthropicMessagesClient(options)\n : new OpenAiCompatibleChatClient(options);\n }\n\n /** Switch which configured profile is the default. */\n async setDefaultModelProvider(\n profileRef: ProviderProfileRef,\n ): Promise<ProviderStatus> {\n return this.#status(await this.#profiles.setEnabled(profileRef));\n }\n\n async #status(profile: ModelProviderProfile): Promise<ProviderStatus> {\n const binding = exactProviderProfileBinding(profile, []);\n return {\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n capabilities: profile.capabilities,\n created_at: profile.created_at,\n display_name: profile.display_name,\n enabled: profile.enabled,\n model: profile.model,\n profile_ref: profile.profile_ref,\n profile_revision: binding.profileRevision,\n profile_hash: binding.profileHash,\n provider_kind: profile.provider_kind,\n secret_configured: await this.#secrets.has(\n modelProviderSecretName(profile.profile_ref),\n ),\n updated_at: profile.updated_at,\n };\n }\n}\n","import type { ModelProviderProfile } from './provider-profile';\n\nexport const PI_PROJECTED_KEY_ENV = 'PI_PROVIDER_API_KEY';\n\n/** Keep projected providers disjoint from Pi built-ins so composition can never fall back to one. */\nexport function piProjectionProviderId(profileRef: string): string {\n return `byok-sdk-${profileRef}`;\n}\n\n/**\n * Credential-blind Pi configuration derived from one validated local profile.\n *\n * The projected provider is namespaced by the profile's own ref, not by its\n * provider kind, so two independently configured endpoints of the same kind\n * project to two distinct Pi providers instead of colliding on one. Model\n * `input` modalities are projected from the profile's declared capabilities —\n * declared local configuration is the only authority; nothing is inferred from\n * the model name or base URL.\n */\nexport function buildPiProviderProjection(profile: ModelProviderProfile): object {\n const projectedProviderId = piProjectionProviderId(profile.profile_ref);\n return {\n providers: {\n [projectedProviderId]: {\n baseUrl: profile.base_url,\n api:\n profile.adapter === 'anthropic'\n ? 'anthropic-messages'\n : 'openai-completions',\n ...(profile.auth_mode === 'none'\n ? {}\n : { apiKey: `$${PI_PROJECTED_KEY_ENV}` }),\n ...(profile.auth_mode === 'bearer' ? { authHeader: true } : {}),\n models: [\n {\n id: profile.model,\n name: profile.display_name,\n input: [\n 'text',\n ...(profile.capabilities.includes('image-input') ? ['image'] : []),\n ],\n },\n ],\n },\n },\n };\n}\n\n/**\n * Validate the credential-blind RPC argv the client may delegate, then bind\n * the Pi child to the namespaced projection and exact configured model.\n */\nexport function buildPiProviderArgs(\n profile: ModelProviderProfile,\n delegatedArgs: readonly string[],\n): string[] {\n let modeCount = 0;\n for (let index = 0; index < delegatedArgs.length; index += 1) {\n const flag = delegatedArgs[index];\n if (flag === '--no-tools') continue;\n if (flag === '--mode') {\n modeCount += 1;\n const value = delegatedArgs[index + 1];\n if (value !== 'rpc') throw new Error('Pi launcher requires --mode rpc');\n index += 1;\n continue;\n }\n if (flag === '--session' || flag === '--tools' || flag === '--exclude-tools') {\n const value = delegatedArgs[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`${flag} requires a value`);\n }\n index += 1;\n continue;\n }\n throw new Error(`Pi launcher does not allow delegated argument ${flag ?? '<missing>'}`);\n }\n if (modeCount !== 1) throw new Error('Pi launcher requires exactly one --mode rpc');\n\n return [\n ...delegatedArgs,\n '--provider',\n piProjectionProviderId(profile.profile_ref),\n '--model',\n profile.model,\n ];\n}\n"]}
|