zidane 6.5.4 → 6.5.5

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.
Files changed (128) hide show
  1. package/dist/{acp-CIpD8UIw.js → acp-BPJbXS2J.js} +6 -6
  2. package/dist/{acp-CIpD8UIw.js.map → acp-BPJbXS2J.js.map} +1 -1
  3. package/dist/acp-cli.js +6 -6
  4. package/dist/acp.d.ts +1 -1
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-8kfGIDb_.js → agent-gZjHsUft.js} +176 -166
  7. package/dist/agent-gZjHsUft.js.map +1 -0
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/{anthropic-qaw8XAc9.js → anthropic-D3le2d-s.js} +75 -14
  11. package/dist/anthropic-D3le2d-s.js.map +1 -0
  12. package/dist/{auth-BLy7X1SY.js → auth-DCiXCwGa.js} +5 -5
  13. package/dist/{auth-BLy7X1SY.js.map → auth-DCiXCwGa.js.map} +1 -1
  14. package/dist/chat/pure.d.ts +3 -3
  15. package/dist/chat/pure.js +2 -2
  16. package/dist/chat.d.ts +29 -8
  17. package/dist/chat.d.ts.map +1 -1
  18. package/dist/chat.js +8 -8
  19. package/dist/{context-segments-1mcqSCM3.js → context-segments-CJCtJ9sU.js} +16 -3
  20. package/dist/{context-segments-1mcqSCM3.js.map → context-segments-CJCtJ9sU.js.map} +1 -1
  21. package/dist/{context-transport-Bco9Wo0b.js → context-transport-D8yeGdpd.js} +2 -2
  22. package/dist/{context-transport-Bco9Wo0b.js.map → context-transport-D8yeGdpd.js.map} +1 -1
  23. package/dist/contexts/daytona.d.ts +1 -1
  24. package/dist/contexts/daytona.js +1 -1
  25. package/dist/contexts/e2b.d.ts +1 -1
  26. package/dist/{errors-BwBxu3zD.js → errors-DKiMrOKq.js} +61 -2
  27. package/dist/{errors-BwBxu3zD.js.map → errors-DKiMrOKq.js.map} +1 -1
  28. package/dist/errors.js +2 -2
  29. package/dist/eval.d.ts +1 -1
  30. package/dist/eval.js +1 -1
  31. package/dist/extensions.d.ts +1 -1
  32. package/dist/extensions.js +1 -1
  33. package/dist/{fetch-url-B7aSg6Bp.js → fetch-url-ma-5_p0p.js} +2 -2
  34. package/dist/{fetch-url-B7aSg6Bp.js.map → fetch-url-ma-5_p0p.js.map} +1 -1
  35. package/dist/headless.d.ts +1 -1
  36. package/dist/headless.js +3 -3
  37. package/dist/{index-BSNr0OQn.d.ts → index-BYKzzYzi.d.ts} +68 -22
  38. package/dist/index-BYKzzYzi.d.ts.map +1 -0
  39. package/dist/index.d.ts +1 -1
  40. package/dist/index.js +13 -13
  41. package/dist/{login-D3CKhgbI.js → login-CB23LyI1.js} +3 -3
  42. package/dist/{login-D3CKhgbI.js.map → login-CB23LyI1.js.map} +1 -1
  43. package/dist/{mcp-D9fqOQo5.js → mcp-CVtSQTWg.js} +3 -3
  44. package/dist/{mcp-D9fqOQo5.js.map → mcp-CVtSQTWg.js.map} +1 -1
  45. package/dist/mcp.d.ts +1 -1
  46. package/dist/mcp.js +1 -1
  47. package/dist/{messages-C_H9soi5.js → messages-CVVg5jUL.js} +2 -2
  48. package/dist/{messages-C_H9soi5.js.map → messages-CVVg5jUL.js.map} +1 -1
  49. package/dist/{oauth-ZebH9NHb.js → oauth-C4GvY_p1.js} +27 -8
  50. package/dist/oauth-C4GvY_p1.js.map +1 -0
  51. package/dist/{openai-compat-CnHeo4Lz.js → openai-compat-hmZzpDrB.js} +2 -2
  52. package/dist/{openai-compat-CnHeo4Lz.js.map → openai-compat-hmZzpDrB.js.map} +1 -1
  53. package/dist/output/stream-json.d.ts +1 -1
  54. package/dist/output/terminal.d.ts +1 -1
  55. package/dist/{plugins-2PMTVcp-.js → plugins-onDvTHEm.js} +2 -2
  56. package/dist/{plugins-2PMTVcp-.js.map → plugins-onDvTHEm.js.map} +1 -1
  57. package/dist/plugins.d.ts +1 -1
  58. package/dist/plugins.js +1 -1
  59. package/dist/presets.d.ts +1 -1
  60. package/dist/presets.js +1 -1
  61. package/dist/providers/anthropic.d.ts +1 -1
  62. package/dist/providers/anthropic.js +1 -1
  63. package/dist/providers/arcee.d.ts +1 -1
  64. package/dist/providers/arcee.js +1 -1
  65. package/dist/providers/baseten.d.ts +1 -1
  66. package/dist/providers/baseten.js +1 -1
  67. package/dist/providers/cerebras.d.ts +1 -1
  68. package/dist/providers/cerebras.js +1 -1
  69. package/dist/providers/local.d.ts +1 -1
  70. package/dist/providers/local.js +1 -1
  71. package/dist/providers/openai-compat.d.ts +1 -1
  72. package/dist/providers/openai-compat.js +1 -1
  73. package/dist/providers/openai.d.ts +1 -1
  74. package/dist/providers/openai.js +4 -4
  75. package/dist/providers/openrouter.d.ts +1 -1
  76. package/dist/providers/openrouter.js +1 -1
  77. package/dist/providers/xai.d.ts +1 -1
  78. package/dist/providers/xai.js +2 -2
  79. package/dist/{providers-Bxs-XHir.js → providers-Cf0AXIIZ.js} +3 -3
  80. package/dist/{providers-Bxs-XHir.js.map → providers-Cf0AXIIZ.js.map} +1 -1
  81. package/dist/providers.d.ts +1 -1
  82. package/dist/providers.js +4 -4
  83. package/dist/restate.d.ts +1 -1
  84. package/dist/restate.js +2 -2
  85. package/dist/session/sqlite.d.ts +1 -1
  86. package/dist/session/sqlite.js +1 -1
  87. package/dist/{session-VpLrNaFQ.js → session-cqN5NbO-.js} +2 -2
  88. package/dist/{session-VpLrNaFQ.js.map → session-cqN5NbO-.js.map} +1 -1
  89. package/dist/session.d.ts +1 -1
  90. package/dist/session.js +2 -2
  91. package/dist/{skills-Cp9vnBwd.js → skills-BMGH_KK1.js} +2 -2
  92. package/dist/{skills-Cp9vnBwd.js.map → skills-BMGH_KK1.js.map} +1 -1
  93. package/dist/skills.d.ts +1 -1
  94. package/dist/skills.js +1 -1
  95. package/dist/{timeout-BDetbuN6.js → timeout-CjOG2mea.js} +29 -2
  96. package/dist/timeout-CjOG2mea.js.map +1 -0
  97. package/dist/timeout-DEaqslLO.d.ts.map +1 -1
  98. package/dist/{tool-formatters-BfKqWm5N.d.ts → tool-formatters-B5WSHMCU.d.ts} +2 -2
  99. package/dist/{tool-formatters-BfKqWm5N.d.ts.map → tool-formatters-B5WSHMCU.d.ts.map} +1 -1
  100. package/dist/tools/fetch-url.d.ts +1 -1
  101. package/dist/tools/fetch-url.js +1 -1
  102. package/dist/tools/web-search.d.ts +1 -1
  103. package/dist/tools/web-search.js +2 -2
  104. package/dist/tools.d.ts +1 -1
  105. package/dist/tools.js +1 -1
  106. package/dist/{transcript-anchors-CNqDbrc9.d.ts → transcript-anchors-BPnWHLyr.d.ts} +2 -2
  107. package/dist/{transcript-anchors-CNqDbrc9.d.ts.map → transcript-anchors-BPnWHLyr.d.ts.map} +1 -1
  108. package/dist/{transcript-anchors-Bv8HQ3S2.js → transcript-anchors-BvC8t7dt.js} +177 -63
  109. package/dist/transcript-anchors-BvC8t7dt.js.map +1 -0
  110. package/dist/tui.d.ts +18 -29
  111. package/dist/tui.d.ts.map +1 -1
  112. package/dist/tui.js +737 -236
  113. package/dist/tui.js.map +1 -1
  114. package/dist/{turn-operations-iGu5J08j.js → turn-operations-7_Ff7INF.js} +2 -2
  115. package/dist/{turn-operations-iGu5J08j.js.map → turn-operations-7_Ff7INF.js.map} +1 -1
  116. package/dist/{turn-operations-CnIpcenJ.d.ts → turn-operations-BvP3_HsU.d.ts} +3 -3
  117. package/dist/{turn-operations-CnIpcenJ.d.ts.map → turn-operations-BvP3_HsU.d.ts.map} +1 -1
  118. package/dist/types.d.ts +1 -1
  119. package/dist/types.js +1 -1
  120. package/docs/CHAT.md +1 -1
  121. package/docs/TUI.md +4 -4
  122. package/package.json +2 -1
  123. package/dist/agent-8kfGIDb_.js.map +0 -1
  124. package/dist/anthropic-qaw8XAc9.js.map +0 -1
  125. package/dist/index-BSNr0OQn.d.ts.map +0 -1
  126. package/dist/oauth-ZebH9NHb.js.map +0 -1
  127. package/dist/timeout-BDetbuN6.js.map +0 -1
  128. package/dist/transcript-anchors-Bv8HQ3S2.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-C4GvY_p1.js","names":[],"sources":["../src/providers/oauth-registry.ts","../src/providers/oauth.ts"],"sourcesContent":["/**\n * Local OAuth provider registry.\n *\n * pi-ai 0.80.8 removed its global OAuth registry (`registerOAuthProvider`,\n * `getOAuthApiKey`, `OAuthProviderInterface`) and the public low-level\n * refresh helpers in favor of canonical `Provider.auth.oauth` objects\n * resolved through a `Models` collection + `CredentialStore`. zidane's\n * credential architecture (shared `.credentials.json`, cross-process refresh\n * locks in `./oauth.ts`, themed login flows in `src/chat/oauth-page/`)\n * predates that and owns storage itself, so this module reproduces the\n * removed registry surface locally with the same semantics.\n *\n * Nothing protocol-level is duplicated here: token refresh for the built-in\n * providers delegates to pi-ai's canonical `auth.oauth.refresh` flows via the\n * public `providers/*` subpaths (lazily imported, so processes that never\n * authenticate don't load provider code).\n */\n\nimport type { OAuthAuth } from '@earendil-works/pi-ai'\nimport type { OAuthCredentials, OAuthLoginCallbacks } from '@earendil-works/pi-ai/oauth'\nimport { errorMessage } from '../errors'\n\n/**\n * Provider-owned OAuth flow. Mirrors the interface pi-ai exported from\n * `@earendil-works/pi-ai/oauth` up to 0.80.6 — kept as a local type so\n * zidane's descriptor seam (`ProviderDescriptor.oauthProvider`) and provider\n * extensions (e.g. `extensions/bolt`) stay source-compatible across the\n * upstream removal.\n */\nexport interface OAuthProviderInterface {\n readonly id: string\n readonly name: string\n\n /** Run the login flow, return credentials to persist. */\n login: (callbacks: OAuthLoginCallbacks) => Promise<OAuthCredentials>\n\n /** Whether login uses a local callback server and supports manual code input. */\n usesCallbackServer?: boolean\n\n /** Refresh expired credentials, return updated credentials to persist. */\n refreshToken: (credentials: OAuthCredentials) => Promise<OAuthCredentials>\n\n /** Convert credentials to an API key string for the provider. */\n getApiKey: (credentials: OAuthCredentials) => string\n}\n\n/**\n * Run a canonical pi-ai `OAuthAuth.refresh` from a bare refresh token.\n * pi-ai's built-in refresh implementations only read `credential.refresh`,\n * so the placeholder access/expires fields are never observed.\n *\n * The canonical result is an `OAuthCredential` tagged `type: 'oauth'`. Strip\n * the tag before returning: refresh results get merged into stored\n * `.credentials.json` entries and `onOAuthRefresh` hook payloads (see\n * `resolveCredentialSource` in `./oauth.ts`), whose documented shape carries\n * zidane's own `kind` tag — letting pi-ai's `type` leak through would\n * silently drift the on-disk shape.\n */\nasync function refreshViaCanonicalFlow(\n providerId: string,\n oauth: OAuthAuth | undefined,\n refreshToken: string,\n): Promise<OAuthCredentials> {\n if (!oauth)\n throw new Error(`pi-ai provider ${providerId} exposes no OAuth flow`)\n // pi-ai 0.84 made `signal` a required second argument. These refreshers are\n // called from token-expiry paths that carry no cancellation of their own, so\n // a never-aborting signal keeps the pre-0.84 behavior exactly — same idiom as\n // `completion-core.ts`.\n const { type: _type, ...credentials }\n = await oauth.refresh(\n { type: 'oauth', access: '', refresh: refreshToken, expires: 0 },\n new AbortController().signal,\n )\n return credentials\n}\n\n/**\n * Refresh an Anthropic (Claude Pro/Max) OAuth token. Drop-in replacement for\n * the `refreshAnthropicToken` pi-ai exported until 0.80.6; delegates to the\n * canonical flow on `anthropicProvider().auth.oauth`.\n */\nexport async function refreshAnthropicToken(refreshToken: string): Promise<OAuthCredentials> {\n const { anthropicProvider } = await import('@earendil-works/pi-ai/providers/anthropic')\n return refreshViaCanonicalFlow('anthropic', anthropicProvider().auth.oauth, refreshToken)\n}\n\n/**\n * Refresh an OpenAI Codex (ChatGPT) OAuth token. Drop-in replacement for the\n * removed `refreshOpenAICodexToken`; the canonical flow still derives\n * `accountId` from the refreshed access token's JWT claims, so the returned\n * credentials keep the extra field older callers persisted.\n */\nexport async function refreshOpenAICodexToken(refreshToken: string): Promise<OAuthCredentials> {\n const { openaiCodexProvider } = await import('@earendil-works/pi-ai/providers/openai-codex')\n return refreshViaCanonicalFlow('openai-codex', openaiCodexProvider().auth.oauth, refreshToken)\n}\n\n/**\n * Built-in registry seeds. Every id whose stored credential can expire has to\n * be seeded here, because zidane's lazy token refresh (`getOAuthApiKey` inside\n * `resolveOAuthApiKey`) resolves through the registry — an unseeded id is not a\n * degraded path but a dead end, with no way to renew the session. That is wider\n * than the Anthropic / OpenAI Codex pair pi-ai's removed registry pre-seeded:\n * flows zidane implements itself (xAI) need seeding just as much.\n *\n * Login is intentionally unsupported here: interactive login always goes\n * through `ProviderDescriptor.oauthProvider` (the themed flows in\n * `src/chat/oauth-page/`), never through the registry.\n */\nfunction builtinProvider(\n id: string,\n name: string,\n refreshToken: (credentials: OAuthCredentials) => Promise<OAuthCredentials>,\n): OAuthProviderInterface {\n return {\n id,\n name,\n login: async () => {\n throw new Error(`OAuth login for ${id} must run through a provider descriptor flow, not the registry`)\n },\n refreshToken,\n getApiKey: credentials => credentials.access,\n }\n}\n\n/**\n * Seed id for the xAI Grok OAuth flow. Duplicated from\n * `XAI_OAUTH_PROVIDER_ID` in `../chat/oauth-page/xai` rather than imported:\n * that module pulls in `node:http` and the PKCE helpers at module scope, and\n * this registry is loaded by every consumer that resolves a credential. The\n * ids are pinned together by a test, so the duplication cannot drift.\n */\nconst XAI_SEED_ID = 'xai-oauth'\n\n/**\n * Refresh an xAI Grok token. Imported lazily so seeding the registry does not\n * drag the login flow's `node:http` callback server into every consumer —\n * and so the static import edge back to this module stays type-only, leaving\n * no runtime cycle.\n *\n * Unlike the Anthropic / Codex seeds, this receives the FULL credential rather\n * than a bare refresh token: xAI stores its resolved `token_endpoint` (and the\n * cached discovery doc) alongside the tokens, and dropping them would force a\n * fresh OIDC discovery round-trip on every refresh — and discard the validated\n * endpoint that `refreshXaiToken` re-checks before posting the refresh token\n * to it.\n */\nasync function refreshXaiTokenSeed(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n const { refreshXaiToken } = await import('../chat/oauth-page/xai')\n return refreshXaiToken(credentials)\n}\n\n/**\n * Seed id for the Cursor OAuth flow. Duplicated from\n * `CURSOR_OAUTH_PROVIDER_ID` for the same reason as {@link XAI_SEED_ID}, and\n * pinned to it by a test.\n */\nconst CURSOR_SEED_ID = 'cursor'\n\n/**\n * Refresh a Cursor token. Lazy for the same reason as the xAI seed: the login\n * module owns a callback server, and seeding must not drag it into every\n * consumer that merely resolves a credential.\n */\nasync function refreshCursorTokenSeed(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n const { refreshCursorToken } = await import('../chat/oauth-page/cursor')\n return refreshCursorToken(credentials)\n}\n\n/**\n * The registry map is anchored on a process-wide `globalThis` slot rather\n * than module state. The pi-ai registry this replaces lived in pi-ai's own\n * module, so every copy of zidane code in a process shared one map — and two\n * copies is a real configuration, not a hypothetical: a host running from\n * `src` while a disk-loaded extension resolves `'zidane'` to `dist` through\n * ordinary node_modules resolution (see `import()` in\n * `src/extensions/discovery.ts`). The extension registers its flow at setup;\n * `resolveOAuthApiKey` looks it up only once a stored token expires — with\n * per-module maps that fails as a deferred \"Unknown OAuth provider\", which is\n * nasty to debug. `Symbol.for` restores the process-wide sharing. Whichever\n * copy touches the slot first seeds the built-ins, so a `dist` consumer can end\n * up refreshing through the `src` copy's closure (and vice versa). That is\n * harmless because the seeds are STATELESS refresh delegations — they close over\n * no module state and no configuration, so the two copies compute the same\n * result from the same stored credential. It is that property, not where the\n * refresh happens to be implemented, that makes first-copy-wins safe: it holds\n * equally for the seeds that delegate to pi-ai's canonical flows and for the\n * xAI one implemented in `../chat/oauth-page/xai`.\n */\n/**\n * Exported so tests that register a throwaway provider can remove it from the\n * same slot rather than re-deriving the key with a copied string: the registry\n * exposes no unregister, and a `Symbol.for` looked up from a duplicated literal\n * would silently stop matching if this key were ever renamed, leaving the test\n * provider resident in shared state. Deliberately kept out of the package's\n * public surface — `./index.ts` re-exports this module by explicit name list.\n */\nexport const REGISTRY_SLOT = Symbol.for('zidane.oauth-provider-registry')\n\nfunction oauthProviderRegistry(): Map<string, OAuthProviderInterface> {\n const slots = globalThis as { [key: symbol]: Map<string, OAuthProviderInterface> | undefined }\n slots[REGISTRY_SLOT] ??= new Map(\n [\n builtinProvider('anthropic', 'Anthropic (Claude Pro/Max)', c => refreshAnthropicToken(c.refresh)),\n builtinProvider('openai-codex', 'OpenAI (ChatGPT Plus/Pro)', c => refreshOpenAICodexToken(c.refresh)),\n // xAI is NOT built into pi-ai, so unlike the two above there is no\n // canonical flow to delegate to — `../chat/oauth-page/xai` implements it.\n // It is seeded here anyway because seeding is what makes refresh work for\n // consumers that never import `chat/providers.ts` or `auth.ts`, whose\n // module-scope `registerXaiOAuthProvider()` call was previously the ONLY\n // thing that registered it. A library consumer resolving a stored\n // credential through `getOAuthApiKey` got `Unknown OAuth provider:\n // xai-oauth` and had no way to renew a session — a dead end rather than a\n // degraded path. The interactive login half still comes from\n // `registerXaiOAuthProvider(renderPage)`, which replaces this seed.\n builtinProvider(XAI_SEED_ID, 'xAI Grok (SuperGrok / X Premium+)', refreshXaiTokenSeed),\n // Cursor has the identical shape and had the identical defect: its flow\n // lives in `../chat/oauth-page/cursor` and was registered only as a\n // module-scope side effect of importing `chat/providers.ts` / `auth.ts`.\n builtinProvider(CURSOR_SEED_ID, 'Cursor', refreshCursorTokenSeed),\n ].map(provider => [provider.id, provider]),\n )\n return slots[REGISTRY_SLOT]\n}\n\n/** Register (or replace) an OAuth provider by id. */\nexport function registerOAuthProvider(provider: OAuthProviderInterface): void {\n oauthProviderRegistry().set(provider.id, provider)\n}\n\n/** Get a registered OAuth provider by id. */\nexport function getOAuthProvider(id: string): OAuthProviderInterface | undefined {\n return oauthProviderRegistry().get(id)\n}\n\n/**\n * Get an API key for a provider from OAuth credentials, refreshing expired\n * tokens through the registered flow. Same contract as the pi-ai original\n * (`null` when no credentials are stored for the provider, throws on unknown\n * provider or refresh failure), with two deliberate additions:\n *\n * - refresh failures keep the underlying reason — the original discarded it,\n * leaving invalid_grant (needs re-login) indistinguishable from a transient\n * network error.\n * - `options.force` rotates regardless of the local expiry, for 401 recovery\n * when the server revoked the grant before our stored timestamp said so.\n * Expressed as a flag rather than by handing this function a credential\n * with a doctored `expires`: callers persist whatever comes back, so a\n * fabricated expiry that a provider echoes through would land in the\n * credential store. See `resolveCredentialSource` in `./oauth.ts`.\n */\nexport async function getOAuthApiKey(\n providerId: string,\n credentials: Record<string, OAuthCredentials>,\n options?: { force?: boolean },\n): Promise<{ newCredentials: OAuthCredentials, apiKey: string } | null> {\n const provider = oauthProviderRegistry().get(providerId)\n if (!provider)\n throw new Error(`Unknown OAuth provider: ${providerId}`)\n\n let creds = credentials[providerId]\n if (!creds)\n return null\n\n if (options?.force || Date.now() >= creds.expires) {\n try {\n creds = await provider.refreshToken(creds)\n }\n catch (err) {\n throw new Error(`Failed to refresh OAuth token for ${providerId}: ${errorMessage(err)}`, { cause: err })\n }\n }\n\n return { newCredentials: creds, apiKey: provider.getApiKey(creds) }\n}\n","import type { OAuthCredentials } from '@earendil-works/pi-ai/oauth'\nimport type { StreamCallbacks } from '.'\nimport type { OAuthRefreshHookContext } from '../types'\nimport { Buffer } from 'node:buffer'\nimport { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { resolve } from 'node:path'\nimport { writeFileAtomic } from '../atomic-write'\nimport { errorMessage } from '../errors'\nimport { getOAuthApiKey, registerOAuthProvider } from './oauth-registry'\n\ntype GetOAuthApiKey = typeof getOAuthApiKey\n\n/**\n * Resolve the creds-file path at call time rather than module-load time, so\n * env changes between import and first OAuth use (test suites, multi-project\n * CLIs) are honored.\n *\n * Order:\n * 1. `ZIDANE_CREDENTIALS_PATH` — explicit override. The TUI sets this at\n * launch to point at `<storageDir>/credentials.json` so the harness\n * providers find the same file the TUI manages.\n * 2. `~/.credentials.json` — home-anchored default.\n *\n * The historic `cwd/.credentials.json` fallback was deliberately dropped:\n * launching zidane inside an untrusted checkout would let that repo plant a\n * `.credentials.json` and become the credential source (and receive rotated\n * refresh tokens on the next refresh persist). Same trust model as the TUI's\n * legacy-file migration in `chat/credentials.ts`, which only honors the\n * home-anchored location. The only \"trusted\" cwd under that model is `$HOME`\n * itself — where the cwd-relative path resolves to `~/.credentials.json`\n * anyway, so anchoring at home preserves the legitimate legacy case.\n */\nexport function credentialsFilePath(): string {\n return process.env.ZIDANE_CREDENTIALS_PATH ?? resolve(homedir(), '.credentials.json')\n}\n\n/**\n * POSIX mode for credentials on disk. Read+write for the owner only — refresh\n * tokens and API keys leak if the file is world-readable on a shared box.\n * Ignored on Windows.\n */\nconst CREDENTIALS_FILE_MODE = 0o600\n\n/**\n * In-process mutex table keyed by provider id. Concurrent `resolveOAuthApiKey`\n * calls for the same provider (typical when a host fans out multiple streams\n * at once) coalesce onto a single refresh. Without this, N concurrent calls\n * each hit `getOAuthApiKey`, producing N writes to `.credentials.json` with\n * last-write-wins semantics — and, in worst-case interleaving, a corrupted\n * file.\n */\nconst refreshLocks = new Map<string, Promise<string>>()\n\n/**\n * Register a custom OAuth flow with the local registry (`./oauth-registry`)\n * so lazy refresh through {@link resolveOAuthApiKey} can resolve `providerId`.\n *\n * Public because provider extensions need it: without registration,\n * `getOAuthApiKey('<id>', …)` throws `Unknown OAuth provider` the first time a\n * stored token expires. Idempotent per id (the registry is a keyed map). Kept\n * async for API stability — it awaited a dynamic pi-ai import before pi-ai\n * 0.80.8 removed its global registry and this moved in-repo.\n */\nexport async function registerCustomOAuthProvider(\n provider: import('./oauth-registry').OAuthProviderInterface,\n): Promise<void> {\n registerOAuthProvider(provider)\n}\n\nexport interface OAuthParams {\n apiKey?: string\n access?: string\n refresh?: string\n expires?: number\n}\n\n/**\n * Pull a complete `{ access, refresh, expires }` triple out of provider params\n * when (and only when) all three OAuth fields are present and well-typed.\n * Returns `undefined` for the static-api-key path. Shared by the OAuth-capable\n * providers so the runtime-credential guard can't drift between them.\n */\n/**\n * Whether a credential string is an OAuth *access token* rather than a real,\n * static API key. Anthropic OAuth tokens are prefixed `sk-ant-oat`; OpenAI\n * Codex OAuth access tokens are JWTs (`eyJ...`). Used to decide whether an\n * env-provided value can be refreshed (OAuth) or must be sent verbatim (API key).\n */\nexport function isOAuthAccessToken(value: string): boolean {\n return value.startsWith('sk-ant-oat') || isJwtLikeAccessToken(value)\n}\n\nfunction isJwtLikeAccessToken(value: string): boolean {\n const parts = value.split('.')\n if (parts.length !== 3 || !parts[0]?.startsWith('eyJ'))\n return false\n try {\n const header = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8')) as unknown\n return Boolean(header && typeof header === 'object' && 'alg' in header)\n }\n catch {\n return false\n }\n}\n\nexport function extractRuntimeCredentials(\n params?: OAuthParams,\n): { access: string, refresh: string, expires: number } | undefined {\n if (\n typeof params?.access === 'string'\n && typeof params.refresh === 'string'\n && typeof params.expires === 'number'\n ) {\n return { access: params.access, refresh: params.refresh, expires: params.expires }\n }\n return undefined\n}\n\nexport interface ResolveOAuthApiKeyOptions<TParams extends OAuthParams = OAuthParams> {\n provider: string\n providerId: string\n params?: TParams\n envKey?: string\n extraCredentialKeys?: (keyof TParams & string)[]\n missingError: string\n refreshError: (reason: string) => string\n readCredentials?: () => Record<string, OAuthCredentials | undefined>\n writeCredentials?: (credentials: Record<string, OAuthCredentials | undefined>) => void\n getOAuthApiKey?: GetOAuthApiKey\n /**\n * Force a refresh even when the credential's local expiry is still in the\n * future (for one-shot 401 recovery). Reaches the refresh helper as an\n * explicit flag, so no credential with a fabricated expiry ever exists to\n * leak into the store — see {@link getOAuthApiKey}.\n */\n forceRefresh?: boolean\n /** Access token rejected by the server; a different token found under lock is reused instead of rotated again. */\n rejectedAccess?: string\n}\n\n/**\n * Read the shared credentials file.\n *\n * Returns `{}` when the file is missing OR when the file exists but is corrupted\n * / not valid JSON. Corrupt-file tolerance is important: the refresh-then-persist\n * path below writes atomically, but older builds wrote in place and could have\n * truncated the file on a crash. Treating corruption as \"no stored creds\" lets\n * users re-auth without manually deleting the file.\n *\n * Supports two on-disk shapes:\n * 1. **Legacy** (untagged): `{ \"anthropic\": { access, refresh, expires, ... } }`\n * — written by older `bun run auth`.\n * 2. **New** (kind-tagged): `{ \"anthropic\": { kind: 'oauth', access, refresh, expires, ... } }`\n * — written by the TUI. Entries with `kind: 'apikey'` are skipped — those\n * reach providers via env vars set at TUI launch (see `applyApiKeyEnv`).\n */\nexport function readOAuthCredentials(): Record<string, OAuthCredentials | undefined> {\n const path = credentialsFilePath()\n if (!existsSync(path))\n return {}\n\n try {\n const raw = readFileSync(path, 'utf-8')\n const parsed = JSON.parse(raw)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))\n return {}\n const result: Record<string, OAuthCredentials | undefined> = {}\n for (const [key, value] of Object.entries(parsed)) {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n continue\n const v = value as Record<string, unknown>\n // New schema: explicit `kind` tag.\n if (v.kind === 'apikey')\n continue\n // Both new (`kind: 'oauth'`) and legacy (untagged) entries have `access`;\n // the harmless `kind` field is allowed by `OAuthCredentials`'s\n // `[key: string]: unknown` index signature. Validate the required\n // fields explicitly so the assignment doesn't need a double-cast.\n if (\n typeof v.access === 'string'\n && typeof v.refresh === 'string'\n && typeof v.expires === 'number'\n ) {\n result[key] = { ...v, access: v.access, refresh: v.refresh, expires: v.expires }\n }\n }\n return result\n }\n catch {\n return {}\n }\n}\n\n/**\n * Cross-process lockfile parameters for the credentials read-merge-write.\n * A holder normally completes in well under a millisecond (read + JSON merge\n * + atomic write of a tiny file), so the stale threshold is generous and the\n * total wait short — on timeout we proceed without the lock rather than fail\n * the refresh (degrades to the historic last-write-wins behavior).\n */\nconst CREDENTIALS_LOCK_STALE_MS = 5000\nconst CREDENTIALS_LOCK_RETRY_MS = 20\nconst CREDENTIALS_LOCK_MAX_WAIT_MS = 2000\n\n/** Synchronous sleep without spinning — works on Bun and Node main threads. */\nfunction sleepSync(ms: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)\n}\n\n/**\n * Best-effort exclusive lock via `O_EXCL` create of `<file>.lock`. Returns\n * `true` when the lock was acquired (caller must release), `false` on\n * timeout (caller proceeds unlocked — see threshold rationale above). Locks\n * older than {@link CREDENTIALS_LOCK_STALE_MS} are treated as leftovers from\n * a crashed process and broken.\n */\nfunction acquireCredentialsLock(lockPath: string): boolean {\n const deadline = Date.now() + CREDENTIALS_LOCK_MAX_WAIT_MS\n while (true) {\n try {\n writeFileSync(lockPath, String(process.pid), { flag: 'wx', mode: CREDENTIALS_FILE_MODE })\n return true\n }\n catch (err) {\n // Only EEXIST means \"lock held\" — anything else (EPERM, ENOENT for a\n // missing parent dir, read-only fs) won't resolve by waiting, so bail\n // immediately and let the subsequent write surface the real error.\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST')\n return false\n try {\n const age = Date.now() - statSync(lockPath).mtimeMs\n if (age > CREDENTIALS_LOCK_STALE_MS) {\n unlinkSync(lockPath)\n continue\n }\n }\n catch { /* lock vanished between create-fail and stat — retry */ }\n if (Date.now() >= deadline)\n return false\n sleepSync(CREDENTIALS_LOCK_RETRY_MS)\n }\n }\n}\n\nfunction releaseCredentialsLock(lockPath: string): void {\n try {\n unlinkSync(lockPath)\n }\n catch { /* already gone */ }\n}\n\n/**\n * Cross-process lock parameters for the REFRESH critical section (read →\n * check expiry → refresh → persist), held per provider around file-backed\n * resolves in {@link resolveOAuthApiKey}.\n *\n * This is a different beast from the write lock above: the holder performs a\n * network call, so it can legitimately hold the lock for seconds. Hence its\n * own generous thresholds — and async waiting, because blocking the event\n * loop for a peer's refresh round-trip is not acceptable. The stakes are\n * higher too: providers with single-use rotating refresh tokens (Bolt) treat\n * a replayed token as theft and revoke the WHOLE grant, so two processes\n * refreshing the same provider concurrently don't just race a write — they\n * self-revoke. A process that loses the race re-reads under the lock, finds\n * the winner's fresh token, and skips its own refresh entirely.\n *\n * On timeout we proceed without the lock (degrades to the pre-lock racy\n * behavior) rather than fail a resolve that would probably have succeeded.\n */\nconst REFRESH_LOCK_STALE_MS = 60_000\nconst REFRESH_LOCK_RETRY_MS = 50\nconst REFRESH_LOCK_MAX_WAIT_MS = 30_000\n\nfunction refreshLockPath(providerId: string): string {\n return `${credentialsFilePath()}.refresh-${providerId.replace(/[^\\w.-]/g, '_')}.lock`\n}\n\n/** Async sibling of {@link acquireCredentialsLock} with refresh-scale thresholds. */\nasync function acquireRefreshLock(lockPath: string): Promise<boolean> {\n const deadline = Date.now() + REFRESH_LOCK_MAX_WAIT_MS\n while (true) {\n try {\n writeFileSync(lockPath, String(process.pid), { flag: 'wx', mode: CREDENTIALS_FILE_MODE })\n return true\n }\n catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST')\n return false\n try {\n const age = Date.now() - statSync(lockPath).mtimeMs\n if (age > REFRESH_LOCK_STALE_MS) {\n unlinkSync(lockPath)\n continue\n }\n }\n catch { /* lock vanished between create-fail and stat — retry */ }\n if (Date.now() >= deadline)\n return false\n await new Promise(resolve => setTimeout(resolve, REFRESH_LOCK_RETRY_MS))\n }\n }\n}\n\n/**\n * Atomically write `.credentials.json` with mode 0o600.\n *\n * Writes to a sibling temp file first, then renames. `rename(2)` is atomic on\n * the same filesystem, so readers either see the old file or the new one —\n * never a half-written one. This matters when a host has multiple processes\n * pointed at the same creds file.\n *\n * Merges the incoming OAuth entries on top of the raw file contents so that\n * entries this layer doesn't manage (e.g. `kind: 'apikey'` from the TUI\n * wizard) survive an OAuth refresh cycle. Without this merge,\n * `readOAuthCredentials` filters those entries out, and a naive overwrite\n * would delete them.\n *\n * The read-merge-write runs under a best-effort cross-process lockfile\n * (`<file>.lock`) so two processes refreshing different providers at the\n * same moment can't drop each other's rotated refresh tokens. On lock\n * timeout the write proceeds unlocked (last-write-wins, the pre-lock\n * behavior) rather than failing the refresh.\n */\nexport function writeOAuthCredentials(credentials: Record<string, OAuthCredentials | undefined>) {\n const path = credentialsFilePath()\n const lockPath = `${path}.lock`\n const locked = acquireCredentialsLock(lockPath)\n\n try {\n let existing: Record<string, unknown> = {}\n try {\n if (existsSync(path)) {\n const raw = readFileSync(path, 'utf-8')\n const parsed = JSON.parse(raw)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))\n existing = parsed as Record<string, unknown>\n }\n }\n catch { /* corrupt file — start fresh */ }\n\n const merged = { ...existing, ...credentials }\n // Remove keys explicitly set to undefined (provider was deleted).\n for (const [key, value] of Object.entries(merged)) {\n if (value === undefined)\n delete merged[key]\n }\n\n writeFileAtomic(path, JSON.stringify(merged, null, 2), { mode: CREDENTIALS_FILE_MODE })\n }\n finally {\n if (locked)\n releaseCredentialsLock(lockPath)\n }\n}\n\nexport function credentialsFromParams<TParams extends OAuthParams>(params?: TParams, extraKeys: (keyof TParams & string)[] = []): OAuthCredentials | undefined {\n if (typeof params?.access !== 'string' || typeof params.refresh !== 'string' || typeof params.expires !== 'number')\n return undefined\n\n const extras = Object.fromEntries(\n extraKeys\n .map(key => [key, params[key]])\n .filter(([, value]) => value !== undefined),\n )\n\n return {\n access: params.access,\n refresh: params.refresh,\n expires: params.expires,\n ...extras,\n }\n}\n\nexport async function resolveOAuthApiKey<TParams extends OAuthParams>(\n options: ResolveOAuthApiKeyOptions<TParams>,\n callbacks?: Pick<StreamCallbacks, 'onOAuthRefresh'>,\n): Promise<string> {\n if (typeof options.params?.apiKey === 'string')\n return options.params.apiKey\n\n const paramsCredentials = credentialsFromParams(options.params, options.extraCredentialKeys)\n if (paramsCredentials) {\n return await withRefreshLock(\n `params:${options.providerId}`,\n () => resolveCredentialSource('params', paramsCredentials),\n )\n }\n\n if (typeof options.params?.access === 'string')\n return options.params.access\n\n const readCredentials = options.readCredentials ?? readOAuthCredentials\n const writeCredentials = options.writeCredentials ?? writeOAuthCredentials\n // The cross-process refresh lock only means something when we're actually\n // backed by the shared credentials file; injected stores (tests, embedders)\n // have no cross-process story to protect and must not touch real lock files.\n const usingDefaultStore = !options.readCredentials && !options.writeCredentials\n\n // Env key handling. A real API key (e.g. `sk-ant-api…`) is used as-is. But an\n // OAuth *access token* (`sk-ant-oat…`) pasted into the API-key env var can't\n // be refreshed and will 401 once expired — so if refreshable OAuth creds for\n // this provider exist on disk, prefer those (they self-heal via refresh).\n const envValue = options.envKey ? process.env[options.envKey] : undefined\n if (envValue) {\n if (!isOAuthAccessToken(envValue))\n return envValue\n if (!readCredentials()[options.providerId])\n return envValue // no refreshable creds — fall back to the raw token\n return await withRefreshLock(`file:${options.providerId}`, () => withCrossProcessRefreshLock(async () => {\n // Re-read under the locks — a concurrent resolve (in this process or\n // another) may have rotated the refresh token between the pre-check\n // above and lock acquisition, and refreshing with the stale token would\n // invalidate the new one.\n const allCredentials = readCredentials()\n const stored = allCredentials[options.providerId]\n if (!stored)\n return envValue\n return await resolveCredentialSource('file', stored, allCredentials, writeCredentials)\n }))\n }\n\n return await withRefreshLock(`file:${options.providerId}`, () => withCrossProcessRefreshLock(async () => {\n // Read under the locks so we're always operating on the latest file state\n // and never interleave read/refresh/write against another concurrent\n // resolve — in-process (withRefreshLock) or cross-process (the lockfile).\n const allCredentials = readCredentials()\n const storedCredentials = allCredentials[options.providerId]\n if (!storedCredentials)\n throw new Error(options.missingError)\n\n return await resolveCredentialSource('file', storedCredentials, allCredentials, writeCredentials)\n }))\n\n /**\n * Hold the per-provider cross-process lockfile across the WHOLE file-backed\n * critical section, not just the persist. Guarding only the write (as\n * `writeOAuthCredentials` does) still lets two processes both spend a\n * single-use rotating refresh token — which self-revokes providers with\n * replay-detecting rotation. See the {@link REFRESH_LOCK_STALE_MS} note.\n */\n async function withCrossProcessRefreshLock(fn: () => Promise<string>): Promise<string> {\n if (!usingDefaultStore)\n return fn()\n const lockPath = refreshLockPath(options.providerId)\n const locked = await acquireRefreshLock(lockPath)\n try {\n return await fn()\n }\n finally {\n if (locked)\n releaseCredentialsLock(lockPath)\n }\n }\n\n async function resolveCredentialSource(\n source: OAuthRefreshHookContext['source'],\n current: OAuthCredentials,\n allCredentials?: Record<string, OAuthCredentials | undefined>,\n persistCredentials?: (credentials: Record<string, OAuthCredentials | undefined>) => void,\n ): Promise<string> {\n // Only the refresh call itself maps to `refreshError` — a throwing\n // persist or onOAuthRefresh hook after a SUCCESSFUL refresh must not be\n // misreported as a refresh failure, so those run outside the try.\n let result: Awaited<ReturnType<GetOAuthApiKey>>\n try {\n const refreshOAuthApiKey = options.getOAuthApiKey ?? getOAuthApiKey\n // A 401 can mean server-side revocation/expiry before our local timestamp,\n // so ask the helper to rotate regardless of what `expires` claims. Passed\n // as a flag rather than by handing it `{ ...current, expires: 0 }`: the\n // persist gate below is an identity check against `current`, so a\n // fabricated credential that a provider echoes back (a no-op refresh in a\n // custom flow, or an injected `getOAuthApiKey`) would read as a real\n // rotation and write `expires: 0` into the credential store — poisoning\n // every later resolve into refreshing on every turn.\n const stillRejectedGeneration = options.rejectedAccess === undefined || current.access === options.rejectedAccess\n const force = options.forceRefresh === true && stillRejectedGeneration\n result = await refreshOAuthApiKey(\n options.providerId,\n { [options.providerId]: current } as Record<string, OAuthCredentials>,\n { force },\n )\n }\n catch (err) {\n throw new Error(options.refreshError(errorMessage(err)))\n }\n if (!result)\n throw new Error(options.refreshError(options.missingError))\n\n if (result.newCredentials !== current) {\n // pi-ai's refresh returns only `{ access, refresh, expires }`. Merge it\n // onto the current credential so the persisted entry keeps its on-disk\n // `kind: 'oauth'` tag and any provider extras (e.g. openai-codex\n // `accountId`). A bare overwrite strips `kind`, and the TUI's auth-state\n // detection keys on `kind === 'oauth'` — so without this the provider\n // reads as signed out after every token refresh, forcing a daily re-login.\n const refreshed = { ...current, ...result.newCredentials }\n if (source === 'file' && allCredentials && persistCredentials) {\n allCredentials[options.providerId] = refreshed\n persistCredentials(allCredentials)\n }\n\n await callbacks?.onOAuthRefresh?.({\n provider: options.provider,\n providerId: options.providerId,\n source,\n previousCredentials: { ...current },\n credentials: { ...refreshed },\n })\n }\n\n return result.apiKey\n }\n}\n\n/**\n * Coalesce concurrent refresh calls onto a single in-flight promise per key.\n * The key combines the source (`params` vs `file`) and provider id, so a\n * per-agent param-only refresh does not starve a separate file-backed one.\n */\nasync function withRefreshLock(key: string, fn: () => Promise<string>): Promise<string> {\n const existing = refreshLocks.get(key)\n if (existing)\n return existing\n\n const task = (async () => {\n try {\n return await fn()\n }\n finally {\n refresh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ClB,UACQ;GACN,aAAa,OAAO,GAAG;EACzB;CACF,EAAA,CAAG;CACH,aAAa,IAAI,KAAK,IAAI;CAC1B,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
1
  import { i as documentBlockMarker, n as assertResolvedMediaBlock } from "./types-BIarq1qE.js";
2
2
  import { n as estimateTokens } from "./utils-ngQzYzZD.js";
3
- import { f as isRetryableHttpStatus, l as classifyErrorPrelude, m as matchesToolPairingError, p as matchesContextExceeded } from "./errors-BwBxu3zD.js";
3
+ import { f as isRetryableHttpStatus, h as matchesToolPairingError, l as classifyErrorPrelude, m as matchesContextExceeded } from "./errors-DKiMrOKq.js";
4
4
  import { t as audioFormatFromMediaType } from "./media-sniff-UKijEaiQ.js";
5
5
  import { renderSystemForWire, splitSystemPrompt } from "./prompt.js";
6
6
  import { createHash } from "node:crypto";
@@ -2282,4 +2282,4 @@ function openaiCompat(params) {
2282
2282
  //#endregion
2283
2283
  export { mergeCatalogEntry as A, rewriteMessagesToWire as B, estimateRebilledCostUsd as C, listModelOverlay as D, getModelCatalog as E, unsupportedMediaError as F, toWireName as H, augmentMcpDoubleUnderscoreAliases as I, buildAliasMaps as L, buildPromptMessage as M, canonicalizePrompt as N, listModels as O, defaultPromptMessage as P, buildSanitizedWireAliases as R, resolvePromptCacheKey as S, aliasCatalogProviders as T, fnv1aBase36 as U, toCanonicalName as V, userMessage as _, applyOAICacheBreakpoints as a, sanitizeToolSpecs as b, buildAssistantContent as c, formatTools as d, mapOAIFinishReason as f, toolResultsMessage as g, toOAIMessages as h, TOOL_RESULTS_TAG as i, setModelCatalog as j, lookupModel as k, classifyOpenAICompatError as l, openaiCompat as m, OpenAICompatHttpError as n, applyOAIToolCacheBreakpoint as o, openAICompatPromptMessage as p, OpenAICompatStreamError as r, assistantMessage as s, ASSISTANT_TOOL_CALLS_TAG as t, consumeSSE as u, createToolNameBoundary as v, fillEstimatedCost as w, derivePromptCacheKey as x, sanitizeToolSchema as y, rewriteContentToCanonical as z };
2284
2284
 
2285
- //# sourceMappingURL=openai-compat-CnHeo4Lz.js.map
2285
+ //# sourceMappingURL=openai-compat-hmZzpDrB.js.map