@byok-sdk/keys 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/bin/pi-provider-launcher.js +57 -19
- package/dist/bin/pi-provider-launcher.js.map +1 -1
- package/dist/index.js +26 -14
- package/dist/index.js.map +1 -1
- package/dist/macos-keychain.d.ts +2 -0
- package/dist/pi-provider-launcher-core.d.ts +1 -0
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/command-runner.ts","../../src/secret-name.ts","../../src/secret-store.ts","../../src/macos-keychain.ts","../../src/pi-provider-projection.ts","../../src/url.ts","../../src/provider-profile.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":["fs","path","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,MA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AM,CAAA;AAAA,IAC7D;AAAA,EACF;AACF;AAEA,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). 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';\nimport type { ModelProviderId } from './provider-profile';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\n\n/**\n * Storage contract for a single secret entry in an operating-system credential\n * store.\n *\n * Ported from `aip-main-open@c6a5385` `apps/local-agent/src/index.ts:261-269`\n * with two deliberate changes:\n *\n * 1. `TName` is a generic parameter rather than aip's closed\n * `KeychainSecretName` union. aip's union names device keys, refresh tokens,\n * and market-data entries that this package has no business knowing about,\n * so it stays in aip and consumers pin their own union. The compile-time\n * closure it provided is replaced at runtime by {@link assertSecretName},\n * which every implementation must apply on every name it receives.\n * 2. `scope()` is required, not optional. The source made it optional and its\n * `scopeLocalAgentSecretStore` silently substituted an envelope\n * implementation when a store did not provide one. Scope-envelope prefixing\n * has no installed base, so this package removes the implicit substitution:\n * every store scopes itself, and {@link EnvelopeScopedSecretStore} is a\n * decorator a caller applies on purpose.\n */\nexport interface SecretStore<TName extends string = string> {\n /** Human-readable backend name, safe to show a user. Never contains a secret. */\n readonly providerLabel: string;\n /** Whether this backend can be used on the current machine. Must not throw. */\n available(): Promise<boolean>;\n /** Remove `name`; `false` when it was already absent. */\n delete(name: TName): Promise<boolean>;\n /** Read `name`, or `undefined` when it is absent. */\n get(name: TName): Promise<string | undefined>;\n /** Whether `name` currently holds a secret. */\n has(name: TName): Promise<boolean>;\n /** A view of this store isolated under `namespace`. */\n scope(namespace: string): SecretStore<TName>;\n /** Write `secret` at `name`, replacing any existing value. */\n set(name: TName, secret: string): Promise<void>;\n}\n\n/**\n * Default service prefix for this package's own entries. `servicePrefix` is a\n * constructor option on both OS backends, so K4's aip-main-open swap passes its\n * `com.aiphabee.local-agent` value and keeps existing installs byte-compatible.\n */\nexport const DEFAULT_SECRET_SERVICE_PREFIX = 'com.byok.keys';\n\n/**\n * Credential-store entry name per model provider, ported verbatim from\n * `providers.ts:1624-1632`. The names carry no vendor branding — the branding\n * lives in the service prefix — so they travel unchanged and K4 needs no\n * migration.\n */\nexport const MODEL_PROVIDER_SECRET_NAMES = {\n anthropic: 'model-anthropic-api-key',\n custom: 'model-custom-api-key',\n deepseek: 'model-deepseek-api-key',\n openai: 'model-openai-api-key',\n} as const satisfies Record<ModelProviderId, string>;\n\nexport type ModelProviderSecretName =\n (typeof MODEL_PROVIDER_SECRET_NAMES)[keyof typeof MODEL_PROVIDER_SECRET_NAMES];\n\n/** Resolve a provider id to the credential-store entry holding its API key. */\nexport function modelProviderSecretName(\n providerId: ModelProviderId,\n): ModelProviderSecretName {\n return MODEL_PROVIDER_SECRET_NAMES[providerId];\n}\n\n/**\n * The secret-shape invariant both OS backends share. Their size ceilings differ\n * in both magnitude and unit (macOS counts 16384 characters, Windows counts\n * 2560 UTF-8 bytes) and each reports its own error code, so those checks stay\n * in the backends; only the empty/control-character rule is common.\n */\nexport function assertSharedSecretValue(secret: string): void {\n if (secret.length === 0 || /[\\u0000\\r\\n]/u.test(secret)) {\n throw new ByokKeysError(\n 'SECRET_VALUE_INVALID',\n 'Secret must be a non-empty string without null or newline characters',\n );\n }\n}\n\n/**\n * Decode base64 to UTF-8 text, or return `undefined` — never a repaired\n * approximation.\n *\n * Both decode paths in Node are lenient in ways that matter here: `Buffer.from`\n * silently drops characters outside the base64 alphabet (so `\"a!G@k=\"` would\n * decode to `\"hi\"`), and `Buffer#toString('utf8')` substitutes U+FFFD for\n * invalid byte sequences. A credential store that \"successfully\" returns a\n * silently-mangled secret is worse than one that fails, so the alphabet, the\n * canonical padding, and the UTF-8 round trip are all checked explicitly.\n */\nexport function decodeStrictBase64Utf8(encoded: string): string | undefined {\n if (encoded.length % 4 !== 0) return undefined;\n if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(encoded)) return undefined;\n const bytes = Buffer.from(encoded, 'base64');\n if (bytes.toString('base64') !== encoded) return undefined;\n const text = bytes.toString('utf8');\n if (!Buffer.from(text, 'utf8').equals(bytes)) return undefined;\n return text;\n}\n\n/**\n * A {@link SecretStore} held in process memory, for tests and for embedders\n * that supply their own persistence.\n *\n * It keys entries by the same `` `${servicePrefix}.${name}` `` string the OS\n * backends use, and `scope()` extends that prefix exactly as they do, so a test\n * written against this store exercises the same isolation arithmetic as\n * production. It applies the name validator and the shared secret-shape rule;\n * the platform size ceilings deliberately are not simulated, since they differ\n * per backend.\n */\nexport class InMemorySecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'in-memory';\n readonly #entries: Map<string, string>;\n readonly #servicePrefix: string;\n\n constructor(\n options: {\n /** Shared backing map; a scoped view keeps the parent's map. */\n entries?: Map<string, string>;\n servicePrefix?: string;\n } = {},\n ) {\n this.#entries = options.entries ?? new Map();\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n }\n\n available(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n async delete(name: TName): Promise<boolean> {\n return this.#entries.delete(this.#service(name));\n }\n\n async get(name: TName): Promise<string | undefined> {\n return this.#entries.get(this.#service(name));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new InMemorySecretStore<TName>({\n entries: this.#entries,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n assertSharedSecretValue(secret);\n this.#entries.set(service, secret);\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n","import { type CommandRunner, runCommand } from './command-runner';\nimport { ByokKeysError } from './errors';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\nimport {\n DEFAULT_SECRET_SERVICE_PREFIX,\n type SecretStore,\n decodeStrictBase64Utf8,\n} from './secret-store';\n\n/**\n * Marker written in front of every stored value so a read can tell a value this\n * package wrote from anything else already sitting at the same service name.\n * Injectable, so K4's aip-main-open swap passes `aiphabee-b64-v1:` and stays\n * byte-compatible with existing installs (source: `index.ts:246`).\n */\nexport const DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX = 'byok-b64-v1:';\n\n/** `security` exits 44 for \"the item does not exist\". */\nconst SECURITY_ITEM_NOT_FOUND = 44;\n\nexport interface MacOsKeychainSecretStoreOptions {\n /** Keychain account field; entries are addressed by (account, service). */\n account?: string;\n /**\n * Return a stored value that lacks {@link MacOsKeychainSecretStoreOptions.storagePrefix}\n * instead of throwing. Defaults to `false`.\n *\n * The source returned such values unconditionally\n * (`decodeMacOsKeychainSecret`, `index.ts:536-545`), which meant any\n * unrelated item at the same service name was handed back as if this package\n * had written it. Reading is fail-closed here, and the tolerant behavior is\n * demoted to something a caller must ask for by name — it exists only for a\n * migration that has read an unprefixed value it already knows it wrote.\n */\n allowUnprefixedRead?: boolean;\n commandRunner?: CommandRunner;\n platform?: NodeJS.Platform;\n servicePrefix?: string;\n storagePrefix?: string;\n}\n\n/**\n * macOS Keychain backend, driving `/usr/bin/security`\n * (`aip-main-open@c6a5385` `apps/local-agent/src/index.ts:412-533`).\n *\n * There is deliberately no plaintext fallback: on a non-darwin platform every\n * operation throws `KEYCHAIN_UNAVAILABLE` rather than degrading to a file.\n */\nexport class MacOsKeychainSecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'macOS Keychain';\n readonly #account: string;\n readonly #allowUnprefixedRead: boolean;\n readonly #commandRunner: CommandRunner;\n readonly #platform: NodeJS.Platform;\n readonly #servicePrefix: string;\n readonly #storagePrefix: string;\n\n constructor(options: MacOsKeychainSecretStoreOptions = {}) {\n this.#account = options.account ?? 'local-device';\n this.#allowUnprefixedRead = options.allowUnprefixedRead ?? false;\n this.#commandRunner = options.commandRunner ?? runCommand;\n this.#platform = options.platform ?? process.platform;\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n this.#storagePrefix =\n options.storagePrefix ?? DEFAULT_KEYCHAIN_SECRET_STORAGE_PREFIX;\n }\n\n async available(): Promise<boolean> {\n if (this.#platform !== 'darwin') return false;\n const result = await this.#commandRunner('/usr/bin/security', [\n 'default-keychain',\n '-d',\n 'user',\n ]);\n return result.exitCode === 0;\n }\n\n async delete(name: TName): Promise<boolean> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'delete-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return false;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_DELETE_FAILED',\n 'macOS Keychain could not delete the requested secret',\n );\n }\n return true;\n }\n\n async get(name: TName): Promise<string | undefined> {\n const service = this.#service(name);\n this.#assertMacOs();\n const result = await this.#commandRunner('/usr/bin/security', [\n 'find-generic-password',\n '-a',\n this.#account,\n '-s',\n service,\n '-w',\n ]);\n if (result.exitCode === SECURITY_ITEM_NOT_FOUND) return undefined;\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_READ_FAILED',\n 'macOS Keychain could not read the requested secret',\n );\n }\n return this.#decode(result.stdout.replace(/\\r?\\n$/u, ''));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new MacOsKeychainSecretStore<TName>({\n account: this.#account,\n allowUnprefixedRead: this.#allowUnprefixedRead,\n commandRunner: this.#commandRunner,\n platform: this.#platform,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n storagePrefix: this.#storagePrefix,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n this.#assertMacOs();\n if (\n secret.length === 0 ||\n secret.length > 16_384 ||\n /[\\u0000\\r\\n]/u.test(secret)\n ) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_INVALID',\n 'Secret must contain 1 to 16384 non-newline characters',\n );\n }\n // `security add-generic-password -w` opens /dev/tty when no password\n // argument is supplied, even if the child has a piped stdin. Interactive\n // mode accepts the complete command through stdin, keeping the encoded\n // secret out of argv/process listings and avoiding an unattended prompt.\n const storedSecret = `${this.#storagePrefix}${Buffer.from(secret, 'utf8').toString('base64')}`;\n const command = [\n 'add-generic-password',\n '-U',\n '-a',\n quoteSecurityInteractiveArgument(this.#account),\n '-s',\n quoteSecurityInteractiveArgument(service),\n '-w',\n quoteSecurityInteractiveArgument(storedSecret),\n ].join(' ');\n const result = await this.#commandRunner(\n '/usr/bin/security',\n ['-i'],\n `${command}\\n`,\n );\n if (result.exitCode !== 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_WRITE_FAILED',\n 'macOS Keychain could not store the requested secret',\n );\n }\n }\n\n #assertMacOs(): void {\n if (this.#platform !== 'darwin') {\n throw new ByokKeysError(\n 'KEYCHAIN_UNAVAILABLE',\n 'macOS Keychain is required; plaintext fallback is disabled',\n );\n }\n }\n\n /**\n * Fail-closed inverse of the storage encoding. The error message never\n * echoes the undecodable value — it may still be somebody's live credential.\n */\n #decode(storedSecret: string): string {\n if (!storedSecret.startsWith(this.#storagePrefix)) {\n if (this.#allowUnprefixedRead) return storedSecret;\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a value without this store\\'s storage prefix',\n );\n }\n const decoded = decodeStrictBase64Utf8(\n storedSecret.slice(this.#storagePrefix.length),\n );\n if (decoded === undefined || decoded.length === 0) {\n throw new ByokKeysError(\n 'KEYCHAIN_SECRET_DECODE_FAILED',\n 'macOS Keychain returned a secret that is not valid base64-encoded UTF-8',\n );\n }\n return decoded;\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n\n/**\n * Quote a value for `security -i`'s interactive parser (`index.ts:547-557`).\n * Null and newline characters cannot be quoted safely — a newline would end the\n * command line and let the remainder be parsed as a second command — so they are\n * rejected rather than escaped.\n */\nfunction quoteSecurityInteractiveArgument(value: string): string {\n if (/[\\u0000\\r\\n]/u.test(value)) {\n throw new ByokKeysError(\n 'KEYCHAIN_ARGUMENT_INVALID',\n 'macOS Keychain arguments cannot contain null or newline characters',\n );\n }\n return `\"${value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')}\"`;\n}\n","import type { ModelProviderProfile } from './provider-profile';\n\nexport const PI_PROJECTED_KEY_ENV = 'PI_PROVIDER_API_KEY';\n\n/** Keep projected providers disjoint from Pi built-ins so composition can never fall back to one. */\nexport function piProjectionProviderId(profileProviderId: string): string {\n return `byok-sdk-${profileProviderId}`;\n}\n\n/** Credential-blind Pi configuration derived from one validated local profile. */\nexport function buildPiProviderProjection(profile: ModelProviderProfile): object {\n const projectedProviderId = piProjectionProviderId(profile.provider_id);\n return {\n providers: {\n [projectedProviderId]: {\n baseUrl: profile.base_url,\n api:\n profile.adapter === 'anthropic'\n ? 'anthropic-messages'\n : 'openai-completions',\n ...(profile.auth_mode === 'none'\n ? {}\n : { apiKey: `$${PI_PROJECTED_KEY_ENV}` }),\n ...(profile.auth_mode === 'bearer' ? { authHeader: true } : {}),\n models: [\n {\n id: profile.model,\n name: profile.display_name,\n },\n ],\n },\n },\n };\n}\n\n/**\n * Validate the credential-blind RPC argv the client may delegate, then bind\n * the Pi child to the namespaced projection and exact configured model.\n */\nexport function buildPiProviderArgs(\n profile: ModelProviderProfile,\n delegatedArgs: readonly string[],\n): string[] {\n let modeCount = 0;\n for (let index = 0; index < delegatedArgs.length; index += 1) {\n const flag = delegatedArgs[index];\n if (flag === '--no-tools') continue;\n if (flag === '--mode') {\n modeCount += 1;\n const value = delegatedArgs[index + 1];\n if (value !== 'rpc') throw new Error('Pi launcher requires --mode rpc');\n index += 1;\n continue;\n }\n if (flag === '--session' || flag === '--tools' || flag === '--exclude-tools') {\n const value = delegatedArgs[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`${flag} requires a value`);\n }\n index += 1;\n continue;\n }\n throw new Error(`Pi launcher does not allow delegated argument ${flag ?? '<missing>'}`);\n }\n if (modeCount !== 1) throw new Error('Pi launcher requires exactly one --mode rpc');\n\n return [\n ...delegatedArgs,\n '--provider',\n piProjectionProviderId(profile.provider_id),\n '--model',\n profile.model,\n ];\n}\n","import { ByokKeysError } from './errors';\n\n/**\n * Normalize a provider base URL, fail-closed.\n *\n * Ported from `aip-main-open@c6a5385` `providers.ts:1558-1588` plus the two\n * host predicates at `:2216-2242`. Rules, unchanged:\n * - must be an absolute URL;\n * - no embedded credentials, no fragment, no query string;\n * - HTTPS only, except that HTTP is allowed for loopback hosts;\n * - private-network literals are rejected unless they are loopback;\n * - one trailing slash is stripped.\n */\nexport function normalizeProviderUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider base URL must be absolute',\n );\n }\n if (\n url.username ||\n url.password ||\n url.hash ||\n url.search ||\n (url.protocol !== 'https:' &&\n !(url.protocol === 'http:' && isLoopbackHost(url.hostname)))\n ) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider URL requires HTTPS; HTTP is allowed only for localhost',\n );\n }\n if (isPrivateNetworkLiteral(url.hostname) && !isLoopbackHost(url.hostname)) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Private-network provider IPs are not allowed',\n );\n }\n return url.toString().replace(/\\/$/u, '');\n}\n\n/** Whether an already-parseable provider URL points at a loopback host. */\nexport function isLoopbackProviderUrl(value: string): boolean {\n return isLoopbackHost(new URL(value).hostname);\n}\n\nexport function isLoopbackHost(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n return value === 'localhost' || value === '127.0.0.1' || value === '::1';\n}\n\n/**\n * Conservative private-network literal check. Any IPv6 literal counts as\n * private (the `:` branch), matching the source: the guard cannot cheaply\n * classify IPv6 ranges, so it refuses all of them and lets hostnames through.\n */\nexport function isPrivateNetworkLiteral(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n if (value.includes(':')) return true;\n const parts = value.split('.').map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n return (\n parts[0] === 10 ||\n parts[0] === 127 ||\n (parts[0] === 169 && parts[1] === 254) ||\n (parts[0] === 172 && (parts[1] ?? 0) >= 16 && (parts[1] ?? 0) <= 31) ||\n (parts[0] === 192 && parts[1] === 168)\n );\n}\n","import { z } from 'zod';\n\nimport { ByokKeysError } from './errors';\nimport { normalizeProviderUrl } from './url';\n\n/**\n * Model providers this package knows how to address. Ported from\n * `aip-main-open@c6a5385` `providers.ts:30-36` (`LOCAL_MODEL_PROVIDER_IDS`).\n */\nexport const MODEL_PROVIDER_IDS = [\n 'openai',\n 'deepseek',\n 'anthropic',\n 'custom',\n] as const;\n\nexport type ModelProviderId = (typeof MODEL_PROVIDER_IDS)[number];\n\n/** Auth modes a provider profile can request (`providers.ts:29`). */\nexport const PROVIDER_AUTH_MODES = ['bearer', 'x_api_key', 'none'] as const;\n\nexport type ProviderAuthMode = (typeof PROVIDER_AUTH_MODES)[number];\n\n/**\n * Wire dialects. The source's `market_data` / `mcp_http` branch stays in\n * aip-main-open — this package ports the model branch only\n * (`providers.ts:38-61`, second union member).\n */\nexport const MODEL_PROVIDER_ADAPTERS = ['openai_compatible', 'anthropic'] as const;\n\nexport type ModelProviderAdapter = (typeof MODEL_PROVIDER_ADAPTERS)[number];\n\n/**\n * Marker attached to schema issues so {@link parseModelProviderProfile} can\n * reproduce the source's distinct error codes: the URL guard reports\n * `PROVIDER_URL_INVALID`, everything else reports `PROVIDER_PROFILE_INVALID`.\n */\ninterface ProfileIssueParams {\n byokCode: string;\n}\n\nfunction boundedString(field: string, maximumLength: number) {\n return z\n .string()\n .superRefine((value, ctx) => {\n if (\n value.trim().length === 0 ||\n value.length > maximumLength ||\n /[\\u0000\\r\\n]/u.test(value)\n ) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} is invalid`,\n });\n }\n })\n .transform((value) => value.trim());\n}\n\nfunction isoTimestamp(field: string) {\n return boundedString(field, 64).superRefine((value, ctx) => {\n if (!Number.isFinite(Date.parse(value))) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} must be an ISO timestamp`,\n });\n }\n });\n}\n\nconst providerBaseUrl = z\n .string()\n .superRefine((value, ctx) => {\n try {\n normalizeProviderUrl(value);\n } catch (error) {\n ctx.addIssue({\n code: 'custom',\n message:\n error instanceof Error ? error.message : 'Provider base URL is invalid',\n params: {\n byokCode:\n error instanceof ByokKeysError ? error.code : 'PROVIDER_URL_INVALID',\n } satisfies ProfileIssueParams,\n });\n }\n })\n .transform((value) => normalizeProviderUrl(value));\n\n/**\n * A model provider profile: everything needed to address a provider except the\n * secret itself, which lives in the OS credential store.\n *\n * The adapter/auth-mode legality rules are the ones `normalizeProviderProfile`\n * enforced imperatively at `providers.ts:1522-1543`, moved into the schema so\n * there is one validation authority rather than a schema plus a normalizer.\n */\nexport const ModelProviderProfileSchema = z\n .object({\n adapter: z.enum(MODEL_PROVIDER_ADAPTERS),\n auth_mode: z.enum(PROVIDER_AUTH_MODES),\n base_url: providerBaseUrl,\n created_at: isoTimestamp('created_at'),\n display_name: boundedString('display_name', 100),\n enabled: z.boolean(),\n kind: z.literal('model'),\n model: boundedString('model', 160),\n provider_id: z.enum(MODEL_PROVIDER_IDS),\n updated_at: isoTimestamp('updated_at'),\n })\n .superRefine((profile, ctx) => {\n if (profile.adapter === 'anthropic' && profile.auth_mode !== 'x_api_key') {\n ctx.addIssue({\n code: 'custom',\n message: 'Anthropic requires x_api_key authentication',\n path: ['auth_mode'],\n });\n }\n if (\n profile.adapter === 'openai_compatible' &&\n profile.auth_mode === 'x_api_key'\n ) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'OpenAI-compatible providers support bearer or no authentication',\n path: ['auth_mode'],\n });\n }\n if (Date.parse(profile.updated_at) < Date.parse(profile.created_at)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider updated_at cannot precede created_at',\n path: ['updated_at'],\n });\n }\n });\n\n/** Validated, normalized profile. */\nexport type ModelProviderProfile = z.infer<typeof ModelProviderProfileSchema>;\n\n/** Pre-normalization shape callers may hand in. */\nexport type ModelProviderProfileInput = z.input<typeof ModelProviderProfileSchema>;\n\n/**\n * Parse and normalize a profile, or throw {@link ByokKeysError}. Replaces the\n * source's `normalizeProviderProfile` (`providers.ts:1489-1556`) for the model\n * branch, preserving its error codes.\n */\nexport function parseModelProviderProfile(value: unknown): ModelProviderProfile {\n const result = ModelProviderProfileSchema.safeParse(value);\n if (result.success) return result.data;\n const issue = result.error.issues[0];\n const params = (issue as { params?: Partial<ProfileIssueParams> } | undefined)\n ?.params;\n throw new ByokKeysError(\n params?.byokCode ?? 'PROVIDER_PROFILE_INVALID',\n issue?.message ?? 'Provider profile is invalid',\n { cause: result.error },\n );\n}\n","import 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 MODEL_PROVIDER_IDS,\n type ModelProviderId,\n type ModelProviderProfile,\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 providerId: ModelProviderId;\n modelId: string;\n sessionDir: string;\n secretServicePrefix?: string;\n piArgs: string[];\n}\n\nexport function parsePiProviderLauncherOptions(\n args: string[],\n): PiProviderLauncherOptions {\n const separator = args.indexOf('--');\n if (separator < 0) throw new Error('launcher arguments must end with -- <pi args>');\n const ownArgs = args.slice(0, separator);\n const piArgs = args.slice(separator + 1);\n if (piArgs.length === 0) throw new Error('launcher requires Pi arguments after --');\n\n const allowedFlags = new Set([\n '--pi-bin',\n '--profile-db',\n '--provider',\n '--model',\n '--session-dir',\n '--secret-service-prefix',\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 rawProviderId = required('--provider');\n if (!MODEL_PROVIDER_IDS.includes(rawProviderId as ModelProviderId)) {\n throw new Error(`provider ${rawProviderId} is not configured by @byok-sdk/keys`);\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 return {\n piBin: required('--pi-bin'),\n profileDbPath,\n providerId: rawProviderId as ModelProviderId,\n modelId,\n sessionDir,\n ...(secretServicePrefix ? { secretServicePrefix } : {}),\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.provider_id));\n if (!secret) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_MISSING',\n `${profile.provider_id} provider 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 ModelProviderId,\n type ModelProviderProfile,\n parseModelProviderProfile,\n} from './provider-profile';\n\n/**\n * Storage contract for provider profiles — everything needed to address a\n * provider except the API key, which lives in a {@link SecretStore}.\n *\n * Shaped after `@byok-sdk/server`'s `TaskStore` (`packages/server/src/task-store.ts`)\n * as a *pattern*, not a dependency: `keys` must not import `server`, and\n * `server` must not import `keys` (the plan's Security Boundary keeps the\n * agent-dispatch packages free of any credential-adjacent code).\n *\n * Two invariants every implementation MUST enforce, not just\n * {@link InMemoryProviderProfileStore}:\n *\n * 1. **At most one enabled profile.** The source expressed this as a partial\n * unique index (`providers.ts:140-144`); saving an enabled profile disables\n * every other one. {@link resolveDefaultModelProvider} relies on it to\n * answer \"which provider is the default\" with a single row.\n * 2. **Validate on write.** `save` runs {@link parseModelProviderProfile}, so an\n * invalid profile is refused at the boundary rather than discovered later by\n * a reader.\n */\nexport interface ProviderProfileStore {\n /** Release the underlying resource. Safe to call more than once. */\n close(): Promise<void>;\n /** Remove `providerId`; `false` when it was not configured. */\n delete(providerId: ModelProviderId): Promise<boolean>;\n /** Read one provider's profile, configured or not enabled alike. */\n get(providerId: ModelProviderId): Promise<ModelProviderProfile | undefined>;\n /** The single enabled profile, or `undefined` when none is enabled. */\n getEnabled(): Promise<ModelProviderProfile | undefined>;\n /** Every configured profile, ordered by provider id. */\n list(): Promise<ModelProviderProfile[]>;\n /** Insert or update `profile`, enforcing both invariants above. */\n save(profile: ModelProviderProfile): Promise<ModelProviderProfile>;\n /**\n * Make `providerId` the enabled profile. Throws `PROVIDER_NOT_CONFIGURED`\n * when it has no profile — a fail-closed port of `providers.ts:1243-1250`.\n */\n setEnabled(providerId: ModelProviderId): Promise<ModelProviderProfile>;\n}\n\n/** Shared by both implementations so their error text cannot drift apart. */\nexport function providerNotConfigured(\n providerId: ModelProviderId,\n): ByokKeysError {\n return new ByokKeysError(\n 'PROVIDER_NOT_CONFIGURED',\n `${providerId} model provider is not configured`,\n );\n}\n\n/**\n * Profile store held in process memory: the default, and the one every test\n * that does not specifically exercise SQLite should use.\n *\n * Mirrors `InMemoryTaskStore`'s role in `@byok-sdk/server` — a real implementation\n * of the contract, not a stub, so behaviour proven here is the behaviour the\n * SQLite store must match (`profile-store.test.ts` runs one suite against both).\n */\nexport class InMemoryProviderProfileStore implements ProviderProfileStore {\n readonly #profiles = new Map<ModelProviderId, ModelProviderProfile>();\n\n async close(): Promise<void> {\n this.#profiles.clear();\n }\n\n async delete(providerId: ModelProviderId): Promise<boolean> {\n return this.#profiles.delete(providerId);\n }\n\n async get(providerId: ModelProviderId): Promise<ModelProviderProfile | undefined> {\n return this.#profiles.get(providerId);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n return [...this.#profiles.values()].find((profile) => profile.enabled);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n return [...this.#profiles.values()].sort((left, right) =>\n left.provider_id.localeCompare(right.provider_id),\n );\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const validated = parseModelProviderProfile({\n ...profile,\n created_at:\n this.#profiles.get(profile.provider_id)?.created_at ??\n profile.created_at,\n });\n if (validated.enabled) {\n for (const [providerId, existing] of this.#profiles) {\n if (providerId !== validated.provider_id && existing.enabled) {\n this.#profiles.set(providerId, { ...existing, enabled: false });\n }\n }\n }\n this.#profiles.set(validated.provider_id, validated);\n return validated;\n }\n\n async setEnabled(providerId: ModelProviderId): Promise<ModelProviderProfile> {\n const existing = this.#profiles.get(providerId);\n if (existing === undefined) throw providerNotConfigured(providerId);\n return this.save({ ...existing, enabled: true });\n }\n}\n","import { chmodSync, existsSync, mkdirSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname } from 'node:path';\nimport type { DatabaseSync, DatabaseSyncOptions } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\n\nexport type SqliteOpenStep = 'after-open' | 'after-wal' | 'after-synchronous';\n\n/** Test-only seam for proving that post-open initialization failures release the native handle. */\nexport interface SqliteOpenFaultSeam {\n onStep?(step: SqliteOpenStep): void;\n close?(database: DatabaseSync): void;\n}\n\n/** Release an opened handle before propagating an initialization failure. */\nexport function closeSqliteDatabaseAfterInitializationFailure(\n database: DatabaseSync,\n initializationError: unknown,\n message: string,\n close: (database: DatabaseSync) => void = (handle) => handle.close(),\n): never {\n try {\n close(database);\n } catch (closeError) {\n throw new AggregateError([initializationError, closeError], message);\n }\n throw initializationError;\n}\n\n/** Owner-only directory mode, matching `providers.ts:1236`. */\nconst SECURE_DIR_MODE = 0o700;\n\n/** Owner-only file mode, matching `providers.ts:158`. */\nconst SECURE_FILE_MODE = 0o600;\n\nconst DEFAULT_BUSY_TIMEOUT_MS = 5_000;\n\ninterface SqliteModule {\n DatabaseSync: new (\n path: string,\n options?: DatabaseSyncOptions,\n ) => DatabaseSync;\n}\n\n/**\n * Load `node:sqlite`, or fail with a `ByokKeysError` that says why.\n *\n * `node:sqlite` shipped in Node.js 22.5.0 and stays marked experimental (an\n * `ExperimentalWarning` on stderr is expected and harmless). Following\n * `@byok-sdk/server`'s `sqlite-support.ts`, the SQLite-backed store here depends on\n * nothing else — no `better-sqlite3`, no native module — because zero native\n * dependencies is what keeps this package trivially packageable. The tradeoff\n * is that {@link SqliteProviderProfileStore} does not work below Node 22.5, and\n * this error says so instead of letting a cryptic `Cannot find module` surface\n * from deep inside a query.\n */\nexport function loadSqliteModule(): SqliteModule {\n try {\n return createRequire(import.meta.url)('node:sqlite') as SqliteModule;\n } catch (error) {\n throw new ByokKeysError(\n 'PROVIDER_STORE_UNAVAILABLE',\n 'node:sqlite is unavailable in this Node.js runtime. SqliteProviderProfileStore ' +\n 'requires Node.js 22.5+ with the built-in `node:sqlite` module (no native ' +\n 'dependency is used or allowed here). Upgrade Node.js, or use ' +\n 'InMemoryProviderProfileStore instead.',\n { cause: error },\n );\n }\n}\n\n/**\n * Whether `node:sqlite` can ACTUALLY be loaded right now.\n *\n * Same predicate as `@byok-sdk/server`'s `sqlite-support.ts`, and it exists for the\n * same reason: this package's `engines.node` is `>=20` and CI runs the matrix\n * on 20 and 22, but `node:sqlite` shipped in 22.5 and stayed behind\n * `--experimental-sqlite` for part of the 22.x line. A version-number\n * comparison would therefore be wrong in both directions, so this attempts the\n * real require via {@link loadSqliteModule} and reports whether it succeeded.\n *\n * Callers use it to skip a SQLite-backed path rather than fail it — the\n * package's own SQLite-backed suites gate on it — and anything else should call\n * it before assuming a {@link SqliteProviderProfileStore} can be constructed.\n */\nexport function isSqliteAvailable(): boolean {\n try {\n loadSqliteModule();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Open a database, creating its parent directory owner-only first. `:memory:`\n * skips every filesystem step, which is how the shared contract suite exercises\n * the SQLite code path without leaving anything on disk.\n */\nexport function openSqliteDatabase(\n path: string,\n options?: DatabaseSyncOptions,\n faults?: SqliteOpenFaultSeam,\n): DatabaseSync {\n const { DatabaseSync } = loadSqliteModule();\n const readOnly = options?.readOnly === true;\n if (path !== ':memory:' && !readOnly) {\n mkdirSync(dirname(path), { mode: SECURE_DIR_MODE, recursive: true });\n }\n const database = new DatabaseSync(path, {\n timeout: DEFAULT_BUSY_TIMEOUT_MS,\n ...options,\n });\n try {\n faults?.onStep?.('after-open');\n if (path !== ':memory:' && !readOnly) {\n database.exec('PRAGMA journal_mode = WAL');\n faults?.onStep?.('after-wal');\n database.exec('PRAGMA synchronous = FULL');\n faults?.onStep?.('after-synchronous');\n }\n return database;\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n database,\n error,\n 'provider profile SQLite open initialization failed and its native handle could not be closed',\n faults?.close,\n );\n }\n}\n\n/**\n * Restrict `databasePath` and its WAL/SHM siblings to owner-only read/write.\n *\n * The profile table holds no secret — that is the whole point of splitting the\n * key into the OS credential store — but it does hold every provider endpoint\n * this machine talks to, and the source locked the file down\n * (`providers.ts:158`), so the port keeps that. Call after the schema exists,\n * so the lazily-created WAL/SHM files are already there; a sibling that does\n * not exist is skipped rather than treated as an error. No-op for `:memory:`.\n */\nexport function secureSqliteFilePermissions(databasePath: string): void {\n if (databasePath === ':memory:') return;\n for (const candidate of [\n databasePath,\n `${databasePath}-wal`,\n `${databasePath}-shm`,\n ]) {\n if (existsSync(candidate)) {\n chmodSync(candidate, SECURE_FILE_MODE);\n }\n }\n}\n","import type { DatabaseSync } from 'node:sqlite';\n\nimport {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n MODEL_PROVIDER_IDS,\n type ModelProviderId,\n type ModelProviderProfile,\n parseModelProviderProfile,\n} from './provider-profile';\nimport {\n closeSqliteDatabaseAfterInitializationFailure,\n openSqliteDatabase,\n secureSqliteFilePermissions,\n} from './sqlite-support';\n\nexport interface SqliteProviderProfileStoreOptions {\n /**\n * Database file path. `:memory:` exercises the SQLite code path without a\n * temp file, but defeats the point of this store (restart-safety) exactly as\n * it does for `@byok-sdk/server`'s `SqliteTaskStore`.\n */\n path: string;\n /** Open an existing profile database without creating or mutating it. */\n readOnly?: boolean;\n}\n\n/**\n * Ported from `providers.ts:109-140`, narrowed to the model branch. The\n * source's table also carried `market_data` / `mcp_http` rows and a `tool_name`\n * column; that branch stays in aip-main-open per\n * `docs/researches/HANDOFF-byok-keys.md` §4.5, so the CHECK constraints here\n * are the model half only.\n */\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS provider_profile (\n provider_id TEXT PRIMARY KEY CHECK (provider_id IN ('openai', 'deepseek', 'anthropic', 'custom')),\n kind TEXT NOT NULL CHECK (kind = 'model'),\n adapter TEXT NOT NULL CHECK (adapter IN ('openai_compatible', 'anthropic')),\n display_name TEXT NOT NULL,\n base_url TEXT NOT NULL,\n auth_mode TEXT NOT NULL CHECK (auth_mode IN ('bearer', 'x_api_key', 'none')),\n model TEXT NOT NULL,\n enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\n`;\n\n/**\n * The \"at most one enabled profile\" invariant, enforced by the database itself\n * rather than only by {@link SqliteProviderProfileStore.save}\n * (`providers.ts:140-144`). A partial unique index means a bug in the write\n * path surfaces as a constraint violation instead of silently producing two\n * defaults.\n */\nconst ENABLED_INDEX = `\nCREATE UNIQUE INDEX IF NOT EXISTS provider_profile_one_enabled\nON provider_profile(kind)\nWHERE enabled = 1;\n`;\n\ninterface ProfileRow {\n adapter: string;\n auth_mode: string;\n base_url: string;\n created_at: string;\n display_name: string;\n enabled: number;\n kind: string;\n model: string;\n provider_id: string;\n updated_at: string;\n}\n\n/**\n * SQLite-backed {@link ProviderProfileStore}, following `@byok-sdk/server`'s\n * `SqliteTaskStore` shape. Holds no secret: the API key lives in the injected\n * `SecretStore`, and `registry.golden.test.ts` asserts the plaintext key never\n * appears in this file's bytes.\n */\nexport class SqliteProviderProfileStore implements ProviderProfileStore {\n readonly #database: DatabaseSync;\n #closed = false;\n\n constructor(options: SqliteProviderProfileStoreOptions) {\n this.#database = openSqliteDatabase(options.path, {\n readOnly: options.readOnly ?? false,\n });\n if (!options.readOnly) {\n try {\n this.#database.exec(SCHEMA);\n this.#database.exec(ENABLED_INDEX);\n secureSqliteFilePermissions(options.path);\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n this.#database,\n error,\n 'SqliteProviderProfileStore initialization failed and its native handle could not be closed',\n );\n }\n }\n }\n\n /**\n * Idempotent, as {@link ProviderProfileStore.close} requires: `node:sqlite`\n * throws \"database is not open\" on a second `close()`, and a store is\n * routinely closed both by the code that finished with it and by a test's\n * teardown.\n */\n async close(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n this.#database.close();\n }\n\n async delete(providerId: ModelProviderId): Promise<boolean> {\n const result = this.#database\n .prepare('DELETE FROM provider_profile WHERE provider_id = ?')\n .run(providerId);\n return Number(result.changes) === 1;\n }\n\n async get(providerId: ModelProviderId): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE provider_id = ?')\n .get(providerId) as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE enabled = 1')\n .get() as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n const rows = this.#database\n .prepare('SELECT * FROM provider_profile ORDER BY provider_id ASC')\n .all() as unknown as ProfileRow[];\n return rows.map(parseRow);\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const existing = await this.get(profile.provider_id);\n const validated = parseModelProviderProfile({\n ...profile,\n created_at: existing?.created_at ?? profile.created_at,\n });\n this.#transaction(() => {\n if (validated.enabled) {\n this.#database\n .prepare(\n 'UPDATE provider_profile SET enabled = 0 WHERE provider_id <> ?',\n )\n .run(validated.provider_id);\n }\n this.#database\n .prepare(\n `INSERT INTO provider_profile (\n provider_id, kind, adapter, display_name, base_url,\n auth_mode, model, enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(provider_id) DO UPDATE SET\n adapter = excluded.adapter,\n display_name = excluded.display_name,\n base_url = excluded.base_url,\n auth_mode = excluded.auth_mode,\n model = excluded.model,\n enabled = excluded.enabled,\n updated_at = excluded.updated_at`,\n )\n .run(\n validated.provider_id,\n validated.kind,\n validated.adapter,\n validated.display_name,\n validated.base_url,\n validated.auth_mode,\n validated.model,\n validated.enabled ? 1 : 0,\n validated.created_at,\n validated.updated_at,\n );\n });\n return (await this.get(validated.provider_id)) as ModelProviderProfile;\n }\n\n async setEnabled(providerId: ModelProviderId): Promise<ModelProviderProfile> {\n const existing = await this.get(providerId);\n if (existing === undefined) throw providerNotConfigured(providerId);\n return this.save({ ...existing, enabled: true });\n }\n\n /** `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`, per `providers.ts:1252-1263`. */\n #transaction(body: () => void): void {\n this.#database.exec('BEGIN IMMEDIATE');\n try {\n body();\n this.#database.exec('COMMIT');\n } catch (error) {\n this.#database.exec('ROLLBACK');\n throw error;\n }\n }\n}\n\n/**\n * Rows go back through the same zod schema the write path used, so a row that\n * a different process wrote — or an older schema left behind — is rejected\n * rather than trusted. `enabled` is an INTEGER in SQLite and a real boolean in\n * the schema, so it is converted rather than coerced loosely.\n */\nfunction parseRow(row: ProfileRow): ModelProviderProfile {\n return parseModelProviderProfile({\n ...row,\n enabled: row.enabled === 1,\n });\n}\n\n/** Exported for the store's own tests to enumerate the CHECK-constrained ids. */\nexport const SQLITE_PROFILE_PROVIDER_IDS = MODEL_PROVIDER_IDS;\n","import { 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 {\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): SecretStore {\n switch (process.platform) {\n case 'darwin':\n return new MacOsKeychainSecretStore({ servicePrefix });\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 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.providerId);\n if (profile === undefined) {\n throw new Error(`provider ${options.providerId} 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\n const secret = await resolvePiProviderSecret(\n profile,\n () => createSecretStore(options.secretServicePrefix),\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/secret-store.ts","../../src/macos-keychain.ts","../../src/pi-provider-projection.ts","../../src/url.ts","../../src/provider-profile.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,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S,MAAA,KAAW;AACpD,QAAA,KAAA,CAAM,IAAA,CAAK,SAAS,MAAM,CAAA;AAC1B,QAAA,KAAA,CAAM,IAAA,CAAK,OAAA,EAAS,CAAC,IAAA,EAAM,MAAA,KAAW;AACpC,UAAA,OAAA,CAAQ,IAAA,KAAS,MAAA,GAAS,CAAA,GAAI,CAAA,CAAE,CAAA;AAAA,QAClC,CAAC,CAAA;AAAA,MACH,CAAC,CAAA;AAAA,IACH,CAAA,SAAE;AACA,MAAA,OAAA,CAAQ,GAAA,CAAI,UAAU,QAAQ,CAAA;AAC9B,MAAA,OAAA,CAAQ,GAAA,CAAI,WAAW,SAAS,CAAA;AAAA,IAClC;AAAA,EACF,CAAA,SAAE;AACA,IAAA,MAAM,SAAS,KAAA,EAAM;AACrB,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,MAAMD,QAAAA,CAAG,GAAG,aAAA,EAAe,EAAE,WAAW,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAAA,IAC7D;AAAA,EACF;AACF;AAEA,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). 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';\nimport type { ModelProviderId } from './provider-profile';\nimport { assertSecretName, assertSecretNamespace } from './secret-name';\n\n/**\n * Storage contract for a single secret entry in an operating-system credential\n * store.\n *\n * Ported from `aip-main-open@c6a5385` `apps/local-agent/src/index.ts:261-269`\n * with two deliberate changes:\n *\n * 1. `TName` is a generic parameter rather than aip's closed\n * `KeychainSecretName` union. aip's union names device keys, refresh tokens,\n * and market-data entries that this package has no business knowing about,\n * so it stays in aip and consumers pin their own union. The compile-time\n * closure it provided is replaced at runtime by {@link assertSecretName},\n * which every implementation must apply on every name it receives.\n * 2. `scope()` is required, not optional. The source made it optional and its\n * `scopeLocalAgentSecretStore` silently substituted an envelope\n * implementation when a store did not provide one. Scope-envelope prefixing\n * has no installed base, so this package removes the implicit substitution:\n * every store scopes itself, and {@link EnvelopeScopedSecretStore} is a\n * decorator a caller applies on purpose.\n */\nexport interface SecretStore<TName extends string = string> {\n /** Human-readable backend name, safe to show a user. Never contains a secret. */\n readonly providerLabel: string;\n /** Whether this backend can be used on the current machine. Must not throw. */\n available(): Promise<boolean>;\n /** Remove `name`; `false` when it was already absent. */\n delete(name: TName): Promise<boolean>;\n /** Read `name`, or `undefined` when it is absent. */\n get(name: TName): Promise<string | undefined>;\n /** Whether `name` currently holds a secret. */\n has(name: TName): Promise<boolean>;\n /** A view of this store isolated under `namespace`. */\n scope(namespace: string): SecretStore<TName>;\n /** Write `secret` at `name`, replacing any existing value. */\n set(name: TName, secret: string): Promise<void>;\n}\n\n/**\n * Default service prefix for this package's own entries. `servicePrefix` is a\n * constructor option on both OS backends, so K4's aip-main-open swap passes its\n * `com.aiphabee.local-agent` value and keeps existing installs byte-compatible.\n */\nexport const DEFAULT_SECRET_SERVICE_PREFIX = 'com.byok.keys';\n\n/**\n * Credential-store entry name per model provider, ported verbatim from\n * `providers.ts:1624-1632`. The names carry no vendor branding — the branding\n * lives in the service prefix — so they travel unchanged and K4 needs no\n * migration.\n */\nexport const MODEL_PROVIDER_SECRET_NAMES = {\n anthropic: 'model-anthropic-api-key',\n custom: 'model-custom-api-key',\n deepseek: 'model-deepseek-api-key',\n openai: 'model-openai-api-key',\n} as const satisfies Record<ModelProviderId, string>;\n\nexport type ModelProviderSecretName =\n (typeof MODEL_PROVIDER_SECRET_NAMES)[keyof typeof MODEL_PROVIDER_SECRET_NAMES];\n\n/** Resolve a provider id to the credential-store entry holding its API key. */\nexport function modelProviderSecretName(\n providerId: ModelProviderId,\n): ModelProviderSecretName {\n return MODEL_PROVIDER_SECRET_NAMES[providerId];\n}\n\n/**\n * The secret-shape invariant both OS backends share. Their size ceilings differ\n * in both magnitude and unit (macOS counts 16384 characters, Windows counts\n * 2560 UTF-8 bytes) and each reports its own error code, so those checks stay\n * in the backends; only the empty/control-character rule is common.\n */\nexport function assertSharedSecretValue(secret: string): void {\n if (secret.length === 0 || /[\\u0000\\r\\n]/u.test(secret)) {\n throw new ByokKeysError(\n 'SECRET_VALUE_INVALID',\n 'Secret must be a non-empty string without null or newline characters',\n );\n }\n}\n\n/**\n * Decode base64 to UTF-8 text, or return `undefined` — never a repaired\n * approximation.\n *\n * Both decode paths in Node are lenient in ways that matter here: `Buffer.from`\n * silently drops characters outside the base64 alphabet (so `\"a!G@k=\"` would\n * decode to `\"hi\"`), and `Buffer#toString('utf8')` substitutes U+FFFD for\n * invalid byte sequences. A credential store that \"successfully\" returns a\n * silently-mangled secret is worse than one that fails, so the alphabet, the\n * canonical padding, and the UTF-8 round trip are all checked explicitly.\n */\nexport function decodeStrictBase64Utf8(encoded: string): string | undefined {\n if (encoded.length % 4 !== 0) return undefined;\n if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(encoded)) return undefined;\n const bytes = Buffer.from(encoded, 'base64');\n if (bytes.toString('base64') !== encoded) return undefined;\n const text = bytes.toString('utf8');\n if (!Buffer.from(text, 'utf8').equals(bytes)) return undefined;\n return text;\n}\n\n/**\n * A {@link SecretStore} held in process memory, for tests and for embedders\n * that supply their own persistence.\n *\n * It keys entries by the same `` `${servicePrefix}.${name}` `` string the OS\n * backends use, and `scope()` extends that prefix exactly as they do, so a test\n * written against this store exercises the same isolation arithmetic as\n * production. It applies the name validator and the shared secret-shape rule;\n * the platform size ceilings deliberately are not simulated, since they differ\n * per backend.\n */\nexport class InMemorySecretStore<TName extends string = string>\n implements SecretStore<TName>\n{\n readonly providerLabel = 'in-memory';\n readonly #entries: Map<string, string>;\n readonly #servicePrefix: string;\n\n constructor(\n options: {\n /** Shared backing map; a scoped view keeps the parent's map. */\n entries?: Map<string, string>;\n servicePrefix?: string;\n } = {},\n ) {\n this.#entries = options.entries ?? new Map();\n this.#servicePrefix = options.servicePrefix ?? DEFAULT_SECRET_SERVICE_PREFIX;\n }\n\n available(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n async delete(name: TName): Promise<boolean> {\n return this.#entries.delete(this.#service(name));\n }\n\n async get(name: TName): Promise<string | undefined> {\n return this.#entries.get(this.#service(name));\n }\n\n async has(name: TName): Promise<boolean> {\n return (await this.get(name)) !== undefined;\n }\n\n scope(namespace: string): SecretStore<TName> {\n return new InMemorySecretStore<TName>({\n entries: this.#entries,\n servicePrefix: `${this.#servicePrefix}.scope.${assertSecretNamespace(namespace)}`,\n });\n }\n\n async set(name: TName, secret: string): Promise<void> {\n const service = this.#service(name);\n assertSharedSecretValue(secret);\n this.#entries.set(service, secret);\n }\n\n #service(name: TName): string {\n return `${this.#servicePrefix}.${assertSecretName(name)}`;\n }\n}\n","import 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(profileProviderId: string): string {\n return `byok-sdk-${profileProviderId}`;\n}\n\n/** Credential-blind Pi configuration derived from one validated local profile. */\nexport function buildPiProviderProjection(profile: ModelProviderProfile): object {\n const projectedProviderId = piProjectionProviderId(profile.provider_id);\n return {\n providers: {\n [projectedProviderId]: {\n baseUrl: profile.base_url,\n api:\n profile.adapter === 'anthropic'\n ? 'anthropic-messages'\n : 'openai-completions',\n ...(profile.auth_mode === 'none'\n ? {}\n : { apiKey: `$${PI_PROJECTED_KEY_ENV}` }),\n ...(profile.auth_mode === 'bearer' ? { authHeader: true } : {}),\n models: [\n {\n id: profile.model,\n name: profile.display_name,\n },\n ],\n },\n },\n };\n}\n\n/**\n * Validate the credential-blind RPC argv the client may delegate, then bind\n * the Pi child to the namespaced projection and exact configured model.\n */\nexport function buildPiProviderArgs(\n profile: ModelProviderProfile,\n delegatedArgs: readonly string[],\n): string[] {\n let modeCount = 0;\n for (let index = 0; index < delegatedArgs.length; index += 1) {\n const flag = delegatedArgs[index];\n if (flag === '--no-tools') continue;\n if (flag === '--mode') {\n modeCount += 1;\n const value = delegatedArgs[index + 1];\n if (value !== 'rpc') throw new Error('Pi launcher requires --mode rpc');\n index += 1;\n continue;\n }\n if (flag === '--session' || flag === '--tools' || flag === '--exclude-tools') {\n const value = delegatedArgs[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`${flag} requires a value`);\n }\n index += 1;\n continue;\n }\n throw new Error(`Pi launcher does not allow delegated argument ${flag ?? '<missing>'}`);\n }\n if (modeCount !== 1) throw new Error('Pi launcher requires exactly one --mode rpc');\n\n return [\n ...delegatedArgs,\n '--provider',\n piProjectionProviderId(profile.provider_id),\n '--model',\n profile.model,\n ];\n}\n","import { ByokKeysError } from './errors';\n\n/**\n * Normalize a provider base URL, fail-closed.\n *\n * Ported from `aip-main-open@c6a5385` `providers.ts:1558-1588` plus the two\n * host predicates at `:2216-2242`. Rules, unchanged:\n * - must be an absolute URL;\n * - no embedded credentials, no fragment, no query string;\n * - HTTPS only, except that HTTP is allowed for loopback hosts;\n * - private-network literals are rejected unless they are loopback;\n * - one trailing slash is stripped.\n */\nexport function normalizeProviderUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider base URL must be absolute',\n );\n }\n if (\n url.username ||\n url.password ||\n url.hash ||\n url.search ||\n (url.protocol !== 'https:' &&\n !(url.protocol === 'http:' && isLoopbackHost(url.hostname)))\n ) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Provider URL requires HTTPS; HTTP is allowed only for localhost',\n );\n }\n if (isPrivateNetworkLiteral(url.hostname) && !isLoopbackHost(url.hostname)) {\n throw new ByokKeysError(\n 'PROVIDER_URL_INVALID',\n 'Private-network provider IPs are not allowed',\n );\n }\n return url.toString().replace(/\\/$/u, '');\n}\n\n/** Whether an already-parseable provider URL points at a loopback host. */\nexport function isLoopbackProviderUrl(value: string): boolean {\n return isLoopbackHost(new URL(value).hostname);\n}\n\nexport function isLoopbackHost(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n return value === 'localhost' || value === '127.0.0.1' || value === '::1';\n}\n\n/**\n * Conservative private-network literal check. Any IPv6 literal counts as\n * private (the `:` branch), matching the source: the guard cannot cheaply\n * classify IPv6 ranges, so it refuses all of them and lets hostnames through.\n */\nexport function isPrivateNetworkLiteral(hostname: string): boolean {\n const value = hostname.toLowerCase().replace(/^\\[|\\]$/gu, '');\n if (value.includes(':')) return true;\n const parts = value.split('.').map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n return (\n parts[0] === 10 ||\n parts[0] === 127 ||\n (parts[0] === 169 && parts[1] === 254) ||\n (parts[0] === 172 && (parts[1] ?? 0) >= 16 && (parts[1] ?? 0) <= 31) ||\n (parts[0] === 192 && parts[1] === 168)\n );\n}\n","import { z } from 'zod';\n\nimport { ByokKeysError } from './errors';\nimport { normalizeProviderUrl } from './url';\n\n/**\n * Model providers this package knows how to address. Ported from\n * `aip-main-open@c6a5385` `providers.ts:30-36` (`LOCAL_MODEL_PROVIDER_IDS`).\n */\nexport const MODEL_PROVIDER_IDS = [\n 'openai',\n 'deepseek',\n 'anthropic',\n 'custom',\n] as const;\n\nexport type ModelProviderId = (typeof MODEL_PROVIDER_IDS)[number];\n\n/** Auth modes a provider profile can request (`providers.ts:29`). */\nexport const PROVIDER_AUTH_MODES = ['bearer', 'x_api_key', 'none'] as const;\n\nexport type ProviderAuthMode = (typeof PROVIDER_AUTH_MODES)[number];\n\n/**\n * Wire dialects. The source's `market_data` / `mcp_http` branch stays in\n * aip-main-open — this package ports the model branch only\n * (`providers.ts:38-61`, second union member).\n */\nexport const MODEL_PROVIDER_ADAPTERS = ['openai_compatible', 'anthropic'] as const;\n\nexport type ModelProviderAdapter = (typeof MODEL_PROVIDER_ADAPTERS)[number];\n\n/**\n * Marker attached to schema issues so {@link parseModelProviderProfile} can\n * reproduce the source's distinct error codes: the URL guard reports\n * `PROVIDER_URL_INVALID`, everything else reports `PROVIDER_PROFILE_INVALID`.\n */\ninterface ProfileIssueParams {\n byokCode: string;\n}\n\nfunction boundedString(field: string, maximumLength: number) {\n return z\n .string()\n .superRefine((value, ctx) => {\n if (\n value.trim().length === 0 ||\n value.length > maximumLength ||\n /[\\u0000\\r\\n]/u.test(value)\n ) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} is invalid`,\n });\n }\n })\n .transform((value) => value.trim());\n}\n\nfunction isoTimestamp(field: string) {\n return boundedString(field, 64).superRefine((value, ctx) => {\n if (!Number.isFinite(Date.parse(value))) {\n ctx.addIssue({\n code: 'custom',\n message: `Provider ${field} must be an ISO timestamp`,\n });\n }\n });\n}\n\nconst providerBaseUrl = z\n .string()\n .superRefine((value, ctx) => {\n try {\n normalizeProviderUrl(value);\n } catch (error) {\n ctx.addIssue({\n code: 'custom',\n message:\n error instanceof Error ? error.message : 'Provider base URL is invalid',\n params: {\n byokCode:\n error instanceof ByokKeysError ? error.code : 'PROVIDER_URL_INVALID',\n } satisfies ProfileIssueParams,\n });\n }\n })\n .transform((value) => normalizeProviderUrl(value));\n\n/**\n * A model provider profile: everything needed to address a provider except the\n * secret itself, which lives in the OS credential store.\n *\n * The adapter/auth-mode legality rules are the ones `normalizeProviderProfile`\n * enforced imperatively at `providers.ts:1522-1543`, moved into the schema so\n * there is one validation authority rather than a schema plus a normalizer.\n */\nexport const ModelProviderProfileSchema = z\n .object({\n adapter: z.enum(MODEL_PROVIDER_ADAPTERS),\n auth_mode: z.enum(PROVIDER_AUTH_MODES),\n base_url: providerBaseUrl,\n created_at: isoTimestamp('created_at'),\n display_name: boundedString('display_name', 100),\n enabled: z.boolean(),\n kind: z.literal('model'),\n model: boundedString('model', 160),\n provider_id: z.enum(MODEL_PROVIDER_IDS),\n updated_at: isoTimestamp('updated_at'),\n })\n .superRefine((profile, ctx) => {\n if (profile.adapter === 'anthropic' && profile.auth_mode !== 'x_api_key') {\n ctx.addIssue({\n code: 'custom',\n message: 'Anthropic requires x_api_key authentication',\n path: ['auth_mode'],\n });\n }\n if (\n profile.adapter === 'openai_compatible' &&\n profile.auth_mode === 'x_api_key'\n ) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'OpenAI-compatible providers support bearer or no authentication',\n path: ['auth_mode'],\n });\n }\n if (Date.parse(profile.updated_at) < Date.parse(profile.created_at)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Provider updated_at cannot precede created_at',\n path: ['updated_at'],\n });\n }\n });\n\n/** Validated, normalized profile. */\nexport type ModelProviderProfile = z.infer<typeof ModelProviderProfileSchema>;\n\n/** Pre-normalization shape callers may hand in. */\nexport type ModelProviderProfileInput = z.input<typeof ModelProviderProfileSchema>;\n\n/**\n * Parse and normalize a profile, or throw {@link ByokKeysError}. Replaces the\n * source's `normalizeProviderProfile` (`providers.ts:1489-1556`) for the model\n * branch, preserving its error codes.\n */\nexport function parseModelProviderProfile(value: unknown): ModelProviderProfile {\n const result = ModelProviderProfileSchema.safeParse(value);\n if (result.success) return result.data;\n const issue = result.error.issues[0];\n const params = (issue as { params?: Partial<ProfileIssueParams> } | undefined)\n ?.params;\n throw new ByokKeysError(\n params?.byokCode ?? 'PROVIDER_PROFILE_INVALID',\n issue?.message ?? 'Provider profile is invalid',\n { cause: result.error },\n );\n}\n","import 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 MODEL_PROVIDER_IDS,\n type ModelProviderId,\n type ModelProviderProfile,\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 providerId: ModelProviderId;\n modelId: string;\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 if (separator < 0) throw new Error('launcher arguments must end with -- <pi args>');\n const ownArgs = args.slice(0, separator);\n const piArgs = args.slice(separator + 1);\n if (piArgs.length === 0) throw new Error('launcher requires Pi arguments after --');\n\n const allowedFlags = new Set([\n '--pi-bin',\n '--profile-db',\n '--provider',\n '--model',\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 rawProviderId = required('--provider');\n if (!MODEL_PROVIDER_IDS.includes(rawProviderId as ModelProviderId)) {\n throw new Error(`provider ${rawProviderId} is not configured by @byok-sdk/keys`);\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 return {\n piBin: required('--pi-bin'),\n profileDbPath,\n providerId: rawProviderId as ModelProviderId,\n modelId,\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.provider_id));\n if (!secret) {\n throw new ByokKeysError(\n 'PROVIDER_SECRET_MISSING',\n `${profile.provider_id} provider 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 ModelProviderId,\n type ModelProviderProfile,\n parseModelProviderProfile,\n} from './provider-profile';\n\n/**\n * Storage contract for provider profiles — everything needed to address a\n * provider except the API key, which lives in a {@link SecretStore}.\n *\n * Shaped after `@byok-sdk/server`'s `TaskStore` (`packages/server/src/task-store.ts`)\n * as a *pattern*, not a dependency: `keys` must not import `server`, and\n * `server` must not import `keys` (the plan's Security Boundary keeps the\n * agent-dispatch packages free of any credential-adjacent code).\n *\n * Two invariants every implementation MUST enforce, not just\n * {@link InMemoryProviderProfileStore}:\n *\n * 1. **At most one enabled profile.** The source expressed this as a partial\n * unique index (`providers.ts:140-144`); saving an enabled profile disables\n * every other one. {@link resolveDefaultModelProvider} relies on it to\n * answer \"which provider is the default\" with a single row.\n * 2. **Validate on write.** `save` runs {@link parseModelProviderProfile}, so an\n * invalid profile is refused at the boundary rather than discovered later by\n * a reader.\n */\nexport interface ProviderProfileStore {\n /** Release the underlying resource. Safe to call more than once. */\n close(): Promise<void>;\n /** Remove `providerId`; `false` when it was not configured. */\n delete(providerId: ModelProviderId): Promise<boolean>;\n /** Read one provider's profile, configured or not enabled alike. */\n get(providerId: ModelProviderId): Promise<ModelProviderProfile | undefined>;\n /** The single enabled profile, or `undefined` when none is enabled. */\n getEnabled(): Promise<ModelProviderProfile | undefined>;\n /** Every configured profile, ordered by provider id. */\n list(): Promise<ModelProviderProfile[]>;\n /** Insert or update `profile`, enforcing both invariants above. */\n save(profile: ModelProviderProfile): Promise<ModelProviderProfile>;\n /**\n * Make `providerId` the enabled profile. Throws `PROVIDER_NOT_CONFIGURED`\n * when it has no profile — a fail-closed port of `providers.ts:1243-1250`.\n */\n setEnabled(providerId: ModelProviderId): Promise<ModelProviderProfile>;\n}\n\n/** Shared by both implementations so their error text cannot drift apart. */\nexport function providerNotConfigured(\n providerId: ModelProviderId,\n): ByokKeysError {\n return new ByokKeysError(\n 'PROVIDER_NOT_CONFIGURED',\n `${providerId} model provider is not configured`,\n );\n}\n\n/**\n * Profile store held in process memory: the default, and the one every test\n * that does not specifically exercise SQLite should use.\n *\n * Mirrors `InMemoryTaskStore`'s role in `@byok-sdk/server` — a real implementation\n * of the contract, not a stub, so behaviour proven here is the behaviour the\n * SQLite store must match (`profile-store.test.ts` runs one suite against both).\n */\nexport class InMemoryProviderProfileStore implements ProviderProfileStore {\n readonly #profiles = new Map<ModelProviderId, ModelProviderProfile>();\n\n async close(): Promise<void> {\n this.#profiles.clear();\n }\n\n async delete(providerId: ModelProviderId): Promise<boolean> {\n return this.#profiles.delete(providerId);\n }\n\n async get(providerId: ModelProviderId): Promise<ModelProviderProfile | undefined> {\n return this.#profiles.get(providerId);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n return [...this.#profiles.values()].find((profile) => profile.enabled);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n return [...this.#profiles.values()].sort((left, right) =>\n left.provider_id.localeCompare(right.provider_id),\n );\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const validated = parseModelProviderProfile({\n ...profile,\n created_at:\n this.#profiles.get(profile.provider_id)?.created_at ??\n profile.created_at,\n });\n if (validated.enabled) {\n for (const [providerId, existing] of this.#profiles) {\n if (providerId !== validated.provider_id && existing.enabled) {\n this.#profiles.set(providerId, { ...existing, enabled: false });\n }\n }\n }\n this.#profiles.set(validated.provider_id, validated);\n return validated;\n }\n\n async setEnabled(providerId: ModelProviderId): Promise<ModelProviderProfile> {\n const existing = this.#profiles.get(providerId);\n if (existing === undefined) throw providerNotConfigured(providerId);\n return this.save({ ...existing, enabled: true });\n }\n}\n","import { chmodSync, existsSync, mkdirSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname } from 'node:path';\nimport type { DatabaseSync, DatabaseSyncOptions } from 'node:sqlite';\n\nimport { ByokKeysError } from './errors';\n\nexport type SqliteOpenStep = 'after-open' | 'after-wal' | 'after-synchronous';\n\n/** Test-only seam for proving that post-open initialization failures release the native handle. */\nexport interface SqliteOpenFaultSeam {\n onStep?(step: SqliteOpenStep): void;\n close?(database: DatabaseSync): void;\n}\n\n/** Release an opened handle before propagating an initialization failure. */\nexport function closeSqliteDatabaseAfterInitializationFailure(\n database: DatabaseSync,\n initializationError: unknown,\n message: string,\n close: (database: DatabaseSync) => void = (handle) => handle.close(),\n): never {\n try {\n close(database);\n } catch (closeError) {\n throw new AggregateError([initializationError, closeError], message);\n }\n throw initializationError;\n}\n\n/** Owner-only directory mode, matching `providers.ts:1236`. */\nconst SECURE_DIR_MODE = 0o700;\n\n/** Owner-only file mode, matching `providers.ts:158`. */\nconst SECURE_FILE_MODE = 0o600;\n\nconst DEFAULT_BUSY_TIMEOUT_MS = 5_000;\n\ninterface SqliteModule {\n DatabaseSync: new (\n path: string,\n options?: DatabaseSyncOptions,\n ) => DatabaseSync;\n}\n\n/**\n * Load `node:sqlite`, or fail with a `ByokKeysError` that says why.\n *\n * `node:sqlite` shipped in Node.js 22.5.0 and stays marked experimental (an\n * `ExperimentalWarning` on stderr is expected and harmless). Following\n * `@byok-sdk/server`'s `sqlite-support.ts`, the SQLite-backed store here depends on\n * nothing else — no `better-sqlite3`, no native module — because zero native\n * dependencies is what keeps this package trivially packageable. The tradeoff\n * is that {@link SqliteProviderProfileStore} does not work below Node 22.5, and\n * this error says so instead of letting a cryptic `Cannot find module` surface\n * from deep inside a query.\n */\nexport function loadSqliteModule(): SqliteModule {\n try {\n return createRequire(import.meta.url)('node:sqlite') as SqliteModule;\n } catch (error) {\n throw new ByokKeysError(\n 'PROVIDER_STORE_UNAVAILABLE',\n 'node:sqlite is unavailable in this Node.js runtime. SqliteProviderProfileStore ' +\n 'requires Node.js 22.5+ with the built-in `node:sqlite` module (no native ' +\n 'dependency is used or allowed here). Upgrade Node.js, or use ' +\n 'InMemoryProviderProfileStore instead.',\n { cause: error },\n );\n }\n}\n\n/**\n * Whether `node:sqlite` can ACTUALLY be loaded right now.\n *\n * Same predicate as `@byok-sdk/server`'s `sqlite-support.ts`, and it exists for the\n * same reason: this package's `engines.node` is `>=20` and CI runs the matrix\n * on 20 and 22, but `node:sqlite` shipped in 22.5 and stayed behind\n * `--experimental-sqlite` for part of the 22.x line. A version-number\n * comparison would therefore be wrong in both directions, so this attempts the\n * real require via {@link loadSqliteModule} and reports whether it succeeded.\n *\n * Callers use it to skip a SQLite-backed path rather than fail it — the\n * package's own SQLite-backed suites gate on it — and anything else should call\n * it before assuming a {@link SqliteProviderProfileStore} can be constructed.\n */\nexport function isSqliteAvailable(): boolean {\n try {\n loadSqliteModule();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Open a database, creating its parent directory owner-only first. `:memory:`\n * skips every filesystem step, which is how the shared contract suite exercises\n * the SQLite code path without leaving anything on disk.\n */\nexport function openSqliteDatabase(\n path: string,\n options?: DatabaseSyncOptions,\n faults?: SqliteOpenFaultSeam,\n): DatabaseSync {\n const { DatabaseSync } = loadSqliteModule();\n const readOnly = options?.readOnly === true;\n if (path !== ':memory:' && !readOnly) {\n mkdirSync(dirname(path), { mode: SECURE_DIR_MODE, recursive: true });\n }\n const database = new DatabaseSync(path, {\n timeout: DEFAULT_BUSY_TIMEOUT_MS,\n ...options,\n });\n try {\n faults?.onStep?.('after-open');\n if (path !== ':memory:' && !readOnly) {\n database.exec('PRAGMA journal_mode = WAL');\n faults?.onStep?.('after-wal');\n database.exec('PRAGMA synchronous = FULL');\n faults?.onStep?.('after-synchronous');\n }\n return database;\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n database,\n error,\n 'provider profile SQLite open initialization failed and its native handle could not be closed',\n faults?.close,\n );\n }\n}\n\n/**\n * Restrict `databasePath` and its WAL/SHM siblings to owner-only read/write.\n *\n * The profile table holds no secret — that is the whole point of splitting the\n * key into the OS credential store — but it does hold every provider endpoint\n * this machine talks to, and the source locked the file down\n * (`providers.ts:158`), so the port keeps that. Call after the schema exists,\n * so the lazily-created WAL/SHM files are already there; a sibling that does\n * not exist is skipped rather than treated as an error. No-op for `:memory:`.\n */\nexport function secureSqliteFilePermissions(databasePath: string): void {\n if (databasePath === ':memory:') return;\n for (const candidate of [\n databasePath,\n `${databasePath}-wal`,\n `${databasePath}-shm`,\n ]) {\n if (existsSync(candidate)) {\n chmodSync(candidate, SECURE_FILE_MODE);\n }\n }\n}\n","import type { DatabaseSync } from 'node:sqlite';\n\nimport {\n type ProviderProfileStore,\n providerNotConfigured,\n} from './profile-store';\nimport {\n MODEL_PROVIDER_IDS,\n type ModelProviderId,\n type ModelProviderProfile,\n parseModelProviderProfile,\n} from './provider-profile';\nimport {\n closeSqliteDatabaseAfterInitializationFailure,\n openSqliteDatabase,\n secureSqliteFilePermissions,\n} from './sqlite-support';\n\nexport interface SqliteProviderProfileStoreOptions {\n /**\n * Database file path. `:memory:` exercises the SQLite code path without a\n * temp file, but defeats the point of this store (restart-safety) exactly as\n * it does for `@byok-sdk/server`'s `SqliteTaskStore`.\n */\n path: string;\n /** Open an existing profile database without creating or mutating it. */\n readOnly?: boolean;\n}\n\n/**\n * Ported from `providers.ts:109-140`, narrowed to the model branch. The\n * source's table also carried `market_data` / `mcp_http` rows and a `tool_name`\n * column; that branch stays in aip-main-open per\n * `docs/researches/HANDOFF-byok-keys.md` §4.5, so the CHECK constraints here\n * are the model half only.\n */\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS provider_profile (\n provider_id TEXT PRIMARY KEY CHECK (provider_id IN ('openai', 'deepseek', 'anthropic', 'custom')),\n kind TEXT NOT NULL CHECK (kind = 'model'),\n adapter TEXT NOT NULL CHECK (adapter IN ('openai_compatible', 'anthropic')),\n display_name TEXT NOT NULL,\n base_url TEXT NOT NULL,\n auth_mode TEXT NOT NULL CHECK (auth_mode IN ('bearer', 'x_api_key', 'none')),\n model TEXT NOT NULL,\n enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\n`;\n\n/**\n * The \"at most one enabled profile\" invariant, enforced by the database itself\n * rather than only by {@link SqliteProviderProfileStore.save}\n * (`providers.ts:140-144`). A partial unique index means a bug in the write\n * path surfaces as a constraint violation instead of silently producing two\n * defaults.\n */\nconst ENABLED_INDEX = `\nCREATE UNIQUE INDEX IF NOT EXISTS provider_profile_one_enabled\nON provider_profile(kind)\nWHERE enabled = 1;\n`;\n\ninterface ProfileRow {\n adapter: string;\n auth_mode: string;\n base_url: string;\n created_at: string;\n display_name: string;\n enabled: number;\n kind: string;\n model: string;\n provider_id: string;\n updated_at: string;\n}\n\n/**\n * SQLite-backed {@link ProviderProfileStore}, following `@byok-sdk/server`'s\n * `SqliteTaskStore` shape. Holds no secret: the API key lives in the injected\n * `SecretStore`, and `registry.golden.test.ts` asserts the plaintext key never\n * appears in this file's bytes.\n */\nexport class SqliteProviderProfileStore implements ProviderProfileStore {\n readonly #database: DatabaseSync;\n #closed = false;\n\n constructor(options: SqliteProviderProfileStoreOptions) {\n this.#database = openSqliteDatabase(options.path, {\n readOnly: options.readOnly ?? false,\n });\n if (!options.readOnly) {\n try {\n this.#database.exec(SCHEMA);\n this.#database.exec(ENABLED_INDEX);\n secureSqliteFilePermissions(options.path);\n } catch (error) {\n closeSqliteDatabaseAfterInitializationFailure(\n this.#database,\n error,\n 'SqliteProviderProfileStore initialization failed and its native handle could not be closed',\n );\n }\n }\n }\n\n /**\n * Idempotent, as {@link ProviderProfileStore.close} requires: `node:sqlite`\n * throws \"database is not open\" on a second `close()`, and a store is\n * routinely closed both by the code that finished with it and by a test's\n * teardown.\n */\n async close(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n this.#database.close();\n }\n\n async delete(providerId: ModelProviderId): Promise<boolean> {\n const result = this.#database\n .prepare('DELETE FROM provider_profile WHERE provider_id = ?')\n .run(providerId);\n return Number(result.changes) === 1;\n }\n\n async get(providerId: ModelProviderId): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE provider_id = ?')\n .get(providerId) as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async getEnabled(): Promise<ModelProviderProfile | undefined> {\n const row = this.#database\n .prepare('SELECT * FROM provider_profile WHERE enabled = 1')\n .get() as ProfileRow | undefined;\n return row === undefined ? undefined : parseRow(row);\n }\n\n async list(): Promise<ModelProviderProfile[]> {\n const rows = this.#database\n .prepare('SELECT * FROM provider_profile ORDER BY provider_id ASC')\n .all() as unknown as ProfileRow[];\n return rows.map(parseRow);\n }\n\n async save(profile: ModelProviderProfile): Promise<ModelProviderProfile> {\n const existing = await this.get(profile.provider_id);\n const validated = parseModelProviderProfile({\n ...profile,\n created_at: existing?.created_at ?? profile.created_at,\n });\n this.#transaction(() => {\n if (validated.enabled) {\n this.#database\n .prepare(\n 'UPDATE provider_profile SET enabled = 0 WHERE provider_id <> ?',\n )\n .run(validated.provider_id);\n }\n this.#database\n .prepare(\n `INSERT INTO provider_profile (\n provider_id, kind, adapter, display_name, base_url,\n auth_mode, model, enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(provider_id) DO UPDATE SET\n adapter = excluded.adapter,\n display_name = excluded.display_name,\n base_url = excluded.base_url,\n auth_mode = excluded.auth_mode,\n model = excluded.model,\n enabled = excluded.enabled,\n updated_at = excluded.updated_at`,\n )\n .run(\n validated.provider_id,\n validated.kind,\n validated.adapter,\n validated.display_name,\n validated.base_url,\n validated.auth_mode,\n validated.model,\n validated.enabled ? 1 : 0,\n validated.created_at,\n validated.updated_at,\n );\n });\n return (await this.get(validated.provider_id)) as ModelProviderProfile;\n }\n\n async setEnabled(providerId: ModelProviderId): Promise<ModelProviderProfile> {\n const existing = await this.get(providerId);\n if (existing === undefined) throw providerNotConfigured(providerId);\n return this.save({ ...existing, enabled: true });\n }\n\n /** `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`, per `providers.ts:1252-1263`. */\n #transaction(body: () => void): void {\n this.#database.exec('BEGIN IMMEDIATE');\n try {\n body();\n this.#database.exec('COMMIT');\n } catch (error) {\n this.#database.exec('ROLLBACK');\n throw error;\n }\n }\n}\n\n/**\n * Rows go back through the same zod schema the write path used, so a row that\n * a different process wrote — or an older schema left behind — is rejected\n * rather than trusted. `enabled` is an INTEGER in SQLite and a real boolean in\n * the schema, so it is converted rather than coerced loosely.\n */\nfunction parseRow(row: ProfileRow): ModelProviderProfile {\n return parseModelProviderProfile({\n ...row,\n enabled: row.enabled === 1,\n });\n}\n\n/** Exported for the store's own tests to enumerate the CHECK-constrained ids. */\nexport const SQLITE_PROFILE_PROVIDER_IDS = MODEL_PROVIDER_IDS;\n","import { 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 {\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.providerId);\n if (profile === undefined) {\n throw new Error(`provider ${options.providerId} 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\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"]}
|