zidane 7.0.19 → 7.0.22

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 (95) hide show
  1. package/dist/{acp-BgNj1-gv.js → acp-BhbXWwj_.js} +2 -2
  2. package/dist/{acp-BgNj1-gv.js.map → acp-BhbXWwj_.js.map} +1 -1
  3. package/dist/acp-cli.js +4 -4
  4. package/dist/acp.d.ts +1 -1
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-Djzx-1kD.js → agent-LC2c1ue-.js} +18 -5
  7. package/dist/{agent-Djzx-1kD.js.map → agent-LC2c1ue-.js.map} +1 -1
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/{anthropic-DATE-m9f.js → anthropic-BSbDiW0J.js} +34 -4
  11. package/dist/anthropic-BSbDiW0J.js.map +1 -0
  12. package/dist/{approvals-Jztqzqjk.js → approvals-BnDsgTtD.js} +4 -4
  13. package/dist/{approvals-Jztqzqjk.js.map → approvals-BnDsgTtD.js.map} +1 -1
  14. package/dist/{auth-DhkLW1Wu.js → auth-Nq-tSMb9.js} +53 -35
  15. package/dist/{auth-DhkLW1Wu.js.map → auth-Nq-tSMb9.js.map} +1 -1
  16. package/dist/chat/pure.d.ts +3 -3
  17. package/dist/chat/pure.js +2 -2
  18. package/dist/chat.d.ts +5 -5
  19. package/dist/chat.js +5 -5
  20. package/dist/{context-segments-CJCtJ9sU.js → context-segments-BrEsRhA0.js} +11 -3
  21. package/dist/context-segments-BrEsRhA0.js.map +1 -0
  22. package/dist/contexts/daytona.d.ts +1 -1
  23. package/dist/contexts/e2b.d.ts +1 -1
  24. package/dist/daemon-cli.js +1 -1
  25. package/dist/eval.d.ts +1 -1
  26. package/dist/extensions.d.ts +1 -1
  27. package/dist/extensions.js +1 -1
  28. package/dist/headless.d.ts +1 -1
  29. package/dist/headless.js +1 -1
  30. package/dist/{index-CfEJ5Vf9.d.ts → index-C4mY0oKE.d.ts} +18 -21
  31. package/dist/index-C4mY0oKE.d.ts.map +1 -0
  32. package/dist/{index-498gAVpL.d.ts → index-D2JCY11Z.d.ts} +5 -5
  33. package/dist/index-D2JCY11Z.d.ts.map +1 -0
  34. package/dist/index.d.ts +1 -1
  35. package/dist/index.js +4 -4
  36. package/dist/{ipc-B4p0P2tz.js → ipc-Oro3uyMP.js} +2 -2
  37. package/dist/{ipc-B4p0P2tz.js.map → ipc-Oro3uyMP.js.map} +1 -1
  38. package/dist/ipc.d.ts +15 -5
  39. package/dist/ipc.d.ts.map +1 -1
  40. package/dist/ipc.js +3 -3
  41. package/dist/mcp.d.ts +1 -1
  42. package/dist/{oauth-D-LZ4ic-.js → oauth-CmtlmCzi.js} +142 -210
  43. package/dist/oauth-CmtlmCzi.js.map +1 -0
  44. package/dist/output/stream-json.d.ts +1 -1
  45. package/dist/output/terminal.d.ts +1 -1
  46. package/dist/plugins.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/baseten.d.ts +1 -1
  53. package/dist/providers/cerebras.d.ts +1 -1
  54. package/dist/providers/local.d.ts +1 -1
  55. package/dist/providers/openai-compat.d.ts +1 -1
  56. package/dist/providers/openai.d.ts +1 -1
  57. package/dist/providers/openai.js +1 -1
  58. package/dist/providers/openrouter.d.ts +1 -1
  59. package/dist/providers/xai.d.ts +1 -1
  60. package/dist/providers/xai.js +1 -1
  61. package/dist/{providers-Bjdvmpfu.js → providers-ZucqgwU7.js} +2 -2
  62. package/dist/{providers-Bjdvmpfu.js.map → providers-ZucqgwU7.js.map} +1 -1
  63. package/dist/providers.d.ts +1 -1
  64. package/dist/providers.js +3 -3
  65. package/dist/restate.d.ts +1 -1
  66. package/dist/restate.js +1 -1
  67. package/dist/{server-Cccx5jES.js → server-HZdjqDpS.js} +67 -10
  68. package/dist/server-HZdjqDpS.js.map +1 -0
  69. package/dist/session/sqlite.d.ts +1 -1
  70. package/dist/session.d.ts +1 -1
  71. package/dist/skills.d.ts +1 -1
  72. package/dist/{tool-formatters-D1rdZOe3.d.ts → tool-formatters-GZHxP824.d.ts} +2 -2
  73. package/dist/{tool-formatters-D1rdZOe3.d.ts.map → tool-formatters-GZHxP824.d.ts.map} +1 -1
  74. package/dist/tools/fetch-url.d.ts +1 -1
  75. package/dist/tools/web-search.d.ts +1 -1
  76. package/dist/tools.d.ts +1 -1
  77. package/dist/tools.js +1 -1
  78. package/dist/{transcript-anchors-pHga6mOC.d.ts → transcript-anchors-CY50AXdF.d.ts} +2 -2
  79. package/dist/{transcript-anchors-pHga6mOC.d.ts.map → transcript-anchors-CY50AXdF.d.ts.map} +1 -1
  80. package/dist/tui.d.ts +3 -3
  81. package/dist/tui.js +6 -6
  82. package/dist/{turn-operations-Dt5L8smX.js → turn-operations-BgqpLlOG.js} +2 -2
  83. package/dist/{turn-operations-Dt5L8smX.js.map → turn-operations-BgqpLlOG.js.map} +1 -1
  84. package/dist/{turn-operations-Dzo-8TKC.d.ts → turn-operations-CAmNETlu.d.ts} +3 -3
  85. package/dist/{turn-operations-Dzo-8TKC.d.ts.map → turn-operations-CAmNETlu.d.ts.map} +1 -1
  86. package/dist/types.d.ts +1 -1
  87. package/docs/CHAT.md +8 -0
  88. package/docs/IPC.md +10 -0
  89. package/package.json +1 -1
  90. package/dist/anthropic-DATE-m9f.js.map +0 -1
  91. package/dist/context-segments-CJCtJ9sU.js.map +0 -1
  92. package/dist/index-498gAVpL.d.ts.map +0 -1
  93. package/dist/index-CfEJ5Vf9.d.ts.map +0 -1
  94. package/dist/oauth-D-LZ4ic-.js.map +0 -1
  95. package/dist/server-Cccx5jES.js.map +0 -1
