zidane 6.3.0 → 6.3.2

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 (114) hide show
  1. package/dist/{acp-BCg03Fqc.js → acp-CNnevGOW.js} +4 -4
  2. package/dist/{acp-BCg03Fqc.js.map → acp-CNnevGOW.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-DO8s7bDf.js → agent-C5cHuI0r.js} +6 -5
  7. package/dist/{agent-DO8s7bDf.js.map → agent-C5cHuI0r.js.map} +1 -1
  8. package/dist/agent.d.ts +2 -2
  9. package/dist/agent.js +2 -2
  10. package/dist/{anthropic-B3hj9OMm.js → anthropic-DdDVf39o.js} +30 -14
  11. package/dist/anthropic-DdDVf39o.js.map +1 -0
  12. package/dist/{auth-kqdSYLMU.js → auth-C2vaeVqG.js} +5 -5
  13. package/dist/auth-C2vaeVqG.js.map +1 -0
  14. package/dist/{cache-telemetry-DzyfqSds.js → cache-telemetry-ehVdWsg2.js} +23 -4
  15. package/dist/cache-telemetry-ehVdWsg2.js.map +1 -0
  16. package/dist/chat/pure.d.ts +3 -3
  17. package/dist/chat.d.ts +5 -5
  18. package/dist/chat.js +3 -3
  19. package/dist/{context-transport-CTLvmkj8.js → context-transport-CkiORGgx.js} +3 -3
  20. package/dist/{context-transport-CTLvmkj8.js.map → context-transport-CkiORGgx.js.map} +1 -1
  21. package/dist/contexts/daytona.d.ts +1 -1
  22. package/dist/contexts/e2b.d.ts +1 -1
  23. package/dist/eval.d.ts +1 -1
  24. package/dist/eval.js +1 -1
  25. package/dist/extensions.d.ts +1 -1
  26. package/dist/extensions.js +1 -1
  27. package/dist/headless.d.ts +1 -1
  28. package/dist/headless.js +3 -3
  29. package/dist/{index-Bht3PKx6.d.ts → index-BT4Q1nLD.d.ts} +140 -16
  30. package/dist/index-BT4Q1nLD.d.ts.map +1 -0
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.js +10 -10
  33. package/dist/{login-DRy_-rQh.js → login-b2sxfknZ.js} +2 -2
  34. package/dist/{login-DRy_-rQh.js.map → login-b2sxfknZ.js.map} +1 -1
  35. package/dist/{mcp-DHKk_tLV.js → mcp-DvvV6xub.js} +3 -3
  36. package/dist/{mcp-DHKk_tLV.js.map → mcp-DvvV6xub.js.map} +1 -1
  37. package/dist/mcp.d.ts +1 -1
  38. package/dist/mcp.js +1 -1
  39. package/dist/{messages-DHzFOdx_.js → messages-TVh_iU9W.js} +2 -2
  40. package/dist/{messages-DHzFOdx_.js.map → messages-TVh_iU9W.js.map} +1 -1
  41. package/dist/{oauth-CBi9eymX.js → oauth-CuFPhsHY.js} +117 -11
  42. package/dist/oauth-CuFPhsHY.js.map +1 -0
  43. package/dist/{openai-compat-OI68avOl.js → openai-compat-Ba4nw7ip.js} +130 -28
  44. package/dist/openai-compat-Ba4nw7ip.js.map +1 -0
  45. package/dist/output/stream-json.d.ts +1 -1
  46. package/dist/output/terminal.d.ts +1 -1
  47. package/dist/presets.d.ts +1 -1
  48. package/dist/presets.js +1 -1
  49. package/dist/providers/anthropic.d.ts +1 -1
  50. package/dist/providers/anthropic.js +1 -1
  51. package/dist/providers/arcee.d.ts +1 -1
  52. package/dist/providers/arcee.js +1 -1
  53. package/dist/providers/baseten.d.ts +1 -1
  54. package/dist/providers/baseten.js +1 -1
  55. package/dist/providers/cerebras.d.ts +1 -1
  56. package/dist/providers/cerebras.js +1 -1
  57. package/dist/providers/local.d.ts +1 -1
  58. package/dist/providers/local.js +1 -1
  59. package/dist/providers/openai-compat.d.ts +1 -1
  60. package/dist/providers/openai-compat.js +1 -1
  61. package/dist/providers/openai.d.ts +1 -1
  62. package/dist/providers/openai.js +5 -5
  63. package/dist/providers/openai.js.map +1 -1
  64. package/dist/providers/openrouter.d.ts +1 -1
  65. package/dist/providers/openrouter.js +1 -1
  66. package/dist/providers/xai.d.ts +1 -1
  67. package/dist/providers/xai.js +1 -1
  68. package/dist/{providers-y_l5VkAZ.js → providers-g1ilD4qo.js} +4 -4
  69. package/dist/providers-g1ilD4qo.js.map +1 -0
  70. package/dist/providers.d.ts +2 -2
  71. package/dist/providers.js +5 -5
  72. package/dist/restate.d.ts +1 -1
  73. package/dist/session/sqlite.d.ts +1 -1
  74. package/dist/{session-DdT2xT_d.js → session-CFwkU19n.js} +2 -2
  75. package/dist/{session-DdT2xT_d.js.map → session-CFwkU19n.js.map} +1 -1
  76. package/dist/session.d.ts +1 -1
  77. package/dist/session.js +2 -2
  78. package/dist/skills.d.ts +1 -1
  79. package/dist/{stdio-DU3ljLqy.js → stdio-DUu_loK-.js} +2 -2
  80. package/dist/{stdio-DU3ljLqy.js.map → stdio-DUu_loK-.js.map} +1 -1
  81. package/dist/{stdio-loader-9PnQWshg.js → stdio-loader-LlzejufT.js} +2 -2
  82. package/dist/{stdio-loader-9PnQWshg.js.map → stdio-loader-LlzejufT.js.map} +1 -1
  83. package/dist/{tool-formatters-B0ZXWJTe.d.ts → tool-formatters-CHz3OpkJ.d.ts} +2 -2
  84. package/dist/{tool-formatters-B0ZXWJTe.d.ts.map → tool-formatters-CHz3OpkJ.d.ts.map} +1 -1
  85. package/dist/tools/fetch-url.d.ts +1 -1
  86. package/dist/tools/web-search.d.ts +1 -1
  87. package/dist/tools.d.ts +1 -1
  88. package/dist/tools.js +1 -1
  89. package/dist/{transcript-anchors-yt0sGL0w.d.ts → transcript-anchors-BnG23uzH.d.ts} +2 -2
  90. package/dist/{transcript-anchors-yt0sGL0w.d.ts.map → transcript-anchors-BnG23uzH.d.ts.map} +1 -1
  91. package/dist/{transcript-anchors-ChQH1fMm.js → transcript-anchors-D2RZPaGf.js} +5 -4
  92. package/dist/transcript-anchors-D2RZPaGf.js.map +1 -0
  93. package/dist/tui.d.ts +3 -3
  94. package/dist/tui.d.ts.map +1 -1
  95. package/dist/tui.js +73 -46
  96. package/dist/tui.js.map +1 -1
  97. package/dist/{turn-operations-XlnBT7p9.d.ts → turn-operations-BjkxnZL_.d.ts} +3 -3
  98. package/dist/{turn-operations-XlnBT7p9.d.ts.map → turn-operations-BjkxnZL_.d.ts.map} +1 -1
  99. package/dist/types.d.ts +1 -1
  100. package/dist/{xai-DxdI27ds.js → xai-5LbsIfXn.js} +3 -3
  101. package/dist/xai-5LbsIfXn.js.map +1 -0
  102. package/docs/ARCHITECTURE.md +11 -2
  103. package/docs/CHAT.md +1 -1
  104. package/docs/EXTENSIONS.md +1 -1
  105. package/package.json +2 -2
  106. package/dist/anthropic-B3hj9OMm.js.map +0 -1
  107. package/dist/auth-kqdSYLMU.js.map +0 -1
  108. package/dist/cache-telemetry-DzyfqSds.js.map +0 -1
  109. package/dist/index-Bht3PKx6.d.ts.map +0 -1
  110. package/dist/oauth-CBi9eymX.js.map +0 -1
  111. package/dist/openai-compat-OI68avOl.js.map +0 -1
  112. package/dist/providers-y_l5VkAZ.js.map +0 -1
  113. package/dist/transcript-anchors-ChQH1fMm.js.map +0 -1
  114. package/dist/xai-DxdI27ds.js.map +0 -1
