@byok-sdk/keys 0.3.10 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors.ts","../../src/command-runner.ts","../../src/secret-name.ts","../../src/url.ts","../../src/provider-profile.ts","../../src/secret-store.ts","../../src/macos-keychain.ts","../../src/pi-provider-projection.ts","../../src/pi-provider-launcher-core.ts","../../src/profile-store.ts","../../src/sqlite-support.ts","../../src/sqlite-profile-store.ts","../../src/windows-credential-manager.ts","../../src/bin/pi-provider-launcher.ts"],"names":["path","fs","spawn"],"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,CAAA;ACGA,eAAsB,UAAA,CACpB,UAAA,EACA,IAAA,EACA,KAAA,EACwB;AACxB,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,aAAA,KAAkB;AACpC,IAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,UAAA,EAAY,IAAA,EAAM;AAAA,MACpC,KAAK,OAAA,CAAQ,GAAA;AAAA,MACb,KAAA,EAAO,CAAC,MAAA,EAAQ,MAAA,EAAQ,MAAM;AAAA,KAC/B,CAAA;AACD,IAAA,IAAI,MAAA,GAAS,EAAA;AACb,IAAA,IAAI,MAAA,GAAS,EAAA;AACb,IAAA,KAAA,CAAM,MAAA,CAAO,YAAY,MAAM,CAAA;AAC/B,IAAA,KAAA,CAAM,MAAA,CAAO,YAAY,MAAM,CAAA;AAC/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AAyB,OAAO;AAAA,CAAI,CAAA;AACzD,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF;AAEA,KAAK,IAAA,EAAK","file":"pi-provider-launcher.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 { 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';\n\n/**\n * Normalize a provider base URL, fail-closed.\n *\n * Ported from `aip-main-open@c6a5385` `providers.ts:1558-1588` plus the two\n * host predicates at `:2216-2242`. Rules, unchanged:\n * - must be an absolute URL;\n * - no embedded credentials, no fragment, no query string;\n * - HTTPS only, except that HTTP is allowed for loopback hosts;\n * - private-network literals are rejected unless they are loopback;\n * - one trailing slash is stripped.\n */\nexport function normalizeProviderUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider base URL must be absolute',\n );\n }\n if (\n url.username ||\n url.password ||\n url.hash ||\n url.search ||\n (url.protocol !== 'https:' &&\n !(url.protocol === 'http:' && isLoopbackHost(url.hostname)))\n ) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider URL requires HTTPS; HTTP is allowed only for localhost',\n );\n }\n if (isPrivateNetworkLiteral(url.hostname) && !isLoopbackHost(url.hostname)) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Private-network provider IPs are not allowed',\n );\n }\n return url.toString().replace(/\\/$/u, '');\n}\n\n/** Whether an already-parseable provider URL points at a loopback host. */\nexport function isLoopbackProviderUrl(value: string): boolean {\n return isLoopbackHost(new URL(value).hostname);\n}\n\nexport function isLoopbackHost(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n return value === 'localhost' || value === '127.0.0.1' || value === '::1';\n}\n\n/**\n * Conservative private-network literal check. Any IPv6 literal counts as\n * private (the `:` branch), matching the source: the guard cannot cheaply\n * classify IPv6 ranges, so it refuses all of them and lets hostnames through.\n */\nexport function isPrivateNetworkLiteral(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n if (value.includes(':')) return true;\n const parts = value.split('.').map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n return (\n parts[0] === 10 ||\n parts[0] === 127 ||\n (parts[0] === 169 && parts[1] === 254) ||\n (parts[0] === 172 && (parts[1] ?? 0) >= 16 && (parts[1] ?? 0) <= 31) ||\n (parts[0] === 192 && parts[1] === 168)\n );\n}\n","import { z } from 'zod';\nimport { createHash } from 'node:crypto';\n\nimport { ByokKeysError } from './errors';\nimport { normalizeProviderUrl } from './url';\n\n/**\n * Opaque, portable identity of one locally configured provider profile.\n *\n * This is the profile's primary key: it is a local logical id, never a path,\n * and several profiles may share one {@link MODEL_PROVIDER_KINDS} kind (two\n * independent `custom` endpoints, for example). It replaces the former\n * `MODEL_PROVIDER_IDS` primary key, which conflated instance identity with\n * provider kind and therefore allowed exactly one profile per kind.\n *\n * `@byok-sdk/protocol` declares the same lexical rule for the wire form in\n * `provider-profile-binding.ts`. The two definitions are deliberately parallel\n * rather than shared: the release graph (`scripts/release/check-package-graph.mjs`)\n * forbids `@byok-sdk/keys` from depending on any dispatch package, so the\n * device-local authority cannot import the wire authority. This mirrors how\n * `packages/protocol/src/blob.ts`'s `CONTENT_HASH_RE` restates\n * `packages/core/src/blob.ts`'s content-hash format across the same boundary.\n */\nexport const PROVIDER_PROFILE_REF_PATTERN =\n /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/u;\n\nexport const ProviderProfileRefSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(\n PROVIDER_PROFILE_REF_PATTERN,\n 'provider profile refs must be lowercase portable identifiers',\n );\n\nexport type ProviderProfileRef = z.infer<typeof ProviderProfileRefSchema>;\n\n/**\n * Provider kinds this package knows how to address — the surviving half of the\n * former `MODEL_PROVIDER_IDS`. A kind says *what dialect family and vendor\n * shape* a profile is; {@link ProviderProfileRefSchema} says *which* profile.\n * Ported from `aip-main-open@c6a5385` `providers.ts:30-36`\n * (`LOCAL_MODEL_PROVIDER_IDS`).\n */\nexport const MODEL_PROVIDER_KINDS = [\n 'openai',\n 'deepseek',\n 'anthropic',\n 'custom',\n] as const;\n\nexport type ModelProviderKind = (typeof MODEL_PROVIDER_KINDS)[number];\n\n/**\n * Bounded model capabilities a profile may declare. A capability is explicit\n * local configuration, never inferred from the model name or the base URL.\n */\nexport const PROVIDER_MODEL_CAPABILITIES = ['image-input'] as const;\n\nexport const ProviderModelCapabilitySchema = z.enum(PROVIDER_MODEL_CAPABILITIES);\n\nexport type ProviderModelCapability = z.infer<\n typeof ProviderModelCapabilitySchema\n>;\n\n/** Auth modes a provider profile can request (`providers.ts:29`). */\nexport const PROVIDER_AUTH_MODES = ['bearer', 'x_api_key', 'none'] as const;\n\nexport type ProviderAuthMode = (typeof PROVIDER_AUTH_MODES)[number];\n\n/**\n * Wire dialects. The source's `market_data` / `mcp_http` branch stays in\n * aip-main-open — this package ports the model branch only\n * (`providers.ts:38-61`, second union member).\n */\nexport const MODEL_PROVIDER_ADAPTERS = ['openai_compatible', 'anthropic'] as const;\n\nexport type ModelProviderAdapter = (typeof MODEL_PROVIDER_ADAPTERS)[number];\n\n/**\n * Marker attached to schema issues so {@link parseModelProviderProfile} can\n * reproduce the source's distinct error codes: the URL guard reports\n * `PROVIDER_URL_INVALID`, everything else reports `PROVIDER_PROFILE_INVALID`.\n */\ninterface ProfileIssueParams {\n byokCode: string;\n}\n\nfunction boundedString(field: string, maximumLength: number) {\n return z\n .string()\n .superRefine((value, ctx) => {\n if (\n value.trim().length === 0 ||\n value.length > maximumLength ||\n /[\\u0000\\r\\n]/u.test(value)\n ) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} is invalid`,\n });\n }\n })\n .transform((value) => value.trim());\n}\n\nfunction isoTimestamp(field: string) {\n return boundedString(field, 64).superRefine((value, ctx) => {\n if (!Number.isFinite(Date.parse(value))) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} must be an ISO timestamp`,\n });\n }\n });\n}\n\nconst providerBaseUrl = z\n .string()\n .superRefine((value, ctx) => {\n try {\n normalizeProviderUrl(value);\n } catch (error) {\n ctx.addIssue({\n code: 'custom',\n message:\n error instanceof Error ? error.message : 'Provider base URL is invalid',\n params: {\n byokCode:\n error instanceof ByokKeysError ? error.code : 'PROVIDER_URL_INVALID',\n } satisfies ProfileIssueParams,\n });\n }\n })\n .transform((value) => normalizeProviderUrl(value));\n\n/**\n * A model provider profile: everything needed to address a provider except the\n * secret itself, which lives in the OS credential store.\n *\n * The adapter/auth-mode legality rules are the ones `normalizeProviderProfile`\n * enforced imperatively at `providers.ts:1522-1543`, moved into the schema so\n * there is one validation authority rather than a schema plus a normalizer.\n */\nexport const ModelProviderProfileSchema = z\n .object({\n adapter: z.enum(MODEL_PROVIDER_ADAPTERS),\n auth_mode: z.enum(PROVIDER_AUTH_MODES),\n base_url: providerBaseUrl,\n capabilities: z.array(ProviderModelCapabilitySchema).max(8),\n created_at: isoTimestamp('created_at'),\n display_name: boundedString('display_name', 100),\n enabled: z.boolean(),\n kind: z.literal('model'),\n model: boundedString('model', 160),\n profile_ref: ProviderProfileRefSchema,\n provider_kind: z.enum(MODEL_PROVIDER_KINDS),\n updated_at: isoTimestamp('updated_at'),\n })\n .superRefine((profile, ctx) => {\n if (new Set(profile.capabilities).size !== profile.capabilities.length) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider capabilities cannot repeat',\n path: ['capabilities'],\n });\n }\n if (profile.adapter === 'anthropic' && profile.auth_mode !== 'x_api_key') {\n ctx.addIssue({\n code: 'custom',\n message: 'Anthropic requires x_api_key authentication',\n path: ['auth_mode'],\n });\n }\n if (\n profile.adapter === 'openai_compatible' &&\n profile.auth_mode === 'x_api_key'\n ) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'OpenAI-compatible providers support bearer or no authentication',\n path: ['auth_mode'],\n });\n }\n if (Date.parse(profile.updated_at) < Date.parse(profile.created_at)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider updated_at cannot precede created_at',\n path: ['updated_at'],\n });\n }\n });\n\n/** Validated, normalized profile. */\nexport type ModelProviderProfile = z.infer<typeof ModelProviderProfileSchema>;\n\n/** Pre-normalization shape callers may hand in. */\nexport type ModelProviderProfileInput = z.input<typeof ModelProviderProfileSchema>;\n\nexport interface ExactProviderProfileBinding {\n profileRef: ProviderProfileRef;\n profileRevision: string;\n profileHash: string;\n modelId: string;\n requiredCapabilities: readonly ProviderModelCapability[];\n}\n\n/**\n * Derive the credential-free wire identity from the normalized local record.\n * `updated_at` is the persisted monotonic revision authority; the hash covers\n * the complete normalized non-secret record with capability order\n * canonicalized. Secret values are not accepted by this type and therefore\n * cannot enter the digest or any mismatch message.\n */\nexport function exactProviderProfileBinding(\n profileInput: ModelProviderProfile,\n requiredCapabilities: readonly ProviderModelCapability[] = profileInput.capabilities,\n): ExactProviderProfileBinding {\n const profile = parseModelProviderProfile(profileInput);\n const revision = Date.parse(profile.updated_at);\n if (!Number.isSafeInteger(revision) || revision < 0) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider updated_at cannot be represented as a canonical revision',\n );\n }\n const normalizedCapabilities = [...profile.capabilities].sort();\n const canonical = JSON.stringify({\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n capabilities: normalizedCapabilities,\n kind: profile.kind,\n model: profile.model,\n profile_ref: profile.profile_ref,\n provider_kind: profile.provider_kind,\n });\n return {\n profileRef: profile.profile_ref,\n profileRevision: String(revision),\n profileHash: `sha256:${createHash('sha256').update(canonical).digest('hex')}`,\n modelId: profile.model,\n requiredCapabilities: [...requiredCapabilities],\n };\n}\n\n/** Fail closed unless every offered binding field matches local authority. */\nexport function assertExactProviderProfileBinding(\n profile: ModelProviderProfile,\n expected: ExactProviderProfileBinding,\n): void {\n if (new Set(expected.requiredCapabilities).size !== expected.requiredCapabilities.length) {\n throw new Error('provider profile required capabilities must be unique');\n }\n const actual = exactProviderProfileBinding(profile, expected.requiredCapabilities);\n if (actual.profileRef !== expected.profileRef) throw new Error('provider profile ref mismatch');\n if (actual.profileRevision !== expected.profileRevision) throw new Error('provider profile revision mismatch');\n if (actual.profileHash !== expected.profileHash) throw new Error('provider profile hash mismatch');\n if (actual.modelId !== expected.modelId) throw new Error('provider profile model mismatch');\n const supported = new Set(profile.capabilities);\n const unsupported = expected.requiredCapabilities.find((capability) => !supported.has(capability));\n if (unsupported !== undefined) throw new Error(`provider profile does not support required capability ${unsupported}`);\n}\n\n/**\n * Parse and normalize a profile, or throw {@link ByokKeysError}. Replaces the\n * source's `normalizeProviderProfile` (`providers.ts:1489-1556`) for the model\n * branch, preserving its error codes.\n */\nexport function parseModelProviderProfile(value: unknown): ModelProviderProfile {\n const result = ModelProviderProfileSchema.safeParse(value);\n if (result.success) return result.data;\n const issue = result.error.issues[0];\n const params = (issue as { params?: Partial<ProfileIssueParams> } | undefined)\n ?.params;\n throw new ByokKeysError(\n params?.byokCode ?? 'PROVIDER_PROFILE_INVALID',\n issue?.message ?? 'Provider profile is invalid',\n { cause: result.error },\n );\n}\n","import { ByokKeysError } from './errors';\nimport {\n ProviderProfileRefSchema,\n type ProviderProfileRef,\n} from './provider-profile';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\n\n/**\n * Storage contract for a single secret entry in an operating-system credential\n * store.\n *\n * Ported from `aip-main-open@c6a5385` `apps/local-agent/src/index.ts:261-269`\n * with two deliberate changes:\n *\n * 1. `TName` is a generic parameter rather than aip's closed\n * `KeychainSecretName` union. aip's union names device keys, refresh tokens,\n * and market-data entries that this package has no business knowing about,\n * so it stays in aip and consumers pin their own union. The compile-time\n * closure it provided is replaced at runtime by {@link assertSecretName},\n * which every implementation must apply on every name it receives.\n * 2. `scope()` is required, not optional. The source made it optional and its\n * `scopeLocalAgentSecretStore` silently substituted an envelope\n * implementation when a store did not provide one. Scope-envelope prefixing\n * has no installed base, so this package removes the implicit substitution:\n * every store scopes itself, and {@link EnvelopeScopedSecretStore} is a\n * decorator a caller applies on purpose.\n */\nexport interface SecretStore<TName extends string = string> {\n /** Human-readable backend name, safe to show a user. Never contains a secret. */\n readonly providerLabel: string;\n /** Whether this backend can be used on the current machine. Must not throw. */\n available(): Promise<boolean>;\n /** Remove `name`; `false` when it was already absent. */\n delete(name: TName): Promise<boolean>;\n /** Read `name`, or `undefined` when it is absent. */\n get(name: TName): Promise<string | undefined>;\n /** Whether `name` currently holds a secret. */\n has(name: TName): Promise<boolean>;\n /** A view of this store isolated under `namespace`. */\n scope(namespace: string): SecretStore<TName>;\n /** Write `secret` at `name`, replacing any existing value. */\n set(name: TName, secret: string): Promise<void>;\n}\n\n/**\n * Default service prefix for this package's own entries. `servicePrefix` is a\n * constructor option on both OS backends, so K4's aip-main-open swap passes its\n * `com.aiphabee.local-agent` value and keeps existing installs byte-compatible.\n */\nexport const DEFAULT_SECRET_SERVICE_PREFIX = 'com.byok.keys';\n\n/**\n * Credential-store entry name for one provider profile.\n *\n * The former fixed `MODEL_PROVIDER_SECRET_NAMES` table could name exactly one\n * entry per provider kind, so two independent `custom` endpoints would have\n * shared — and overwritten — a single credential. The name is now derived from\n * the profile's own {@link ProviderProfileRef}, keeping the shape\n * `providers.ts:1624-1632` established (`model-<id>-api-key`, no vendor\n * branding; the branding lives in the service prefix).\n */\nexport type ModelProviderSecretName = `model-${string}-api-key`;\n\n/**\n * Resolve a provider profile ref to the credential-store entry holding its API\n * key. The ref is validated here as well as by the profile schema: this\n * function composes a storage address, so an unvalidated ref would be an\n * address-injection surface rather than merely an invalid record.\n */\nexport function modelProviderSecretName(\n profileRef: ProviderProfileRef,\n): ModelProviderSecretName {\n const parsed = ProviderProfileRefSchema.safeParse(profileRef);\n if (!parsed.success) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider profile ref must be a lowercase portable identifier',\n { cause: parsed.error },\n );\n }\n return assertSecretName(`model-${parsed.data}-api-key` as const);\n}\n\n/**\n * The secret-shape invariant both OS backends share. Their size ceilings differ\n * in both magnitude and unit (macOS counts 16384 characters, Windows counts\n * 2560 UTF-8 bytes) and each reports its own error code, so those checks stay\n * in the backends; only the empty/control-character rule is common.\n */\nexport function assertSharedSecretValue(secret: string): void {\n if (secret.length === 0 || /[\\u0000\\r\\n]/u.test(secret)) {\n throw new ByokKeysError(\n 'SECRET_VALUE_INVALID',\n 'Secret must be a non-empty string without null or newline characters',\n );\n }\n}\n\n/**\n * Decode base64 to UTF-8 text, or return `undefined` — never a repaired\n * approximation.\n *\n * Both decode paths in Node are lenient in ways that matter here: `Buffer.from`\n * silently drops characters outside the base64 alphabet (so `\"a!G@k=\"` would\n * decode to `\"hi\"`), and `Buffer#toString('utf8')` substitutes U+FFFD for\n * invalid byte sequences. A credential store that \"successfully\" returns a\n * silently-mangled secret is worse than one that fails, so the alphabet, the\n * canonical padding, and the UTF-8 round trip are all checked explicitly.\n */\nexport function decodeStrictBase64Utf8(encoded: string): string | undefined {\n if (encoded.length % 4 !== 0) return undefined;\n if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(encoded)) return undefined;\n const bytes = Buffer.from(encoded, 'base64');\n if (bytes.toString('base64') !== encoded) return undefined;\n const text = bytes.toString('utf8');\n if (!Buffer.from(text, 'utf8').equals(bytes)) return undefined;\n return text;\n}\n\n/**\n * A {@link SecretStore} held in process memory, for tests and for embedders\n * that supply their own persistence.\n *\n * It keys entries by the same `` `${servicePrefix}.${name}` `` string the OS\n * backends use, and `scope()` extends that prefix exactly as they do, so a test\n * written against this store exercises the same isolation arithmetic as\n * production. It applies the name validator and the shared secret-shape rule;\n * the platform size ceilings deliberately are not simulated, since they differ\n * per backend.\n */\nexport class InMemorySecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'in-memory';\n readonly #entries: Map<string, string>;\n readonly #servicePrefix: string;\n\n constructor(\n options: {\n /** Shared backing map; a scoped view keeps the parent's map. */\n entries?: Map<string, string>;\n servicePrefix?: string;\n } = {},\n ) {\n this.#entries = options.entries ?? new Map();\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n }\n\n available(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n async delete(name: TName): Promise<boolean> {\n return this.#entries.delete(this.#service(name));\n }\n\n async get(name: TName): Promise<string | undefined> {\n return this.#entries.get(this.#service(name));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new InMemorySecretStore<TName>({\n entries: this.#entries,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n assertSharedSecretValue(secret);\n this.#entries.set(service, secret);\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n","import path from 'node:path';\n\nimport { type CommandRunner, runCommand } from './command-runner';\nimport { ByokKeysError } from './errors';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\nimport {\n DEFAULT_SECRET_SERVICE_PREFIX,\n type SecretStore,\n decodeStrictBase64Utf8,\n} from './secret-store';\n\n/**\n * Marker written in front of every stored value so a read can tell a value this\n * package wrote from anything else already sitting at the same service name.\n * Injectable, so K4's aip-main-open swap passes `aiphabee-b64-v1:` and stays\n * byte-compatible with existing installs (source: `index.ts:246`).\n */\nexport const DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX = 'byok-b64-v1:';\n\n/** `security` exits 44 for \"the item does not exist\". */\nconst SECURITY_ITEM_NOT_FOUND = 44;\n\nexport interface MacOsKeychainSecretStoreOptions {\n /** Keychain account field; entries are addressed by (account, service). */\n account?: string;\n /**\n * Return a stored value that lacks {@link MacOsKeychainSecretStoreOptions.storagePrefix}\n * instead of throwing. Defaults to `false`.\n *\n * The source returned such values unconditionally\n * (`decodeMacOsKeychainSecret`, `index.ts:536-545`), which meant any\n * unrelated item at the same service name was handed back as if this package\n * had written it. Reading is fail-closed here, and the tolerant behavior is\n * demoted to something a caller must ask for by name — it exists only for a\n * migration that has read an unprefixed value it already knows it wrote.\n */\n allowUnprefixedRead?: boolean;\n commandRunner?: CommandRunner;\n /** Explicit macOS keychain file; omitted means the user default keychain. */\n keychainPath?: string;\n platform?: NodeJS.Platform;\n servicePrefix?: string;\n storagePrefix?: string;\n}\n\n/**\n * macOS Keychain backend, driving `/usr/bin/security`\n * (`aip-main-open@c6a5385` `apps/local-agent/src/index.ts:412-533`).\n *\n * There is deliberately no plaintext fallback: on a non-darwin platform every\n * operation throws `KEYCHAIN_UNAVAILABLE` rather than degrading to a file.\n */\nexport class MacOsKeychainSecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'macOS Keychain';\n readonly #account: string;\n readonly #allowUnprefixedRead: boolean;\n readonly #commandRunner: CommandRunner;\n readonly #keychainPath: string | undefined;\n readonly #platform: NodeJS.Platform;\n readonly #servicePrefix: string;\n readonly #storagePrefix: string;\n\n constructor(options: MacOsKeychainSecretStoreOptions = {}) {\n this.#account = options.account ?? 'local-device';\n this.#allowUnprefixedRead = options.allowUnprefixedRead ?? false;\n this.#commandRunner = options.commandRunner ?? runCommand;\n this.#keychainPath = assertKeychainPath(options.keychainPath);\n this.#platform = options.platform ?? process.platform;\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n this.#storagePrefix =\n options.storagePrefix ?? DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX;\n }\n\n async available(): Promise<boolean> {\n if (this.#platform !== 'darwin') return false;\n const result = await this.#commandRunner('/usr/bin/security', [\n ...(this.#keychainPath === undefined\n ? ['default-keychain', '-d', 'user']\n : ['show-keychain-info', this.#keychainPath]),\n ]);\n return result.exitCode === 0;\n }\n\n async delete(name: TName): Promise<boolean> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'delete-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n ...(this.#keychainPath === undefined ? [] : [this.#keychainPath]),\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return false;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_DELETE_FAILED',\n 'macOS Keychain could not delete the requested secret',\n );\n }\n return true;\n }\n\n async get(name: TName): Promise<string | undefined> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'find-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n '-w',\n ...(this.#keychainPath === undefined ? [] : [this.#keychainPath]),\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return undefined;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_READ_FAILED',\n 'macOS Keychain could not read the requested secret',\n );\n }\n return this.#decode(result.stdout.replace(/\\r?\\n$/u, ''));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new MacOsKeychainSecretStore<TName>({\n account: this.#account,\n allowUnprefixedRead: this.#allowUnprefixedRead,\n commandRunner: this.#commandRunner,\n keychainPath: this.#keychainPath,\n platform: this.#platform,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n storagePrefix: this.#storagePrefix,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n this.#assertMacOs();\n if (\n secret.length === 0 ||\n secret.length > 16_384 ||\n /[\\u0000\\r\\n]/u.test(secret)\n ) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_INVALID',\n 'Secret must contain 1 to 16384 non-newline characters',\n );\n }\n // `security add-generic-password -w` opens /dev/tty when no password\n // argument is supplied, even if the child has a piped stdin. Interactive\n // mode accepts the complete command through stdin, keeping the encoded\n // secret out of argv/process listings and avoiding an unattended prompt.\n const storedSecret = `${this.#storagePrefix}${Buffer.from(secret, 'utf8').toString('base64')}`;\n const command = [\n 'add-generic-password',\n '-U',\n '-a',\n quoteSecurityInteractiveArgument(this.#account),\n '-s',\n quoteSecurityInteractiveArgument(service),\n '-w',\n quoteSecurityInteractiveArgument(storedSecret),\n ...(this.#keychainPath === undefined\n ? []\n : [quoteSecurityInteractiveArgument(this.#keychainPath)]),\n ].join(' ');\n const result = await this.#commandRunner(\n '/usr/bin/security',\n ['-i'],\n `${command}\\n`,\n );\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_WRITE_FAILED',\n 'macOS Keychain could not store the requested secret',\n );\n }\n }\n\n #assertMacOs(): void {\n if (this.#platform !== 'darwin') {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n 'macOS Keychain is required; plaintext fallback is disabled',\n );\n }\n }\n\n /**\n * Fail-closed inverse of the storage encoding. The error message never\n * echoes the undecodable value — it may still be somebody's live credential.\n */\n #decode(storedSecret: string): string {\n if (!storedSecret.startsWith(this.#storagePrefix)) {\n if (this.#allowUnprefixedRead) return storedSecret;\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a value without this store\\'s storage prefix',\n );\n }\n const decoded = decodeStrictBase64Utf8(\n storedSecret.slice(this.#storagePrefix.length),\n );\n if (decoded === undefined || decoded.length === 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a secret that is not valid base64-encoded UTF-8',\n );\n }\n return decoded;\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n\n/**\n * Quote a value for `security -i`'s interactive parser (`index.ts:547-557`).\n * Null and newline characters cannot be quoted safely — a newline would end the\n * command line and let the remainder be parsed as a second command — so they are\n * rejected rather than escaped.\n */\nfunction quoteSecurityInteractiveArgument(value: string): string {\n if (/[\\u0000\\r\\n]/u.test(value)) {\n throw new ByokKeysError(\n 'KEYCHAIN_ARGUMENT_INVALID',\n 'macOS Keychain arguments cannot contain null or newline characters',\n );\n }\n return `\"${value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')}\"`;\n}\n\nfunction assertKeychainPath(keychainPath: string | undefined): string | undefined {\n if (keychainPath === undefined) return undefined;\n if (\n keychainPath.length === 0 ||\n !path.posix.isAbsolute(keychainPath) ||\n /[\\u0000\\r\\n]/u.test(keychainPath)\n ) {\n throw new ByokKeysError(\n 'KEYCHAIN_ARGUMENT_INVALID',\n 'macOS keychain path must be a non-empty absolute single-line path',\n );\n }\n return keychainPath;\n}\n","import type { ModelProviderProfile } from './provider-profile';\n\nexport const PI_PROJECTED_KEY_ENV = 'PI_PROVIDER_API_KEY';\n\n/** Keep projected providers disjoint from Pi built-ins so composition can never fall back to one. */\nexport function piProjectionProviderId(profileRef: string): string {\n return `byok-sdk-${profileRef}`;\n}\n\n/**\n * Credential-blind Pi configuration derived from one validated local profile.\n *\n * The projected provider is namespaced by the profile's own ref, not by its\n * provider kind, so two independently configured endpoints of the same kind\n * project to two distinct Pi providers instead of colliding on one. Model\n * `input` modalities are projected from the profile's declared capabilities —\n * declared local configuration is the only authority; nothing is inferred from\n * the model name or base URL.\n */\nexport function buildPiProviderProjection(profile: ModelProviderProfile): object {\n const projectedProviderId = piProjectionProviderId(profile.profile_ref);\n return {\n providers: {\n [projectedProviderId]: {\n baseUrl: profile.base_url,\n api:\n profile.adapter === 'anthropic'\n ? 'anthropic-messages'\n : 'openai-completions',\n ...(profile.auth_mode === 'none'\n ? {}\n : { apiKey: `$${PI_PROJECTED_KEY_ENV}` }),\n ...(profile.auth_mode === 'bearer' ? { authHeader: true } : {}),\n models: [\n {\n id: profile.model,\n name: profile.display_name,\n input: [\n 'text',\n ...(profile.capabilities.includes('image-input') ? ['image'] : []),\n ],\n },\n ],\n },\n },\n };\n}\n\n/**\n * Validate the credential-blind RPC argv the client may delegate, then bind\n * the Pi child to the namespaced projection and exact configured model.\n */\nexport function buildPiProviderArgs(\n profile: ModelProviderProfile,\n delegatedArgs: readonly string[],\n): string[] {\n let modeCount = 0;\n for (let index = 0; index < delegatedArgs.length; index += 1) {\n const flag = delegatedArgs[index];\n if (flag === '--no-tools') continue;\n if (flag === '--mode') {\n modeCount += 1;\n const value = delegatedArgs[index + 1];\n if (value !== 'rpc') throw new Error('Pi launcher requires --mode rpc');\n index += 1;\n continue;\n }\n if (flag === '--session' || flag === '--tools' || flag === '--exclude-tools') {\n const value = delegatedArgs[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`${flag} requires a value`);\n }\n index += 1;\n continue;\n }\n throw new Error(`Pi launcher does not allow delegated argument ${flag ?? '<missing>'}`);\n }\n if (modeCount !== 1) throw new Error('Pi launcher requires exactly one --mode rpc');\n\n return [\n ...delegatedArgs,\n '--provider',\n piProjectionProviderId(profile.profile_ref),\n '--model',\n profile.model,\n ];\n}\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\n\nimport { ByokKeysError } from './errors';\nimport { PI_PROJECTED_KEY_ENV } from './pi-provider-projection';\nimport {\n ProviderModelCapabilitySchema,\n ProviderProfileRefSchema,\n type ExactProviderProfileBinding,\n type ModelProviderProfile,\n type ProviderProfileRef,\n} from './provider-profile';\nimport { type SecretStore, modelProviderSecretName } from './secret-store';\n\nconst PI_CHILD_BASE_ENV_NAMES = [\n 'PATH',\n 'HOME',\n 'USERPROFILE',\n 'TMPDIR',\n 'TEMP',\n 'TMP',\n 'LANG',\n 'TZ',\n 'TERM',\n 'SHELL',\n 'HTTP_PROXY',\n 'HTTPS_PROXY',\n 'NO_PROXY',\n 'ALL_PROXY',\n 'http_proxy',\n 'https_proxy',\n 'no_proxy',\n 'all_proxy',\n] as const;\n\nconst PI_CHILD_WINDOWS_ENV_NAMES = [\n 'SystemRoot',\n 'COMSPEC',\n 'PATHEXT',\n 'windir',\n 'SYSTEMDRIVE',\n 'PROGRAMFILES',\n 'APPDATA',\n 'LOCALAPPDATA',\n] as const;\n\nexport interface PiProviderLauncherOptions {\n piBin: string;\n profileDbPath: string;\n /** Carried by the `--provider` flag: the exact local profile to launch. */\n profileRef: ProviderProfileRef;\n modelId: string;\n expectedBinding?: ExactProviderProfileBinding;\n validateOnly: boolean;\n sessionDir: string;\n secretServicePrefix?: string;\n macosKeychainPath?: string;\n piArgs: string[];\n}\n\nexport function parsePiProviderLauncherOptions(\n args: string[],\n): PiProviderLauncherOptions {\n const separator = args.indexOf('--');\n const ownArgs = separator < 0 ? args : args.slice(0, separator);\n const piArgs = separator < 0 ? [] : args.slice(separator + 1);\n\n const allowedFlags = new Set([\n '--pi-bin',\n '--profile-db',\n '--provider',\n '--model',\n '--profile-revision',\n '--profile-hash',\n '--required-capabilities',\n '--validate-only',\n '--session-dir',\n '--secret-service-prefix',\n '--macos-keychain-path',\n ]);\n const values = new Map<string, string>();\n for (let index = 0; index < ownArgs.length; index += 2) {\n const flag = ownArgs[index];\n const value = ownArgs[index + 1];\n if (!flag || !allowedFlags.has(flag)) {\n throw new Error(`unknown launcher argument ${flag ?? '<missing>'}`);\n }\n if (values.has(flag)) throw new Error(`launcher argument ${flag} may only be provided once`);\n if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value`);\n if (/[\\u0000\\r\\n]/u.test(value)) {\n throw new Error(`${flag} must be a single-line value`);\n }\n values.set(flag, value);\n }\n\n const required = (flag: string): string => {\n const value = values.get(flag);\n if (value === undefined) throw new Error(`${flag} requires a value`);\n return value;\n };\n\n const rawProfileRef = required('--provider');\n const profileRef = ProviderProfileRefSchema.safeParse(rawProfileRef);\n if (!profileRef.success) {\n throw new Error(`provider profile ref ${rawProfileRef} is not a valid @byok-sdk/keys identifier`);\n }\n\n const modelId = required('--model');\n if (modelId.length > 160) throw new Error('--model exceeds 160 characters');\n\n const profileDbPath = required('--profile-db');\n const sessionDir = required('--session-dir');\n if (!path.isAbsolute(profileDbPath) || !path.isAbsolute(sessionDir)) {\n throw new Error('launcher profile database and session directory must be absolute paths');\n }\n\n const secretServicePrefix = values.get('--secret-service-prefix');\n const macosKeychainPath = values.get('--macos-keychain-path');\n if (macosKeychainPath !== undefined && !path.posix.isAbsolute(macosKeychainPath)) {\n throw new Error('--macos-keychain-path must be an absolute path');\n }\n const validateOnly = values.get('--validate-only') === 'true';\n if (values.has('--validate-only') && !['true', 'false'].includes(values.get('--validate-only')!)) {\n throw new Error('--validate-only must be true or false');\n }\n if (!validateOnly && piArgs.length === 0) {\n throw new Error('launcher requires Pi arguments after --');\n }\n const exactValues = [\n values.get('--profile-revision'),\n values.get('--profile-hash'),\n values.get('--required-capabilities'),\n ];\n if (exactValues.some((value) => value !== undefined) && exactValues.some((value) => value === undefined)) {\n throw new Error('exact provider binding requires revision, hash, and required capabilities together');\n }\n let expectedBinding: ExactProviderProfileBinding | undefined;\n if (exactValues[0] !== undefined) {\n if (!/^(?:0|[1-9][0-9]{0,19})$/u.test(exactValues[0])) {\n throw new Error('--profile-revision must be canonical decimal');\n }\n if (!/^sha256:[0-9a-f]{64}$/u.test(exactValues[1]!)) {\n throw new Error('--profile-hash must be lowercase sha256');\n }\n let capabilities: unknown;\n try {\n capabilities = JSON.parse(exactValues[2]!);\n } catch {\n throw new Error('--required-capabilities must be a JSON array');\n }\n const parsedCapabilities = ProviderModelCapabilitySchema.array().max(8).safeParse(capabilities);\n if (!parsedCapabilities.success || new Set(parsedCapabilities.data).size !== parsedCapabilities.data.length) {\n throw new Error('--required-capabilities must contain unique supported capabilities');\n }\n expectedBinding = {\n profileRef: profileRef.data,\n profileRevision: exactValues[0],\n profileHash: exactValues[1]!,\n modelId,\n requiredCapabilities: parsedCapabilities.data,\n };\n }\n return {\n piBin: required('--pi-bin'),\n profileDbPath,\n profileRef: profileRef.data,\n modelId,\n ...(expectedBinding === undefined ? {} : { expectedBinding }),\n validateOnly,\n sessionDir,\n ...(secretServicePrefix ? { secretServicePrefix } : {}),\n ...(macosKeychainPath !== undefined ? { macosKeychainPath } : {}),\n piArgs,\n };\n}\n\n/**\n * Resolve only the credential the validated profile requires. In particular,\n * an auth-free local provider must remain usable on hosts without an OS\n * credential backend; constructing a keychain there would invent a false\n * dependency and turn an explicit `auth_mode: none` into a hidden fallback.\n */\nexport async function resolvePiProviderSecret(\n profile: ModelProviderProfile,\n createStore: () => SecretStore,\n): Promise<string | undefined> {\n if (profile.auth_mode === 'none') return undefined;\n\n const secrets = createStore();\n if (!(await secrets.available())) {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n `${secrets.providerLabel} is unavailable`,\n );\n }\n const secret = await secrets.get(modelProviderSecretName(profile.profile_ref));\n if (!secret) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_MISSING',\n `${profile.profile_ref} provider profile requires a secret in ${secrets.providerLabel}`,\n );\n }\n return secret;\n}\n\n/** Build Pi's child environment from a closed platform baseline plus one exact key. */\nexport function buildPiProviderChildEnvironment(options: {\n ambient: NodeJS.ProcessEnv;\n projectionDir: string;\n sessionDir: string;\n secret: string | undefined;\n platform?: NodeJS.Platform;\n}): Record<string, string> {\n const platform = options.platform ?? process.platform;\n const exactNames = new Set<string>([\n ...PI_CHILD_BASE_ENV_NAMES,\n ...(platform === 'win32' ? PI_CHILD_WINDOWS_ENV_NAMES : []),\n ].map((name) => platform === 'win32' ? name.toUpperCase() : name));\n const result: Record<string, string> = {};\n for (const [name, value] of Object.entries(options.ambient)) {\n if (value === undefined) continue;\n const platformName = platform === 'win32' ? name.toUpperCase() : name;\n const isExact = exactNames.has(platformName);\n const isPrefixed = platform === 'win32'\n ? platformName.startsWith('LC_') || platformName.startsWith('XDG_')\n : name.startsWith('LC_') || name.startsWith('XDG_');\n if (isExact || isPrefixed) result[name] = value;\n }\n result.PI_CODING_AGENT_DIR = options.projectionDir;\n result.PI_CODING_AGENT_SESSION_DIR = options.sessionDir;\n if (options.secret !== undefined) {\n result[PI_PROJECTED_KEY_ENV] = options.secret;\n }\n return result;\n}\n\n/**\n * Create the configured session directory owner-only without mutating the\n * mode of an existing host-owned directory. The path is operator config, so\n * an accidental `/`, home, or shared-directory value must never become a\n * recursive chmod sink.\n */\nexport async function ensurePiSessionDirectory(sessionDir: string): Promise<void> {\n const firstCreated = await fs.mkdir(sessionDir, { recursive: true, mode: 0o700 });\n if (firstCreated !== undefined) {\n await fs.chmod(sessionDir, 0o700).catch(() => {});\n }\n const stat = await fs.stat(sessionDir);\n if (!stat.isDirectory()) {\n throw new Error('Pi session path must be a directory');\n }\n if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0) {\n throw new Error(\n 'existing Pi session directory must already be owner-only; refusing to change host-owned permissions',\n );\n }\n}\n","import { ByokKeysError } from './errors';\nimport {\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\n\n/**\n * Storage contract for provider profiles — everything needed to address a\n * provider except the API key, which lives in a {@link SecretStore}.\n *\n * Shaped after `@byok-sdk/server`'s `TaskStore` (`packages/server/src/task-store.ts`)\n * as a *pattern*, not a dependency: `keys` must not import `server`, and\n * `server` must not import `keys` (the plan's Security Boundary keeps the\n * agent-dispatch packages free of any credential-adjacent code).\n *\n * Two invariants every implementation MUST enforce, not just\n * {@link InMemoryProviderProfileStore}:\n *\n * 1. **At most one enabled profile.** The source expressed this as a partial\n * unique index (`providers.ts:140-144`); saving an enabled profile disables\n * every other one. {@link resolveDefaultModelProvider} relies on it to\n * answer \"which provider is the default\" with a single row.\n * 2. **Validate on write.** `save` runs {@link parseModelProviderProfile}, so an\n * invalid profile is refused at the boundary rather than discovered later by\n * a reader.\n */\nexport interface ProviderProfileStore {\n /** Release the underlying resource. Safe to call more than once. */\n close(): Promise<void>;\n /** Remove `profileRef`; `false` when it was not configured. */\n delete(profileRef: ProviderProfileRef): Promise<boolean>;\n /** Read one profile, configured or not enabled alike. */\n get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined>;\n /** The single enabled profile, or `undefined` when none is enabled. */\n getEnabled(): Promise<ModelProviderProfile | undefined>;\n /** Every configured profile, ordered by profile ref. */\n list(): Promise<ModelProviderProfile[]>;\n /** Insert or update `profile`, enforcing both invariants above. */\n save(profile: ModelProviderProfile): Promise<ModelProviderProfile>;\n /**\n * Make `profileRef` the enabled profile. Throws `PROVIDER_NOT_CONFIGURED`\n * when it has no profile — a fail-closed port of `providers.ts:1243-1250`.\n */\n setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile>;\n}\n\n/** Shared by both implementations so their error text cannot drift apart. */\nexport function providerNotConfigured(\n profileRef: ProviderProfileRef,\n): ByokKeysError {\n return new ByokKeysError(\n 'PROVIDER_NOT_CONFIGURED',\n `${profileRef} model provider is not configured`,\n );\n}\n\n/**\n * Profile store held in process memory: the default, and the one every test\n * that does not specifically exercise SQLite should use.\n *\n * Mirrors `InMemoryTaskStore`'s role in `@byok-sdk/server` — a real implementation\n * of the contract, not a stub, so behaviour proven here is the behaviour the\n * SQLite store must match (`profile-store.test.ts` runs one suite against both).\n */\nexport class InMemoryProviderProfileStore implements ProviderProfileStore {\n readonly #profiles = new Map<ProviderProfileRef, ModelProviderProfile>();\n\n async close(): Promise<void> {\n this.#profiles.clear();\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n return this.#profiles.delete(profileRef);\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n return this.#profiles.get(profileRef);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n return [...this.#profiles.values()].find((profile) => profile.enabled);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n return [...this.#profiles.values()].sort((left, right) =>\n left.profile_ref.localeCompare(right.profile_ref),\n );\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const validated = parseModelProviderProfile({\n ...profile,\n created_at:\n this.#profiles.get(profile.profile_ref)?.created_at ??\n profile.created_at,\n });\n if (validated.enabled) {\n for (const [profileRef, existing] of this.#profiles) {\n if (profileRef !== validated.profile_ref && existing.enabled) {\n this.#profiles.set(profileRef, { ...existing, enabled: false });\n }\n }\n }\n this.#profiles.set(validated.profile_ref, validated);\n return validated;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const existing = this.#profiles.get(profileRef);\n if (existing === undefined) throw providerNotConfigured(profileRef);\n return this.save({ ...existing, enabled: true });\n }\n}\n","import { chmodSync, existsSync, mkdirSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname } from 'node:path';\nimport type { DatabaseSync, DatabaseSyncOptions } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\n\nexport type SqliteOpenStep = 'after-open' | 'after-wal' | 'after-synchronous';\n\n/** Test-only seam for proving that post-open initialization failures release the native handle. */\nexport interface SqliteOpenFaultSeam {\n onStep?(step: SqliteOpenStep): void;\n close?(database: DatabaseSync): void;\n}\n\n/** Release an opened handle before propagating an initialization failure. */\nexport function closeSqliteDatabaseAfterInitializationFailure(\n database: DatabaseSync,\n initializationError: unknown,\n message: string,\n close: (database: DatabaseSync) => void = (handle) => handle.close(),\n): never {\n try {\n close(database);\n } catch (closeError) {\n throw new AggregateError([initializationError, closeError], message);\n }\n throw initializationError;\n}\n\n/** Owner-only directory mode, matching `providers.ts:1236`. */\nconst SECURE_DIR_MODE = 0o700;\n\n/** Owner-only file mode, matching `providers.ts:158`. */\nconst SECURE_FILE_MODE = 0o600;\n\nconst DEFAULT_BUSY_TIMEOUT_MS = 5_000;\n\ninterface SqliteModule {\n DatabaseSync: new (\n path: string,\n options?: DatabaseSyncOptions,\n ) => DatabaseSync;\n}\n\n/**\n * Load `node:sqlite`, or fail with a `ByokKeysError` that says why.\n *\n * `node:sqlite` shipped in Node.js 22.5.0 and stays marked experimental (an\n * `ExperimentalWarning` on stderr is expected and harmless). Following\n * `@byok-sdk/server`'s `sqlite-support.ts`, the SQLite-backed store here depends on\n * nothing else — no `better-sqlite3`, no native module — because zero native\n * dependencies is what keeps this package trivially packageable. The tradeoff\n * is that {@link SqliteProviderProfileStore} does not work below Node 22.5, and\n * this error says so instead of letting a cryptic `Cannot find module` surface\n * from deep inside a query.\n */\nexport function loadSqliteModule(): SqliteModule {\n try {\n return createRequire(import.meta.url)('node:sqlite') as SqliteModule;\n } catch (error) {\n throw new ByokKeysError(\n 'PROVIDER_STORE_UNAVAILABLE',\n 'node:sqlite is unavailable in this Node.js runtime. SqliteProviderProfileStore ' +\n 'requires Node.js 22.5+ with the built-in `node:sqlite` module (no native ' +\n 'dependency is used or allowed here). Upgrade Node.js, or use ' +\n 'InMemoryProviderProfileStore instead.',\n { cause: error },\n );\n }\n}\n\n/**\n * Whether `node:sqlite` can ACTUALLY be loaded right now.\n *\n * Same predicate as `@byok-sdk/server`'s `sqlite-support.ts`, and it exists for the\n * same reason: this package's `engines.node` is `>=20` and CI runs the matrix\n * on 20 and 22, but `node:sqlite` shipped in 22.5 and stayed behind\n * `--experimental-sqlite` for part of the 22.x line. A version-number\n * comparison would therefore be wrong in both directions, so this attempts the\n * real require via {@link loadSqliteModule} and reports whether it succeeded.\n *\n * Callers use it to skip a SQLite-backed path rather than fail it — the\n * package's own SQLite-backed suites gate on it — and anything else should call\n * it before assuming a {@link SqliteProviderProfileStore} can be constructed.\n */\nexport function isSqliteAvailable(): boolean {\n try {\n loadSqliteModule();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Open a database, creating its parent directory owner-only first. `:memory:`\n * skips every filesystem step, which is how the shared contract suite exercises\n * the SQLite code path without leaving anything on disk.\n */\nexport function openSqliteDatabase(\n path: string,\n options?: DatabaseSyncOptions,\n faults?: SqliteOpenFaultSeam,\n): DatabaseSync {\n const { DatabaseSync } = loadSqliteModule();\n const readOnly = options?.readOnly === true;\n if (path !== ':memory:' && !readOnly) {\n mkdirSync(dirname(path), { mode: SECURE_DIR_MODE, recursive: true });\n }\n const database = new DatabaseSync(path, {\n timeout: DEFAULT_BUSY_TIMEOUT_MS,\n ...options,\n });\n try {\n faults?.onStep?.('after-open');\n if (path !== ':memory:' && !readOnly) {\n database.exec('PRAGMA journal_mode = WAL');\n faults?.onStep?.('after-wal');\n database.exec('PRAGMA synchronous = FULL');\n faults?.onStep?.('after-synchronous');\n }\n return database;\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n database,\n error,\n 'provider profile SQLite open initialization failed and its native handle could not be closed',\n faults?.close,\n );\n }\n}\n\n/**\n * Restrict `databasePath` and its WAL/SHM siblings to owner-only read/write.\n *\n * The profile table holds no secret — that is the whole point of splitting the\n * key into the OS credential store — but it does hold every provider endpoint\n * this machine talks to, and the source locked the file down\n * (`providers.ts:158`), so the port keeps that. Call after the schema exists,\n * so the lazily-created WAL/SHM files are already there; a sibling that does\n * not exist is skipped rather than treated as an error. No-op for `:memory:`.\n */\nexport function secureSqliteFilePermissions(databasePath: string): void {\n if (databasePath === ':memory:') return;\n for (const candidate of [\n databasePath,\n `${databasePath}-wal`,\n `${databasePath}-shm`,\n ]) {\n if (existsSync(candidate)) {\n chmodSync(candidate, SECURE_FILE_MODE);\n }\n }\n}\n","import type { DatabaseSync } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\nimport {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n MODEL_PROVIDER_KINDS,\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\nimport {\n closeSqliteDatabaseAfterInitializationFailure,\n openSqliteDatabase,\n secureSqliteFilePermissions,\n} from './sqlite-support';\n\nexport interface SqliteProviderProfileStoreOptions {\n /**\n * Database file path. `:memory:` exercises the SQLite code path without a\n * temp file, but defeats the point of this store (restart-safety) exactly as\n * it does for `@byok-sdk/server`'s `SqliteTaskStore`.\n */\n path: string;\n /** Open an existing profile database without creating or mutating it. */\n readOnly?: boolean;\n}\n\n/**\n * Ported from `providers.ts:109-140`, narrowed to the model branch. The\n * source's table also carried `market_data` / `mcp_http` rows and a `tool_name`\n * column; that branch stays in aip-main-open per\n * `docs/researches/HANDOFF-byok-keys.md` §4.5, so the CHECK constraints here\n * are the model half only.\n */\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS provider_profile (\n profile_ref TEXT PRIMARY KEY,\n provider_kind TEXT NOT NULL CHECK (provider_kind IN ('openai', 'deepseek', 'anthropic', 'custom')),\n kind TEXT NOT NULL CHECK (kind = 'model'),\n adapter TEXT NOT NULL CHECK (adapter IN ('openai_compatible', 'anthropic')),\n display_name TEXT NOT NULL,\n base_url TEXT NOT NULL,\n auth_mode TEXT NOT NULL CHECK (auth_mode IN ('bearer', 'x_api_key', 'none')),\n model TEXT NOT NULL,\n capabilities TEXT NOT NULL,\n enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\n`;\n\n/**\n * The \"at most one enabled profile\" invariant, enforced by the database itself\n * rather than only by {@link SqliteProviderProfileStore.save}\n * (`providers.ts:140-144`). A partial unique index means a bug in the write\n * path surfaces as a constraint violation instead of silently producing two\n * defaults.\n */\nconst ENABLED_INDEX = `\nCREATE UNIQUE INDEX IF NOT EXISTS provider_profile_one_enabled\nON provider_profile(kind)\nWHERE enabled = 1;\n`;\n\ninterface ProfileRow {\n adapter: string;\n auth_mode: string;\n base_url: string;\n capabilities: string;\n created_at: string;\n display_name: string;\n enabled: number;\n kind: string;\n model: string;\n profile_ref: string;\n provider_kind: string;\n updated_at: string;\n}\n\n/**\n * SQLite-backed {@link ProviderProfileStore}, following `@byok-sdk/server`'s\n * `SqliteTaskStore` shape. Holds no secret: the API key lives in the injected\n * `SecretStore`, and `registry.golden.test.ts` asserts the plaintext key never\n * appears in this file's bytes.\n */\nexport class SqliteProviderProfileStore implements ProviderProfileStore {\n readonly #database: DatabaseSync;\n #closed = false;\n\n constructor(options: SqliteProviderProfileStoreOptions) {\n this.#database = openSqliteDatabase(options.path, {\n readOnly: options.readOnly ?? false,\n });\n if (!options.readOnly) {\n try {\n this.#database.exec(SCHEMA);\n this.#database.exec(ENABLED_INDEX);\n secureSqliteFilePermissions(options.path);\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n this.#database,\n error,\n 'SqliteProviderProfileStore initialization failed and its native handle could not be closed',\n );\n }\n }\n }\n\n /**\n * Idempotent, as {@link ProviderProfileStore.close} requires: `node:sqlite`\n * throws \"database is not open\" on a second `close()`, and a store is\n * routinely closed both by the code that finished with it and by a test's\n * teardown.\n */\n async close(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n this.#database.close();\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n const result = this.#database\n .prepare('DELETE FROM provider_profile WHERE profile_ref = ?')\n .run(profileRef);\n return Number(result.changes) === 1;\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE profile_ref = ?')\n .get(profileRef) as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE enabled = 1')\n .get() as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n const rows = this.#database\n .prepare('SELECT * FROM provider_profile ORDER BY profile_ref ASC')\n .all() as unknown as ProfileRow[];\n return rows.map(parseRow);\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const existing = await this.get(profile.profile_ref);\n const validated = parseModelProviderProfile({\n ...profile,\n created_at: existing?.created_at ?? profile.created_at,\n });\n this.#transaction(() => {\n if (validated.enabled) {\n this.#database\n .prepare(\n 'UPDATE provider_profile SET enabled = 0 WHERE profile_ref <> ?',\n )\n .run(validated.profile_ref);\n }\n this.#database\n .prepare(\n `INSERT INTO provider_profile (\n profile_ref, provider_kind, kind, adapter, display_name, base_url,\n auth_mode, model, capabilities, enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(profile_ref) DO UPDATE SET\n provider_kind = excluded.provider_kind,\n adapter = excluded.adapter,\n display_name = excluded.display_name,\n base_url = excluded.base_url,\n auth_mode = excluded.auth_mode,\n model = excluded.model,\n capabilities = excluded.capabilities,\n enabled = excluded.enabled,\n updated_at = excluded.updated_at`,\n )\n .run(\n validated.profile_ref,\n validated.provider_kind,\n validated.kind,\n validated.adapter,\n validated.display_name,\n validated.base_url,\n validated.auth_mode,\n validated.model,\n JSON.stringify(validated.capabilities),\n validated.enabled ? 1 : 0,\n validated.created_at,\n validated.updated_at,\n );\n });\n return (await this.get(validated.profile_ref)) as ModelProviderProfile;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const existing = await this.get(profileRef);\n if (existing === undefined) throw providerNotConfigured(profileRef);\n return this.save({ ...existing, enabled: true });\n }\n\n /** `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`, per `providers.ts:1252-1263`. */\n #transaction(body: () => void): void {\n this.#database.exec('BEGIN IMMEDIATE');\n try {\n body();\n this.#database.exec('COMMIT');\n } catch (error) {\n this.#database.exec('ROLLBACK');\n throw error;\n }\n }\n}\n\n/**\n * Rows go back through the same zod schema the write path used, so a row that\n * a different process wrote — or an older schema left behind — is rejected\n * rather than trusted. `enabled` is an INTEGER in SQLite and a real boolean in\n * the schema, and `capabilities` is a JSON array in a TEXT column, so both are\n * decoded explicitly and a row that fails to decode is refused rather than\n * quietly downgraded to an empty capability set.\n */\nfunction parseRow(row: ProfileRow): ModelProviderProfile {\n let capabilities: unknown;\n try {\n capabilities = JSON.parse(row.capabilities);\n } catch (cause) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider profile capabilities column is not valid JSON',\n { cause },\n );\n }\n return parseModelProviderProfile({\n ...row,\n capabilities,\n enabled: row.enabled === 1,\n });\n}\n\n/** Exported for the store's own tests to enumerate the CHECK-constrained kinds. */\nexport const SQLITE_PROFILE_PROVIDER_KINDS = MODEL_PROVIDER_KINDS;\n","import { 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","#!/usr/bin/env node\nimport { spawn } from 'node:child_process';\nimport { promises as fs } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { ByokKeysError } from '../errors';\nimport { MacOsKeychainSecretStore } from '../macos-keychain';\nimport {\n type PiProviderLauncherOptions,\n buildPiProviderChildEnvironment,\n ensurePiSessionDirectory,\n parsePiProviderLauncherOptions,\n resolvePiProviderSecret,\n} from '../pi-provider-launcher-core';\nimport { assertExactProviderProfileBinding } from '../provider-profile';\nimport {\n buildPiProviderArgs,\n buildPiProviderProjection,\n} from '../pi-provider-projection';\nimport { type SecretStore } from '../secret-store';\nimport { SqliteProviderProfileStore } from '../sqlite-profile-store';\nimport { WindowsCredentialManagerSecretStore } from '../windows-credential-manager';\n\nfunction createSecretStore(\n servicePrefix: string | undefined,\n macosKeychainPath: string | undefined,\n): SecretStore {\n if (macosKeychainPath !== undefined && process.platform !== 'darwin') {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n 'macOS keychain path is only supported on darwin',\n );\n }\n switch (process.platform) {\n case 'darwin':\n return new MacOsKeychainSecretStore({\n keychainPath: macosKeychainPath,\n servicePrefix,\n });\n case 'win32':\n return new WindowsCredentialManagerSecretStore({ servicePrefix });\n default:\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n `Pi BYOK credential launcher has no plaintext fallback on ${process.platform}`,\n );\n }\n}\n\nasync function run(options: PiProviderLauncherOptions): Promise<number> {\n if (options.macosKeychainPath !== undefined && process.platform !== 'darwin') {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n 'macOS keychain path is only supported on darwin',\n );\n }\n const profiles = new SqliteProviderProfileStore({\n path: options.profileDbPath,\n readOnly: true,\n });\n let projectionDir: string | undefined;\n try {\n const profile = await profiles.get(options.profileRef);\n if (profile === undefined) {\n throw new Error(`provider profile ${options.profileRef} is not configured`);\n }\n if (profile.model !== options.modelId) {\n throw new Error(\n `selected model ${options.modelId} does not match configured provider model ${profile.model}`,\n );\n }\n if (options.expectedBinding !== undefined) {\n assertExactProviderProfileBinding(profile, options.expectedBinding);\n }\n if (options.validateOnly) return 0;\n\n const secret = await resolvePiProviderSecret(\n profile,\n () => createSecretStore(\n options.secretServicePrefix,\n options.macosKeychainPath,\n ),\n );\n\n projectionDir = await fs.mkdtemp(path.join(os.tmpdir(), 'byok-pi-provider-'));\n await fs.chmod(projectionDir, 0o700).catch(() => {});\n await ensurePiSessionDirectory(options.sessionDir);\n await fs.writeFile(\n path.join(projectionDir, 'models.json'),\n `${JSON.stringify(buildPiProviderProjection(profile))}\\n`,\n { mode: 0o600 },\n );\n\n const child = spawn(options.piBin, buildPiProviderArgs(profile, options.piArgs), {\n env: buildPiProviderChildEnvironment({\n ambient: process.env,\n projectionDir,\n sessionDir: options.sessionDir,\n secret,\n }),\n stdio: 'inherit',\n });\n\n const forward = (signal: NodeJS.Signals): void => {\n if (!child.killed) child.kill(signal);\n };\n const onSigint = (): void => forward('SIGINT');\n const onSigterm = (): void => forward('SIGTERM');\n process.on('SIGINT', onSigint);\n process.on('SIGTERM', onSigterm);\n try {\n return await new Promise<number>((resolve, reject) => {\n child.once('error', reject);\n child.once('close', (code, signal) => {\n resolve(code ?? (signal ? 1 : 0));\n });\n });\n } finally {\n process.off('SIGINT', onSigint);\n process.off('SIGTERM', onSigterm);\n }\n } finally {\n await profiles.close();\n if (projectionDir) {\n await fs.rm(projectionDir, { recursive: true, force: true });\n }\n }\n}\n\nasync function main(): Promise<void> {\n try {\n process.exitCode = await run(parsePiProviderLauncherOptions(process.argv.slice(2)));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`pi provider launcher: ${message}\\n`);\n process.exitCode = 1;\n }\n}\n\nvoid main();\n"]}
1
+ {"version":3,"sources":["../../src/errors.ts","../../src/command-runner.ts","../../src/secret-name.ts","../../src/provider-catalog.ts","../../src/url.ts","../../src/provider-profile.ts","../../src/secret-store.ts","../../src/macos-keychain.ts","../../src/pi-provider-projection.ts","../../src/pi-provider-launcher-core.ts","../../src/profile-store.ts","../../src/sqlite-support.ts","../../src/sqlite-profile-store.ts","../../src/windows-credential-manager.ts","../../src/bin/pi-provider-launcher.ts"],"names":["path","fs","spawn"],"mappings":";;;;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eAAe,IAAA,GAAsB;AACnC,EAAA,IAAI;AACF,IAAA,OAAA,CAAQ,QAAA,GAAW,MAAM,GAAA,CAAI,8BAAA,CAA+B,QAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAC,CAAA;AAAA,EACpF,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACrE,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,sBAAA,EAAyB,OAAO;AAAA,CAAI,CAAA;AACzD,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF;AAEA,KAAK,IAAA,EAAK","file":"pi-provider-launcher.js","sourcesContent":["/**\n * Single error class for `@byok-sdk/keys`.\n *\n * The ported source (`aip-main-open@c6a5385`, `apps/local-agent/src/providers.ts`)\n * raised two different classes — `LocalExecutionError` and\n * `ResearchExecutionError` — that differed only in which subsystem owned the\n * throw site; both carried a `code` string and consumers branched on that code.\n * The narrative/research subsystem stays behind in aip-main-open, so this\n * package keeps one class and preserves the `code` strings verbatim. K4's swap\n * converts aip's two `instanceof` sites to structured code detection, so the\n * strings — not the class identity — are the compatibility surface.\n */\nexport class ByokKeysError extends Error {\n public readonly code: string;\n public readonly httpStatus?: number;\n\n constructor(\n code: string,\n message: string,\n options?: ErrorOptions & { httpStatus?: number },\n ) {\n super(message, options);\n this.name = 'ByokKeysError';\n this.code = code;\n this.httpStatus = options?.httpStatus;\n }\n}\n\n/**\n * Error codes this package can throw, ported verbatim from the source. Kept as\n * a named record so consumers (and K4's aip-main-open swap) can branch on\n * `error.code` without retyping string literals.\n *\n * Four codes have no source counterpart, and each guards a check the source did\n * not make: `KEYCHAIN_SECRET_DECODE_FAILED` (the source returned an undecodable\n * stored value as-is), `SECRET_ENVELOPE_INVALID` (it reported a malformed\n * envelope as an absent secret), and `SECRET_NAME_INVALID` /\n * `SECRET_VALUE_INVALID` (the runtime replacements for the closed\n * `KeychainSecretName` union). `PROVIDER_STORE_SCHEMA_STALE` joins them: it\n * guards a persisted `provider_profile` DDL that differs from the one this\n * package generates. Everything else matches the source string for string.\n *\n * `SECRET_NAMESPACE_INVALID` is a separate case. The source does record it:\n * `normalizeSecretNamespace` (`index.ts:748-757`) throws the verbatim string\n * `'SECRET_NAMESPACE_INVALID'` at `index.ts:752`, and this package ports both\n * that string and its pattern unchanged. It is still not a compatibility\n * surface K4 must match, but for a different reason than the string: neither\n * side has a branch consumer. In the source the only callers are the two OS\n * stores' `scope()` methods, which just compose a service prefix; here the code\n * is only ever asserted in tests. Matching it costs nothing and constrains\n * nothing.\n */\nexport const BYOK_KEYS_ERROR_CODES = {\n CREDENTIAL_MANAGER_DELETE_FAILED: 'CREDENTIAL_MANAGER_DELETE_FAILED',\n CREDENTIAL_MANAGER_READ_FAILED: 'CREDENTIAL_MANAGER_READ_FAILED',\n CREDENTIAL_MANAGER_SECRET_INVALID: 'CREDENTIAL_MANAGER_SECRET_INVALID',\n CREDENTIAL_MANAGER_UNAVAILABLE: 'CREDENTIAL_MANAGER_UNAVAILABLE',\n CREDENTIAL_MANAGER_WRITE_FAILED: 'CREDENTIAL_MANAGER_WRITE_FAILED',\n KEYCHAIN_ARGUMENT_INVALID: 'KEYCHAIN_ARGUMENT_INVALID',\n KEYCHAIN_DELETE_FAILED: 'KEYCHAIN_DELETE_FAILED',\n KEYCHAIN_READ_FAILED: 'KEYCHAIN_READ_FAILED',\n KEYCHAIN_SECRET_DECODE_FAILED: 'KEYCHAIN_SECRET_DECODE_FAILED',\n KEYCHAIN_SECRET_INVALID: 'KEYCHAIN_SECRET_INVALID',\n KEYCHAIN_UNAVAILABLE: 'KEYCHAIN_UNAVAILABLE',\n KEYCHAIN_WRITE_FAILED: 'KEYCHAIN_WRITE_FAILED',\n LOCAL_ACCOUNT_SCOPE_INVALID: 'LOCAL_ACCOUNT_SCOPE_INVALID',\n MODEL_PROVIDER_AUTH_FAILED: 'MODEL_PROVIDER_AUTH_FAILED',\n MODEL_PROVIDER_BALANCE_INSUFFICIENT: 'MODEL_PROVIDER_BALANCE_INSUFFICIENT',\n MODEL_PROVIDER_HTTP_ERROR: 'MODEL_PROVIDER_HTTP_ERROR',\n MODEL_PROVIDER_MODEL_NOT_FOUND: 'MODEL_PROVIDER_MODEL_NOT_FOUND',\n MODEL_PROVIDER_RATE_LIMITED: 'MODEL_PROVIDER_RATE_LIMITED',\n MODEL_RESPONSE_INVALID: 'MODEL_RESPONSE_INVALID',\n PROVIDER_NOT_CONFIGURED: 'PROVIDER_NOT_CONFIGURED',\n PROVIDER_PROFILE_INVALID: 'PROVIDER_PROFILE_INVALID',\n PROVIDER_PROFILE_CONFLICT: 'PROVIDER_PROFILE_CONFLICT',\n PROVIDER_REQUEST_TIMEOUT: 'PROVIDER_REQUEST_TIMEOUT',\n PROVIDER_RESPONSE_INVALID: 'PROVIDER_RESPONSE_INVALID',\n PROVIDER_RESPONSE_TOO_LARGE: 'PROVIDER_RESPONSE_TOO_LARGE',\n PROVIDER_SECRET_EMPTY: 'PROVIDER_SECRET_EMPTY',\n PROVIDER_SECRET_MISSING: 'PROVIDER_SECRET_MISSING',\n PROVIDER_SECRET_NOT_ALLOWED: 'PROVIDER_SECRET_NOT_ALLOWED',\n PROVIDER_SECRET_ROLLBACK_FAILED: 'PROVIDER_SECRET_ROLLBACK_FAILED',\n PROVIDER_STORE_SCHEMA_STALE: 'PROVIDER_STORE_SCHEMA_STALE',\n PROVIDER_STORE_UNAVAILABLE: 'PROVIDER_STORE_UNAVAILABLE',\n PROVIDER_TRUTH_INVALID: 'PROVIDER_TRUTH_INVALID',\n PROVIDER_URL_INVALID: 'PROVIDER_URL_INVALID',\n SECRET_ENVELOPE_INVALID: 'SECRET_ENVELOPE_INVALID',\n SECRET_NAME_INVALID: 'SECRET_NAME_INVALID',\n SECRET_NAMESPACE_INVALID: 'SECRET_NAMESPACE_INVALID',\n SECRET_VALUE_INVALID: 'SECRET_VALUE_INVALID',\n} as const;\n\nexport type ByokKeysErrorCode =\n (typeof BYOK_KEYS_ERROR_CODES)[keyof typeof BYOK_KEYS_ERROR_CODES];\n","import { 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 type { ModelProviderAdapter, ProviderAuthMode } from './provider-profile';\n\n/**\n * One vendor the SDK can address without the consumer typing its endpoint.\n *\n * Ported from the provider catalog deepseek-harness resolves its routes from:\n * pi-ai 0.84.2 `dist/providers/*.js` (the version the SDK's pinned\n * `@earendil-works/pi-coding-agent` 0.84.2 resolves) plus the harness's own\n * `packages/llm/llm-deepseek/src/index.ts` `PUBLIC_BASE_URL`, which agrees\n * with pi-ai's `deepseek` entry. Selection and the URL mapping rule are\n * recorded in `docs/researches/2026-09-06_deepseek-harness-provider-catalog-port.md`.\n *\n * Every field is declared configuration a consumer may copy into a\n * `ModelProviderProfile`; nothing here is read at request time, and a\n * profile still carries its own `base_url` so a self-hosted gateway for a\n * vendor stays expressible. `api_key_env` is the credential name the vendor's\n * own tooling reads; this package never reads it, and `@byok-sdk/client`'s\n * credential deny list must contain every value listed here.\n */\nexport interface ModelProviderVendor {\n readonly display_name: string;\n /**\n * Endpoint base in this package's suffix convention: an\n * `openai_compatible` client appends `chat/completions`, an `anthropic`\n * client appends `messages`. pi-ai's anthropic-dialect entries therefore\n * gain a `/v1` segment here; its OpenAI-dialect entries are verbatim.\n */\n readonly base_url: string;\n readonly adapter: ModelProviderAdapter;\n readonly auth_mode: Exclude<ProviderAuthMode, 'none'>;\n readonly api_key_env: string;\n}\n\nfunction openAiCompatible(\n display_name: string,\n base_url: string,\n api_key_env: string,\n): ModelProviderVendor {\n return {\n display_name,\n base_url,\n adapter: 'openai_compatible',\n auth_mode: 'bearer',\n api_key_env,\n };\n}\n\nfunction anthropicMessages(\n display_name: string,\n base_url: string,\n api_key_env: string,\n): ModelProviderVendor {\n return {\n display_name,\n base_url,\n adapter: 'anthropic',\n auth_mode: 'x_api_key',\n api_key_env,\n };\n}\n\n/**\n * Vendor id → declared endpoint facts. Ids are pi-ai's provider ids so a\n * profile's `provider_kind` names the same route deepseek-harness would.\n * Ordered by dialect, then alphabetically; order carries no meaning.\n */\nexport const MODEL_PROVIDER_VENDORS = {\n 'ant-ling': openAiCompatible('Ant Ling', 'https://api.ant-ling.com/v1', 'ANT_LING_API_KEY'),\n baseten: openAiCompatible('Baseten', 'https://inference.baseten.co/v1', 'BASETEN_API_KEY'),\n cerebras: openAiCompatible('Cerebras', 'https://api.cerebras.ai/v1', 'CEREBRAS_API_KEY'),\n deepseek: openAiCompatible('DeepSeek', 'https://api.deepseek.com', 'DEEPSEEK_API_KEY'),\n groq: openAiCompatible('Groq', 'https://api.groq.com/openai/v1', 'GROQ_API_KEY'),\n huggingface: openAiCompatible('Hugging Face', 'https://router.huggingface.co/v1', 'HF_TOKEN'),\n moonshotai: openAiCompatible('Moonshot AI', 'https://api.moonshot.ai/v1', 'MOONSHOT_API_KEY'),\n 'moonshotai-cn': openAiCompatible('Moonshot AI CN', 'https://api.moonshot.cn/v1', 'MOONSHOT_API_KEY'),\n nvidia: openAiCompatible('NVIDIA', 'https://integrate.api.nvidia.com/v1', 'NVIDIA_API_KEY'),\n openai: openAiCompatible('OpenAI', 'https://api.openai.com/v1', 'OPENAI_API_KEY'),\n openrouter: openAiCompatible('OpenRouter', 'https://openrouter.ai/api/v1', 'OPENROUTER_API_KEY'),\n 'qwen-token-plan': openAiCompatible(\n 'Qwen Token Plan',\n 'https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1',\n 'QWEN_TOKEN_PLAN_API_KEY',\n ),\n 'qwen-token-plan-cn': openAiCompatible(\n 'Qwen Token Plan CN',\n 'https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',\n 'QWEN_TOKEN_PLAN_CN_API_KEY',\n ),\n together: openAiCompatible('Together', 'https://api.together.ai/v1', 'TOGETHER_API_KEY'),\n xai: openAiCompatible('xAI', 'https://api.x.ai/v1', 'XAI_API_KEY'),\n xiaomi: openAiCompatible('Xiaomi', 'https://api.xiaomimimo.com/v1', 'XIAOMI_API_KEY'),\n 'xiaomi-token-plan-ams': openAiCompatible(\n 'Xiaomi Token Plan AMS',\n 'https://token-plan-ams.xiaomimimo.com/v1',\n 'XIAOMI_TOKEN_PLAN_AMS_API_KEY',\n ),\n 'xiaomi-token-plan-cn': openAiCompatible(\n 'Xiaomi Token Plan CN',\n 'https://token-plan-cn.xiaomimimo.com/v1',\n 'XIAOMI_TOKEN_PLAN_CN_API_KEY',\n ),\n 'xiaomi-token-plan-sgp': openAiCompatible(\n 'Xiaomi Token Plan SGP',\n 'https://token-plan-sgp.xiaomimimo.com/v1',\n 'XIAOMI_TOKEN_PLAN_SGP_API_KEY',\n ),\n zai: openAiCompatible('Z.AI', 'https://api.z.ai/api/coding/paas/v4', 'ZAI_API_KEY'),\n 'zai-coding-cn': openAiCompatible(\n 'Z.AI Coding CN',\n 'https://open.bigmodel.cn/api/coding/paas/v4',\n 'ZAI_CODING_CN_API_KEY',\n ),\n anthropic: anthropicMessages('Anthropic', 'https://api.anthropic.com/v1', 'ANTHROPIC_API_KEY'),\n fireworks: anthropicMessages('Fireworks', 'https://api.fireworks.ai/inference/v1', 'FIREWORKS_API_KEY'),\n 'kimi-coding': anthropicMessages('Kimi For Coding', 'https://api.kimi.com/coding/v1', 'KIMI_API_KEY'),\n minimax: anthropicMessages('MiniMax', 'https://api.minimax.io/anthropic/v1', 'MINIMAX_API_KEY'),\n 'minimax-cn': anthropicMessages('MiniMax CN', 'https://api.minimaxi.com/anthropic/v1', 'MINIMAX_CN_API_KEY'),\n 'vercel-ai-gateway': anthropicMessages(\n 'Vercel AI Gateway',\n 'https://ai-gateway.vercel.sh/v1',\n 'AI_GATEWAY_API_KEY',\n ),\n} as const satisfies Record<string, ModelProviderVendor>;\n\nexport type ModelProviderVendorId = keyof typeof MODEL_PROVIDER_VENDORS;\n\n/** Catalog vendor ids; `MODEL_PROVIDER_KINDS` is this list plus `custom`. */\nexport const MODEL_PROVIDER_VENDOR_IDS = Object.keys(\n MODEL_PROVIDER_VENDORS,\n) as readonly ModelProviderVendorId[];\n\n/**\n * The catalog entry for a provider kind, or `undefined` for `custom`, which\n * by definition declares everything itself.\n */\nexport function modelProviderVendor(\n kind: string,\n): ModelProviderVendor | undefined {\n return Object.hasOwn(MODEL_PROVIDER_VENDORS, kind)\n ? MODEL_PROVIDER_VENDORS[kind as ModelProviderVendorId]\n : undefined;\n}\n","import { ByokKeysError } from './errors';\n\n/**\n * Normalize a provider base URL, fail-closed.\n *\n * Ported from `aip-main-open@c6a5385` `providers.ts:1558-1588` plus the two\n * host predicates at `:2216-2242`. Rules, unchanged:\n * - must be an absolute URL;\n * - no embedded credentials, no fragment, no query string;\n * - HTTPS only, except that HTTP is allowed for loopback hosts;\n * - private-network literals are rejected unless they are loopback;\n * - one trailing slash is stripped.\n */\nexport function normalizeProviderUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider base URL must be absolute',\n );\n }\n if (\n url.username ||\n url.password ||\n url.hash ||\n url.search ||\n (url.protocol !== 'https:' &&\n !(url.protocol === 'http:' && isLoopbackHost(url.hostname)))\n ) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider URL requires HTTPS; HTTP is allowed only for localhost',\n );\n }\n if (isPrivateNetworkLiteral(url.hostname) && !isLoopbackHost(url.hostname)) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Private-network provider IPs are not allowed',\n );\n }\n return url.toString().replace(/\\/$/u, '');\n}\n\n/** Whether an already-parseable provider URL points at a loopback host. */\nexport function isLoopbackProviderUrl(value: string): boolean {\n return isLoopbackHost(new URL(value).hostname);\n}\n\nexport function isLoopbackHost(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n return value === 'localhost' || value === '127.0.0.1' || value === '::1';\n}\n\n/**\n * Conservative private-network literal check. Any IPv6 literal counts as\n * private (the `:` branch), matching the source: the guard cannot cheaply\n * classify IPv6 ranges, so it refuses all of them and lets hostnames through.\n */\nexport function isPrivateNetworkLiteral(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n if (value.includes(':')) return true;\n const parts = value.split('.').map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n return (\n parts[0] === 10 ||\n parts[0] === 127 ||\n (parts[0] === 169 && parts[1] === 254) ||\n (parts[0] === 172 && (parts[1] ?? 0) >= 16 && (parts[1] ?? 0) <= 31) ||\n (parts[0] === 192 && parts[1] === 168)\n );\n}\n","import { z } from 'zod';\nimport { createHash } from 'node:crypto';\n\nimport { ByokKeysError } from './errors';\nimport {\n MODEL_PROVIDER_VENDOR_IDS,\n modelProviderVendor,\n type ModelProviderVendorId,\n} from './provider-catalog';\nimport { normalizeProviderUrl } from './url';\n\n/**\n * Opaque, portable identity of one locally configured provider profile.\n *\n * This is the profile's primary key: it is a local logical id, never a path,\n * and several profiles may share one {@link MODEL_PROVIDER_KINDS} kind (two\n * independent `custom` endpoints, for example). It replaces the former\n * `MODEL_PROVIDER_IDS` primary key, which conflated instance identity with\n * provider kind and therefore allowed exactly one profile per kind.\n *\n * `@byok-sdk/protocol` declares the same lexical rule for the wire form in\n * `provider-profile-binding.ts`. The two definitions are deliberately parallel\n * rather than shared: the release graph (`scripts/release/check-package-graph.mjs`)\n * forbids `@byok-sdk/keys` from depending on any dispatch package, so the\n * device-local authority cannot import the wire authority. This mirrors how\n * `packages/protocol/src/blob.ts`'s `CONTENT_HASH_RE` restates\n * `packages/core/src/blob.ts`'s content-hash format across the same boundary.\n */\nexport const PROVIDER_PROFILE_REF_PATTERN =\n /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/u;\n\nexport const ProviderProfileRefSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(\n PROVIDER_PROFILE_REF_PATTERN,\n 'provider profile refs must be lowercase portable identifiers',\n );\n\nexport type ProviderProfileRef = z.infer<typeof ProviderProfileRefSchema>;\n\n/**\n * Provider kinds this package knows how to address — the surviving half of the\n * former `MODEL_PROVIDER_IDS`. A kind says *what dialect family and vendor\n * shape* a profile is; {@link ProviderProfileRefSchema} says *which* profile.\n * Originally ported from `aip-main-open@c6a5385` `providers.ts:30-36`\n * (`LOCAL_MODEL_PROVIDER_IDS`); the list is now derived: every id in\n * {@link MODEL_PROVIDER_VENDORS}, plus `custom` for an endpoint the catalog\n * does not name. `provider-catalog.ts` is the single authority, and\n * `sqlite-profile-store.ts` generates its CHECK constraint from this list.\n */\nexport type ModelProviderKind = ModelProviderVendorId | 'custom';\n\nexport const MODEL_PROVIDER_KINDS = [\n ...MODEL_PROVIDER_VENDOR_IDS,\n 'custom',\n] as readonly ModelProviderKind[] as readonly [\n ModelProviderKind,\n ...ModelProviderKind[],\n];\n\n/**\n * Bounded model capabilities a profile may declare. A capability is explicit\n * local configuration, never inferred from the model name or the base URL.\n */\nexport const PROVIDER_MODEL_CAPABILITIES = ['image-input'] as const;\n\nexport const ProviderModelCapabilitySchema = z.enum(PROVIDER_MODEL_CAPABILITIES);\n\nexport type ProviderModelCapability = z.infer<\n typeof ProviderModelCapabilitySchema\n>;\n\n/** Auth modes a provider profile can request (`providers.ts:29`). */\nexport const PROVIDER_AUTH_MODES = ['bearer', 'x_api_key', 'none'] as const;\n\nexport type ProviderAuthMode = (typeof PROVIDER_AUTH_MODES)[number];\n\n/**\n * Wire dialects. The source's `market_data` / `mcp_http` branch stays in\n * aip-main-open — this package ports the model branch only\n * (`providers.ts:38-61`, second union member).\n */\nexport const MODEL_PROVIDER_ADAPTERS = ['openai_compatible', 'anthropic'] as const;\n\nexport type ModelProviderAdapter = (typeof MODEL_PROVIDER_ADAPTERS)[number];\n\n/**\n * Marker attached to schema issues so {@link parseModelProviderProfile} can\n * reproduce the source's distinct error codes: the URL guard reports\n * `PROVIDER_URL_INVALID`, everything else reports `PROVIDER_PROFILE_INVALID`.\n */\ninterface ProfileIssueParams {\n byokCode: string;\n}\n\nfunction boundedString(field: string, maximumLength: number) {\n return z\n .string()\n .superRefine((value, ctx) => {\n if (\n value.trim().length === 0 ||\n value.length > maximumLength ||\n /[\\u0000\\r\\n]/u.test(value)\n ) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} is invalid`,\n });\n }\n })\n .transform((value) => value.trim());\n}\n\nfunction isoTimestamp(field: string) {\n return boundedString(field, 64).superRefine((value, ctx) => {\n if (!Number.isFinite(Date.parse(value))) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} must be an ISO timestamp`,\n });\n }\n });\n}\n\nconst providerBaseUrl = z\n .string()\n .superRefine((value, ctx) => {\n try {\n normalizeProviderUrl(value);\n } catch (error) {\n ctx.addIssue({\n code: 'custom',\n message:\n error instanceof Error ? error.message : 'Provider base URL is invalid',\n params: {\n byokCode:\n error instanceof ByokKeysError ? error.code : 'PROVIDER_URL_INVALID',\n } satisfies ProfileIssueParams,\n });\n }\n })\n .transform((value) => normalizeProviderUrl(value));\n\n/**\n * A model provider profile: everything needed to address a provider except the\n * secret itself, which lives in the OS credential store.\n *\n * The adapter/auth-mode legality rules are the ones `normalizeProviderProfile`\n * enforced imperatively at `providers.ts:1522-1543`, moved into the schema so\n * there is one validation authority rather than a schema plus a normalizer.\n */\nexport const ModelProviderProfileSchema = z\n .object({\n adapter: z.enum(MODEL_PROVIDER_ADAPTERS),\n auth_mode: z.enum(PROVIDER_AUTH_MODES),\n base_url: providerBaseUrl,\n capabilities: z.array(ProviderModelCapabilitySchema).max(8),\n created_at: isoTimestamp('created_at'),\n display_name: boundedString('display_name', 100),\n enabled: z.boolean(),\n kind: z.literal('model'),\n model: boundedString('model', 160),\n profile_ref: ProviderProfileRefSchema,\n provider_kind: z.enum(MODEL_PROVIDER_KINDS),\n updated_at: isoTimestamp('updated_at'),\n })\n .superRefine((profile, ctx) => {\n if (new Set(profile.capabilities).size !== profile.capabilities.length) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider capabilities cannot repeat',\n path: ['capabilities'],\n });\n }\n if (profile.adapter === 'anthropic' && profile.auth_mode !== 'x_api_key') {\n ctx.addIssue({\n code: 'custom',\n message: 'Anthropic requires x_api_key authentication',\n path: ['auth_mode'],\n });\n }\n if (\n profile.adapter === 'openai_compatible' &&\n profile.auth_mode === 'x_api_key'\n ) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'OpenAI-compatible providers support bearer or no authentication',\n path: ['auth_mode'],\n });\n }\n const vendor = modelProviderVendor(profile.provider_kind);\n if (vendor !== undefined && vendor.adapter !== profile.adapter) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider kind ${profile.provider_kind} speaks the ${vendor.adapter} adapter`,\n path: ['adapter'],\n });\n }\n if (Date.parse(profile.updated_at) < Date.parse(profile.created_at)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider updated_at cannot precede created_at',\n path: ['updated_at'],\n });\n }\n });\n\n/** Validated, normalized profile. */\nexport type ModelProviderProfile = z.infer<typeof ModelProviderProfileSchema>;\n\n/** Pre-normalization shape callers may hand in. */\nexport type ModelProviderProfileInput = z.input<typeof ModelProviderProfileSchema>;\n\nexport interface ExactProviderProfileBinding {\n profileRef: ProviderProfileRef;\n profileRevision: string;\n profileHash: string;\n modelId: string;\n requiredCapabilities: readonly ProviderModelCapability[];\n}\n\n/**\n * Derive the credential-free wire identity from the normalized local record.\n * `updated_at` is the persisted monotonic revision authority; the hash covers\n * the complete normalized non-secret record with capability order\n * canonicalized. Secret values are not accepted by this type and therefore\n * cannot enter the digest or any mismatch message.\n */\nexport function exactProviderProfileBinding(\n profileInput: ModelProviderProfile,\n requiredCapabilities: readonly ProviderModelCapability[] = profileInput.capabilities,\n): ExactProviderProfileBinding {\n const profile = parseModelProviderProfile(profileInput);\n const revision = Date.parse(profile.updated_at);\n if (!Number.isSafeInteger(revision) || revision < 0) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider updated_at cannot be represented as a canonical revision',\n );\n }\n const normalizedCapabilities = [...profile.capabilities].sort();\n const canonical = JSON.stringify({\n adapter: profile.adapter,\n auth_mode: profile.auth_mode,\n base_url: profile.base_url,\n capabilities: normalizedCapabilities,\n kind: profile.kind,\n model: profile.model,\n profile_ref: profile.profile_ref,\n provider_kind: profile.provider_kind,\n });\n return {\n profileRef: profile.profile_ref,\n profileRevision: String(revision),\n profileHash: `sha256:${createHash('sha256').update(canonical).digest('hex')}`,\n modelId: profile.model,\n requiredCapabilities: [...requiredCapabilities],\n };\n}\n\n/** Fail closed unless every offered binding field matches local authority. */\nexport function assertExactProviderProfileBinding(\n profile: ModelProviderProfile,\n expected: ExactProviderProfileBinding,\n): void {\n if (new Set(expected.requiredCapabilities).size !== expected.requiredCapabilities.length) {\n throw new Error('provider profile required capabilities must be unique');\n }\n const actual = exactProviderProfileBinding(profile, expected.requiredCapabilities);\n if (actual.profileRef !== expected.profileRef) throw new Error('provider profile ref mismatch');\n if (actual.profileRevision !== expected.profileRevision) throw new Error('provider profile revision mismatch');\n if (actual.profileHash !== expected.profileHash) throw new Error('provider profile hash mismatch');\n if (actual.modelId !== expected.modelId) throw new Error('provider profile model mismatch');\n const supported = new Set(profile.capabilities);\n const unsupported = expected.requiredCapabilities.find((capability) => !supported.has(capability));\n if (unsupported !== undefined) throw new Error(`provider profile does not support required capability ${unsupported}`);\n}\n\n/**\n * Parse and normalize a profile, or throw {@link ByokKeysError}. Replaces the\n * source's `normalizeProviderProfile` (`providers.ts:1489-1556`) for the model\n * branch, preserving its error codes.\n */\nexport function parseModelProviderProfile(value: unknown): ModelProviderProfile {\n const result = ModelProviderProfileSchema.safeParse(value);\n if (result.success) return result.data;\n const issue = result.error.issues[0];\n const params = (issue as { params?: Partial<ProfileIssueParams> } | undefined)\n ?.params;\n throw new ByokKeysError(\n params?.byokCode ?? 'PROVIDER_PROFILE_INVALID',\n issue?.message ?? 'Provider profile is invalid',\n { cause: result.error },\n );\n}\n","import { ByokKeysError } from './errors';\nimport {\n ProviderProfileRefSchema,\n type ProviderProfileRef,\n} from './provider-profile';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\n\n/**\n * Storage contract for a single secret entry in an operating-system credential\n * store.\n *\n * Ported from `aip-main-open@c6a5385` `apps/local-agent/src/index.ts:261-269`\n * with two deliberate changes:\n *\n * 1. `TName` is a generic parameter rather than aip's closed\n * `KeychainSecretName` union. aip's union names device keys, refresh tokens,\n * and market-data entries that this package has no business knowing about,\n * so it stays in aip and consumers pin their own union. The compile-time\n * closure it provided is replaced at runtime by {@link assertSecretName},\n * which every implementation must apply on every name it receives.\n * 2. `scope()` is required, not optional. The source made it optional and its\n * `scopeLocalAgentSecretStore` silently substituted an envelope\n * implementation when a store did not provide one. Scope-envelope prefixing\n * has no installed base, so this package removes the implicit substitution:\n * every store scopes itself, and {@link EnvelopeScopedSecretStore} is a\n * decorator a caller applies on purpose.\n */\nexport interface SecretStore<TName extends string = string> {\n /** Human-readable backend name, safe to show a user. Never contains a secret. */\n readonly providerLabel: string;\n /** Whether this backend can be used on the current machine. Must not throw. */\n available(): Promise<boolean>;\n /** Remove `name`; `false` when it was already absent. */\n delete(name: TName): Promise<boolean>;\n /** Read `name`, or `undefined` when it is absent. */\n get(name: TName): Promise<string | undefined>;\n /** Whether `name` currently holds a secret. */\n has(name: TName): Promise<boolean>;\n /** A view of this store isolated under `namespace`. */\n scope(namespace: string): SecretStore<TName>;\n /** Write `secret` at `name`, replacing any existing value. */\n set(name: TName, secret: string): Promise<void>;\n}\n\n/**\n * Default service prefix for this package's own entries. `servicePrefix` is a\n * constructor option on both OS backends, so K4's aip-main-open swap passes its\n * `com.aiphabee.local-agent` value and keeps existing installs byte-compatible.\n */\nexport const DEFAULT_SECRET_SERVICE_PREFIX = 'com.byok.keys';\n\n/**\n * Credential-store entry name for one provider profile.\n *\n * The former fixed `MODEL_PROVIDER_SECRET_NAMES` table could name exactly one\n * entry per provider kind, so two independent `custom` endpoints would have\n * shared — and overwritten — a single credential. The name is now derived from\n * the profile's own {@link ProviderProfileRef}, keeping the shape\n * `providers.ts:1624-1632` established (`model-<id>-api-key`, no vendor\n * branding; the branding lives in the service prefix).\n */\nexport type ModelProviderSecretName = `model-${string}-api-key`;\n\n/**\n * Resolve a provider profile ref to the credential-store entry holding its API\n * key. The ref is validated here as well as by the profile schema: this\n * function composes a storage address, so an unvalidated ref would be an\n * address-injection surface rather than merely an invalid record.\n */\nexport function modelProviderSecretName(\n profileRef: ProviderProfileRef,\n): ModelProviderSecretName {\n const parsed = ProviderProfileRefSchema.safeParse(profileRef);\n if (!parsed.success) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider profile ref must be a lowercase portable identifier',\n { cause: parsed.error },\n );\n }\n return assertSecretName(`model-${parsed.data}-api-key` as const);\n}\n\n/**\n * The secret-shape invariant both OS backends share. Their size ceilings differ\n * in both magnitude and unit (macOS counts 16384 characters, Windows counts\n * 2560 UTF-8 bytes) and each reports its own error code, so those checks stay\n * in the backends; only the empty/control-character rule is common.\n */\nexport function assertSharedSecretValue(secret: string): void {\n if (secret.length === 0 || /[\\u0000\\r\\n]/u.test(secret)) {\n throw new ByokKeysError(\n 'SECRET_VALUE_INVALID',\n 'Secret must be a non-empty string without null or newline characters',\n );\n }\n}\n\n/**\n * Decode base64 to UTF-8 text, or return `undefined` — never a repaired\n * approximation.\n *\n * Both decode paths in Node are lenient in ways that matter here: `Buffer.from`\n * silently drops characters outside the base64 alphabet (so `\"a!G@k=\"` would\n * decode to `\"hi\"`), and `Buffer#toString('utf8')` substitutes U+FFFD for\n * invalid byte sequences. A credential store that \"successfully\" returns a\n * silently-mangled secret is worse than one that fails, so the alphabet, the\n * canonical padding, and the UTF-8 round trip are all checked explicitly.\n */\nexport function decodeStrictBase64Utf8(encoded: string): string | undefined {\n if (encoded.length % 4 !== 0) return undefined;\n if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(encoded)) return undefined;\n const bytes = Buffer.from(encoded, 'base64');\n if (bytes.toString('base64') !== encoded) return undefined;\n const text = bytes.toString('utf8');\n if (!Buffer.from(text, 'utf8').equals(bytes)) return undefined;\n return text;\n}\n\n/**\n * A {@link SecretStore} held in process memory, for tests and for embedders\n * that supply their own persistence.\n *\n * It keys entries by the same `` `${servicePrefix}.${name}` `` string the OS\n * backends use, and `scope()` extends that prefix exactly as they do, so a test\n * written against this store exercises the same isolation arithmetic as\n * production. It applies the name validator and the shared secret-shape rule;\n * the platform size ceilings deliberately are not simulated, since they differ\n * per backend.\n */\nexport class InMemorySecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'in-memory';\n readonly #entries: Map<string, string>;\n readonly #servicePrefix: string;\n\n constructor(\n options: {\n /** Shared backing map; a scoped view keeps the parent's map. */\n entries?: Map<string, string>;\n servicePrefix?: string;\n } = {},\n ) {\n this.#entries = options.entries ?? new Map();\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n }\n\n available(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n async delete(name: TName): Promise<boolean> {\n return this.#entries.delete(this.#service(name));\n }\n\n async get(name: TName): Promise<string | undefined> {\n return this.#entries.get(this.#service(name));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new InMemorySecretStore<TName>({\n entries: this.#entries,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n assertSharedSecretValue(secret);\n this.#entries.set(service, secret);\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n","import path from 'node:path';\n\nimport { type CommandRunner, runCommand } from './command-runner';\nimport { ByokKeysError } from './errors';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\nimport {\n DEFAULT_SECRET_SERVICE_PREFIX,\n type SecretStore,\n decodeStrictBase64Utf8,\n} from './secret-store';\n\n/**\n * Marker written in front of every stored value so a read can tell a value this\n * package wrote from anything else already sitting at the same service name.\n * Injectable, so K4's aip-main-open swap passes `aiphabee-b64-v1:` and stays\n * byte-compatible with existing installs (source: `index.ts:246`).\n */\nexport const DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX = 'byok-b64-v1:';\n\n/** `security` exits 44 for \"the item does not exist\". */\nconst SECURITY_ITEM_NOT_FOUND = 44;\n\nexport interface MacOsKeychainSecretStoreOptions {\n /** Keychain account field; entries are addressed by (account, service). */\n account?: string;\n /**\n * Return a stored value that lacks {@link MacOsKeychainSecretStoreOptions.storagePrefix}\n * instead of throwing. Defaults to `false`.\n *\n * The source returned such values unconditionally\n * (`decodeMacOsKeychainSecret`, `index.ts:536-545`), which meant any\n * unrelated item at the same service name was handed back as if this package\n * had written it. Reading is fail-closed here, and the tolerant behavior is\n * demoted to something a caller must ask for by name — it exists only for a\n * migration that has read an unprefixed value it already knows it wrote.\n */\n allowUnprefixedRead?: boolean;\n commandRunner?: CommandRunner;\n /** Explicit macOS keychain file; omitted means the user default keychain. */\n keychainPath?: string;\n platform?: NodeJS.Platform;\n servicePrefix?: string;\n storagePrefix?: string;\n}\n\n/**\n * macOS Keychain backend, driving `/usr/bin/security`\n * (`aip-main-open@c6a5385` `apps/local-agent/src/index.ts:412-533`).\n *\n * There is deliberately no plaintext fallback: on a non-darwin platform every\n * operation throws `KEYCHAIN_UNAVAILABLE` rather than degrading to a file.\n */\nexport class MacOsKeychainSecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'macOS Keychain';\n readonly #account: string;\n readonly #allowUnprefixedRead: boolean;\n readonly #commandRunner: CommandRunner;\n readonly #keychainPath: string | undefined;\n readonly #platform: NodeJS.Platform;\n readonly #servicePrefix: string;\n readonly #storagePrefix: string;\n\n constructor(options: MacOsKeychainSecretStoreOptions = {}) {\n this.#account = options.account ?? 'local-device';\n this.#allowUnprefixedRead = options.allowUnprefixedRead ?? false;\n this.#commandRunner = options.commandRunner ?? runCommand;\n this.#keychainPath = assertKeychainPath(options.keychainPath);\n this.#platform = options.platform ?? process.platform;\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n this.#storagePrefix =\n options.storagePrefix ?? DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX;\n }\n\n async available(): Promise<boolean> {\n if (this.#platform !== 'darwin') return false;\n const result = await this.#commandRunner('/usr/bin/security', [\n ...(this.#keychainPath === undefined\n ? ['default-keychain', '-d', 'user']\n : ['show-keychain-info', this.#keychainPath]),\n ]);\n return result.exitCode === 0;\n }\n\n async delete(name: TName): Promise<boolean> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'delete-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n ...(this.#keychainPath === undefined ? [] : [this.#keychainPath]),\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return false;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_DELETE_FAILED',\n 'macOS Keychain could not delete the requested secret',\n );\n }\n return true;\n }\n\n async get(name: TName): Promise<string | undefined> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'find-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n '-w',\n ...(this.#keychainPath === undefined ? [] : [this.#keychainPath]),\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return undefined;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_READ_FAILED',\n 'macOS Keychain could not read the requested secret',\n );\n }\n return this.#decode(result.stdout.replace(/\\r?\\n$/u, ''));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new MacOsKeychainSecretStore<TName>({\n account: this.#account,\n allowUnprefixedRead: this.#allowUnprefixedRead,\n commandRunner: this.#commandRunner,\n keychainPath: this.#keychainPath,\n platform: this.#platform,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n storagePrefix: this.#storagePrefix,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n this.#assertMacOs();\n if (\n secret.length === 0 ||\n secret.length > 16_384 ||\n /[\\u0000\\r\\n]/u.test(secret)\n ) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_INVALID',\n 'Secret must contain 1 to 16384 non-newline characters',\n );\n }\n // `security add-generic-password -w` opens /dev/tty when no password\n // argument is supplied, even if the child has a piped stdin. Interactive\n // mode accepts the complete command through stdin, keeping the encoded\n // secret out of argv/process listings and avoiding an unattended prompt.\n const storedSecret = `${this.#storagePrefix}${Buffer.from(secret, 'utf8').toString('base64')}`;\n const command = [\n 'add-generic-password',\n '-U',\n '-a',\n quoteSecurityInteractiveArgument(this.#account),\n '-s',\n quoteSecurityInteractiveArgument(service),\n '-w',\n quoteSecurityInteractiveArgument(storedSecret),\n ...(this.#keychainPath === undefined\n ? []\n : [quoteSecurityInteractiveArgument(this.#keychainPath)]),\n ].join(' ');\n const result = await this.#commandRunner(\n '/usr/bin/security',\n ['-i'],\n `${command}\\n`,\n );\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_WRITE_FAILED',\n 'macOS Keychain could not store the requested secret',\n );\n }\n }\n\n #assertMacOs(): void {\n if (this.#platform !== 'darwin') {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n 'macOS Keychain is required; plaintext fallback is disabled',\n );\n }\n }\n\n /**\n * Fail-closed inverse of the storage encoding. The error message never\n * echoes the undecodable value — it may still be somebody's live credential.\n */\n #decode(storedSecret: string): string {\n if (!storedSecret.startsWith(this.#storagePrefix)) {\n if (this.#allowUnprefixedRead) return storedSecret;\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a value without this store\\'s storage prefix',\n );\n }\n const decoded = decodeStrictBase64Utf8(\n storedSecret.slice(this.#storagePrefix.length),\n );\n if (decoded === undefined || decoded.length === 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a secret that is not valid base64-encoded UTF-8',\n );\n }\n return decoded;\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n\n/**\n * Quote a value for `security -i`'s interactive parser (`index.ts:547-557`).\n * Null and newline characters cannot be quoted safely — a newline would end the\n * command line and let the remainder be parsed as a second command — so they are\n * rejected rather than escaped.\n */\nfunction quoteSecurityInteractiveArgument(value: string): string {\n if (/[\\u0000\\r\\n]/u.test(value)) {\n throw new ByokKeysError(\n 'KEYCHAIN_ARGUMENT_INVALID',\n 'macOS Keychain arguments cannot contain null or newline characters',\n );\n }\n return `\"${value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')}\"`;\n}\n\nfunction assertKeychainPath(keychainPath: string | undefined): string | undefined {\n if (keychainPath === undefined) return undefined;\n if (\n keychainPath.length === 0 ||\n !path.posix.isAbsolute(keychainPath) ||\n /[\\u0000\\r\\n]/u.test(keychainPath)\n ) {\n throw new ByokKeysError(\n 'KEYCHAIN_ARGUMENT_INVALID',\n 'macOS keychain path must be a non-empty absolute single-line path',\n );\n }\n return keychainPath;\n}\n","import type { ModelProviderProfile } from './provider-profile';\n\nexport const PI_PROJECTED_KEY_ENV = 'PI_PROVIDER_API_KEY';\n\n/** Keep projected providers disjoint from Pi built-ins so composition can never fall back to one. */\nexport function piProjectionProviderId(profileRef: string): string {\n return `byok-sdk-${profileRef}`;\n}\n\n/**\n * Credential-blind Pi configuration derived from one validated local profile.\n *\n * The projected provider is namespaced by the profile's own ref, not by its\n * provider kind, so two independently configured endpoints of the same kind\n * project to two distinct Pi providers instead of colliding on one. Model\n * `input` modalities are projected from the profile's declared capabilities —\n * declared local configuration is the only authority; nothing is inferred from\n * the model name or base URL.\n */\nexport function buildPiProviderProjection(profile: ModelProviderProfile): object {\n const projectedProviderId = piProjectionProviderId(profile.profile_ref);\n return {\n providers: {\n [projectedProviderId]: {\n baseUrl: profile.base_url,\n api:\n profile.adapter === 'anthropic'\n ? 'anthropic-messages'\n : 'openai-completions',\n ...(profile.auth_mode === 'none'\n ? {}\n : { apiKey: `$${PI_PROJECTED_KEY_ENV}` }),\n ...(profile.auth_mode === 'bearer' ? { authHeader: true } : {}),\n models: [\n {\n id: profile.model,\n name: profile.display_name,\n input: [\n 'text',\n ...(profile.capabilities.includes('image-input') ? ['image'] : []),\n ],\n },\n ],\n },\n },\n };\n}\n\n/**\n * Validate the credential-blind RPC argv the client may delegate, then bind\n * the Pi child to the namespaced projection and exact configured model.\n */\nexport function buildPiProviderArgs(\n profile: ModelProviderProfile,\n delegatedArgs: readonly string[],\n): string[] {\n let modeCount = 0;\n for (let index = 0; index < delegatedArgs.length; index += 1) {\n const flag = delegatedArgs[index];\n if (flag === '--no-tools') continue;\n if (flag === '--mode') {\n modeCount += 1;\n const value = delegatedArgs[index + 1];\n if (value !== 'rpc') throw new Error('Pi launcher requires --mode rpc');\n index += 1;\n continue;\n }\n if (flag === '--session' || flag === '--tools' || flag === '--exclude-tools') {\n const value = delegatedArgs[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`${flag} requires a value`);\n }\n index += 1;\n continue;\n }\n throw new Error(`Pi launcher does not allow delegated argument ${flag ?? '<missing>'}`);\n }\n if (modeCount !== 1) throw new Error('Pi launcher requires exactly one --mode rpc');\n\n return [\n ...delegatedArgs,\n '--provider',\n piProjectionProviderId(profile.profile_ref),\n '--model',\n profile.model,\n ];\n}\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\n\nimport { ByokKeysError } from './errors';\nimport { PI_PROJECTED_KEY_ENV } from './pi-provider-projection';\nimport {\n ProviderModelCapabilitySchema,\n ProviderProfileRefSchema,\n type ExactProviderProfileBinding,\n type ModelProviderProfile,\n type ProviderProfileRef,\n} from './provider-profile';\nimport { type SecretStore, modelProviderSecretName } from './secret-store';\n\nconst PI_CHILD_BASE_ENV_NAMES = [\n 'PATH',\n 'HOME',\n 'USERPROFILE',\n 'TMPDIR',\n 'TEMP',\n 'TMP',\n 'LANG',\n 'TZ',\n 'TERM',\n 'SHELL',\n 'HTTP_PROXY',\n 'HTTPS_PROXY',\n 'NO_PROXY',\n 'ALL_PROXY',\n 'http_proxy',\n 'https_proxy',\n 'no_proxy',\n 'all_proxy',\n] as const;\n\nconst PI_CHILD_WINDOWS_ENV_NAMES = [\n 'SystemRoot',\n 'COMSPEC',\n 'PATHEXT',\n 'windir',\n 'SYSTEMDRIVE',\n 'PROGRAMFILES',\n 'APPDATA',\n 'LOCALAPPDATA',\n] as const;\n\nexport interface PiProviderLauncherOptions {\n piBin: string;\n profileDbPath: string;\n /** Carried by the `--provider` flag: the exact local profile to launch. */\n profileRef: ProviderProfileRef;\n modelId: string;\n expectedBinding?: ExactProviderProfileBinding;\n validateOnly: boolean;\n sessionDir: string;\n secretServicePrefix?: string;\n macosKeychainPath?: string;\n piArgs: string[];\n}\n\nexport function parsePiProviderLauncherOptions(\n args: string[],\n): PiProviderLauncherOptions {\n const separator = args.indexOf('--');\n const ownArgs = separator < 0 ? args : args.slice(0, separator);\n const piArgs = separator < 0 ? [] : args.slice(separator + 1);\n\n const allowedFlags = new Set([\n '--pi-bin',\n '--profile-db',\n '--provider',\n '--model',\n '--profile-revision',\n '--profile-hash',\n '--required-capabilities',\n '--validate-only',\n '--session-dir',\n '--secret-service-prefix',\n '--macos-keychain-path',\n ]);\n const values = new Map<string, string>();\n for (let index = 0; index < ownArgs.length; index += 2) {\n const flag = ownArgs[index];\n const value = ownArgs[index + 1];\n if (!flag || !allowedFlags.has(flag)) {\n throw new Error(`unknown launcher argument ${flag ?? '<missing>'}`);\n }\n if (values.has(flag)) throw new Error(`launcher argument ${flag} may only be provided once`);\n if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value`);\n if (/[\\u0000\\r\\n]/u.test(value)) {\n throw new Error(`${flag} must be a single-line value`);\n }\n values.set(flag, value);\n }\n\n const required = (flag: string): string => {\n const value = values.get(flag);\n if (value === undefined) throw new Error(`${flag} requires a value`);\n return value;\n };\n\n const rawProfileRef = required('--provider');\n const profileRef = ProviderProfileRefSchema.safeParse(rawProfileRef);\n if (!profileRef.success) {\n throw new Error(`provider profile ref ${rawProfileRef} is not a valid @byok-sdk/keys identifier`);\n }\n\n const modelId = required('--model');\n if (modelId.length > 160) throw new Error('--model exceeds 160 characters');\n\n const profileDbPath = required('--profile-db');\n const sessionDir = required('--session-dir');\n if (!path.isAbsolute(profileDbPath) || !path.isAbsolute(sessionDir)) {\n throw new Error('launcher profile database and session directory must be absolute paths');\n }\n\n const secretServicePrefix = values.get('--secret-service-prefix');\n const macosKeychainPath = values.get('--macos-keychain-path');\n if (macosKeychainPath !== undefined && !path.posix.isAbsolute(macosKeychainPath)) {\n throw new Error('--macos-keychain-path must be an absolute path');\n }\n const validateOnly = values.get('--validate-only') === 'true';\n if (values.has('--validate-only') && !['true', 'false'].includes(values.get('--validate-only')!)) {\n throw new Error('--validate-only must be true or false');\n }\n if (!validateOnly && piArgs.length === 0) {\n throw new Error('launcher requires Pi arguments after --');\n }\n const exactValues = [\n values.get('--profile-revision'),\n values.get('--profile-hash'),\n values.get('--required-capabilities'),\n ];\n if (exactValues.some((value) => value !== undefined) && exactValues.some((value) => value === undefined)) {\n throw new Error('exact provider binding requires revision, hash, and required capabilities together');\n }\n let expectedBinding: ExactProviderProfileBinding | undefined;\n if (exactValues[0] !== undefined) {\n if (!/^(?:0|[1-9][0-9]{0,19})$/u.test(exactValues[0])) {\n throw new Error('--profile-revision must be canonical decimal');\n }\n if (!/^sha256:[0-9a-f]{64}$/u.test(exactValues[1]!)) {\n throw new Error('--profile-hash must be lowercase sha256');\n }\n let capabilities: unknown;\n try {\n capabilities = JSON.parse(exactValues[2]!);\n } catch {\n throw new Error('--required-capabilities must be a JSON array');\n }\n const parsedCapabilities = ProviderModelCapabilitySchema.array().max(8).safeParse(capabilities);\n if (!parsedCapabilities.success || new Set(parsedCapabilities.data).size !== parsedCapabilities.data.length) {\n throw new Error('--required-capabilities must contain unique supported capabilities');\n }\n expectedBinding = {\n profileRef: profileRef.data,\n profileRevision: exactValues[0],\n profileHash: exactValues[1]!,\n modelId,\n requiredCapabilities: parsedCapabilities.data,\n };\n }\n return {\n piBin: required('--pi-bin'),\n profileDbPath,\n profileRef: profileRef.data,\n modelId,\n ...(expectedBinding === undefined ? {} : { expectedBinding }),\n validateOnly,\n sessionDir,\n ...(secretServicePrefix ? { secretServicePrefix } : {}),\n ...(macosKeychainPath !== undefined ? { macosKeychainPath } : {}),\n piArgs,\n };\n}\n\n/**\n * Resolve only the credential the validated profile requires. In particular,\n * an auth-free local provider must remain usable on hosts without an OS\n * credential backend; constructing a keychain there would invent a false\n * dependency and turn an explicit `auth_mode: none` into a hidden fallback.\n */\nexport async function resolvePiProviderSecret(\n profile: ModelProviderProfile,\n createStore: () => SecretStore,\n): Promise<string | undefined> {\n if (profile.auth_mode === 'none') return undefined;\n\n const secrets = createStore();\n if (!(await secrets.available())) {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n `${secrets.providerLabel} is unavailable`,\n );\n }\n const secret = await secrets.get(modelProviderSecretName(profile.profile_ref));\n if (!secret) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_MISSING',\n `${profile.profile_ref} provider profile requires a secret in ${secrets.providerLabel}`,\n );\n }\n return secret;\n}\n\n/** Build Pi's child environment from a closed platform baseline plus one exact key. */\nexport function buildPiProviderChildEnvironment(options: {\n ambient: NodeJS.ProcessEnv;\n projectionDir: string;\n sessionDir: string;\n secret: string | undefined;\n platform?: NodeJS.Platform;\n}): Record<string, string> {\n const platform = options.platform ?? process.platform;\n const exactNames = new Set<string>([\n ...PI_CHILD_BASE_ENV_NAMES,\n ...(platform === 'win32' ? PI_CHILD_WINDOWS_ENV_NAMES : []),\n ].map((name) => platform === 'win32' ? name.toUpperCase() : name));\n const result: Record<string, string> = {};\n for (const [name, value] of Object.entries(options.ambient)) {\n if (value === undefined) continue;\n const platformName = platform === 'win32' ? name.toUpperCase() : name;\n const isExact = exactNames.has(platformName);\n const isPrefixed = platform === 'win32'\n ? platformName.startsWith('LC_') || platformName.startsWith('XDG_')\n : name.startsWith('LC_') || name.startsWith('XDG_');\n if (isExact || isPrefixed) result[name] = value;\n }\n result.PI_CODING_AGENT_DIR = options.projectionDir;\n result.PI_CODING_AGENT_SESSION_DIR = options.sessionDir;\n if (options.secret !== undefined) {\n result[PI_PROJECTED_KEY_ENV] = options.secret;\n }\n return result;\n}\n\n/**\n * Create the configured session directory owner-only without mutating the\n * mode of an existing host-owned directory. The path is operator config, so\n * an accidental `/`, home, or shared-directory value must never become a\n * recursive chmod sink.\n */\nexport async function ensurePiSessionDirectory(sessionDir: string): Promise<void> {\n const firstCreated = await fs.mkdir(sessionDir, { recursive: true, mode: 0o700 });\n if (firstCreated !== undefined) {\n await fs.chmod(sessionDir, 0o700).catch(() => {});\n }\n const stat = await fs.stat(sessionDir);\n if (!stat.isDirectory()) {\n throw new Error('Pi session path must be a directory');\n }\n if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0) {\n throw new Error(\n 'existing Pi session directory must already be owner-only; refusing to change host-owned permissions',\n );\n }\n}\n","import { ByokKeysError } from './errors';\nimport {\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\n\n/**\n * Storage contract for provider profiles — everything needed to address a\n * provider except the API key, which lives in a {@link SecretStore}.\n *\n * Shaped after `@byok-sdk/server`'s `TaskStore` (`packages/server/src/task-store.ts`)\n * as a *pattern*, not a dependency: `keys` must not import `server`, and\n * `server` must not import `keys` (the plan's Security Boundary keeps the\n * agent-dispatch packages free of any credential-adjacent code).\n *\n * Two invariants every implementation MUST enforce, not just\n * {@link InMemoryProviderProfileStore}:\n *\n * 1. **At most one enabled profile.** The source expressed this as a partial\n * unique index (`providers.ts:140-144`); saving an enabled profile disables\n * every other one. {@link resolveDefaultModelProvider} relies on it to\n * answer \"which provider is the default\" with a single row.\n * 2. **Validate on write.** `save` runs {@link parseModelProviderProfile}, so an\n * invalid profile is refused at the boundary rather than discovered later by\n * a reader.\n */\nexport interface ProviderProfileStore {\n /** Release the underlying resource. Safe to call more than once. */\n close(): Promise<void>;\n /** Remove `profileRef`; `false` when it was not configured. */\n delete(profileRef: ProviderProfileRef): Promise<boolean>;\n /** Read one profile, configured or not enabled alike. */\n get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined>;\n /** The single enabled profile, or `undefined` when none is enabled. */\n getEnabled(): Promise<ModelProviderProfile | undefined>;\n /** Every configured profile, ordered by profile ref. */\n list(): Promise<ModelProviderProfile[]>;\n /** Insert or update `profile`, enforcing both invariants above. */\n save(profile: ModelProviderProfile): Promise<ModelProviderProfile>;\n /**\n * Make `profileRef` the enabled profile. Throws `PROVIDER_NOT_CONFIGURED`\n * when it has no profile — a fail-closed port of `providers.ts:1243-1250`.\n */\n setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile>;\n}\n\n/** Shared by both implementations so their error text cannot drift apart. */\nexport function providerNotConfigured(\n profileRef: ProviderProfileRef,\n): ByokKeysError {\n return new ByokKeysError(\n 'PROVIDER_NOT_CONFIGURED',\n `${profileRef} model provider is not configured`,\n );\n}\n\n/**\n * Profile store held in process memory: the default, and the one every test\n * that does not specifically exercise SQLite should use.\n *\n * Mirrors `InMemoryTaskStore`'s role in `@byok-sdk/server` — a real implementation\n * of the contract, not a stub, so behaviour proven here is the behaviour the\n * SQLite store must match (`profile-store.test.ts` runs one suite against both).\n */\nexport class InMemoryProviderProfileStore implements ProviderProfileStore {\n readonly #profiles = new Map<ProviderProfileRef, ModelProviderProfile>();\n\n async close(): Promise<void> {\n this.#profiles.clear();\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n return this.#profiles.delete(profileRef);\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n return this.#profiles.get(profileRef);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n return [...this.#profiles.values()].find((profile) => profile.enabled);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n return [...this.#profiles.values()].sort((left, right) =>\n left.profile_ref.localeCompare(right.profile_ref),\n );\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const validated = parseModelProviderProfile({\n ...profile,\n created_at:\n this.#profiles.get(profile.profile_ref)?.created_at ??\n profile.created_at,\n });\n if (validated.enabled) {\n for (const [profileRef, existing] of this.#profiles) {\n if (profileRef !== validated.profile_ref && existing.enabled) {\n this.#profiles.set(profileRef, { ...existing, enabled: false });\n }\n }\n }\n this.#profiles.set(validated.profile_ref, validated);\n return validated;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const existing = this.#profiles.get(profileRef);\n if (existing === undefined) throw providerNotConfigured(profileRef);\n return this.save({ ...existing, enabled: true });\n }\n}\n","import { chmodSync, existsSync, mkdirSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname } from 'node:path';\nimport type { DatabaseSync, DatabaseSyncOptions } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\n\nexport type SqliteOpenStep = 'after-open' | 'after-wal' | 'after-synchronous';\n\n/** Test-only seam for proving that post-open initialization failures release the native handle. */\nexport interface SqliteOpenFaultSeam {\n onStep?(step: SqliteOpenStep): void;\n close?(database: DatabaseSync): void;\n}\n\n/** Release an opened handle before propagating an initialization failure. */\nexport function closeSqliteDatabaseAfterInitializationFailure(\n database: DatabaseSync,\n initializationError: unknown,\n message: string,\n close: (database: DatabaseSync) => void = (handle) => handle.close(),\n): never {\n try {\n close(database);\n } catch (closeError) {\n throw new AggregateError([initializationError, closeError], message);\n }\n throw initializationError;\n}\n\n/** Owner-only directory mode, matching `providers.ts:1236`. */\nconst SECURE_DIR_MODE = 0o700;\n\n/** Owner-only file mode, matching `providers.ts:158`. */\nconst SECURE_FILE_MODE = 0o600;\n\nconst DEFAULT_BUSY_TIMEOUT_MS = 5_000;\n\ninterface SqliteModule {\n DatabaseSync: new (\n path: string,\n options?: DatabaseSyncOptions,\n ) => DatabaseSync;\n}\n\n/**\n * Load `node:sqlite`, or fail with a `ByokKeysError` that says why.\n *\n * `node:sqlite` shipped in Node.js 22.5.0 and stays marked experimental (an\n * `ExperimentalWarning` on stderr is expected and harmless). Following\n * `@byok-sdk/server`'s `sqlite-support.ts`, the SQLite-backed store here depends on\n * nothing else — no `better-sqlite3`, no native module — because zero native\n * dependencies is what keeps this package trivially packageable. The tradeoff\n * is that {@link SqliteProviderProfileStore} does not work below Node 22.5, and\n * this error says so instead of letting a cryptic `Cannot find module` surface\n * from deep inside a query.\n */\nexport function loadSqliteModule(): SqliteModule {\n try {\n return createRequire(import.meta.url)('node:sqlite') as SqliteModule;\n } catch (error) {\n throw new ByokKeysError(\n 'PROVIDER_STORE_UNAVAILABLE',\n 'node:sqlite is unavailable in this Node.js runtime. SqliteProviderProfileStore ' +\n 'requires Node.js 22.5+ with the built-in `node:sqlite` module (no native ' +\n 'dependency is used or allowed here). Upgrade Node.js, or use ' +\n 'InMemoryProviderProfileStore instead.',\n { cause: error },\n );\n }\n}\n\n/**\n * Whether `node:sqlite` can ACTUALLY be loaded right now.\n *\n * Same predicate as `@byok-sdk/server`'s `sqlite-support.ts`, and it exists for the\n * same reason: this package's `engines.node` is `>=20` and CI runs the matrix\n * on 20 and 22, but `node:sqlite` shipped in 22.5 and stayed behind\n * `--experimental-sqlite` for part of the 22.x line. A version-number\n * comparison would therefore be wrong in both directions, so this attempts the\n * real require via {@link loadSqliteModule} and reports whether it succeeded.\n *\n * Callers use it to skip a SQLite-backed path rather than fail it — the\n * package's own SQLite-backed suites gate on it — and anything else should call\n * it before assuming a {@link SqliteProviderProfileStore} can be constructed.\n */\nexport function isSqliteAvailable(): boolean {\n try {\n loadSqliteModule();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Open a database, creating its parent directory owner-only first. `:memory:`\n * skips every filesystem step, which is how the shared contract suite exercises\n * the SQLite code path without leaving anything on disk.\n */\nexport function openSqliteDatabase(\n path: string,\n options?: DatabaseSyncOptions,\n faults?: SqliteOpenFaultSeam,\n): DatabaseSync {\n const { DatabaseSync } = loadSqliteModule();\n const readOnly = options?.readOnly === true;\n if (path !== ':memory:' && !readOnly) {\n mkdirSync(dirname(path), { mode: SECURE_DIR_MODE, recursive: true });\n }\n const database = new DatabaseSync(path, {\n timeout: DEFAULT_BUSY_TIMEOUT_MS,\n ...options,\n });\n try {\n faults?.onStep?.('after-open');\n if (path !== ':memory:' && !readOnly) {\n database.exec('PRAGMA journal_mode = WAL');\n faults?.onStep?.('after-wal');\n database.exec('PRAGMA synchronous = FULL');\n faults?.onStep?.('after-synchronous');\n }\n return database;\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n database,\n error,\n 'provider profile SQLite open initialization failed and its native handle could not be closed',\n faults?.close,\n );\n }\n}\n\n/**\n * Restrict `databasePath` and its WAL/SHM siblings to owner-only read/write.\n *\n * The profile table holds no secret — that is the whole point of splitting the\n * key into the OS credential store — but it does hold every provider endpoint\n * this machine talks to, and the source locked the file down\n * (`providers.ts:158`), so the port keeps that. Call after the schema exists,\n * so the lazily-created WAL/SHM files are already there; a sibling that does\n * not exist is skipped rather than treated as an error. No-op for `:memory:`.\n */\nexport function secureSqliteFilePermissions(databasePath: string): void {\n if (databasePath === ':memory:') return;\n for (const candidate of [\n databasePath,\n `${databasePath}-wal`,\n `${databasePath}-shm`,\n ]) {\n if (existsSync(candidate)) {\n chmodSync(candidate, SECURE_FILE_MODE);\n }\n }\n}\n","import type { DatabaseSync } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\nimport {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n MODEL_PROVIDER_ADAPTERS,\n MODEL_PROVIDER_KINDS,\n PROVIDER_AUTH_MODES,\n type ModelProviderProfile,\n type ProviderProfileRef,\n parseModelProviderProfile,\n} from './provider-profile';\nimport {\n closeSqliteDatabaseAfterInitializationFailure,\n openSqliteDatabase,\n secureSqliteFilePermissions,\n} from './sqlite-support';\n\nexport interface SqliteProviderProfileStoreOptions {\n /**\n * Database file path. `:memory:` exercises the SQLite code path without a\n * temp file, but defeats the point of this store (restart-safety) exactly as\n * it does for `@byok-sdk/server`'s `SqliteTaskStore`.\n */\n path: string;\n /** Open an existing profile database without creating or mutating it. */\n readOnly?: boolean;\n}\n\n/** SQL string-literal list for a CHECK constraint's `IN (...)` set. */\nfunction sqlList(values: readonly string[]): string {\n return values.map((value) => `'${value}'`).join(', ');\n}\n\n/**\n * Ported from `providers.ts:109-140`, narrowed to the model branch. The\n * source's table also carried `market_data` / `mcp_http` rows and a `tool_name`\n * column; that branch stays in aip-main-open per\n * `docs/researches/HANDOFF-byok-keys.md` §4.5, so the CHECK constraints here\n * are the model half only.\n *\n * The three enumerated CHECK lists are generated from the schema authorities in\n * `provider-profile.ts` rather than restated here: `MODEL_PROVIDER_KINDS` (in\n * turn derived from `provider-catalog.ts`), `MODEL_PROVIDER_ADAPTERS`, and\n * `PROVIDER_AUTH_MODES`. A widened enum therefore cannot silently disagree with\n * a persisted table, and {@link assertProviderProfileSchemaIsCurrent} fails\n * closed on a database whose stored DDL was generated by a different version.\n */\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS provider_profile (\n profile_ref TEXT PRIMARY KEY,\n provider_kind TEXT NOT NULL CHECK (provider_kind IN (${sqlList(MODEL_PROVIDER_KINDS)})),\n kind TEXT NOT NULL CHECK (kind = 'model'),\n adapter TEXT NOT NULL CHECK (adapter IN (${sqlList(MODEL_PROVIDER_ADAPTERS)})),\n display_name TEXT NOT NULL,\n base_url TEXT NOT NULL,\n auth_mode TEXT NOT NULL CHECK (auth_mode IN (${sqlList(PROVIDER_AUTH_MODES)})),\n model TEXT NOT NULL,\n capabilities TEXT NOT NULL,\n enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\n`;\n\n/**\n * Compare a `CREATE TABLE` statement by shape rather than by byte: SQLite\n * stores the original statement text in `sqlite_master.sql` with `IF NOT\n * EXISTS` removed and the trailing semicolon dropped, so both sides are\n * stripped of those and their whitespace runs collapsed before comparison.\n */\nfunction normalizeTableDdl(sql: string): string {\n return sql\n .replace(/\\bIF\\s+NOT\\s+EXISTS\\b/giu, '')\n .replace(/\\s+/gu, ' ')\n .trim()\n .replace(/;$/u, '')\n .trim();\n}\n\n/**\n * Fail closed when the opened database's `provider_profile` table was created\n * by a different `@byok-sdk/keys` schema.\n *\n * `CREATE TABLE IF NOT EXISTS` is a no-op against an existing table, so a store\n * written by a version with a narrower `provider_kind` CHECK would otherwise\n * keep opening and only reject the new kind at `save` time, from inside a\n * transaction, as an opaque constraint violation. There is deliberately no\n * in-place migration: the local profile database holds declared configuration\n * the operator can retype, and a silent ALTER would be exactly the steady-state\n * compatibility path this package refuses. A database that does not carry the\n * table yet passes.\n */\nfunction assertProviderProfileSchemaIsCurrent(\n database: DatabaseSync,\n path: string,\n): void {\n const row = database\n .prepare(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'provider_profile'\",\n )\n .get() as { sql?: string | null } | undefined;\n const stored = row?.sql;\n if (typeof stored !== 'string') return;\n if (normalizeTableDdl(stored) === normalizeTableDdl(SCHEMA)) return;\n throw new ByokKeysError(\n 'PROVIDER_STORE_SCHEMA_STALE',\n `Provider profile store at ${path} was created by a different @byok-sdk/keys schema; recreate the store file to continue`,\n );\n}\n\n/**\n * The \"at most one enabled profile\" invariant, enforced by the database itself\n * rather than only by {@link SqliteProviderProfileStore.save}\n * (`providers.ts:140-144`). A partial unique index means a bug in the write\n * path surfaces as a constraint violation instead of silently producing two\n * defaults.\n */\nconst ENABLED_INDEX = `\nCREATE UNIQUE INDEX IF NOT EXISTS provider_profile_one_enabled\nON provider_profile(kind)\nWHERE enabled = 1;\n`;\n\ninterface ProfileRow {\n adapter: string;\n auth_mode: string;\n base_url: string;\n capabilities: string;\n created_at: string;\n display_name: string;\n enabled: number;\n kind: string;\n model: string;\n profile_ref: string;\n provider_kind: string;\n updated_at: string;\n}\n\n/**\n * SQLite-backed {@link ProviderProfileStore}, following `@byok-sdk/server`'s\n * `SqliteTaskStore` shape. Holds no secret: the API key lives in the injected\n * `SecretStore`, and `registry.golden.test.ts` asserts the plaintext key never\n * appears in this file's bytes.\n */\nexport class SqliteProviderProfileStore implements ProviderProfileStore {\n readonly #database: DatabaseSync;\n #closed = false;\n\n constructor(options: SqliteProviderProfileStoreOptions) {\n this.#database = openSqliteDatabase(options.path, {\n readOnly: options.readOnly ?? false,\n });\n if (!options.readOnly) {\n try {\n this.#database.exec(SCHEMA);\n this.#database.exec(ENABLED_INDEX);\n assertProviderProfileSchemaIsCurrent(this.#database, options.path);\n secureSqliteFilePermissions(options.path);\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n this.#database,\n error,\n 'SqliteProviderProfileStore initialization failed and its native handle could not be closed',\n );\n }\n } else {\n try {\n assertProviderProfileSchemaIsCurrent(this.#database, options.path);\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n this.#database,\n error,\n 'SqliteProviderProfileStore read-only schema check failed and its native handle could not be closed',\n );\n }\n }\n }\n\n /**\n * Idempotent, as {@link ProviderProfileStore.close} requires: `node:sqlite`\n * throws \"database is not open\" on a second `close()`, and a store is\n * routinely closed both by the code that finished with it and by a test's\n * teardown.\n */\n async close(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n this.#database.close();\n }\n\n async delete(profileRef: ProviderProfileRef): Promise<boolean> {\n const result = this.#database\n .prepare('DELETE FROM provider_profile WHERE profile_ref = ?')\n .run(profileRef);\n return Number(result.changes) === 1;\n }\n\n async get(profileRef: ProviderProfileRef): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE profile_ref = ?')\n .get(profileRef) as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE enabled = 1')\n .get() as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n const rows = this.#database\n .prepare('SELECT * FROM provider_profile ORDER BY profile_ref ASC')\n .all() as unknown as ProfileRow[];\n return rows.map(parseRow);\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const existing = await this.get(profile.profile_ref);\n const validated = parseModelProviderProfile({\n ...profile,\n created_at: existing?.created_at ?? profile.created_at,\n });\n this.#transaction(() => {\n if (validated.enabled) {\n this.#database\n .prepare(\n 'UPDATE provider_profile SET enabled = 0 WHERE profile_ref <> ?',\n )\n .run(validated.profile_ref);\n }\n this.#database\n .prepare(\n `INSERT INTO provider_profile (\n profile_ref, provider_kind, kind, adapter, display_name, base_url,\n auth_mode, model, capabilities, enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(profile_ref) DO UPDATE SET\n provider_kind = excluded.provider_kind,\n adapter = excluded.adapter,\n display_name = excluded.display_name,\n base_url = excluded.base_url,\n auth_mode = excluded.auth_mode,\n model = excluded.model,\n capabilities = excluded.capabilities,\n enabled = excluded.enabled,\n updated_at = excluded.updated_at`,\n )\n .run(\n validated.profile_ref,\n validated.provider_kind,\n validated.kind,\n validated.adapter,\n validated.display_name,\n validated.base_url,\n validated.auth_mode,\n validated.model,\n JSON.stringify(validated.capabilities),\n validated.enabled ? 1 : 0,\n validated.created_at,\n validated.updated_at,\n );\n });\n return (await this.get(validated.profile_ref)) as ModelProviderProfile;\n }\n\n async setEnabled(profileRef: ProviderProfileRef): Promise<ModelProviderProfile> {\n const existing = await this.get(profileRef);\n if (existing === undefined) throw providerNotConfigured(profileRef);\n return this.save({ ...existing, enabled: true });\n }\n\n /** `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`, per `providers.ts:1252-1263`. */\n #transaction(body: () => void): void {\n this.#database.exec('BEGIN IMMEDIATE');\n try {\n body();\n this.#database.exec('COMMIT');\n } catch (error) {\n this.#database.exec('ROLLBACK');\n throw error;\n }\n }\n}\n\n/**\n * Rows go back through the same zod schema the write path used, so a row that\n * a different process wrote — or an older schema left behind — is rejected\n * rather than trusted. `enabled` is an INTEGER in SQLite and a real boolean in\n * the schema, and `capabilities` is a JSON array in a TEXT column, so both are\n * decoded explicitly and a row that fails to decode is refused rather than\n * quietly downgraded to an empty capability set.\n */\nfunction parseRow(row: ProfileRow): ModelProviderProfile {\n let capabilities: unknown;\n try {\n capabilities = JSON.parse(row.capabilities);\n } catch (cause) {\n throw new ByokKeysError(\n 'PROVIDER_PROFILE_INVALID',\n 'Provider profile capabilities column is not valid JSON',\n { cause },\n );\n }\n return parseModelProviderProfile({\n ...row,\n capabilities,\n enabled: row.enabled === 1,\n });\n}\n\n/** Exported for the store's own tests to enumerate the CHECK-constrained kinds. */\nexport const SQLITE_PROFILE_PROVIDER_KINDS = MODEL_PROVIDER_KINDS;\n","import { 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","#!/usr/bin/env node\nimport { spawn } from 'node:child_process';\nimport { promises as fs } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { ByokKeysError } from '../errors';\nimport { MacOsKeychainSecretStore } from '../macos-keychain';\nimport {\n type PiProviderLauncherOptions,\n buildPiProviderChildEnvironment,\n ensurePiSessionDirectory,\n parsePiProviderLauncherOptions,\n resolvePiProviderSecret,\n} from '../pi-provider-launcher-core';\nimport { assertExactProviderProfileBinding } from '../provider-profile';\nimport {\n buildPiProviderArgs,\n buildPiProviderProjection,\n} from '../pi-provider-projection';\nimport { type SecretStore } from '../secret-store';\nimport { SqliteProviderProfileStore } from '../sqlite-profile-store';\nimport { WindowsCredentialManagerSecretStore } from '../windows-credential-manager';\n\nfunction createSecretStore(\n servicePrefix: string | undefined,\n macosKeychainPath: string | undefined,\n): SecretStore {\n if (macosKeychainPath !== undefined && process.platform !== 'darwin') {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n 'macOS keychain path is only supported on darwin',\n );\n }\n switch (process.platform) {\n case 'darwin':\n return new MacOsKeychainSecretStore({\n keychainPath: macosKeychainPath,\n servicePrefix,\n });\n case 'win32':\n return new WindowsCredentialManagerSecretStore({ servicePrefix });\n default:\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n `Pi BYOK credential launcher has no plaintext fallback on ${process.platform}`,\n );\n }\n}\n\nasync function run(options: PiProviderLauncherOptions): Promise<number> {\n if (options.macosKeychainPath !== undefined && process.platform !== 'darwin') {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n 'macOS keychain path is only supported on darwin',\n );\n }\n const profiles = new SqliteProviderProfileStore({\n path: options.profileDbPath,\n readOnly: true,\n });\n let projectionDir: string | undefined;\n try {\n const profile = await profiles.get(options.profileRef);\n if (profile === undefined) {\n throw new Error(`provider profile ${options.profileRef} is not configured`);\n }\n if (profile.model !== options.modelId) {\n throw new Error(\n `selected model ${options.modelId} does not match configured provider model ${profile.model}`,\n );\n }\n if (options.expectedBinding !== undefined) {\n assertExactProviderProfileBinding(profile, options.expectedBinding);\n }\n if (options.validateOnly) return 0;\n\n const secret = await resolvePiProviderSecret(\n profile,\n () => createSecretStore(\n options.secretServicePrefix,\n options.macosKeychainPath,\n ),\n );\n\n projectionDir = await fs.mkdtemp(path.join(os.tmpdir(), 'byok-pi-provider-'));\n await fs.chmod(projectionDir, 0o700).catch(() => {});\n await ensurePiSessionDirectory(options.sessionDir);\n await fs.writeFile(\n path.join(projectionDir, 'models.json'),\n `${JSON.stringify(buildPiProviderProjection(profile))}\\n`,\n { mode: 0o600 },\n );\n\n const child = spawn(options.piBin, buildPiProviderArgs(profile, options.piArgs), {\n env: buildPiProviderChildEnvironment({\n ambient: process.env,\n projectionDir,\n sessionDir: options.sessionDir,\n secret,\n }),\n stdio: 'inherit',\n });\n\n const forward = (signal: NodeJS.Signals): void => {\n if (!child.killed) child.kill(signal);\n };\n const onSigint = (): void => forward('SIGINT');\n const onSigterm = (): void => forward('SIGTERM');\n process.on('SIGINT', onSigint);\n process.on('SIGTERM', onSigterm);\n try {\n return await new Promise<number>((resolve, reject) => {\n child.once('error', reject);\n child.once('close', (code, signal) => {\n resolve(code ?? (signal ? 1 : 0));\n });\n });\n } finally {\n process.off('SIGINT', onSigint);\n process.off('SIGTERM', onSigterm);\n }\n } finally {\n await profiles.close();\n if (projectionDir) {\n await fs.rm(projectionDir, { recursive: true, force: true });\n }\n }\n}\n\nasync function main(): Promise<void> {\n try {\n process.exitCode = await run(parsePiProviderLauncherOptions(process.argv.slice(2)));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`pi provider launcher: ${message}\\n`);\n process.exitCode = 1;\n }\n}\n\nvoid main();\n"]}