@@ -1,9 +1,11 @@
1
1
  import { u as errorMessage } from "./errors-DKiMrOKq.js";
2
2
  import { t as writeFileAtomic } from "./atomic-write-B7zr1ddF.js";
3
- import { resolve } from "node:path";
3
+ import { dirname, resolve } from "node:path";
4
4
  import { Buffer } from "node:buffer";
5
- import { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
6
6
  import { homedir } from "node:os";
7
+ import { randomUUID } from "node:crypto";
8
+ import { isDeepStrictEqual } from "node:util";
7
9
  //#region src/providers/oauth-registry.ts
8
10
  /**
9
11
  * Run a canonical pi-ai `OAuthAuth.refresh` from a bare refresh token.
@@ -245,15 +247,17 @@ function credentialsFilePath() {
245
247
  * Ignored on Windows.
246
248
  */
247
249
  const CREDENTIALS_FILE_MODE = 384;
248
- /**
249
- * In-process mutex table keyed by provider id. Concurrent `resolveOAuthApiKey`
250
- * calls for the same provider (typical when a host fans out multiple streams
251
- * at once) coalesce onto a single refresh. Without this, N concurrent calls
252
- * each hit `getOAuthApiKey`, producing N writes to `.credentials.json` with
253
- * last-write-wins semantics — and, in worst-case interleaving, a corrupted
254
- * file.
255
- */
256
250
  const refreshLocks = /* @__PURE__ */ new Map();
251
+ const storeIds = /* @__PURE__ */ new WeakMap();
252
+ let nextStoreId = 0;
253
+ function identity(value) {
254
+ let id = storeIds.get(value);
255
+ if (id === void 0) {
256
+ id = ++nextStoreId;
257
+ storeIds.set(value, id);
258
+ }
259
+ return id;
260
+ }
257
261
  /**
258
262
  * Register a custom OAuth flow with the local registry (`./oauth-registry`)
259
263
  * so lazy refresh through {@link resolveOAuthApiKey} can resolve `providerId`.
@@ -316,7 +320,9 @@ function extractRuntimeCredentials(params) {
316
320
  * reach providers via env vars set at TUI launch (see `applyApiKeyEnv`).
317
321
  */
318
322
  function readOAuthCredentials() {
319
- const path = credentialsFilePath();
323
+ return readOAuthCredentialsAt(credentialsFilePath());
324
+ }
325
+ function readOAuthCredentialsAt(path) {
320
326
  if (!existsSync(path)) return {};
321
327
  try {
322
328
  const raw = readFileSync(path, "utf-8");
@@ -339,139 +345,77 @@ function readOAuthCredentials() {
339
345
  return {};
340
346
  }
341
347
  }
342
- /**
343
- * Cross-process lockfile parameters for the credentials read-merge-write.
344
- * A holder normally completes in well under a millisecond (read + JSON merge
345
- * + atomic write of a tiny file), so the stale threshold is generous and the
346
- * total wait short — on timeout we proceed without the lock rather than fail
347
- * the refresh (degrades to the historic last-write-wins behavior).
348
- */
349
- const CREDENTIALS_LOCK_STALE_MS = 5e3;
350
- const CREDENTIALS_LOCK_RETRY_MS = 20;
351
- const CREDENTIALS_LOCK_MAX_WAIT_MS = 2e3;
352
- /** Synchronous sleep without spinning — works on Bun and Node main threads. */
353
- function sleepSync(ms) {
354
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
355
- }
356
- /**
357
- * Best-effort exclusive lock via `O_EXCL` create of `<file>.lock`. Returns
358
- * `true` when the lock was acquired (caller must release), `false` on
359
- * timeout (caller proceeds unlocked — see threshold rationale above). Locks
360
- * older than {@link CREDENTIALS_LOCK_STALE_MS} are treated as leftovers from
361
- * a crashed process and broken.
362
- */
363
- function acquireCredentialsLock(lockPath) {
364
- const deadline = Date.now() + CREDENTIALS_LOCK_MAX_WAIT_MS;
365
- while (true) try {
366
- writeFileSync(lockPath, String(process.pid), {
348
+ /** Never steal a lock based on age: a suspended holder may still own it. */
349
+ function tryAcquireLock(lockPath) {
350
+ const owner = `${process.pid}:${randomUUID()}`;
351
+ try {
352
+ writeFileSync(lockPath, owner, {
367
353
  flag: "wx",
368
354
  mode: CREDENTIALS_FILE_MODE
369
355
  });
370
- return true;
371
356
  } catch (err) {
372
- if (err.code !== "EEXIST") return false;
373
- try {
374
- if (Date.now() - statSync(lockPath).mtimeMs > CREDENTIALS_LOCK_STALE_MS) {
375
- unlinkSync(lockPath);
376
- continue;
377
- }
378
- } catch {}
379
- if (Date.now() >= deadline) return false;
380
- sleepSync(CREDENTIALS_LOCK_RETRY_MS);
357
+ if (err.code === "EEXIST") return void 0;
358
+ throw err;
381
359
  }
360
+ return () => {
361
+ try {
362
+ if (readFileSync(lockPath, "utf8") === owner) unlinkSync(lockPath);
363
+ } catch (err) {
364
+ if (err.code !== "ENOENT") throw err;
365
+ }
366
+ };
382
367
  }
383
- function releaseCredentialsLock(lockPath) {
368
+ /** Shared by refresh persistence and interactive credential mutations. */
369
+ function withCredentialsLock(path, fn) {
370
+ mkdirSync(dirname(path), {
371
+ recursive: true,
372
+ mode: 448
373
+ });
374
+ const deadline = Date.now() + 2e3;
375
+ let release = tryAcquireLock(`${path}.lock`);
376
+ while (!release) {
377
+ if (Date.now() >= deadline) throw new Error("Timed out waiting for credentials lock");
378
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
379
+ release = tryAcquireLock(`${path}.lock`);
380
+ }
384
381
  try {
385
- unlinkSync(lockPath);
386
- } catch {}
387
- }
388
- /**
389
- * Cross-process lock parameters for the REFRESH critical section (read →
390
- * check expiry → refresh → persist), held per provider around file-backed
391
- * resolves in {@link resolveOAuthApiKey}.
392
- *
393
- * This is a different beast from the write lock above: the holder performs a
394
- * network call, so it can legitimately hold the lock for seconds. Hence its
395
- * own generous thresholds — and async waiting, because blocking the event
396
- * loop for a peer's refresh round-trip is not acceptable. The stakes are
397
- * higher too: providers with single-use rotating refresh tokens (Bolt) treat
398
- * a replayed token as theft and revoke the WHOLE grant, so two processes
399
- * refreshing the same provider concurrently don't just race a write — they
400
- * self-revoke. A process that loses the race re-reads under the lock, finds
401
- * the winner's fresh token, and skips its own refresh entirely.
402
- *
403
- * On timeout we proceed without the lock (degrades to the pre-lock racy
404
- * behavior) rather than fail a resolve that would probably have succeeded.
405
- */
406
- const REFRESH_LOCK_STALE_MS = 6e4;
407
- const REFRESH_LOCK_RETRY_MS = 50;
408
- const REFRESH_LOCK_MAX_WAIT_MS = 3e4;
409
- function refreshLockPath(providerId) {
410
- return `${credentialsFilePath()}.refresh-${providerId.replace(/[^\w.-]/g, "_")}.lock`;
382
+ return fn();
383
+ } finally {
384
+ release();
385
+ }
411
386
  }
412
- /** Async sibling of {@link acquireCredentialsLock} with refresh-scale thresholds. */
413
387
  async function acquireRefreshLock(lockPath) {
414
- const deadline = Date.now() + REFRESH_LOCK_MAX_WAIT_MS;
415
- while (true) try {
416
- writeFileSync(lockPath, String(process.pid), {
417
- flag: "wx",
418
- mode: CREDENTIALS_FILE_MODE
419
- });
420
- return true;
421
- } catch (err) {
422
- if (err.code !== "EEXIST") return false;
423
- try {
424
- if (Date.now() - statSync(lockPath).mtimeMs > REFRESH_LOCK_STALE_MS) {
425
- unlinkSync(lockPath);
426
- continue;
427
- }
428
- } catch {}
429
- if (Date.now() >= deadline) return false;
430
- await new Promise((resolve) => setTimeout(resolve, REFRESH_LOCK_RETRY_MS));
388
+ mkdirSync(dirname(lockPath), {
389
+ recursive: true,
390
+ mode: 448
391
+ });
392
+ const deadline = Date.now() + 3e4;
393
+ while (true) {
394
+ const release = tryAcquireLock(lockPath);
395
+ if (release) return release;
396
+ if (Date.now() >= deadline) throw new Error("Timed out waiting for OAuth refresh lock");
397
+ await new Promise((resolve) => setTimeout(resolve, 50));
431
398
  }
432
399
  }
433
- /**
434
- * Atomically write `.credentials.json` with mode 0o600.
435
- *
436
- * Writes to a sibling temp file first, then renames. `rename(2)` is atomic on
437
- * the same filesystem, so readers either see the old file or the new one —
438
- * never a half-written one. This matters when a host has multiple processes
439
- * pointed at the same creds file.
440
- *
441
- * Merges the incoming OAuth entries on top of the raw file contents so that
442
- * entries this layer doesn't manage (e.g. `kind: 'apikey'` from the TUI
443
- * wizard) survive an OAuth refresh cycle. Without this merge,
444
- * `readOAuthCredentials` filters those entries out, and a naive overwrite
445
- * would delete them.
446
- *
447
- * The read-merge-write runs under a best-effort cross-process lockfile
448
- * (`<file>.lock`) so two processes refreshing different providers at the
449
- * same moment can't drop each other's rotated refresh tokens. On lock
450
- * timeout the write proceeds unlocked (last-write-wins, the pre-lock
451
- * behavior) rather than failing the refresh.
452
- */
400
+ function readRawCredentials(path) {
401
+ try {
402
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
403
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
404
+ } catch {}
405
+ return {};
406
+ }
407
+ function writeCredentialPatch(path, credentials) {
408
+ const merged = {
409
+ ...readRawCredentials(path),
410
+ ...credentials
411
+ };
412
+ for (const [key, value] of Object.entries(merged)) if (value === void 0) delete merged[key];
413
+ writeFileAtomic(path, JSON.stringify(merged, null, 2), { mode: CREDENTIALS_FILE_MODE });
414
+ }
415
+ /** Incoming entries are a provider-local patch, not a read-time snapshot. */
453
416
  function writeOAuthCredentials(credentials) {
454
417
  const path = credentialsFilePath();
455
- const lockPath = `${path}.lock`;
456
- const locked = acquireCredentialsLock(lockPath);
457
- try {
458
- let existing = {};
459
- try {
460
- if (existsSync(path)) {
461
- const raw = readFileSync(path, "utf-8");
462
- const parsed = JSON.parse(raw);
463
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) existing = parsed;
464
- }
465
- } catch {}
466
- const merged = {
467
- ...existing,
468
- ...credentials
469
- };
470
- for (const [key, value] of Object.entries(merged)) if (value === void 0) delete merged[key];
471
- writeFileAtomic(path, JSON.stringify(merged, null, 2), { mode: CREDENTIALS_FILE_MODE });
472
- } finally {
473
- if (locked) releaseCredentialsLock(lockPath);
474
- }
418
+ withCredentialsLock(path, () => writeCredentialPatch(path, credentials));
475
419
  }
476
420
  function credentialsFromParams(params, extraKeys = []) {
477
421
  if (typeof params?.access !== "string" || typeof params.refresh !== "string" || typeof params.expires !== "number") return void 0;
@@ -486,95 +430,83 @@ function credentialsFromParams(params, extraKeys = []) {
486
430
  async function resolveOAuthApiKey(options, callbacks) {
487
431
  if (typeof options.params?.apiKey === "string") return options.params.apiKey;
488
432
  const paramsCredentials = credentialsFromParams(options.params, options.extraCredentialKeys);
489
- if (paramsCredentials) return await withRefreshLock(`params:${options.providerId}`, () => resolveCredentialSource("params", paramsCredentials));
490
- if (typeof options.params?.access === "string") return options.params.access;
491
- const readCredentials = options.readCredentials ?? readOAuthCredentials;
492
- const writeCredentials = options.writeCredentials ?? writeOAuthCredentials;
433
+ if (!paramsCredentials && typeof options.params?.access === "string") return options.params.access;
434
+ const path = resolve(credentialsFilePath());
493
435
  const usingDefaultStore = !options.readCredentials && !options.writeCredentials;
436
+ const read = options.readCredentials ?? (() => readOAuthCredentialsAt(path));
437
+ const write = options.writeCredentials ?? ((patch) => withCredentialsLock(path, () => writeCredentialPatch(path, patch)));
494
438
  const envValue = options.envKey ? process.env[options.envKey] : void 0;
495
- if (envValue) {
496
- if (!isOAuthAccessToken(envValue)) return envValue;
497
- if (!readCredentials()[options.providerId]) return envValue;
498
- return await withRefreshLock(`file:${options.providerId}`, () => withCrossProcessRefreshLock(async () => {
499
- const allCredentials = readCredentials();
500
- const stored = allCredentials[options.providerId];
501
- if (!stored) return envValue;
502
- return await resolveCredentialSource("file", stored, allCredentials, writeCredentials);
503
- }));
439
+ if (!paramsCredentials && envValue && (!isOAuthAccessToken(envValue) || !read()[options.providerId])) return envValue;
440
+ const source = paramsCredentials ? "params" : "file";
441
+ const initial = paramsCredentials ?? read()[options.providerId];
442
+ const store = usingDefaultStore ? path : [identity(options.readCredentials ?? readOAuthCredentials), identity(options.writeCredentials ?? writeOAuthCredentials)];
443
+ const key = JSON.stringify([
444
+ source,
445
+ options.providerId,
446
+ source === "file" ? store : null,
447
+ initial,
448
+ options.forceRefresh === true,
449
+ options.rejectedAccess,
450
+ identity(options.getOAuthApiKey ?? getOAuthApiKey)
451
+ ]);
452
+ let task = refreshLocks.get(key);
453
+ if (!task) {
454
+ task = run();
455
+ refreshLocks.set(key, task);
456
+ task.finally(() => refreshLocks.delete(key)).catch(() => {});
504
457
  }
505
- return await withRefreshLock(`file:${options.providerId}`, () => withCrossProcessRefreshLock(async () => {
506
- const allCredentials = readCredentials();
507
- const storedCredentials = allCredentials[options.providerId];
508
- if (!storedCredentials) throw new Error(options.missingError);
509
- return await resolveCredentialSource("file", storedCredentials, allCredentials, writeCredentials);
510
- }));
511
- /**
512
- * Hold the per-provider cross-process lockfile across the WHOLE file-backed
513
- * critical section, not just the persist. Guarding only the write (as
514
- * `writeOAuthCredentials` does) still lets two processes both spend a
515
- * single-use rotating refresh token — which self-revokes providers with
516
- * replay-detecting rotation. See the {@link REFRESH_LOCK_STALE_MS} note.
517
- */
518
- async function withCrossProcessRefreshLock(fn) {
519
- if (!usingDefaultStore) return fn();
520
- const lockPath = refreshLockPath(options.providerId);
521
- const locked = await acquireRefreshLock(lockPath);
522
- try {
523
- return await fn();
524
- } finally {
525
- if (locked) releaseCredentialsLock(lockPath);
526
- }
527
- }
528
- async function resolveCredentialSource(source, current, allCredentials, persistCredentials) {
529
- let result;
458
+ const result = await task;
459
+ if (result.event) await callbacks?.onOAuthRefresh?.({
460
+ ...structuredClone(result.event),
461
+ provider: options.provider
462
+ });
463
+ return result.apiKey;
464
+ async function run() {
465
+ const release = source === "file" && usingDefaultStore ? await acquireRefreshLock(`${path}.refresh-${encodeURIComponent(options.providerId)}.lock`) : void 0;
530
466
  try {
531
- const refreshOAuthApiKey = options.getOAuthApiKey ?? getOAuthApiKey;
532
- const stillRejectedGeneration = options.rejectedAccess === void 0 || current.access === options.rejectedAccess;
533
- const force = options.forceRefresh === true && stillRejectedGeneration;
534
- result = await refreshOAuthApiKey(options.providerId, { [options.providerId]: current }, { force });
535
- } catch (err) {
536
- throw new Error(options.refreshError(errorMessage(err)));
537
- }
538
- if (!result) throw new Error(options.refreshError(options.missingError));
539
- if (result.newCredentials !== current) {
467
+ const current = paramsCredentials ?? read()[options.providerId];
468
+ if (!current) throw new Error(options.missingError);
469
+ const generation = structuredClone(current);
470
+ let result;
471
+ try {
472
+ const stillRejected = options.rejectedAccess === void 0 || current.access === options.rejectedAccess;
473
+ result = await (options.getOAuthApiKey ?? getOAuthApiKey)(options.providerId, { [options.providerId]: current }, { force: options.forceRefresh === true && stillRejected });
474
+ } catch (err) {
475
+ throw new Error(options.refreshError(errorMessage(err)), { cause: err });
476
+ }
477
+ if (!result) throw new Error(options.refreshError(options.missingError));
540
478
  const refreshed = {
541
- ...current,
479
+ ...generation,
542
480
  ...result.newCredentials
543
481
  };
544
- if (source === "file" && allCredentials && persistCredentials) {
545
- allCredentials[options.providerId] = refreshed;
546
- persistCredentials(allCredentials);
482
+ if (source === "file") {
483
+ const persist = () => {
484
+ if (!isDeepStrictEqual(read()[options.providerId], generation)) throw new Error("OAuth credentials changed during refresh; retry with current credentials");
485
+ if (result.newCredentials !== current) {
486
+ const patch = { [options.providerId]: refreshed };
487
+ if (usingDefaultStore) writeCredentialPatch(path, patch);
488
+ else write(patch);
489
+ }
490
+ };
491
+ if (usingDefaultStore) withCredentialsLock(path, persist);
492
+ else persist();
547
493
  }
548
- await callbacks?.onOAuthRefresh?.({
549
- provider: options.provider,
550
- providerId: options.providerId,
551
- source,
552
- previousCredentials: { ...current },
553
- credentials: { ...refreshed }
554
- });
555
- }
556
- return result.apiKey;
557
- }
558
- }
559
- /**
560
- * Coalesce concurrent refresh calls onto a single in-flight promise per key.
561
- * The key combines the source (`params` vs `file`) and provider id, so a
562
- * per-agent param-only refresh does not starve a separate file-backed one.
563
- */
564
- async function withRefreshLock(key, fn) {
565
- const existing = refreshLocks.get(key);
566
- if (existing) return existing;
567
- const task = (async () => {
568
- try {
569
- return await fn();
494
+ return {
495
+ apiKey: result.apiKey,
496
+ ...result.newCredentials !== current ? { event: {
497
+ provider: options.provider,
498
+ providerId: options.providerId,
499
+ source,
500
+ previousCredentials: generation,
501
+ credentials: refreshed
502
+ } } : {}
503
+ };
570
504
  } finally {
571
- refreshLocks.delete(key);
505
+ release?.();
572
506
  }
573
- })();
574
- refreshLocks.set(key, task);
575
- return task;
507
+ }
576
508
  }
577
509
  //#endregion
578
- export { readOAuthCredentials as a, writeOAuthCredentials as c, getOAuthProvider as d, refreshAnthropicToken as f, isOAuthAccessToken as i, ensureBundledOAuthFlows as l, registerOAuthProvider as m, credentialsFromParams as n, registerCustomOAuthProvider as o, refreshOpenAICodexToken as p, extractRuntimeCredentials as r, resolveOAuthApiKey as s, credentialsFilePath as t, getOAuthApiKey as u };
510
+ export { readOAuthCredentials as a, withCredentialsLock as c, getOAuthApiKey as d, getOAuthProvider as f, registerOAuthProvider as h, isOAuthAccessToken as i, writeOAuthCredentials as l, refreshOpenAICodexToken as m, credentialsFromParams as n, registerCustomOAuthProvider as o, refreshAnthropicToken as p, extractRuntimeCredentials as r, resolveOAuthApiKey as s, credentialsFilePath as t, ensureBundledOAuthFlows as u };
579
511
 
580
- //# sourceMappingURL=oauth-D-LZ4ic-.js.map
512
+ //# sourceMappingURL=oauth-CmtlmCzi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-CmtlmCzi.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 * pi-ai ≥ 0.85 loads each OAuth flow module through a VARIABLE specifier\n * (`auth/oauth/load.js`: `import(rewrite(\"./anthropic.ts\"))`) precisely so\n * bundlers cannot follow it. Fine under plain Node/Bun where the file sits\n * next to `load.js`; fatal inside anything bundled — the compiled `zidane`\n * binary, the packaged Electron main — where the refresh path died with\n * `Cannot find module './anthropic.js'` and the user was told to re-run auth\n * for a token that was perfectly renewable.\n *\n * pi-ai ships the escape hatch for exactly this: `bun-oauth` statically\n * imports every flow and registers them with the loader. We call it lazily,\n * once, right before the first refresh — a static specifier the bundler DOES\n * follow — so every host (TUI binary, GUI, daemon, SDK) refreshes the same\n * way. Idempotent; failure to register falls through to the loader's own\n * behavior (works unbundled, so nothing gets worse).\n */\nlet bundledFlowsReady: Promise<void> | null = null\nexport function ensureBundledOAuthFlows(): Promise<void> {\n bundledFlowsReady ??= import('@earendil-works/pi-ai/bun-oauth')\n .then(({ registerBunOAuthFlows }) => {\n registerBunOAuthFlows()\n })\n .catch(() => {\n bundledFlowsReady = null\n })\n return bundledFlowsReady\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 await ensureBundledOAuthFlows()\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 await ensureBundledOAuthFlows()\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 { randomUUID } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, resolve } from 'node:path'\nimport { isDeepStrictEqual } from 'node:util'\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\ninterface RefreshResult {\n apiKey: string\n event?: OAuthRefreshHookContext\n}\n\nconst refreshLocks = new Map<string, Promise<RefreshResult>>()\nconst storeIds = new WeakMap<object, number>()\nlet nextStoreId = 0\nfunction identity(value: object): number {\n let id = storeIds.get(value)\n if (id === undefined) {\n id = ++nextStoreId\n storeIds.set(value, id)\n }\n return id\n}\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 /** Synchronous provider-local patch writer; injected stores own cross-process coordination. */\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 return readOAuthCredentialsAt(credentialsFilePath())\n}\n\nfunction readOAuthCredentialsAt(path: string): Record<string, OAuthCredentials | undefined> {\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/** Never steal a lock based on age: a suspended holder may still own it. */\nfunction tryAcquireLock(lockPath: string): (() => void) | undefined {\n const owner = `${process.pid}:${randomUUID()}`\n try {\n writeFileSync(lockPath, owner, { flag: 'wx', mode: CREDENTIALS_FILE_MODE })\n }\n catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST')\n return undefined\n throw err\n }\n return () => {\n try {\n if (readFileSync(lockPath, 'utf8') === owner)\n unlinkSync(lockPath)\n }\n catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT')\n throw err\n }\n }\n}\n\n/** Shared by refresh persistence and interactive credential mutations. */\nexport function withCredentialsLock<T>(path: string, fn: () => T): T {\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 })\n const deadline = Date.now() + 2000\n let release = tryAcquireLock(`${path}.lock`)\n while (!release) {\n if (Date.now() >= deadline)\n throw new Error('Timed out waiting for credentials lock')\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20)\n release = tryAcquireLock(`${path}.lock`)\n }\n try {\n return fn()\n }\n finally {\n release()\n }\n}\n\nasync function acquireRefreshLock(lockPath: string): Promise<() => void> {\n mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 })\n const deadline = Date.now() + 30_000\n while (true) {\n const release = tryAcquireLock(lockPath)\n if (release)\n return release\n if (Date.now() >= deadline)\n throw new Error('Timed out waiting for OAuth refresh lock')\n await new Promise(resolve => setTimeout(resolve, 50))\n }\n}\n\nfunction readRawCredentials(path: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(readFileSync(path, 'utf8'))\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))\n return parsed\n }\n catch { /* Missing or corrupt file. */ }\n return {}\n}\n\nfunction writeCredentialPatch(path: string, credentials: Record<string, unknown>): void {\n const merged = { ...readRawCredentials(path), ...credentials }\n for (const [key, value] of Object.entries(merged)) {\n if (value === undefined)\n delete merged[key]\n }\n writeFileAtomic(path, JSON.stringify(merged, null, 2), { mode: CREDENTIALS_FILE_MODE })\n}\n\n/** Incoming entries are a provider-local patch, not a read-time snapshot. */\nexport function writeOAuthCredentials(credentials: Record<string, OAuthCredentials | undefined>) {\n const path = credentialsFilePath()\n withCredentialsLock(path, () => writeCredentialPatch(path, credentials))\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 const paramsCredentials = credentialsFromParams(options.params, options.extraCredentialKeys)\n if (!paramsCredentials && typeof options.params?.access === 'string')\n return options.params.access\n\n // Capture the store before awaiting: environment changes cannot redirect writes.\n const path = resolve(credentialsFilePath())\n const usingDefaultStore = !options.readCredentials && !options.writeCredentials\n const read = options.readCredentials ?? (() => readOAuthCredentialsAt(path))\n const write = options.writeCredentials ?? (patch => withCredentialsLock(path, () => writeCredentialPatch(path, patch)))\n const envValue = options.envKey ? process.env[options.envKey] : undefined\n if (!paramsCredentials && envValue && (!isOAuthAccessToken(envValue) || !read()[options.providerId]))\n return envValue\n\n const source = paramsCredentials ? 'params' : 'file'\n const initial = paramsCredentials ?? read()[options.providerId]\n const store = usingDefaultStore ? path : [identity(options.readCredentials ?? readOAuthCredentials), identity(options.writeCredentials ?? writeOAuthCredentials)]\n const key = JSON.stringify([source, options.providerId, source === 'file' ? store : null, initial, options.forceRefresh === true, options.rejectedAccess, identity(options.getOAuthApiKey ?? getOAuthApiKey)])\n let task = refreshLocks.get(key)\n if (!task) {\n task = run()\n refreshLocks.set(key, task)\n // Delete before callbacks run; a failing subscriber must not poison peers.\n void task.finally(() => refreshLocks.delete(key)).catch(() => {})\n }\n const result = await task\n if (result.event) {\n await callbacks?.onOAuthRefresh?.({\n ...structuredClone(result.event),\n provider: options.provider,\n })\n }\n return result.apiKey\n\n async function run(): Promise<RefreshResult> {\n const release = source === 'file' && usingDefaultStore\n ? await acquireRefreshLock(`${path}.refresh-${encodeURIComponent(options.providerId)}.lock`)\n : undefined\n try {\n const current = paramsCredentials ?? read()[options.providerId]\n if (!current)\n throw new Error(options.missingError)\n const generation = structuredClone(current)\n let result: Awaited<ReturnType<GetOAuthApiKey>>\n try {\n const stillRejected = options.rejectedAccess === undefined || current.access === options.rejectedAccess\n result = await (options.getOAuthApiKey ?? getOAuthApiKey)(\n options.providerId,\n { [options.providerId]: current },\n { force: options.forceRefresh === true && stillRejected },\n )\n }\n catch (err) {\n throw new Error(options.refreshError(errorMessage(err)), { cause: err })\n }\n if (!result)\n throw new Error(options.refreshError(options.missingError))\n const refreshed = { ...generation, ...result.newCredentials }\n if (source === 'file') {\n const persist = () => {\n if (!isDeepStrictEqual(read()[options.providerId], generation))\n throw new Error('OAuth credentials changed during refresh; retry with current credentials')\n if (result.newCredentials !== current) {\n const patch = { [options.providerId]: refreshed }\n if (usingDefaultStore)\n writeCredentialPatch(path, patch)\n else\n write(patch)\n }\n }\n if (usingDefaultStore)\n withCredentialsLock(path, persist)\n else\n persist()\n }\n return {\n apiKey: result.apiKey,\n ...(result.newCredentials !== current\n ? { event: {\n provider: options.provider,\n providerId: options.providerId,\n source,\n previousCredentials: generation,\n credentials: refreshed,\n } }\n : {}),\n }\n }\n finally {\n release?.()\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0DA,eAAe,wBACb,YACA,OACA,cAC2B;CAC3B,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,kBAAkB,WAAW,uBAAuB;CAKtE,MAAM,EAAE,MAAM,OAAO,GAAG,gBACpB,MAAM,MAAM,QACZ;EAAE,MAAM;EAAS,QAAQ;EAAI,SAAS;EAAc,SAAS;CAAE,GAC/D,IAAI,gBAAgB,CAAC,CAAC,MACxB;CACF,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,IAAI,oBAA0C;AAC9C,SAAgB,0BAAyC;CACvD,sBAAsB,OAAO,kCAAkC,CAC5D,MAAM,EAAE,4BAA4B;EACnC,sBAAsB;CACxB,CAAC,CAAC,CACD,YAAY;EACX,oBAAoB;CACtB,CAAC;CACH,OAAO;AACT;;;;;;AAOA,eAAsB,sBAAsB,cAAiD;CAC3F,MAAM,wBAAwB;CAC9B,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,OAAO,wBAAwB,aAAa,kBAAkB,CAAC,CAAC,KAAK,OAAO,YAAY;AAC1F;;;;;;;AAQA,eAAsB,wBAAw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AM,gBAAgB,QAAQ,mBAAmB,KAAA,KAAa,QAAQ,WAAW,QAAQ;IACzF,SAAS,OAAO,QAAQ,kBAAkB,eAAA,CACxC,QAAQ,YACR,GAAG,QAAQ,aAAa,QAAQ,GAChC,EAAE,OAAO,QAAQ,iBAAiB,QAAQ,cAAc,CAC1D;GACF,SACO,KAAK;IACV,MAAM,IAAI,MAAM,QAAQ,aAAa,aAAa,GAAG,CAAC,GAAG,EAAE,OAAO,IAAI,CAAC;GACzE;GACA,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,QAAQ,aAAa,QAAQ,YAAY,CAAC;GAC5D,MAAM,YAAY;IAAE,GAAG;IAAY,GAAG,OAAO;GAAe;GAC5D,IAAI,WAAW,QAAQ;IACrB,MAAM,gBAAgB;KACpB,IAAI,CAAC,kBAAkB,KAAK,CAAC,CAAC,QAAQ,aAAa,UAAU,GAC3D,MAAM,IAAI,MAAM,0EAA0E;KAC5F,IAAI,OAAO,mBAAmB,SAAS;MACrC,MAAM,QAAQ,GAAG,QAAQ,aAAa,UAAU;MAChD,IAAI,mBACF,qBAAqB,MAAM,KAAK;WAEhC,MAAM,KAAK;KACf;IACF;IACA,IAAI,mBACF,oBAAoB,MAAM,OAAO;SAEjC,QAAQ;GACZ;GACA,OAAO;IACL,QAAQ,OAAO;IACf,GAAI,OAAO,mBAAmB,UAC1B,EAAE,OAAO;KACP,UAAU,QAAQ;KAClB,YAAY,QAAQ;KACpB;KACA,qBAAqB;KACrB,aAAa;IACf,EAAE,IACF,CAAC;GACP;EACF,UACQ;GACN,UAAU;EACZ;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { $n as HeadlessResult, Jn as FormattedHeadlessTurnEvent, Qn as HeadlessOutputFormat, Xn as HeadlessEvent, qi as Agent, qn as FormattedHeadlessResult } from "../index-CfEJ5Vf9.js";
1
+ import { $n as HeadlessResult, Jn as FormattedHeadlessTurnEvent, Qn as HeadlessOutputFormat, Xn as HeadlessEvent, qi as Agent, qn as FormattedHeadlessResult } from "../index-C4mY0oKE.js";
2
2
 
3
3
  //#region src/output/stream-json.d.ts
4
4
  type StreamJsonOutputFormat = HeadlessOutputFormat;
@@ -1,4 +1,4 @@
1
- import { Yi as AgentHooks, qi as Agent, t as Preset } from "../index-CfEJ5Vf9.js";
1
+ import { Yi as AgentHooks, qi as Agent, t as Preset } from "../index-C4mY0oKE.js";
2
2
 
3
3
  //#region src/output/terminal.d.ts
4
4
  interface TerminalOutputOptions {
package/dist/plugins.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { Ac as PLUGIN_MANIFEST_FILE, Bc as PluginSchemaKind, Dc as ManifestValidation, Ec as expandPluginVars, Fc as LoadedPlugin, Hc as agentPluginsSchemaId, Ic as PluginAuthor, Lc as PluginComponentStatus, Mc as loadAgentPlugin, Nc as AgentPluginsVersion, Oc as parsePluginManifest, Pc as LoadAgentPluginOptions, Rc as PluginDiagnostic, Tc as PLUGIN_MCP_FILE, Uc as isSupportedAgentPluginsVersion, Vc as SUPPORTED_AGENT_PLUGINS_VERSIONS, Wc as parseSchemaId, jc as defaultPluginDataRoot, kc as validatePluginManifest, wc as PLUGIN_SKILLS_DIR, zc as PluginManifest } from "./index-CfEJ5Vf9.js";
1
+ import { Ac as PLUGIN_MANIFEST_FILE, Bc as PluginSchemaKind, Dc as ManifestValidation, Ec as expandPluginVars, Fc as LoadedPlugin, Hc as agentPluginsSchemaId, Ic as PluginAuthor, Lc as PluginComponentStatus, Mc as loadAgentPlugin, Nc as AgentPluginsVersion, Oc as parsePluginManifest, Pc as LoadAgentPluginOptions, Rc as PluginDiagnostic, Tc as PLUGIN_MCP_FILE, Uc as isSupportedAgentPluginsVersion, Vc as SUPPORTED_AGENT_PLUGINS_VERSIONS, Wc as parseSchemaId, jc as defaultPluginDataRoot, kc as validatePluginManifest, wc as PLUGIN_SKILLS_DIR, zc as PluginManifest } from "./index-C4mY0oKE.js";
2
2
  export { type AgentPluginsVersion, type LoadAgentPluginOptions, type LoadedPlugin, type ManifestValidation, PLUGIN_MANIFEST_FILE, PLUGIN_MCP_FILE, PLUGIN_SKILLS_DIR, type PluginAuthor, type PluginComponentStatus, type PluginDiagnostic, type PluginManifest, type PluginSchemaKind, SUPPORTED_AGENT_PLUGINS_VERSIONS, agentPluginsSchemaId, defaultPluginDataRoot, expandPluginVars, isSupportedAgentPluginsVersion, loadAgentPlugin, parsePluginManifest, parseSchemaId, validatePluginManifest };
package/dist/presets.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { Ji as AgentHookMap, Ki as _default, a as basicTools, i as _default$1, n as composePresets, r as definePreset, t as Preset } from "./index-CfEJ5Vf9.js";
1
+ import { Ji as AgentHookMap, Ki as _default, a as basicTools, i as _default$1, n as composePresets, r as definePreset, t as Preset } from "./index-C4mY0oKE.js";
2
2
  export { type AgentHookMap, Preset, _default as artifacts, _default$1 as basic, basicTools, composePresets, definePreset };
package/dist/presets.js CHANGED
@@ -1,2 +1,2 @@
1
- import { Jt as artifacts_default, bt as basicTools, vt as composePresets, xt as basic_default, yt as definePreset } from "./agent-Djzx-1kD.js";
1
+ import { Jt as artifacts_default, bt as basicTools, vt as composePresets, xt as basic_default, yt as definePreset } from "./agent-LC2c1ue-.js";
2
2
  export { artifacts_default as artifacts, basic_default as basic, basicTools, composePresets, definePreset };
@@ -1,2 +1,2 @@
1
- import { Ah as anthropic, Bh as resolveAnthropicMaxOutput, Dh as AnthropicParams, Eh as AnthropicContextManagement, Fh as credentialIdentity, Ih as defaultAnthropicMaxTokens, Lh as planAnthropicThinking, Mh as buildAnthropicClientOptions, Nh as cacheWriteTtlMultiplier, Oh as AnthropicThinkingPlan, Ph as classifyAnthropicError, Rh as resolveAnthropicAuthShape, Th as AnthropicBedrockConfig, jh as applyAnthropicCacheBreakpoints, kh as EXTENDED_CACHE_TTL_BETA, zh as resolveAnthropicBetas } from "../index-CfEJ5Vf9.js";
1
+ import { Ah as anthropic, Bh as resolveAnthropicMaxOutput, Dh as AnthropicParams, Eh as AnthropicContextManagement, Fh as credentialIdentity, Ih as defaultAnthropicMaxTokens, Lh as planAnthropicThinking, Mh as buildAnthropicClientOptions, Nh as cacheWriteTtlMultiplier, Oh as AnthropicThinkingPlan, Ph as classifyAnthropicError, Rh as resolveAnthropicAuthShape, Th as AnthropicBedrockConfig, jh as applyAnthropicCacheBreakpoints, kh as EXTENDED_CACHE_TTL_BETA, zh as resolveAnthropicBetas } from "../index-C4mY0oKE.js";
2
2
  export { AnthropicBedrockConfig, AnthropicContextManagement, AnthropicParams, AnthropicThinkingPlan, EXTENDED_CACHE_TTL_BETA, anthropic, applyAnthropicCacheBreakpoints, buildAnthropicClientOptions, cacheWriteTtlMultiplier, classifyAnthropicError, credentialIdentity, defaultAnthropicMaxTokens, planAnthropicThinking, resolveAnthropicAuthShape, resolveAnthropicBetas, resolveAnthropicMaxOutput };
@@ -1,2 +1,2 @@
1
- import { a as cacheWriteTtlMultiplier, c as defaultAnthropicMaxTokens, d as resolveAnthropicBetas, f as resolveAnthropicMaxOutput, i as buildAnthropicClientOptions, l as planAnthropicThinking, n as anthropic, o as classifyAnthropicError, r as applyAnthropicCacheBreakpoints, s as credentialIdentity, t as EXTENDED_CACHE_TTL_BETA, u as resolveAnthropicAuthShape } from "../anthropic-DATE-m9f.js";
1
+ import { a as cacheWriteTtlMultiplier, c as defaultAnthropicMaxTokens, d as resolveAnthropicBetas, f as resolveAnthropicMaxOutput, i as buildAnthropicClientOptions, l as planAnthropicThinking, n as anthropic, o as classifyAnthropicError, r as applyAnthropicCacheBreakpoints, s as credentialIdentity, t as EXTENDED_CACHE_TTL_BETA, u as resolveAnthropicAuthShape } from "../anthropic-BSbDiW0J.js";
2
2
  export { EXTENDED_CACHE_TTL_BETA, anthropic, applyAnthropicCacheBreakpoints, buildAnthropicClientOptions, cacheWriteTtlMultiplier, classifyAnthropicError, credentialIdentity, defaultAnthropicMaxTokens, planAnthropicThinking, resolveAnthropicAuthShape, resolveAnthropicBetas, resolveAnthropicMaxOutput };
@@ -1,2 +1,2 @@
1
- import { Ch as ArceeParams, wh as arcee } from "../index-CfEJ5Vf9.js";
1
+ import { Ch as ArceeParams, wh as arcee } from "../index-C4mY0oKE.js";
2
2
  export { ArceeParams, arcee };
@@ -1,2 +1,2 @@
1
- import { Sh as planBasetenReasoning, bh as BasetenParams, xh as baseten } from "../index-CfEJ5Vf9.js";
1
+ import { Sh as planBasetenReasoning, bh as BasetenParams, xh as baseten } from "../index-C4mY0oKE.js";
2
2
  export { BasetenParams, baseten, planBasetenReasoning };
@@ -1,2 +1,2 @@
1
- import { vh as CerebrasParams, yh as cerebras } from "../index-CfEJ5Vf9.js";
1
+ import { vh as CerebrasParams, yh as cerebras } from "../index-C4mY0oKE.js";
2
2
  export { CerebrasParams, cerebras };
@@ -1,2 +1,2 @@
1
- import { hh as local, mh as LocalParams } from "../index-CfEJ5Vf9.js";
1
+ import { hh as local, mh as LocalParams } from "../index-C4mY0oKE.js";
2
2
  export { LocalParams, local };
@@ -1,2 +1,2 @@
1
- import { $m as formatTools, Bm as OAIMessage, Gm as OpenAICompatStreamError, Hm as OpenAICompatAuthHeader, Jm as applyOAIToolCacheBreakpoint, Km as TOOL_RESULTS_TAG, Qm as consumeSSE, Um as OpenAICompatHttpError, Vm as OAITool, Wm as OpenAICompatParams, Xm as buildAssistantContent, Ym as assistantMessage, Zm as classifyOpenAICompatError, ah as userMessage, eh as mapOAIFinishReason, ih as toolResultsMessage, nh as openaiCompat, qm as applyOAICacheBreakpoints, rh as toOAIMessages, th as openAICompatPromptMessage, zm as ASSISTANT_TOOL_CALLS_TAG } from "../index-CfEJ5Vf9.js";
1
+ import { $m as formatTools, Bm as OAIMessage, Gm as OpenAICompatStreamError, Hm as OpenAICompatAuthHeader, Jm as applyOAIToolCacheBreakpoint, Km as TOOL_RESULTS_TAG, Qm as consumeSSE, Um as OpenAICompatHttpError, Vm as OAITool, Wm as OpenAICompatParams, Xm as buildAssistantContent, Ym as assistantMessage, Zm as classifyOpenAICompatError, ah as userMessage, eh as mapOAIFinishReason, ih as toolResultsMessage, nh as openaiCompat, qm as applyOAICacheBreakpoints, rh as toOAIMessages, th as openAICompatPromptMessage, zm as ASSISTANT_TOOL_CALLS_TAG } from "../index-C4mY0oKE.js";
2
2
  export { ASSISTANT_TOOL_CALLS_TAG, OAIMessage, OAITool, OpenAICompatAuthHeader, OpenAICompatHttpError, OpenAICompatParams, OpenAICompatStreamError, TOOL_RESULTS_TAG, applyOAICacheBreakpoints, applyOAIToolCacheBreakpoint, assistantMessage, buildAssistantContent, classifyOpenAICompatError, consumeSSE, formatTools, mapOAIFinishReason, openAICompatPromptMessage, openaiCompat, toOAIMessages, toolResultsMessage, userMessage };
@@ -1,2 +1,2 @@
1
- import { ch as mapCodexStopReason, lh as openai, oh as OpenAIParams, sh as classifyOpenAIError, uh as toPiMessages } from "../index-CfEJ5Vf9.js";
1
+ import { ch as mapCodexStopReason, lh as openai, oh as OpenAIParams, sh as classifyOpenAIError, uh as toPiMessages } from "../index-C4mY0oKE.js";
2
2
  export { OpenAIParams, classifyOpenAIError, mapCodexStopReason, openai, toPiMessages };
@@ -3,7 +3,7 @@ import { a as documentBlockMarker, r as assertResolvedMediaBlock } from "../type
3
3
  import { f as isRetryableHttpStatus, h as matchesToolPairingError, l as classifyErrorPrelude, m as matchesContextExceeded } from "../errors-DKiMrOKq.js";
4
4
  import { renderSystemForWire } from "../prompt.js";
5
5
  import { f as reasoningWireAction, n as SYNTHETIC_TOOL_RESULT_PLACEHOLDER } from "../messages-aORUmIKe.js";
6
- import { r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "../oauth-D-LZ4ic-.js";
6
+ import { r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "../oauth-CmtlmCzi.js";
7
7
  import { stream } from "@earendil-works/pi-ai/api/openai-codex-responses";
8
8
  import { stream as stream$1 } from "@earendil-works/pi-ai/api/openai-responses";
9
9
  import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
@@ -1,2 +1,2 @@
1
- import { Im as OpenRouterParams, Lm as normalizeOpenRouterModelId, Rm as openrouter } from "../index-CfEJ5Vf9.js";
1
+ import { Im as OpenRouterParams, Lm as normalizeOpenRouterModelId, Rm as openrouter } from "../index-C4mY0oKE.js";
2
2
  export { OpenRouterParams, normalizeOpenRouterModelId, openrouter };
@@ -1,2 +1,2 @@
1
- import { Am as xai, km as XaiParams } from "../index-CfEJ5Vf9.js";
1
+ import { Am as xai, km as XaiParams } from "../index-C4mY0oKE.js";
2
2
  export { XaiParams, xai };
@@ -1,5 +1,5 @@
1
1
  import { m as openaiCompat } from "../openai-compat-cIeLSED_.js";
2
- import { i as isOAuthAccessToken, r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "../oauth-D-LZ4ic-.js";
2
+ import { i as isOAuthAccessToken, r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "../oauth-CmtlmCzi.js";
3
3
  import { r as xaiBaseUrl, t as XAI_OAUTH_PROVIDER_ID } from "../xai-CazjStOK.js";
4
4
  //#region src/providers/xai.ts
5
5
  const DEFAULT_MODEL = "grok-4.6";