@@ -1,12 +1,119 @@
1
- import { t as lazyAsync } from "./lazy-DLOurOC_.js";
2
1
  import { l as errorMessage } from "./errors-DJUxZg9b.js";
3
2
  import { t as writeFileAtomic } from "./atomic-write-B7zr1ddF.js";
4
3
  import { resolve } from "node:path";
5
4
  import { Buffer } from "node:buffer";
6
5
  import { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
6
  import { homedir } from "node:os";
7
+ //#region src/providers/oauth-registry.ts
8
+ /**
9
+ * Run a canonical pi-ai `OAuthAuth.refresh` from a bare refresh token.
10
+ * pi-ai's built-in refresh implementations only read `credential.refresh`,
11
+ * so the placeholder access/expires fields are never observed.
12
+ *
13
+ * The canonical result is an `OAuthCredential` tagged `type: 'oauth'`. Strip
14
+ * the tag before returning: refresh results get merged into stored
15
+ * `.credentials.json` entries and `onOAuthRefresh` hook payloads (see
16
+ * `resolveCredentialSource` in `./oauth.ts`), whose documented shape carries
17
+ * zidane's own `kind` tag — letting pi-ai's `type` leak through would
18
+ * silently drift the on-disk shape.
19
+ */
20
+ async function refreshViaCanonicalFlow(providerId, oauth, refreshToken) {
21
+ if (!oauth) throw new Error(`pi-ai provider ${providerId} exposes no OAuth flow`);
22
+ const { type: _type, ...credentials } = await oauth.refresh({
23
+ type: "oauth",
24
+ access: "",
25
+ refresh: refreshToken,
26
+ expires: 0
27
+ });
28
+ return credentials;
29
+ }
30
+ /**
31
+ * Refresh an Anthropic (Claude Pro/Max) OAuth token. Drop-in replacement for
32
+ * the `refreshAnthropicToken` pi-ai exported until 0.80.6; delegates to the
33
+ * canonical flow on `anthropicProvider().auth.oauth`.
34
+ */
35
+ async function refreshAnthropicToken(refreshToken) {
36
+ const { anthropicProvider } = await import("@earendil-works/pi-ai/providers/anthropic");
37
+ return refreshViaCanonicalFlow("anthropic", anthropicProvider().auth.oauth, refreshToken);
38
+ }
39
+ /**
40
+ * Refresh an OpenAI Codex (ChatGPT) OAuth token. Drop-in replacement for the
41
+ * removed `refreshOpenAICodexToken`; the canonical flow still derives
42
+ * `accountId` from the refreshed access token's JWT claims, so the returned
43
+ * credentials keep the extra field older callers persisted.
44
+ */
45
+ async function refreshOpenAICodexToken(refreshToken) {
46
+ const { openaiCodexProvider } = await import("@earendil-works/pi-ai/providers/openai-codex");
47
+ return refreshViaCanonicalFlow("openai-codex", openaiCodexProvider().auth.oauth, refreshToken);
48
+ }
49
+ /**
50
+ * Built-in registry seeds. pi-ai's removed registry pre-seeded Anthropic and
51
+ * OpenAI Codex, and zidane's lazy token refresh (`getOAuthApiKey` inside
52
+ * `resolveOAuthApiKey`) relied on that — so the local registry seeds the same
53
+ * ids. Login is intentionally unsupported here: interactive login always goes
54
+ * through `ProviderDescriptor.oauthProvider` (the themed flows in
55
+ * `src/chat/oauth-page/`), never through the registry.
56
+ */
57
+ function builtinProvider(id, name, refreshToken) {
58
+ return {
59
+ id,
60
+ name,
61
+ login: async () => {
62
+ throw new Error(`OAuth login for ${id} must run through a provider descriptor flow, not the registry`);
63
+ },
64
+ refreshToken: (credentials) => refreshToken(credentials.refresh),
65
+ getApiKey: (credentials) => credentials.access
66
+ };
67
+ }
68
+ /**
69
+ * The registry map is anchored on a process-wide `globalThis` slot rather
70
+ * than module state. The pi-ai registry this replaces lived in pi-ai's own
71
+ * module, so every copy of zidane code in a process shared one map — and two
72
+ * copies is a real configuration, not a hypothetical: a host running from
73
+ * `src` while a disk-loaded extension resolves `'zidane'` to `dist` through
74
+ * ordinary node_modules resolution (see `import()` in
75
+ * `src/extensions/discovery.ts`). The extension registers its flow at setup;
76
+ * `resolveOAuthApiKey` looks it up only once a stored token expires — with
77
+ * per-module maps that fails as a deferred "Unknown OAuth provider", which is
78
+ * nasty to debug. `Symbol.for` restores the process-wide sharing. Whichever
79
+ * copy touches the slot first seeds the built-ins; the seeds are pure
80
+ * delegations to pi-ai's canonical flows, so first-copy-wins is harmless.
81
+ */
82
+ const REGISTRY_SLOT = Symbol.for("zidane.oauth-provider-registry");
83
+ function oauthProviderRegistry() {
84
+ const slots = globalThis;
85
+ slots[REGISTRY_SLOT] ??= new Map([builtinProvider("anthropic", "Anthropic (Claude Pro/Max)", refreshAnthropicToken), builtinProvider("openai-codex", "OpenAI (ChatGPT Plus/Pro)", refreshOpenAICodexToken)].map((provider) => [provider.id, provider]));
86
+ return slots[REGISTRY_SLOT];
87
+ }
88
+ /** Register (or replace) an OAuth provider by id. */
89
+ function registerOAuthProvider(provider) {
90
+ oauthProviderRegistry().set(provider.id, provider);
91
+ }
92
+ /**
93
+ * Get an API key for a provider from OAuth credentials, refreshing expired
94
+ * tokens through the registered flow. Same contract as the pi-ai original
95
+ * (`null` when no credentials are stored for the provider, throws on unknown
96
+ * provider or refresh failure), except refresh failures keep the underlying
97
+ * reason — the original discarded it, leaving invalid_grant (needs re-login)
98
+ * indistinguishable from a transient network error.
99
+ */
100
+ async function getOAuthApiKey(providerId, credentials) {
101
+ const provider = oauthProviderRegistry().get(providerId);
102
+ if (!provider) throw new Error(`Unknown OAuth provider: ${providerId}`);
103
+ let creds = credentials[providerId];
104
+ if (!creds) return null;
105
+ if (Date.now() >= creds.expires) try {
106
+ creds = await provider.refreshToken(creds);
107
+ } catch (err) {
108
+ throw new Error(`Failed to refresh OAuth token for ${providerId}: ${errorMessage(err)}`, { cause: err });
109
+ }
110
+ return {
111
+ newCredentials: creds,
112
+ apiKey: provider.getApiKey(creds)
113
+ };
114
+ }
115
+ //#endregion
8
116
  //#region src/providers/oauth.ts
9
- const loadGetOAuthApiKey = lazyAsync(async () => (await import("@earendil-works/pi-ai/oauth")).getOAuthApiKey);
10
117
  /**
11
118
  * Resolve the creds-file path at call time rather than module-load time, so
12
119
  * env changes between import and first OAuth use (test suites, multi-project
@@ -46,17 +153,16 @@ const CREDENTIALS_FILE_MODE = 384;
46
153
  */
47
154
  const refreshLocks = /* @__PURE__ */ new Map();
48
155
  /**
49
- * Register a custom OAuth flow with pi-ai's registry so lazy refresh through
50
- * {@link resolveOAuthApiKey} can resolve `providerId`.
156
+ * Register a custom OAuth flow with the local registry (`./oauth-registry`)
157
+ * so lazy refresh through {@link resolveOAuthApiKey} can resolve `providerId`.
51
158
  *
52
159
  * Public because provider extensions need it: without registration,
53
160
  * `getOAuthApiKey('<id>', …)` throws `Unknown OAuth provider` the first time a
54
- * stored token expires. Idempotent per id (the registry is a keyed map), and
55
- * lazily imported so importing this module never pulls pi-ai's OAuth surface
56
- * into processes that don't authenticate.
161
+ * stored token expires. Idempotent per id (the registry is a keyed map). Kept
162
+ * async for API stability — it awaited a dynamic pi-ai import before pi-ai
163
+ * 0.80.8 removed its global registry and this moved in-repo.
57
164
  */
58
165
  async function registerCustomOAuthProvider(provider) {
59
- const { registerOAuthProvider } = await import("@earendil-works/pi-ai/oauth");
60
166
  registerOAuthProvider(provider);
61
167
  }
62
168
  /**
@@ -320,7 +426,7 @@ async function resolveOAuthApiKey(options, callbacks) {
320
426
  async function resolveCredentialSource(source, current, allCredentials, persistCredentials) {
321
427
  let result;
322
428
  try {
323
- result = await (options.getOAuthApiKey ?? await loadGetOAuthApiKey())(options.providerId, { [options.providerId]: current });
429
+ result = await (options.getOAuthApiKey ?? getOAuthApiKey)(options.providerId, { [options.providerId]: current });
324
430
  } catch (err) {
325
431
  throw new Error(options.refreshError(errorMessage(err)));
326
432
  }
@@ -364,6 +470,6 @@ async function withRefreshLock(key, fn) {
364
470
  return task;
365
471
  }
366
472
  //#endregion
367
- export { readOAuthCredentials as a, writeOAuthCredentials as c, isOAuthAccessToken as i, credentialsFromParams as n, registerCustomOAuthProvider as o, extractRuntimeCredentials as r, resolveOAuthApiKey as s, credentialsFilePath as t };
473
+ export { readOAuthCredentials as a, writeOAuthCredentials as c, registerOAuthProvider as d, isOAuthAccessToken as i, refreshAnthropicToken as l, credentialsFromParams as n, registerCustomOAuthProvider as o, extractRuntimeCredentials as r, resolveOAuthApiKey as s, credentialsFilePath as t, refreshOpenAICodexToken as u };
368
474
 
369
- //# sourceMappingURL=oauth-CBi9eymX.js.map
475
+ //# sourceMappingURL=oauth-CuFPhsHY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-CuFPhsHY.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 const { type: _type, ...credentials }\n = await oauth.refresh({ type: 'oauth', access: '', refresh: refreshToken, expires: 0 })\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. pi-ai's removed registry pre-seeded Anthropic and\n * OpenAI Codex, and zidane's lazy token refresh (`getOAuthApiKey` inside\n * `resolveOAuthApiKey`) relied on that — so the local registry seeds the same\n * ids. 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: (token: string) => 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: credentials => refreshToken(credentials.refresh),\n getApiKey: credentials => credentials.access,\n }\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; the seeds are pure\n * delegations to pi-ai's canonical flows, so first-copy-wins is harmless.\n */\nconst 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)', refreshAnthropicToken),\n builtinProvider('openai-codex', 'OpenAI (ChatGPT Plus/Pro)', refreshOpenAICodexToken),\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), except refresh failures keep the underlying\n * reason — the original discarded it, leaving invalid_grant (needs re-login)\n * indistinguishable from a transient network error.\n */\nexport async function getOAuthApiKey(\n providerId: string,\n credentials: Record<string, OAuthCredentials>,\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 (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\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 result = await refreshOAuthApiKey(options.providerId, { [options.providerId]: current } as Record<string, OAuthCredentials>)\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 refreshLocks.delete(key)\n }\n })()\n refreshLocks.set(key, task)\n return task\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA0DA,eAAe,wBACb,YACA,OACA,cAC2B;CAC3B,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,kBAAkB,WAAW,uBAAuB;CACtE,MAAM,EAAE,MAAM,OAAO,GAAG,gBACpB,MAAM,MAAM,QAAQ;EAAE,MAAM;EAAS,QAAQ;EAAI,SAAS;EAAc,SAAS;CAAE,CAAC;CACxF,OAAO;AACT;;;;;;AAOA,eAAsB,sBAAsB,cAAiD;CAC3F,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,OAAO,wBAAwB,aAAa,kBAAkB,CAAC,CAAC,KAAK,OAAO,YAAY;AAC1F;;;;;;;AAQA,eAAsB,wBAAwB,cAAiD;CAC7F,MAAM,EAAE,wBAAwB,MAAM,OAAO;CAC7C,OAAO,wBAAwB,gBAAgB,oBAAoB,CAAC,CAAC,KAAK,OAAO,YAAY;AAC/F;;;;;;;;;AAUA,SAAS,gBACP,IACA,MACA,cACwB;CACxB,OAAO;EACL;EACA;EACA,OAAO,YAAY;GACjB,MAAM,IAAI,MAAM,mBAAmB,GAAG,+DAA+D;EACvG;EACA,eAAc,gBAAe,aAAa,YAAY,OAAO;EAC7D,YAAW,gBAAe,YAAY;CACxC;AACF;;;;;;;;;;;;;;;AAgBA,MAAM,gBAAgB,OAAO,IAAI,gCAAgC;AAEjE,SAAS,wBAA6D;CACpE,MAAM,QAAQ;CACd,MAAM,mBAAmB,IAAI,IAC3B,CACE,gBAAgB,aAAa,8BAA8B,qBAAqB,GAChF,gBAAgB,gBAAgB,6BAA6B,uBAAuB,CACtF,C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AC7H,SACO,KAAK;GACV,MAAM,IAAI,MAAM,QAAQ,aAAa,aAAa,GAAG,CAAC,CAAC;EACzD;EACA,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,QAAQ,aAAa,QAAQ,YAAY,CAAC;EAE5D,IAAI,OAAO,mBAAmB,SAAS;GAOrC,MAAM,YAAY;IAAE,GAAG;IAAS,GAAG,OAAO;GAAe;GACzD,IAAI,WAAW,UAAU,kBAAkB,oBAAoB;IAC7D,eAAe,QAAQ,cAAc;IACrC,mBAAmB,cAAc;GACnC;GAEA,MAAM,WAAW,iBAAiB;IAChC,UAAU,QAAQ;IAClB,YAAY,QAAQ;IACpB;IACA,qBAAqB,EAAE,GAAG,QAAQ;IAClC,aAAa,EAAE,GAAG,UAAU;GAC9B,CAAC;EACH;EAEA,OAAO,OAAO;CAChB;AACF;;;;;;AAOA,eAAe,gBAAgB,KAAa,IAA4C;CACtF,MAAM,WAAW,aAAa,IAAI,GAAG;CACrC,IAAI,UACF,OAAO;CAET,MAAM,QAAQ,YAAY;EACxB,IAAI;GACF,OAAO,MAAM,GAAG;EAClB,UACQ;GACN,aAAa,OAAO,GAAG;EACzB;CACF,EAAA,CAAG;CACH,aAAa,IAAI,KAAK,IAAI;CAC1B,OAAO;AACT"}
@@ -1,7 +1,7 @@
1
1
  import { a as rewriteMessagesToWire, n as buildAliasMaps, o as toCanonicalName, r as buildSanitizedWireAliases, s as toWireName } from "./aliasing-lVFbm81n.js";
