@byok-sdk/keys 0.1.0 → 0.2.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/README.md +34 -15
- package/dist/bin/pi-provider-launcher.d.ts +2 -0
- package/dist/bin/pi-provider-launcher.js +1137 -0
- package/dist/bin/pi-provider-launcher.js.map +1 -0
- package/dist/errors.d.ts +4 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +340 -40
- package/dist/index.js.map +1 -1
- package/dist/pi-provider-launcher-core.d.ts +34 -0
- package/dist/pi-provider-projection.d.ts +11 -0
- package/dist/profile-store.d.ts +16 -16
- package/dist/registry.d.ts +1 -1
- package/dist/sqlite-profile-store.d.ts +11 -9
- package/dist/sqlite-support.d.ts +11 -3
- package/dist/truth-profile-store.d.ts +27 -0
- package/package.json +14 -7
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/registry.ts"],"names":[],"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;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AAA,CAAU,UAAA,EAAW;AAC1C,IAAA,IAAI,OAAA,KAAY,QAAW,OAAO,MAAA;AAClC,IAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,QAAA,CAAS,GAAA;AAAA,MACjC,uBAAA,CAAwB,QAAQ,WAAW;AAAA,KAC7C;AACA,IAAA,MAAM,UAAU,EAAE,SAAA,EAAW,IAAA,CAAK,MAAA,EAAQ,SAAS,MAAA,EAAO;AAC1D,IAAA,OAAO,OAAA,CAAQ,YAAY,WAAA,GACvB,IAAI,wBAAwB,OAAO,CAAA,GACnC,IAAI,0BAAA,CAA2B,OAAO,CAAA;AAAA,EAC5C;AAAA;AAAA,EAGA,MAAM,wBACJ,UAAA,EACyB;AACzB,IAAA,OAAO,KAAK,OAAA,CAAQ,IAAA,CAAK,SAAA,CAAU,UAAA,CAAW,UAAU,CAAC,CAAA;AAAA,EAC3D;AAAA,EAEA,MAAM,QAAQ,OAAA,EAAwD;AACpE,IAAA,OAAO;AAAA,MACL,SAAS,OAAA,CAAQ,OAAA;AAAA,MACjB,WAAW,OAAA,CAAQ,SAAA;AAAA,MACnB,UAAU,OAAA,CAAQ,QAAA;AAAA,MAClB,YAAY,OAAA,CAAQ,UAAA;AAAA,MACpB,cAAc,OAAA,CAAQ,YAAA;AAAA,MACtB,SAAS,OAAA,CAAQ,OAAA;AAAA,MACjB,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,aAAa,OAAA,CAAQ,WAAA;AAAA,MACrB,iBAAA,EAAmB,MAAM,IAAA,CAAK,QAAA,CAAS,GAAA;AAAA,QACrC,uBAAA,CAAwB,QAAQ,WAAW;AAAA,OAC7C;AAAA,MACA,YAAY,OAAA,CAAQ;AAAA,KACtB;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * Single error class for `@byok/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_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_STORE_UNAVAILABLE: 'PROVIDER_STORE_UNAVAILABLE',\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';\n\nimport { ByokKeysError } from './errors';\nimport { normalizeProviderUrl } from './url';\n\n/**\n * Model providers this package knows how to address. Ported from\n * `aip-main-open@c6a5385` `providers.ts:30-36` (`LOCAL_MODEL_PROVIDER_IDS`).\n */\nexport const MODEL_PROVIDER_IDS = [\n 'openai',\n 'deepseek',\n 'anthropic',\n 'custom',\n] as const;\n\nexport type ModelProviderId = (typeof MODEL_PROVIDER_IDS)[number];\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 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 provider_id: z.enum(MODEL_PROVIDER_IDS),\n updated_at: isoTimestamp('updated_at'),\n })\n .superRefine((profile, ctx) => {\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\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 type { ModelProviderId } 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 per model provider, ported verbatim from\n * `providers.ts:1624-1632`. The names carry no vendor branding — the branding\n * lives in the service prefix — so they travel unchanged and K4 needs no\n * migration.\n */\nexport const MODEL_PROVIDER_SECRET_NAMES = {\n anthropic: 'model-anthropic-api-key',\n custom: 'model-custom-api-key',\n deepseek: 'model-deepseek-api-key',\n openai: 'model-openai-api-key',\n} as const satisfies Record<ModelProviderId, string>;\n\nexport type ModelProviderSecretName =\n (typeof MODEL_PROVIDER_SECRET_NAMES)[keyof typeof MODEL_PROVIDER_SECRET_NAMES];\n\n/** Resolve a provider id to the credential-store entry holding its API key. */\nexport function modelProviderSecretName(\n providerId: ModelProviderId,\n): ModelProviderSecretName {\n return MODEL_PROVIDER_SECRET_NAMES[providerId];\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 { 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 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 #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.#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 'default-keychain',\n '-d',\n 'user',\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 ]);\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 ]);\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 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 ].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","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 ModelProviderId,\n type ModelProviderProfile,\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/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(): void;\n /** Remove `providerId`; `false` when it was not configured. */\n delete(providerId: ModelProviderId): boolean;\n /** Read one provider's profile, configured or not enabled alike. */\n get(providerId: ModelProviderId): ModelProviderProfile | undefined;\n /** The single enabled profile, or `undefined` when none is enabled. */\n getEnabled(): ModelProviderProfile | undefined;\n /** Every configured profile, ordered by provider id. */\n list(): ModelProviderProfile[];\n /** Insert or update `profile`, enforcing both invariants above. */\n save(profile: ModelProviderProfile): ModelProviderProfile;\n /**\n * Make `providerId` 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(providerId: ModelProviderId): ModelProviderProfile;\n}\n\n/** Shared by both implementations so their error text cannot drift apart. */\nexport function providerNotConfigured(\n providerId: ModelProviderId,\n): ByokKeysError {\n return new ByokKeysError(\n 'PROVIDER_NOT_CONFIGURED',\n `${providerId} 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/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<ModelProviderId, ModelProviderProfile>();\n\n close(): void {\n this.#profiles.clear();\n }\n\n delete(providerId: ModelProviderId): boolean {\n return this.#profiles.delete(providerId);\n }\n\n get(providerId: ModelProviderId): ModelProviderProfile | undefined {\n return this.#profiles.get(providerId);\n }\n\n getEnabled(): ModelProviderProfile | undefined {\n return this.list().find((profile) => profile.enabled);\n }\n\n list(): ModelProviderProfile[] {\n return [...this.#profiles.values()].sort((left, right) =>\n left.provider_id.localeCompare(right.provider_id),\n );\n }\n\n save(profile: ModelProviderProfile): ModelProviderProfile {\n const validated = parseModelProviderProfile({\n ...profile,\n created_at:\n this.#profiles.get(profile.provider_id)?.created_at ??\n profile.created_at,\n });\n if (validated.enabled) {\n for (const [providerId, existing] of this.#profiles) {\n if (providerId !== validated.provider_id && existing.enabled) {\n this.#profiles.set(providerId, { ...existing, enabled: false });\n }\n }\n }\n this.#profiles.set(validated.provider_id, validated);\n return validated;\n }\n\n setEnabled(providerId: ModelProviderId): ModelProviderProfile {\n const existing = this.#profiles.get(providerId);\n if (existing === undefined) throw providerNotConfigured(providerId);\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\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/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/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): DatabaseSync {\n const { DatabaseSync } = loadSqliteModule();\n if (path !== ':memory:') {\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 if (path !== ':memory:') {\n database.exec('PRAGMA journal_mode = WAL');\n database.exec('PRAGMA synchronous = FULL');\n }\n return database;\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 {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n MODEL_PROVIDER_IDS,\n type ModelProviderId,\n type ModelProviderProfile,\n parseModelProviderProfile,\n} from './provider-profile';\nimport {\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/server`'s `SqliteTaskStore`.\n */\n path: string;\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 provider_id TEXT PRIMARY KEY CHECK (provider_id 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 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 created_at: string;\n display_name: string;\n enabled: number;\n kind: string;\n model: string;\n provider_id: string;\n updated_at: string;\n}\n\n/**\n * SQLite-backed {@link ProviderProfileStore}, following `@byok/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 this.#database.exec(SCHEMA);\n this.#database.exec(ENABLED_INDEX);\n secureSqliteFilePermissions(options.path);\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 close(): void {\n if (this.#closed) return;\n this.#closed = true;\n this.#database.close();\n }\n\n delete(providerId: ModelProviderId): boolean {\n const result = this.#database\n .prepare('DELETE FROM provider_profile WHERE provider_id = ?')\n .run(providerId);\n return Number(result.changes) === 1;\n }\n\n get(providerId: ModelProviderId): ModelProviderProfile | undefined {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE provider_id = ?')\n .get(providerId) as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n getEnabled(): 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 list(): ModelProviderProfile[] {\n const rows = this.#database\n .prepare('SELECT * FROM provider_profile ORDER BY provider_id ASC')\n .all() as unknown as ProfileRow[];\n return rows.map(parseRow);\n }\n\n save(profile: ModelProviderProfile): ModelProviderProfile {\n const validated = parseModelProviderProfile({\n ...profile,\n created_at: this.get(profile.provider_id)?.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 provider_id <> ?',\n )\n .run(validated.provider_id);\n }\n this.#database\n .prepare(\n `INSERT INTO provider_profile (\n provider_id, kind, adapter, display_name, base_url,\n auth_mode, model, enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(provider_id) DO UPDATE SET\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 enabled = excluded.enabled,\n updated_at = excluded.updated_at`,\n )\n .run(\n validated.provider_id,\n validated.kind,\n validated.adapter,\n validated.display_name,\n validated.base_url,\n validated.auth_mode,\n validated.model,\n validated.enabled ? 1 : 0,\n validated.created_at,\n validated.updated_at,\n );\n });\n return this.get(validated.provider_id) as ModelProviderProfile;\n }\n\n setEnabled(providerId: ModelProviderId): ModelProviderProfile {\n const existing = this.get(providerId);\n if (existing === undefined) throw providerNotConfigured(providerId);\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, so it is converted rather than coerced loosely.\n */\nfunction parseRow(row: ProfileRow): ModelProviderProfile {\n return parseModelProviderProfile({\n ...row,\n enabled: row.enabled === 1,\n });\n}\n\n/** Exported for the store's own tests to enumerate the CHECK-constrained ids. */\nexport const SQLITE_PROFILE_PROVIDER_IDS = MODEL_PROVIDER_IDS;\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 ModelProviderId,\n type ModelProviderProfile,\n type ProviderAuthMode,\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 display_name: string;\n /** Defaults to `true`: configuring a provider makes it the default. */\n enabled?: boolean;\n model: string;\n provider_id: ModelProviderId;\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 created_at: string;\n display_name: string;\n enabled: boolean;\n model: string;\n provider_id: ModelProviderId;\n /** Whether the credential store currently holds this provider'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 close(): void {\n 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 timestamp = this.#now().toISOString();\n const previous = this.#profiles.get(configuration.provider_id);\n const profile = {\n ...configuration,\n created_at: previous?.created_at ?? timestamp,\n enabled: configuration.enabled ?? true,\n kind: 'model',\n updated_at: timestamp,\n } as ModelProviderProfile;\n const secretName = modelProviderSecretName(configuration.provider_id);\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 await this.#secrets.set(secretName, secret);\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 const saved = this.#profiles.save(profile);\n if (saved.auth_mode === 'none') {\n await this.#secrets.delete(secretName);\n }\n return this.#status(saved);\n }\n\n /** Remove a provider's profile and its secret together. */\n async delete(providerId: ModelProviderId): Promise<boolean> {\n const removed = this.#profiles.delete(providerId);\n await this.#secrets.delete(modelProviderSecretName(providerId));\n return removed;\n }\n\n async get(providerId: ModelProviderId): Promise<ProviderStatus | undefined> {\n const profile = this.#profiles.get(providerId);\n return profile === undefined ? undefined : this.#status(profile);\n }\n\n async list(): Promise<ProviderStatus[]> {\n return Promise.all(\n 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 = this.#profiles.getEnabled();\n if (profile === undefined) return undefined;\n const secret = await this.#secrets.get(\n modelProviderSecretName(profile.provider_id),\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 provider is the default. */\n async setDefaultModelProvider(\n providerId: ModelProviderId,\n ): Promise<ProviderStatus> {\n return this.#status(this.#profiles.setEnabled(providerId));\n }\n\n async #status(profile: ModelProviderProfile): Promise<ProviderStatus> {\n return {\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n created_at: profile.created_at,\n display_name: profile.display_name,\n enabled: profile.enabled,\n model: profile.model,\n provider_id: profile.provider_id,\n secret_configured: await this.#secrets.has(\n modelProviderSecretName(profile.provider_id),\n ),\n updated_at: profile.updated_at,\n };\n }\n}\n"]}
|
|
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"],"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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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;AAAA;AAChB;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';\n\nimport { ByokKeysError } from './errors';\nimport { normalizeProviderUrl } from './url';\n\n/**\n * Model providers this package knows how to address. Ported from\n * `aip-main-open@c6a5385` `providers.ts:30-36` (`LOCAL_MODEL_PROVIDER_IDS`).\n */\nexport const MODEL_PROVIDER_IDS = [\n 'openai',\n 'deepseek',\n 'anthropic',\n 'custom',\n] as const;\n\nexport type ModelProviderId = (typeof MODEL_PROVIDER_IDS)[number];\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 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 provider_id: z.enum(MODEL_PROVIDER_IDS),\n updated_at: isoTimestamp('updated_at'),\n })\n .superRefine((profile, ctx) => {\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\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 type { ModelProviderId } 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 per model provider, ported verbatim from\n * `providers.ts:1624-1632`. The names carry no vendor branding — the branding\n * lives in the service prefix — so they travel unchanged and K4 needs no\n * migration.\n */\nexport const MODEL_PROVIDER_SECRET_NAMES = {\n anthropic: 'model-anthropic-api-key',\n custom: 'model-custom-api-key',\n deepseek: 'model-deepseek-api-key',\n openai: 'model-openai-api-key',\n} as const satisfies Record<ModelProviderId, string>;\n\nexport type ModelProviderSecretName =\n (typeof MODEL_PROVIDER_SECRET_NAMES)[keyof typeof MODEL_PROVIDER_SECRET_NAMES];\n\n/** Resolve a provider id to the credential-store entry holding its API key. */\nexport function modelProviderSecretName(\n providerId: ModelProviderId,\n): ModelProviderSecretName {\n return MODEL_PROVIDER_SECRET_NAMES[providerId];\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 { 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 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 #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.#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 'default-keychain',\n '-d',\n 'user',\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 ]);\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 ]);\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 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 ].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","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 ModelProviderId,\n type ModelProviderProfile,\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 `providerId`; `false` when it was not configured. */\n delete(providerId: ModelProviderId): Promise<boolean>;\n /** Read one provider's profile, configured or not enabled alike. */\n get(providerId: ModelProviderId): 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 provider id. */\n list(): Promise<ModelProviderProfile[]>;\n /** Insert or update `profile`, enforcing both invariants above. */\n save(profile: ModelProviderProfile): Promise<ModelProviderProfile>;\n /**\n * Make `providerId` 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(providerId: ModelProviderId): Promise<ModelProviderProfile>;\n}\n\n/** Shared by both implementations so their error text cannot drift apart. */\nexport function providerNotConfigured(\n providerId: ModelProviderId,\n): ByokKeysError {\n return new ByokKeysError(\n 'PROVIDER_NOT_CONFIGURED',\n `${providerId} 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<ModelProviderId, ModelProviderProfile>();\n\n async close(): Promise<void> {\n this.#profiles.clear();\n }\n\n async delete(providerId: ModelProviderId): Promise<boolean> {\n return this.#profiles.delete(providerId);\n }\n\n async get(providerId: ModelProviderId): Promise<ModelProviderProfile | undefined> {\n return this.#profiles.get(providerId);\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.provider_id.localeCompare(right.provider_id),\n );\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const validated = parseModelProviderProfile({\n ...profile,\n created_at:\n this.#profiles.get(profile.provider_id)?.created_at ??\n profile.created_at,\n });\n if (validated.enabled) {\n for (const [providerId, existing] of this.#profiles) {\n if (providerId !== validated.provider_id && existing.enabled) {\n this.#profiles.set(providerId, { ...existing, enabled: false });\n }\n }\n }\n this.#profiles.set(validated.provider_id, validated);\n return validated;\n }\n\n async setEnabled(providerId: ModelProviderId): Promise<ModelProviderProfile> {\n const existing = this.#profiles.get(providerId);\n if (existing === undefined) throw providerNotConfigured(providerId);\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 {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n MODEL_PROVIDER_IDS,\n type ModelProviderId,\n type ModelProviderProfile,\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 provider_id TEXT PRIMARY KEY CHECK (provider_id 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 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 created_at: string;\n display_name: string;\n enabled: number;\n kind: string;\n model: string;\n provider_id: 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(providerId: ModelProviderId): Promise<boolean> {\n const result = this.#database\n .prepare('DELETE FROM provider_profile WHERE provider_id = ?')\n .run(providerId);\n return Number(result.changes) === 1;\n }\n\n async get(providerId: ModelProviderId): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE provider_id = ?')\n .get(providerId) 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 provider_id 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.provider_id);\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 provider_id <> ?',\n )\n .run(validated.provider_id);\n }\n this.#database\n .prepare(\n `INSERT INTO provider_profile (\n provider_id, kind, adapter, display_name, base_url,\n auth_mode, model, enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(provider_id) DO UPDATE SET\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 enabled = excluded.enabled,\n updated_at = excluded.updated_at`,\n )\n .run(\n validated.provider_id,\n validated.kind,\n validated.adapter,\n validated.display_name,\n validated.base_url,\n validated.auth_mode,\n validated.model,\n validated.enabled ? 1 : 0,\n validated.created_at,\n validated.updated_at,\n );\n });\n return (await this.get(validated.provider_id)) as ModelProviderProfile;\n }\n\n async setEnabled(providerId: ModelProviderId): Promise<ModelProviderProfile> {\n const existing = await this.get(providerId);\n if (existing === undefined) throw providerNotConfigured(providerId);\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, so it is converted rather than coerced loosely.\n */\nfunction parseRow(row: ProfileRow): ModelProviderProfile {\n return parseModelProviderProfile({\n ...row,\n enabled: row.enabled === 1,\n });\n}\n\n/** Exported for the store's own tests to enumerate the CHECK-constrained ids. */\nexport const SQLITE_PROFILE_PROVIDER_IDS = MODEL_PROVIDER_IDS;\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 MODEL_PROVIDER_IDS,\n type ModelProviderId,\n type ModelProviderProfile,\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 'created_at',\n 'display_name',\n 'enabled',\n 'kind',\n 'model',\n 'provider_id',\n 'updated_at',\n] as const;\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(providerId: ModelProviderId): Promise<boolean> {\n const current = await this.#load();\n if (!current.profiles.some((profile) => profile.provider_id === providerId)) {\n return false;\n }\n await this.#write(\n current.profiles.filter((profile) => profile.provider_id !== providerId),\n current.rev,\n );\n return true;\n }\n\n async get(providerId: ModelProviderId): Promise<ModelProviderProfile | undefined> {\n return (await this.#load()).profiles.find(\n (profile) => profile.provider_id === providerId,\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.provider_id === profile.provider_id,\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.provider_id !== validated.provider_id)\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(providerId: ModelProviderId): Promise<ModelProviderProfile> {\n const current = await this.#load();\n const selected = current.profiles.find(\n (profile) => profile.provider_id === providerId,\n );\n if (selected === undefined) throw providerNotConfigured(providerId);\n const next = current.profiles.map((profile) => ({\n ...profile,\n enabled: profile.provider_id === providerId,\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.provider_id.localeCompare(right.provider_id));\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 created_at: profile.created_at,\n display_name: profile.display_name,\n enabled: profile.enabled,\n kind: profile.kind,\n model: profile.model,\n provider_id: profile.provider_id,\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 > MODEL_PROVIDER_IDS.length) {\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<ModelProviderId>();\n let enabled = 0;\n for (const profile of profiles) {\n if (seen.has(profile.provider_id)) {\n throw invalidTruth(`Provider profile ${profile.provider_id} appears more than once`);\n }\n seen.add(profile.provider_id);\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 ModelProviderId,\n type ModelProviderProfile,\n type ProviderAuthMode,\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 display_name: string;\n /** Defaults to `true`: configuring a provider makes it the default. */\n enabled?: boolean;\n model: string;\n provider_id: ModelProviderId;\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 created_at: string;\n display_name: string;\n enabled: boolean;\n model: string;\n provider_id: ModelProviderId;\n /** Whether the credential store currently holds this provider'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 timestamp = this.#now().toISOString();\n const previous = await this.#profiles.get(configuration.provider_id);\n const profile = parseModelProviderProfile({\n ...configuration,\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.provider_id);\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 provider's profile and its secret together. */\n async delete(providerId: ModelProviderId): Promise<boolean> {\n const removed = await this.#profiles.delete(providerId);\n await this.#secrets.delete(modelProviderSecretName(providerId));\n return removed;\n }\n\n async get(providerId: ModelProviderId): Promise<ProviderStatus | undefined> {\n const profile = await this.#profiles.get(providerId);\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.provider_id),\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 provider is the default. */\n async setDefaultModelProvider(\n providerId: ModelProviderId,\n ): Promise<ProviderStatus> {\n return this.#status(await this.#profiles.setEnabled(providerId));\n }\n\n async #status(profile: ModelProviderProfile): Promise<ProviderStatus> {\n return {\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n created_at: profile.created_at,\n display_name: profile.display_name,\n enabled: profile.enabled,\n model: profile.model,\n provider_id: profile.provider_id,\n secret_configured: await this.#secrets.has(\n modelProviderSecretName(profile.provider_id),\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(profileProviderId: string): string {\n return `byok-sdk-${profileProviderId}`;\n}\n\n/** Credential-blind Pi configuration derived from one validated local profile. */\nexport function buildPiProviderProjection(profile: ModelProviderProfile): object {\n const projectedProviderId = piProjectionProviderId(profile.provider_id);\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 },\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.provider_id),\n '--model',\n profile.model,\n ];\n}\n"]}
|