2
2
  import { i as documentBlockMarker, n as assertResolvedMediaBlock } from "./types-BIarq1qE.js";
3
3
  import { n as estimateTokens } from "./utils-ngQzYzZD.js";
4
- import { c as classifyErrorPrelude, d as isRetryableHttpStatus, f as matchesContextExceeded, l as errorMessage, p as matchesToolPairingError } from "./errors-DJUxZg9b.js";
4
+ import { c as classifyErrorPrelude, d as isRetryableHttpStatus, f as matchesContextExceeded, p as matchesToolPairingError } from "./errors-DJUxZg9b.js";
5
5
  import { t as audioFormatFromMediaType } from "./media-sniff-Bn76JxAu.js";
6
6
  import { renderSystemForWire, splitSystemPrompt } from "./prompt.js";
7
7
  //#region src/prompt.ts
@@ -269,19 +269,6 @@ async function fillEstimatedCost(usage, provider, multiplier) {
269
269
  };
270
270
  }
271
271
  //#endregion
272
- //#region src/providers/openai-tool-names.ts
273
- function createOpenAIToolNameBoundary(messages, currentToolNames = []) {
274
- const names = new Set(currentToolNames);
275
- for (const message of messages) for (const block of message.content) if (block.type === "tool_call") names.add(block.name);
276
- const maps = buildAliasMaps(buildSanitizedWireAliases(names, void 0), names);
277
- return {
278
- messages: rewriteMessagesToWire([...messages], maps),
279
- toWire: (name) => toWireName(name, maps),
280
- fromWire: (name) => toCanonicalName(name, maps),
281
- changed: maps.aliasByCanonical.size > 0
282
- };
283
- }
284
- //#endregion
285
272
  //#region src/providers/schema-sanitize.ts
286
273
  /**
287
274
  * Provider tool-name constraint. The charset (`[A-Za-z0-9_-]`) is universal
@@ -633,6 +620,114 @@ function defaultWarn(line) {
633
620
  console.warn(`[zidane:schema] ${line}`);
634
621
  }
635
622
  //#endregion
623
+ //#region src/providers/tool-args.ts
624
+ /**
625
+ * Parse a tool-call arguments payload, repairing truncation and trailing
626
+ * garbage when strict parsing fails. Returns `undefined` when no bounded
627
+ * repair produces valid JSON.
628
+ */
629
+ function parseToolCallArguments(raw) {
630
+ try {
631
+ const parsed = JSON.parse(raw);
632
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return {
633
+ input: parsed,
634
+ repaired: false
635
+ };
636
+ } catch {}
637
+ for (const { candidate, fabricated } of repairCandidates(raw)) try {
638
+ const parsed = JSON.parse(candidate);
639
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
640
+ if (fabricated && Object.keys(parsed).length === 0) continue;
641
+ return {
642
+ input: parsed,
643
+ repaired: true
644
+ };
645
+ }
646
+ } catch {}
647
+ }
648
+ /**
649
+ * Bounded, ordered repair candidates:
650
+ * 1. longest complete top-level object prefix (trailing-garbage case)
651
+ * 2. payload + structural closers (truncated mid-string / mid-object)
652
+ * 3. payload minus a dangling partial token, + closers (truncated mid-token)
653
+ *
654
+ * `fabricated` marks candidates whose closure was invented here (2 and 3) —
655
+ * the caller holds those to a stricter acceptance bar than a prefix that was
656
+ * complete in the payload itself.
657
+ */
658
+ function* repairCandidates(raw) {
659
+ const text = raw.trim();
660
+ if (!text.startsWith("{")) return;
661
+ const scan = scanJson(text);
662
+ if (scan.completeAt !== void 0) yield {
663
+ candidate: text.slice(0, scan.completeAt),
664
+ fabricated: false
665
+ };
666
+ yield {
667
+ candidate: close(text, scan),
668
+ fabricated: true
669
+ };
670
+ let trimmed = text;
671
+ for (let step = 0; step < 6; step++) {
672
+ const next = (scanJson(trimmed).inString ? trimmed.replace(/"(?:[^"\\]|\\.)*$/, "") : trimmed.replace(/(?:"(?:[^"\\]|\\.)*"|[^\s{}[\],:"]+|[,:])\s*$/, "")).trimEnd();
673
+ if (next === trimmed || !next.startsWith("{")) break;
674
+ trimmed = next;
675
+ yield {
676
+ candidate: close(trimmed, scanJson(trimmed)),
677
+ fabricated: true
678
+ };
679
+ }
680
+ }
681
+ function scanJson(text) {
682
+ const stack = [];
683
+ let inString = false;
684
+ let escaped = false;
685
+ let completeAt;
686
+ for (let i = 0; i < text.length; i++) {
687
+ const ch = text[i];
688
+ if (inString) {
689
+ if (escaped) escaped = false;
690
+ else if (ch === "\\") escaped = true;
691
+ else if (ch === "\"") inString = false;
692
+ continue;
693
+ }
694
+ if (ch === "\"") inString = true;
695
+ else if (ch === "{") stack.push("}");
696
+ else if (ch === "[") stack.push("]");
697
+ else if (ch === "}" || ch === "]") {
698
+ stack.pop();
699
+ if (stack.length === 0 && completeAt === void 0) completeAt = i + 1;
700
+ }
701
+ }
702
+ return {
703
+ stack,
704
+ inString,
705
+ completeAt
706
+ };
707
+ }
708
+ function close(text, scan) {
709
+ let out = text;
710
+ if (scan.inString) {
711
+ if (/(?:^|[^\\])(?:\\\\)*\\$/.test(out)) out = out.slice(0, -1);
712
+ out += "\"";
713
+ }
714
+ for (let i = scan.stack.length - 1; i >= 0; i--) out += scan.stack[i];
715
+ return out;
716
+ }
717
+ //#endregion
718
+ //#region src/providers/tool-name-boundary.ts
719
+ function createToolNameBoundary(messages, currentToolNames = []) {
720
+ const names = new Set(currentToolNames);
721
+ for (const message of messages) for (const block of message.content) if (block.type === "tool_call") names.add(block.name);
722
+ const maps = buildAliasMaps(buildSanitizedWireAliases(names, void 0), names);
723
+ return {
724
+ messages: rewriteMessagesToWire([...messages], maps),
725
+ toWire: (name) => toWireName(name, maps),
726
+ fromWire: (name) => toCanonicalName(name, maps),
727
+ changed: maps.aliasByCanonical.size > 0
728
+ };
729
+ }
730
+ //#endregion
636
731
  //#region src/providers/openai-compat.ts
637
732
  const TOOL_RESULTS_TAG = "__zidane_tool_results__";
638
733
  const ASSISTANT_TOOL_CALLS_TAG = "__zidane_assistant_tc__";
@@ -684,6 +779,7 @@ async function consumeSSE(response, callbacks, signal) {
684
779
  let text = "";
685
780
  let thinking = "";
686
781
  let finishReason = "stop";
782
+ let sawTerminator = false;
687
783
  let usage = {
688
784
  input: 0,
689
785
  output: 0
@@ -704,7 +800,10 @@ async function consumeSSE(response, callbacks, signal) {
704
800
  for (const line of lines) {
705
801
  if (!line.startsWith("data:")) continue;
706
802
  const data = line.slice(5).trim();
707
- if (data === "[DONE]") continue;
803
+ if (data === "[DONE]") {
804
+ sawTerminator = true;
805
+ continue;
806
+ }
708
807
  let chunk;
709
808
  try {
710
809
  chunk = JSON.parse(data);
@@ -716,7 +815,10 @@ async function consumeSSE(response, callbacks, signal) {
716
815
  const choice = chunk.choices?.[0];
717
816
  if (!choice) continue;
718
817
  const fr = choice.finish_reason;
719
- if (fr) finishReason = fr;
818
+ if (fr) {
819
+ finishReason = fr;
820
+ sawTerminator = true;
821
+ }
720
822
  const delta = choice.delta;
721
823
  const reasoningDeltaArr = delta?.reasoning_details;
722
824
  if (reasoningDeltaArr && reasoningDeltaArr.length > 0) {
@@ -783,6 +885,7 @@ async function consumeSSE(response, callbacks, signal) {
783
885
  } finally {
784
886
  reader.releaseLock();
785
887
  }
888
+ const clipForError = (args) => args.length > 200 ? `${args.slice(0, 200)}… [${args.length} chars]` : args;
786
889
  const toolCalls = [];
787
890
  for (const tc of tcMap.values()) {
788
891
  if (!tc.args) {
@@ -793,15 +896,14 @@ async function consumeSSE(response, callbacks, signal) {
793
896
  });
794
897
  continue;
795
898
  }
796
- try {
797
- toolCalls.push({
798
- id: tc.id,
799
- name: tc.name,
800
- input: JSON.parse(tc.args)
801
- });
802
- } catch (err) {
803
- throw new OpenAICompatStreamError(`Tool call "${tc.name}" (${tc.id}) arguments were truncated or malformed: ${errorMessage(err)}`);
804
- }
899
+ const parsed = parseToolCallArguments(tc.args);
900
+ if (!parsed) throw new OpenAICompatStreamError(`Tool call "${tc.name}" (${tc.id}) arguments were truncated or malformed beyond repair: ${clipForError(tc.args)}`);
901
+ if (parsed.repaired && !sawTerminator) throw new OpenAICompatStreamError(`Tool call "${tc.name}" (${tc.id}) arguments were cut off by a truncated stream: ${clipForError(tc.args)}`);
902
+ toolCalls.push({
903
+ id: tc.id,
904
+ name: tc.name,
905
+ input: parsed.input
906
+ });
805
907
  }
806
908
  const reasoningDetails = Array.from(reasoningMap.entries()).sort(([a], [b]) => a - b).map(([, item]) => item);
807
909
  return {
@@ -1580,7 +1682,7 @@ function openaiCompat(params) {
1580
1682
  async stream(options, callbacks) {
1581
1683
  const modelId = options.model || defaultModel;
1582
1684
  const inputTools = options.tools ?? [];
1583
- const nameBoundary = createOpenAIToolNameBoundary(options.messages, inputTools.map((tool) => tool.function.name));
1685
+ const nameBoundary = createToolNameBoundary(options.messages, inputTools.map((tool) => tool.function.name));
1584
1686
  const messages = toOAIMessages(options.system, nameBoundary.messages, {
1585
1687
  imageInToolResult: capabilities.imageInToolResult === true,
1586
1688
  audio: capabilities.audio === true,
@@ -1695,6 +1797,6 @@ function openaiCompat(params) {
1695
1797
  };
1696
1798
  }
1697
1799
  //#endregion
1698
- export { buildPromptMessage as C, unsupportedMediaError as E, fillEstimatedCost as S, defaultPromptMessage as T, userMessage as _, applyOAICacheBreakpoints as a, createOpenAIToolNameBoundary as b, buildAssistantContent as c, formatTools as d, mapOAIFinishReason as f, toolResultsMessage as g, toOAIMessages as h, TOOL_RESULTS_TAG as i, 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, sanitizeToolSchema as v, canonicalizePrompt as w, estimateRebilledCostUsd as x, sanitizeToolSpecs as y };
1800
+ export { buildPromptMessage as C, unsupportedMediaError as E, fillEstimatedCost as S, defaultPromptMessage as T, 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, 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, canonicalizePrompt as w, estimateRebilledCostUsd as x, sanitizeToolSchema as y };
1699
1801
 
1700
- //# sourceMappingURL=openai-compat-OI68avOl.js.map
1802
+ //# sourceMappingURL=openai-compat-Ba4nw7ip.js.map