zidane 6.5.2 → 6.5.3

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 (98) hide show
  1. package/dist/{acp-565X8nVP.js → acp-CIpD8UIw.js} +2 -2
  2. package/dist/{acp-565X8nVP.js.map → acp-CIpD8UIw.js.map} +1 -1
  3. package/dist/acp-cli.js +5 -5
  4. package/dist/acp.d.ts +1 -1
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-CvO7UOxv.js → agent-8kfGIDb_.js} +2 -2
  7. package/dist/{agent-CvO7UOxv.js.map → agent-8kfGIDb_.js.map} +1 -1
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/{anthropic-Dov2mC5e.js → anthropic-_Hn1YiWr.js} +2 -2
  11. package/dist/{anthropic-Dov2mC5e.js.map → anthropic-_Hn1YiWr.js.map} +1 -1
  12. package/dist/{auth-B8ZuBcKC.js → auth-CS_e8ng1.js} +6 -5
  13. package/dist/{auth-B8ZuBcKC.js.map → auth-CS_e8ng1.js.map} +1 -1
  14. package/dist/chat/pure.d.ts +3 -3
  15. package/dist/chat.d.ts +20 -15
  16. package/dist/chat.d.ts.map +1 -1
  17. package/dist/chat.js +3 -3
  18. package/dist/{context-transport-ClvadrlH.js → context-transport-Bco9Wo0b.js} +3 -3
  19. package/dist/{context-transport-ClvadrlH.js.map → context-transport-Bco9Wo0b.js.map} +1 -1
  20. package/dist/contexts/daytona.d.ts +1 -1
  21. package/dist/contexts/daytona.d.ts.map +1 -1
  22. package/dist/contexts/daytona.js +5 -2
  23. package/dist/contexts/daytona.js.map +1 -1
  24. package/dist/contexts/e2b.d.ts +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-DfERTrql.d.ts → index-BKyWhILQ.d.ts} +2 -2
  31. package/dist/{index-DfERTrql.d.ts.map → index-BKyWhILQ.d.ts.map} +1 -1
  32. package/dist/index.d.ts +1 -1
  33. package/dist/index.js +7 -7
  34. package/dist/{login-Cl6ML2XN.js → login-D3CKhgbI.js} +2 -2
  35. package/dist/{login-Cl6ML2XN.js.map → login-D3CKhgbI.js.map} +1 -1
  36. package/dist/{mcp-DdntU47g.js → mcp-D9fqOQo5.js} +3 -3
  37. package/dist/{mcp-DdntU47g.js.map → mcp-D9fqOQo5.js.map} +1 -1
  38. package/dist/mcp.d.ts +1 -1
  39. package/dist/mcp.js +1 -1
  40. package/dist/{oauth-bkEOybqm.js → oauth-BYjlFR-J.js} +49 -10
  41. package/dist/oauth-BYjlFR-J.js.map +1 -0
  42. package/dist/output/stream-json.d.ts +1 -1
  43. package/dist/output/terminal.d.ts +1 -1
  44. package/dist/plugins.d.ts +1 -1
  45. package/dist/presets.d.ts +1 -1
  46. package/dist/presets.js +1 -1
  47. package/dist/providers/anthropic.d.ts +1 -1
  48. package/dist/providers/anthropic.js +1 -1
  49. package/dist/providers/arcee.d.ts +1 -1
  50. package/dist/providers/baseten.d.ts +1 -1
  51. package/dist/providers/cerebras.d.ts +1 -1
  52. package/dist/providers/local.d.ts +1 -1
  53. package/dist/providers/openai-compat.d.ts +1 -1
  54. package/dist/providers/openai.d.ts +1 -1
  55. package/dist/providers/openai.js +1 -1
  56. package/dist/providers/openrouter.d.ts +1 -1
  57. package/dist/providers/xai.d.ts +1 -1
  58. package/dist/providers/xai.js +68 -1
  59. package/dist/providers/xai.js.map +1 -0
  60. package/dist/{providers-B6mFe7OD.js → providers-VypZh7rD.js} +3 -3
  61. package/dist/{providers-B6mFe7OD.js.map → providers-VypZh7rD.js.map} +1 -1
  62. package/dist/providers.d.ts +1 -1
  63. package/dist/providers.js +4 -4
  64. package/dist/restate.d.ts +1 -1
  65. package/dist/restate.js +1 -1
  66. package/dist/rolldown-runtime-BhDjJH2R.js +15 -0
  67. package/dist/session/sqlite.d.ts +1 -1
  68. package/dist/session.d.ts +1 -1
  69. package/dist/skills.d.ts +1 -1
  70. package/dist/{stdio-BQeCMmuK.js → stdio-DPpBDPx5.js} +13 -4
  71. package/dist/{stdio-BQeCMmuK.js.map → stdio-DPpBDPx5.js.map} +1 -1
  72. package/dist/{stdio-loader-BN1l1ZAG.js → stdio-loader-CI4sPFve.js} +11 -6
  73. package/dist/stdio-loader-CI4sPFve.js.map +1 -0
  74. package/dist/{tool-formatters-B2gBbKaS.d.ts → tool-formatters-DMr62Hpy.d.ts} +3 -3
  75. package/dist/{tool-formatters-B2gBbKaS.d.ts.map → tool-formatters-DMr62Hpy.d.ts.map} +1 -1
  76. package/dist/tools/fetch-url.d.ts +1 -1
  77. package/dist/tools/web-search.d.ts +1 -1
  78. package/dist/tools.d.ts +1 -1
  79. package/dist/tools.js +1 -1
  80. package/dist/{transcript-anchors-CeIxhKP7.d.ts → transcript-anchors-BHihk9nf.d.ts} +2 -2
  81. package/dist/{transcript-anchors-CeIxhKP7.d.ts.map → transcript-anchors-BHihk9nf.d.ts.map} +1 -1
  82. package/dist/{transcript-anchors-CmFKUw8M.js → transcript-anchors-uU_KZLsp.js} +36 -31
  83. package/dist/transcript-anchors-uU_KZLsp.js.map +1 -0
  84. package/dist/tui.d.ts +3 -3
  85. package/dist/tui.d.ts.map +1 -1
  86. package/dist/tui.js +19 -13
  87. package/dist/tui.js.map +1 -1
  88. package/dist/{turn-operations-Dyv3Z-Ff.d.ts → turn-operations-BgqVUjtl.d.ts} +3 -3
  89. package/dist/{turn-operations-Dyv3Z-Ff.d.ts.map → turn-operations-BgqVUjtl.d.ts.map} +1 -1
  90. package/dist/types.d.ts +1 -1
  91. package/dist/{xai-Du6Wfnlb.js → xai-CfmI5Y5k.js} +10 -67
  92. package/dist/xai-CfmI5Y5k.js.map +1 -0
  93. package/docs/RESTATE.md +7 -0
  94. package/package.json +18 -17
  95. package/dist/oauth-bkEOybqm.js.map +0 -1
  96. package/dist/stdio-loader-BN1l1ZAG.js.map +0 -1
  97. package/dist/transcript-anchors-CmFKUw8M.js.map +0 -1
  98. package/dist/xai-Du6Wfnlb.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { Al as CompletionReference, Rl as Command, bd as StreamEvent, bh as ToolResultContent, fd as EditOutcome, hd as Owner, kh as TurnUsage, kl as CompletionProvider, lh as SessionTurn, md as EditPayload, tg as SkillConfig } from "./index-DfERTrql.js";
2
- import { B as ApprovalDecision } from "./tool-formatters-B2gBbKaS.js";
1
+ import { Al as CompletionReference, Rl as Command, bd as StreamEvent, bh as ToolResultContent, fd as EditOutcome, hd as Owner, kh as TurnUsage, kl as CompletionProvider, lh as SessionTurn, md as EditPayload, tg as SkillConfig } from "./index-BKyWhILQ.js";
2
+ import { B as ApprovalDecision } from "./tool-formatters-DMr62Hpy.js";
3
3
 
4
4
  //#region src/chat/color-gradient.d.ts
5
5
  /**
@@ -684,4 +684,4 @@ declare function countNeighbors(turnIds: readonly string[], turnId: string): {
684
684
  } | null;
685
685
  //#endregion
686
686
  export { uniqueFilesFromReferences as $, buildUnifiedDiff as A, buildEditOutcomesAnnotation as B, EditSummary as C, PreviewResult as D, InlineSegment as E, previewEditPayload as F, rewriteMultiEditHeader as G, mergeApprovalAndBodyOutcomes as H, splitLines as I, SKILLS_TRIGGER as J, stripEditOutcomesAnnotation as K, summarizeEditPayload as L, computeLineDiff as M, extractEditPayload as N, applyEditPayload as O, filetypeFromPath as P, createFilesCompletionProvider as Q, tokenize as R, EditHunkSummary as S, InlineDiff as T, parseEditOutcomesFromResult as U, maskToOutcomeKinds as V, resolveApprovalForPayload as W, uniqueSkillNamesFromReferences as X, createSkillsCompletionProvider as Y, FILES_TRIGGER as Z, formatTaskSummary as _, MAX_TRANSCRIPT_EVENTS as a, CHATS_TRIGGER as at, DiffLine as b, finalizeStreamingMarkdown as c, ChatReferenceScope as ct, ageString as d, uniqueChatIdsFromReferences as dt, FileEntry as et, compactPath as f, blendHsl as ft, formatTaskStatus as g, formatDuration as h, turnAsText as i, createCommandsCompletionProvider as it, computeInlineDiff as j, buildContextualDiff as k, finalizeStreamingMarkdownForOwner as l, chatReferenceTokensFromText as lt, fmtTokens as m, deleteTurnSafely as n, listProjectFiles as nt, TRANSCRIPT_TRIM_TO_EVENTS as o, ChatReferenceData as ot, fmtCost as p, buildLinearRamp as pt, summarizeOutcomes as q, truncateTurnsAt as r, COMMANDS_TRIGGER as rt, capTranscriptEvents as s, ChatReferenceEntry as st, countNeighbors as t, ListProjectFilesOptions as tt, turnContextSize as u, createChatsCompletionProvider as ut, previewLine as v, HunkResolution as w, DiffOp as x, shortId as y, ResolvedApproval as z };
687
- //# sourceMappingURL=turn-operations-Dyv3Z-Ff.d.ts.map
687
+ //# sourceMappingURL=turn-operations-BgqVUjtl.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"turn-operations-Dyv3Z-Ff.d.ts","names":[],"sources":["../src/chat/color-gradient.ts","../src/chat/completion-chats.ts","../src/chat/completion-commands.ts","../src/chat/files-discovery.ts","../src/chat/completion-files.ts","../src/chat/completion-skills.ts","../src/chat/edit-approval.ts","../src/tools/edit-utils.ts","../src/chat/edit-diff.ts","../src/chat/format.ts","../src/chat/streaming-pure.ts","../src/chat/turn-operations.ts"],"mappings":";;;;;;;;iBAmFgB,QAAA,CAAS,IAAA,UAAc,EAAA,UAAY,CAAA;;;;;;iBAuBnC,eAAA,CAAgB,IAAA,UAAc,EAAA,UAAY,CAAA;;;cCxF7C,aAAA;AAAA,KAKD,kBAAA;AAAA,UAEK,kBAAA;EACf,EAAA;EACA,KAAA;EACA,SAAA;EACA,gBAAA;EACA,QAAA;EACA,WAAA;EACA,SAAA;AAAA;AAAA,UAGe,iBAAA;EACf,KAAA,EAAO,kBAAkB;EACzB,KAAA;AAAA;AAAA,iBAmIc,6BAAA,CAA8B,IAAA;EAC5C,UAAA,iBAA2B,kBAAA;EAC3B,mBAAA,kBAAqC,kBAAA;EACrC,QAAA,SAAiB,kBAAA;EACjB,aAAA,SAAsB,OAAA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AAA,WAAgB,WAAA,IAAe,MAAA,WAAiB,WAAW;;;AVV7D;AAE9B;;;;;;;;;;;;AAOW;AAGX;iBUuBgB,gBAAA,CAAiB,KAAA,WAAgB,WAAA,IAAe,MAAA,WAAiB,WAAW;;;;;;;AVrBrF;AAmIP;iBUtDgB,UAAA,CAAW,IAAiB,EAAX,WAAW;;;;;;iBA+B5B,cAAA,CACd,OAAA,qBACA,MAAA;EACG,MAAA;EAAgB,KAAA;AAAA"}
1
+ {"version":3,"file":"turn-operations-BgqVUjtl.d.ts","names":[],"sources":["../src/chat/color-gradient.ts","../src/chat/completion-chats.ts","../src/chat/completion-commands.ts","../src/chat/files-discovery.ts","../src/chat/completion-files.ts","../src/chat/completion-skills.ts","../src/chat/edit-approval.ts","../src/tools/edit-utils.ts","../src/chat/edit-diff.ts","../src/chat/format.ts","../src/chat/streaming-pure.ts","../src/chat/turn-operations.ts"],"mappings":";;;;;;;;iBAmFgB,QAAA,CAAS,IAAA,UAAc,EAAA,UAAY,CAAA;;;;;;iBAuBnC,eAAA,CAAgB,IAAA,UAAc,EAAA,UAAY,CAAA;;;cCxF7C,aAAA;AAAA,KAKD,kBAAA;AAAA,UAEK,kBAAA;EACf,EAAA;EACA,KAAA;EACA,SAAA;EACA,gBAAA;EACA,QAAA;EACA,WAAA;EACA,SAAA;AAAA;AAAA,UAGe,iBAAA;EACf,KAAA,EAAO,kBAAkB;EACzB,KAAA;AAAA;AAAA,iBAmIc,6BAAA,CAA8B,IAAA;EAC5C,UAAA,iBAA2B,kBAAA;EAC3B,mBAAA,kBAAqC,kBAAA;EACrC,QAAA,SAAiB,kBAAA;EACjB,aAAA,SAAsB,OAAA,UAAiB,kBAAA;EACvC,KAAA;AAAA,IACE,kBAAA,CAAmB,iBAAA;AAAA,iBAoDP,2BAAA,CACd,UAAmD,WAA9B,mBAAmB;AAAA,iBAe1B,2BAAA,CAA4B,IAAY;;;;cCnO3C,gBAAA;AF2Fb;;;;;AAAA,iBE3BgB,gCAAA,C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AiB,EAAX,WAAW;;;;;;iBA+B5B,cAAA,CACd,OAAA,qBACA,MAAA;EACG,MAAA;EAAgB,KAAA;AAAA"}
package/dist/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { d as ClassifiedErrorKind, i as AgentContextExceededError, l as CONTEXT_EXCEEDED_MESSAGE_PATTERNS, n as AgentAbortedError, o as AgentProviderError, p as matchesContextExceeded, r as AgentBudgetExceededError, s as AgentToolNotAllowedError, u as ClassifiedError } from "./timeout-DEaqslLO.js";
2
- import { $m as RepeatGuardConfig, Ah as toolOutputBudgetByteLength, Bf as StreamCallbacks, Bm as McpToolHookContext, C as SuccessfulMutationOutcome, Ch as ToolResultImageContent, Cm as AgentClock, Dh as ToolResultVideoContent, Dp as OpenAIParams, Eh as ToolResultTextContent, Fh as ToolMap, Gf as ToolSpec, Gi as AgentHookMap, Gm as ProgressNudgeKind, Jh as ToolStateOp, Jm as PromptDocumentPart, Jp as AnthropicParams, Kf as TurnResult, Kh as StagedToolState, Ki as AgentHooks, Km as ProgressNudgeMessage, Lf as Provider, Lh as ReadStateEntry, Mh as toolResultToText, Nh as ToolContext, Ns as SpawnToolOptions, Oh as TurnFinishReason, Os as ChildAgent, Ph as ToolDef, Pm as DEFAULT_AGENT_CLOCK, Ps as SpawnToolState, Qm as PromptVideoPart, Rf as ProviderCapabilities, Rh as ReadStateMap, Rr as InteractionToolOptions, S as MutationValidationResult, Sg as RemoteStoreOptions, Sh as ToolResultDocumentRefContent, Sm as AgentBehavior, Th as ToolResultMetadata, Tm as AgentStats, Uf as ToolCall, Vf as StreamOptions, Wf as ToolResult, Wi as Agent, Wm as OAuthRefreshHookContext, Xh as ToolStateView, Xm as PromptPart, Yh as ToolStateStore, Ym as PromptImagePart, Zm as PromptTextPart, _ as statsByModel, _h as ToolHookContext, ag as SkillsConfig, ah as SessionContentBlock, b as MutationValidationHooksOptions, bh as ToolResultContent, cg as Session, ch as SessionMessage, dg as SessionRun, eh as RepeatGuardToolMatcher, fg as SessionStore, h as flattenTurns, hh as ThinkingLevel, ih as RunHookMap, jh as toolOutputByteLength, kh as TurnUsage, km as ChildRunStats, lg as SessionData, lh as SessionTurn, nh as ResolveContentRefBlock, og as CreateSessionOptions, oh as SessionEndStatus, p as ModelUsage, ph as StreamHookContext, qh as ToolStateController, qi as AgentOptions, qm as PromptAudioPart, rg as SkillResource, rh as RetryConfig, rp as OpenRouterParams, sh as SessionHookContext, t as Preset, t_ as McpConnection, tg as SkillConfig, th as ResolveContentRef, uh as SpawnHookContext, v as MutationValidationBatch, vh as ToolOutcome, vr as ValidationResult, wh as ToolResultImageRefContent, wm as AgentRunOptions, x as MutationValidationMutation, xh as ToolResultDocumentContent, y as MutationValidationFailure, yh as ToolResultAudioContent, zm as McpServerConfig, zp as CerebrasParams } from "./index-DfERTrql.js";
2
+ import { $m as RepeatGuardConfig, Ah as toolOutputBudgetByteLength, Bf as StreamCallbacks, Bm as McpToolHookContext, C as SuccessfulMutationOutcome, Ch as ToolResultImageContent, Cm as AgentClock, Dh as ToolResultVideoContent, Dp as OpenAIParams, Eh as ToolResultTextContent, Fh as ToolMap, Gf as ToolSpec, Gi as AgentHookMap, Gm as ProgressNudgeKind, Jh as ToolStateOp, Jm as PromptDocumentPart, Jp as AnthropicParams, Kf as TurnResult, Kh as StagedToolState, Ki as AgentHooks, Km as ProgressNudgeMessage, Lf as Provider, Lh as ReadStateEntry, Mh as toolResultToText, Nh as ToolContext, Ns as SpawnToolOptions, Oh as TurnFinishReason, Os as ChildAgent, Ph as ToolDef, Pm as DEFAULT_AGENT_CLOCK, Ps as SpawnToolState, Qm as PromptVideoPart, Rf as ProviderCapabilities, Rh as ReadStateMap, Rr as InteractionToolOptions, S as MutationValidationResult, Sg as RemoteStoreOptions, Sh as ToolResultDocumentRefContent, Sm as AgentBehavior, Th as ToolResultMetadata, Tm as AgentStats, Uf as ToolCall, Vf as StreamOptions, Wf as ToolResult, Wi as Agent, Wm as OAuthRefreshHookContext, Xh as ToolStateView, Xm as PromptPart, Yh as ToolStateStore, Ym as PromptImagePart, Zm as PromptTextPart, _ as statsByModel, _h as ToolHookContext, ag as SkillsConfig, ah as SessionContentBlock, b as MutationValidationHooksOptions, bh as ToolResultContent, cg as Session, ch as SessionMessage, dg as SessionRun, eh as RepeatGuardToolMatcher, fg as SessionStore, h as flattenTurns, hh as ThinkingLevel, ih as RunHookMap, jh as toolOutputByteLength, kh as TurnUsage, km as ChildRunStats, lg as SessionData, lh as SessionTurn, nh as ResolveContentRefBlock, og as CreateSessionOptions, oh as SessionEndStatus, p as ModelUsage, ph as StreamHookContext, qh as ToolStateController, qi as AgentOptions, qm as PromptAudioPart, rg as SkillResource, rh as RetryConfig, rp as OpenRouterParams, sh as SessionHookContext, t as Preset, t_ as McpConnection, tg as SkillConfig, th as ResolveContentRef, uh as SpawnHookContext, v as MutationValidationBatch, vh as ToolOutcome, vr as ValidationResult, wh as ToolResultImageRefContent, wm as AgentRunOptions, x as MutationValidationMutation, xh as ToolResultDocumentContent, y as MutationValidationFailure, yh as ToolResultAudioContent, zm as McpServerConfig, zp as CerebrasParams } from "./index-BKyWhILQ.js";
3
3
  import { _ as TaskHandle, a as ContextType, c as ExecutionContext, g as TaskExitInfo, h as TaskEntry, l as ExecutionHandle, n as ContextCapabilities, o as DetachedTasksCapability, p as SpawnConfig, r as ContextHardening, s as ExecResult, t as BackgroundTaskStatus, v as TaskStallInfo } from "./types-M2DauK2D.js";
4
4
  import { t as SandboxProvider } from "./sandbox-DLY6uah7.js";
5
5
  export { type Agent, AgentAbortedError, type AgentBehavior, AgentBudgetExceededError, type AgentClock, AgentContextExceededError, type AgentHookMap, type AgentHooks, type AgentOptions, AgentProviderError, type AgentRunOptions, type AgentStats, AgentToolNotAllowedError, type AnthropicParams, type BackgroundTaskStatus, CONTEXT_EXCEEDED_MESSAGE_PATTERNS, type CerebrasParams, type ChildAgent, type ChildRunStats, type ClassifiedError, type ClassifiedErrorKind, type ContextCapabilities, type ContextHardening, type ContextType, type CreateSessionOptions, DEFAULT_AGENT_CLOCK, type DetachedTasksCapability, type ExecResult, type ExecutionContext, type ExecutionHandle, type InteractionToolOptions, type McpConnection, type McpServerConfig, type McpToolHookContext, type ModelUsage, type MutationValidationBatch, type MutationValidationFailure, type MutationValidationHooksOptions, type MutationValidationMutation, type MutationValidationResult, type OAuthRefreshHookContext, type OpenAIParams, type OpenRouterParams, type Preset, type ProgressNudgeKind, type ProgressNudgeMessage, type PromptAudioPart, type PromptDocumentPart, type PromptImagePart, type PromptPart, type PromptTextPart, type PromptVideoPart, type Provider, type ProviderCapabilities, type ReadStateEntry, type ReadStateMap, type RemoteStoreOptions, type RepeatGuardConfig, type RepeatGuardToolMatcher, type ResolveContentRef, type ResolveContentRefBlock, type RetryConfig, type RunHookMap, type SandboxProvider, type Session, type SessionContentBlock, type SessionData, type SessionEndStatus, type SessionHookContext, type SessionMessage, type SessionRun, type SessionStore, type SessionTurn, type SkillConfig, type SkillResource, type SkillsConfig, type SpawnConfig, type SpawnHookContext, type SpawnToolOptions, type SpawnToolState, type StagedToolState, type StreamCallbacks, type StreamHookContext, type StreamOptions, type SuccessfulMutationOutcome, type TaskEntry, type TaskExitInfo, type TaskHandle, type TaskStallInfo, type ThinkingLevel, type ToolCall, type ToolContext, type ToolDef, type ToolHookContext, type ToolMap, type ToolOutcome, type ToolResult, type ToolResultAudioContent, type ToolResultContent, type ToolResultDocumentContent, type ToolResultDocumentRefContent, type ToolResultImageContent, type ToolResultImageRefContent, type ToolResultMetadata, type ToolResultTextContent, type ToolResultVideoContent, type ToolSpec, type ToolStateController, type ToolStateOp, type ToolStateStore, type ToolStateView, type TurnFinishReason, type TurnResult, type TurnUsage, type ValidationResult, flattenTurns, matchesContextExceeded, statsByModel, toolOutputBudgetByteLength, toolOutputByteLength, toolResultToText };
@@ -1,5 +1,4 @@
1
- import { m as openaiCompat } from "./openai-compat-CnHeo4Lz.js";
2
- import { i as isOAuthAccessToken, r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "./oauth-bkEOybqm.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.js";
3
2
  import { createServer } from "node:http";
4
3
  //#region src/chat/oauth-page/pkce.ts
5
4
  /**
@@ -29,6 +28,13 @@ async function generatePkce() {
29
28
  }
30
29
  //#endregion
31
30
  //#region src/chat/oauth-page/xai.ts
31
+ var xai_exports = /* @__PURE__ */ __exportAll({
32
+ XAI_OAUTH_PROVIDER_ID: () => XAI_OAUTH_PROVIDER_ID,
33
+ createXaiOAuthProvider: () => createXaiOAuthProvider,
34
+ loginXai: () => loginXai,
35
+ refreshXaiToken: () => refreshXaiToken,
36
+ xaiBaseUrl: () => xaiBaseUrl
37
+ });
32
38
  /** pi-ai / zidane OAuth provider id. Also the credentials-file key. */
33
39
  const XAI_OAUTH_PROVIDER_ID = "xai-oauth";
34
40
  const DEFAULT_BASE_URL = "https://api.x.ai/v1";
@@ -311,69 +317,6 @@ function createXaiOAuthProvider(renderPage) {
311
317
  };
312
318
  }
313
319
  //#endregion
314
- //#region src/providers/xai.ts
315
- const DEFAULT_MODEL = "grok-4.3";
316
- function xai(params) {
317
- const defaultModel = params?.defaultModel || DEFAULT_MODEL;
318
- const baseURL = xaiBaseUrl();
319
- const capabilities = params?.capabilities ?? {
320
- vision: true,
321
- imageInToolResult: false
322
- };
323
- const baseCredentials = extractRuntimeCredentials(params);
324
- let runtimeCredentials = baseCredentials;
325
- const staticKey = params?.apiKey ?? process.env.XAI_API_KEY;
326
- const isOAuth = baseCredentials !== void 0 || !staticKey || isOAuthAccessToken(staticKey);
327
- /**
328
- * Build the openai-compat delegate for a resolved bearer. Cheap — the factory
329
- * only wires closures — so we re-create it per turn with the freshly resolved
330
- * (possibly refreshed) OAuth token rather than baking a stale key in once.
331
- */
332
- function delegateFor(apiKey) {
333
- return openaiCompat({
334
- name: "xai",
335
- apiKey,
336
- baseURL,
337
- defaultModel,
338
- capabilities,
339
- extraHeaders: params?.extraHeaders
340
- });
341
- }
342
- const skeleton = delegateFor("placeholder-resolved-at-stream");
343
- return {
344
- ...skeleton,
345
- name: "xai",
346
- meta: {
347
- ...skeleton.meta,
348
- defaultModel,
349
- isOAuth
350
- },
351
- async stream(options, callbacks) {
352
- return delegateFor(await resolveOAuthApiKey({
353
- provider: "xai",
354
- providerId: XAI_OAUTH_PROVIDER_ID,
355
- params: runtimeCredentials ? {
356
- ...params,
357
- ...runtimeCredentials
358
- } : params,
359
- envKey: "XAI_API_KEY",
360
- missingError: "No xAI credentials found. Set XAI_API_KEY or run `bun run auth --xai` first.",
361
- refreshError: (reason) => `xAI OAuth token refresh failed. Run \`bun run auth --xai\` again. ${reason}`
362
- }, {
363
- ...callbacks,
364
- async onOAuthRefresh(ctx) {
365
- if (ctx.source === "params") runtimeCredentials = {
366
- access: ctx.credentials.access,
367
- refresh: ctx.credentials.refresh,
368
- expires: ctx.credentials.expires
369
- };
370
- await callbacks.onOAuthRefresh?.(ctx);
371
- }
372
- })).stream(options, callbacks);
373
- }
374
- };
375
- }
376
- //#endregion
377
- export { createXaiOAuthProvider as n, generatePkce as r, xai as t };
320
+ export { generatePkce as a, xai_exports as i, createXaiOAuthProvider as n, xaiBaseUrl as r, XAI_OAUTH_PROVIDER_ID as t };
378
321
 
379
- //# sourceMappingURL=xai-Du6Wfnlb.js.map
322
+ //# sourceMappingURL=xai-CfmI5Y5k.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xai-CfmI5Y5k.js","names":[],"sources":["../src/chat/oauth-page/pkce.ts","../src/chat/oauth-page/xai.ts"],"sourcesContent":["/**\n * PKCE helper. Inlined here (rather than imported from pi-ai) because\n * `@earendil-works/pi-ai/oauth` does not re-export it, and we don't want\n * to reach into `node_modules/.../utils/oauth/pkce.js` — that's an\n * implementation-detail path that breaks on minor upstream rearrangements.\n *\n * Web Crypto API only. Works under Bun + Node 22+ without any node:crypto\n * import (matches pi-ai's own behavior). Output is base64url per RFC 7636.\n */\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = ''\n for (const byte of bytes)\n binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n}\n\nexport interface PkcePair {\n /** Random verifier used in the token-exchange step. */\n verifier: string\n /** SHA-256(verifier) sent on the authorize URL. */\n challenge: string\n}\n\nexport async function generatePkce(): Promise<PkcePair> {\n const verifierBytes = new Uint8Array(32)\n crypto.getRandomValues(verifierBytes)\n const verifier = base64UrlEncode(verifierBytes)\n\n const data = new TextEncoder().encode(verifier)\n const hashBuffer = await crypto.subtle.digest('SHA-256', data)\n const challenge = base64UrlEncode(new Uint8Array(hashBuffer))\n\n return { verifier, challenge }\n}\n","/**\n * xAI Grok OAuth flow (SuperGrok / X Premium+).\n *\n * xAI is **not** built into pi-ai, so — like Cursor — we implement the flow\n * here and register it with pi-ai's OAuth registry (`registerXaiOAuthProvider`)\n * so `getOAuthApiKey('xai-oauth', …)` resolves to it during lazy token refresh.\n *\n * Auth shape: OAuth 2.0 + PKCE with a loopback callback server, against xAI's\n * OIDC issuer (`https://auth.x.ai`). Differs from the Anthropic / Codex flows\n * (which use the shared `startCallbackServer`) on three points, so it gets its\n * own login impl rather than reusing that primitive:\n *\n * 1. The `redirect_uri` must be `http://127.0.0.1:56121/callback` verbatim\n * (xAI matches the registered loopback IP, not `localhost`).\n * 2. Endpoints come from OIDC discovery, not hard-coded constants.\n * 3. Token exchange + refresh are `application/x-www-form-urlencoded`\n * (the Anthropic flow posts JSON).\n *\n * The callback page still routes through {@link OAuthCallbackPageRenderer} so\n * the post-redirect HTML matches the rest of zidane's themed flows.\n *\n * Flow + constants adapted from the public reference implementations\n * (`stnly/pi-grok`, `BlockedPath/pi-xai-oauth`) and the Hermes Agent docs.\n * xAI's OAuth surface is unofficial/undocumented — re-verify the client id,\n * scopes, and callback port if login starts failing.\n */\n\nimport type {\n OAuthCredentials,\n OAuthLoginCallbacks,\n} from '@earendil-works/pi-ai/oauth'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { OAuthProviderInterface } from '../../providers/oauth-registry'\nimport type { OAuthCallbackPageRenderer } from './render'\nimport { createServer } from 'node:http'\nimport { generatePkce } from './pkce'\n\n/** pi-ai / zidane OAuth provider id. Also the credentials-file key. */\nexport const XAI_OAUTH_PROVIDER_ID = 'xai-oauth'\n\nconst DEFAULT_BASE_URL = 'https://api.x.ai/v1'\nconst ISSUER = 'https://auth.x.ai'\nconst DISCOVERY_URL = `${ISSUER}/.well-known/openid-configuration`\n/** Public client id used by the Grok CLI OAuth surface. */\nconst DEFAULT_CLIENT_ID = 'b1a00492-073a-47ea-816f-4c329264a828'\nconst DEFAULT_SCOPE = 'openid profile email offline_access grok-cli:access api:access'\n/** xAI matches the registered loopback IP exactly — `localhost` is rejected. */\nconst DEFAULT_CALLBACK_HOST = '127.0.0.1'\nconst DEFAULT_CALLBACK_PORT = 56121\nconst CALLBACK_PATH = '/callback'\nconst PROVIDER_NAME = 'xAI Grok'\n/** Refresh slightly early so requests don't race expiry. */\nconst REFRESH_SKEW_MS = 120_000\nconst CALLBACK_TIMEOUT_MS = 180_000\n\nfunction xaiOAuthClientId(): string {\n return process.env.PI_XAI_OAUTH_CLIENT_ID || DEFAULT_CLIENT_ID\n}\n\nfunction xaiOAuthScope(): string {\n return process.env.PI_XAI_OAUTH_SCOPE || DEFAULT_SCOPE\n}\n\nfunction xaiOAuthCallbackHost(): string {\n return process.env.PI_XAI_OAUTH_CALLBACK_HOST || DEFAULT_CALLBACK_HOST\n}\n\nfunction xaiOAuthCallbackPort(): number {\n const parsed = Number.parseInt(process.env.PI_XAI_OAUTH_CALLBACK_PORT || String(DEFAULT_CALLBACK_PORT), 10)\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_CALLBACK_PORT\n}\n\n/** Resolve the xAI API base URL (env override → default). */\nexport function xaiBaseUrl(): string {\n return (process.env.PI_XAI_BASE_URL || process.env.XAI_BASE_URL || DEFAULT_BASE_URL)\n .replace(/\\/+$/, '')\n}\n\ninterface XaiDiscovery {\n authorization_endpoint: string\n token_endpoint: string\n}\n\n/**\n * xAI OAuth credentials. Extends the base `{ access, refresh, expires }` with\n * the resolved `token_endpoint` so refresh doesn't need a second discovery\n * round-trip, plus the cached discovery doc for validation.\n */\nexport interface XaiOAuthCredentials extends OAuthCredentials {\n tokenEndpoint?: string\n discovery?: XaiDiscovery\n}\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = ''\n for (const b of bytes)\n binary += String.fromCharCode(b)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction randomToken(byteLength = 16): string {\n return base64Url(crypto.getRandomValues(new Uint8Array(byteLength)))\n}\n\n/**\n * Refuse any OIDC endpoint that isn't HTTPS on an xAI origin.\n *\n * The discovery doc is cached long-term in `credentials.json`. A single MITM\n * during initial login could otherwise pin a malicious `token_endpoint` that\n * receives every subsequent refresh token. Validating scheme + host keeps the\n * endpoint on `x.ai` / `*.x.ai`.\n */\nfunction validateEndpoint(value: string, field: string): string {\n let url: URL\n try {\n url = new URL(value)\n }\n catch {\n throw new Error(`xAI OAuth discovery returned an invalid ${field}: ${value}`)\n }\n if (url.protocol !== 'https:')\n throw new Error(`xAI OAuth ${field} must use HTTPS: ${value}`)\n const host = url.hostname.toLowerCase()\n if (host !== 'x.ai' && !host.endsWith('.x.ai'))\n throw new Error(`Refusing non-xAI OAuth ${field}: ${value}`)\n return url.toString()\n}\n\nasync function discover(): Promise<XaiDiscovery> {\n let response: Response\n try {\n response = await fetch(DISCOVERY_URL, {\n headers: { Accept: 'application/json' },\n signal: AbortSignal.timeout(15_000),\n })\n }\n catch (cause) {\n throw new Error(`xAI OIDC discovery failed: ${cause instanceof Error ? cause.message : String(cause)}`)\n }\n if (!response.ok)\n throw new Error(`xAI OIDC discovery returned ${response.status}`)\n\n const payload = await response.json() as Record<string, unknown>\n return {\n authorization_endpoint: validateEndpoint(String(payload.authorization_endpoint ?? ''), 'authorization_endpoint'),\n token_endpoint: validateEndpoint(String(payload.token_endpoint ?? ''), 'token_endpoint'),\n }\n}\n\ninterface CallbackResult {\n code?: string\n state?: string\n error?: string\n errorDescription?: string\n}\n\ninterface XaiCallbackServer {\n redirectUri: string\n waitForCallback: (timeoutMs: number) => Promise<CallbackResult>\n close: () => void\n}\n\n/**\n * Start the loopback callback server on `127.0.0.1:56121`. Falls back to an\n * OS-assigned port if 56121 is taken — xAI accepts any loopback port as long\n * as the `redirect_uri` we send on the authorize URL matches the listener.\n */\nasync function startXaiCallbackServer(renderPage: OAuthCallbackPageRenderer): Promise<XaiCallbackServer> {\n const callbackHost = xaiOAuthCallbackHost()\n const callbackPort = xaiOAuthCallbackPort()\n let settle: ((value: CallbackResult) => void) | undefined\n let settled = false\n const callbackPromise = new Promise<CallbackResult>((resolve) => {\n settle = (value) => {\n if (settled)\n return\n settled = true\n resolve(value)\n }\n })\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n try {\n // accounts.x.ai may issue a CORS preflight against the loopback listener.\n const origin = req.headers.origin\n if (origin === 'https://accounts.x.ai' || origin === 'https://auth.x.ai') {\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS')\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type')\n res.setHeader('Access-Control-Allow-Private-Network', 'true')\n res.setHeader('Vary', 'Origin')\n }\n if (req.method === 'OPTIONS') {\n res.statusCode = 204\n res.end()\n return\n }\n\n const url = new URL(req.url ?? '/', `http://${callbackHost}`)\n if (url.pathname !== CALLBACK_PATH) {\n res.statusCode = 404\n res.end('Not found')\n return\n }\n\n const result: CallbackResult = {\n code: url.searchParams.get('code') ?? undefined,\n state: url.searchParams.get('state') ?? undefined,\n error: url.searchParams.get('error') ?? undefined,\n errorDescription: url.searchParams.get('error_description') ?? undefined,\n }\n\n res.statusCode = result.error ? 400 : 200\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.end(renderPage(result.error\n ? {\n kind: 'error',\n provider: PROVIDER_NAME,\n message: `${PROVIDER_NAME} authentication did not complete.`,\n details: result.errorDescription ?? result.error,\n }\n : {\n kind: 'success',\n provider: PROVIDER_NAME,\n message: 'xAI authentication completed. You can close this window.',\n }))\n settle?.(result)\n }\n catch {\n res.statusCode = 500\n res.end('Internal error')\n }\n })\n\n const listen = (port: number) => new Promise<number>((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, callbackHost, () => {\n server.removeListener('error', reject)\n const addr = server.address()\n resolve(typeof addr === 'object' && addr ? addr.port : port)\n })\n })\n\n let actualPort: number\n try {\n actualPort = await listen(callbackPort)\n }\n catch {\n actualPort = await listen(0)\n }\n\n return {\n redirectUri: `http://${callbackHost}:${actualPort}${CALLBACK_PATH}`,\n waitForCallback: timeoutMs => Promise.race([\n callbackPromise,\n new Promise<CallbackResult>(resolve =>\n setTimeout(\n resolve,\n timeoutMs,\n { error: 'timeout', errorDescription: 'Timed out waiting for the xAI OAuth callback.' },\n )),\n ]),\n close: () => {\n try { server.close() }\n catch { /* already closed */ }\n },\n }\n}\n\nfunction expiryFromPayload(payload: Record<string, unknown>): number {\n const expiresIn = typeof payload.expires_in === 'number'\n ? payload.expires_in\n : Number(payload.expires_in ?? 3600)\n return Date.now() + expiresIn * 1000 - REFRESH_SKEW_MS\n}\n\nasync function exchangeCode(\n tokenEndpoint: string,\n code: string,\n redirectUri: string,\n verifier: string,\n discovery: XaiDiscovery,\n): Promise<XaiOAuthCredentials> {\n const clientId = xaiOAuthClientId()\n const response = await fetch(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: clientId,\n code,\n redirect_uri: redirectUri,\n code_verifier: verifier,\n }),\n signal: AbortSignal.timeout(30_000),\n })\n if (!response.ok)\n throw new Error(`xAI token exchange failed: ${response.status} ${await response.text().catch(() => '')}`)\n\n const payload = await response.json() as Record<string, unknown>\n const access = String(payload.access_token ?? '')\n const refresh = String(payload.refresh_token ?? '')\n if (!access)\n throw new Error('xAI token exchange did not return an access_token.')\n if (!refresh)\n throw new Error('xAI token exchange did not return a refresh_token.')\n\n return { access, refresh, expires: expiryFromPayload(payload), tokenEndpoint, discovery }\n}\n\nexport async function loginXai(\n renderPage: OAuthCallbackPageRenderer,\n callbacks: OAuthLoginCallbacks,\n): Promise<XaiOAuthCredentials> {\n const discovery = await discover()\n const { verifier, challenge } = await generatePkce()\n const state = randomToken()\n const nonce = randomToken()\n const server = await startXaiCallbackServer(renderPage)\n\n try {\n const authUrl = new URL(discovery.authorization_endpoint)\n authUrl.searchParams.set('response_type', 'code')\n authUrl.searchParams.set('client_id', xaiOAuthClientId())\n authUrl.searchParams.set('redirect_uri', server.redirectUri)\n authUrl.searchParams.set('scope', xaiOAuthScope())\n authUrl.searchParams.set('code_challenge', challenge)\n authUrl.searchParams.set('code_challenge_method', 'S256')\n authUrl.searchParams.set('state', state)\n authUrl.searchParams.set('nonce', nonce)\n // Opt into xAI's generic OAuth plan tier (SuperGrok / X Premium+).\n authUrl.searchParams.set('plan', 'generic')\n authUrl.searchParams.set('referrer', 'zidane')\n\n callbacks.onAuth({\n url: authUrl.toString(),\n instructions: `Sign in to xAI and approve access. If the browser is on another machine, the callback listener is ${server.redirectUri}.`,\n })\n\n const result = await server.waitForCallback(CALLBACK_TIMEOUT_MS)\n if (result.error)\n throw new Error(result.errorDescription ?? result.error)\n if (result.state !== state)\n throw new Error('xAI OAuth state mismatch — possible CSRF. Please retry.')\n if (!result.code)\n throw new Error('xAI OAuth callback did not include an authorization code.')\n\n callbacks.onProgress?.('Exchanging authorization code for tokens...')\n return await exchangeCode(discovery.token_endpoint, result.code, server.redirectUri, verifier, discovery)\n }\n finally {\n server.close()\n }\n}\n\nexport async function refreshXaiToken(credentials: OAuthCredentials): Promise<XaiOAuthCredentials> {\n const xai = credentials as XaiOAuthCredentials\n const clientId = xaiOAuthClientId()\n if (!credentials.refresh)\n throw new Error('xAI credentials are missing a refresh token — re-login required.')\n\n const tokenEndpoint = xai.tokenEndpoint\n ?? xai.discovery?.token_endpoint\n ?? (await discover()).token_endpoint\n validateEndpoint(tokenEndpoint, 'token_endpoint')\n\n const response = await fetch(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: clientId,\n refresh_token: credentials.refresh,\n }),\n signal: AbortSignal.timeout(30_000),\n })\n if (!response.ok)\n throw new Error(`xAI token refresh failed: ${response.status} ${await response.text().catch(() => '')}`)\n\n const payload = await response.json() as Record<string, unknown>\n const access = String(payload.access_token ?? '')\n if (!access)\n throw new Error('xAI token refresh did not return an access_token.')\n\n return {\n ...xai,\n access,\n // xAI may omit a rotated refresh token — keep the existing one.\n refresh: String(payload.refresh_token ?? credentials.refresh),\n expires: expiryFromPayload(payload),\n tokenEndpoint,\n }\n}\n\n/**\n * Build an xAI `OAuthProviderInterface`. Shape matches Anthropic / Codex /\n * Cursor so it drops into `BUILTIN_PROVIDERS` and `src/auth.ts` unchanged.\n *\n * `usesCallbackServer: true` — the loopback flow has a real callback server,\n * so the TUI doesn't need to prompt for a manual code paste.\n */\nexport function createXaiOAuthProvider(renderPage: OAuthCallbackPageRenderer): OAuthProviderInterface {\n return {\n id: XAI_OAUTH_PROVIDER_ID,\n name: 'xAI Grok (SuperGrok / X Premium+)',\n usesCallbackServer: true,\n login: callbacks => loginXai(renderPage, callbacks),\n refreshToken: refreshXaiToken,\n getApiKey: credentials => credentials.access,\n }\n}\n"],"mappings":";;;;;;;;;;;;AAUA,SAAS,gBAAgB,OAA2B;CAClD,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OACjB,UAAU,OAAO,aAAa,IAAI;CACpC,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,MAAM,EAAE;AAC9E;AASA,eAA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ACN,OAAO,MAAM;CACf;AACF;AAEA,eAAsB,gBAAgB,aAA6D;CACjG,MAAM,MAAM;CACZ,MAAM,WAAW,iBAAiB;CAClC,IAAI,CAAC,YAAY,SACf,MAAM,IAAI,MAAM,kEAAkE;CAEpF,MAAM,gBAAgB,IAAI,iBACrB,IAAI,WAAW,mBACd,MAAM,SAAS,EAAA,CAAG;CACxB,iBAAiB,eAAe,gBAAgB;CAEhD,MAAM,WAAW,MAAM,MAAM,eAAe;EAC1C,QAAQ;EACR,SAAS;GAAE,gBAAgB;GAAqC,UAAU;EAAmB;EAC7F,MAAM,IAAI,gBAAgB;GACxB,YAAY;GACZ,WAAW;GACX,eAAe,YAAY;EAC7B,CAAC;EACD,QAAQ,YAAY,QAAQ,GAAM;CACpC,CAAC;CACD,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,6BAA6B,SAAS,OAAO,GAAG,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,EAAE,GAAG;CAEzG,MAAM,UAAU,MAAM,SAAS,KAAK;CACpC,MAAM,SAAS,OAAO,QAAQ,gBAAgB,EAAE;CAChD,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,mDAAmD;CAErE,OAAO;EACL,GAAG;EACH;EAEA,SAAS,OAAO,QAAQ,iBAAiB,YAAY,OAAO;EAC5D,SAAS,kBAAkB,OAAO;EAClC;CACF;AACF;;;;;;;;AASA,SAAgB,uBAAuB,YAA+D;CACpG,OAAO;EACL,IAAI;EACJ,MAAM;EACN,oBAAoB;EACpB,QAAO,cAAa,SAAS,YAAY,SAAS;EAClD,cAAc;EACd,YAAW,gBAAe,YAAY;CACxC;AACF"}
package/docs/RESTATE.md CHANGED
@@ -699,6 +699,13 @@ const agent = createAgent({
699
699
  - **`createSandboxContext`** re-attaches by handle id: its handle id IS the sandbox id, so a handle from a prior invocation routes operations to the same sandbox even though this instance never ran `spawn()`. Pair with the provider's reconnect option (`createDaytonaProvider({ sandboxId })`).
700
700
  - **`createDaytonaProvider({ ownAttached: true })`** — by default an attached (`sandboxId`) sandbox is treated as externally owned and left running on `destroy()`. Set `ownAttached` when the *host* owns it across invocations so `destroy()` applies `onDestroy` (stop / archive / delete). Spawn-time failures still never delete a pre-existing attached sandbox.
701
701
  - **`zidane/contexts/sandbox` subpath** — import `createSandboxContext` from here (not the `zidane/contexts` barrel) on workerd/edge: this entry's graph is node-free, so it doesn't drag `createProcessContext` → `node:child_process` into the bundle.
702
+ - **`@daytona/sdk` needs a root `tslib` override.** It is a peer dependency, so *you* install it — and it declares no `tslib` dependency of its own while reaching AWS SDK v3 through `@aws-sdk/client-s3`. A stale `@aws-crypto` v3/v4 floor (`tslib: ^1.11.1`) can win the hoist, and the AWS SDK's initializer helpers then resolve against tslib 1.x, which lacks them — `import('@daytona/sdk')` fails with `Export named '__runInitializers' not found`. npm/bun overrides are **root-only** and are not inherited from zidane, so add this to your own `package.json`:
703
+
704
+ ```json
705
+ { "overrides": { "tslib": "^2.8.1" } }
706
+ ```
707
+
708
+ Safe because tslib 2 is a superset of the v1 helper set; the `^1.11.1` requirements are stale floors from packages AWS has since moved off. `createDaytonaProvider` reports the underlying load error (and names tslib) rather than claiming the package is missing.
702
709
 
703
710
  ### Streaming on fresh vs resumed invocations
704
711
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zidane",
3
- "version": "6.5.2",
3
+ "version": "6.5.3",
4
4
  "description": "an agent that goes straight to the goal",
5
5
  "type": "module",
6
6
  "private": false,
@@ -267,15 +267,16 @@
267
267
  "typecheck": "tsc --noEmit"
268
268
  },
269
269
  "dependencies": {
270
- "@earendil-works/pi-ai": "0.82.1",
270
+ "@earendil-works/pi-ai": "0.84.2",
271
271
  "chalk": "^5.6.2",
272
272
  "fzf": "^0.5.2",
273
273
  "hookable": "^6.1.1",
274
- "marked": "18.0.4"
274
+ "marked": "18.0.9"
275
275
  },
276
276
  "overrides": {
277
- "@types/react": "19.2.15",
278
- "@types/react-dom": "19.2.3"
277
+ "@types/react": "19.2.18",
278
+ "@types/react-dom": "19.2.3",
279
+ "tslib": "^2.8.1"
279
280
  },
280
281
  "peerDependencies": {
281
282
  "@anthropic-ai/bedrock-sdk": ">=0.32.0",
@@ -327,25 +328,25 @@
327
328
  },
328
329
  "devDependencies": {
329
330
  "@antfu/eslint-config": "^8.2.0",
330
- "@anthropic-ai/bedrock-sdk": "^0.32.0",
331
+ "@anthropic-ai/bedrock-sdk": "^0.32.4",
331
332
  "@anthropic-ai/sdk": "^0.104.2",
332
333
  "@daytona/sdk": "^0.187.0",
333
- "@modelcontextprotocol/sdk": "^1.29.0",
334
- "@opentui/core": "^0.5.1",
335
- "@opentui/core-darwin-x64": "^0.5.1",
336
- "@opentui/core-linux-arm64": "^0.5.1",
337
- "@opentui/core-linux-x64": "^0.5.1",
338
- "@opentui/react": "^0.5.1",
339
- "@restatedev/restate-sdk": "^1.11.0",
334
+ "@modelcontextprotocol/sdk": "^1.30.0",
335
+ "@opentui/core": "^0.5.3",
336
+ "@opentui/core-darwin-x64": "^0.5.3",
337
+ "@opentui/core-linux-arm64": "^0.5.3",
338
+ "@opentui/core-linux-x64": "^0.5.3",
339
+ "@opentui/react": "^0.5.3",
340
+ "@restatedev/restate-sdk": "^1.16.5",
340
341
  "@types/bun": "^1.3.13",
341
342
  "@types/dockerode": "^4.0.1",
342
- "@types/react": "19.2.15",
343
+ "@types/react": "19.2.18",
343
344
  "bumpp": "^11.0.1",
344
345
  "dockerode": "^5.0.0",
345
- "e2b": "^2.27.1",
346
- "eslint": "^10.2.1",
346
+ "e2b": "^2.39.0",
347
+ "eslint": "^10.8.1",
347
348
  "jiti": "^2.6.1",
348
- "react": "^19.2.7",
349
+ "react": "^19.2.8",
349
350
  "tsdown": "^0.22.0",
350
351
  "typescript": "~6.0.3",
351
352
  "unrun": "^0.3.1"
@@ -1 +0,0 @@
1
- {"version":3,"file":"oauth-bkEOybqm.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,CA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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"stdio-loader-BN1l1ZAG.js","names":["spawn","nodeSpawn","spawnSync","nodeSpawnSync","spawn"],"sources":["../scripts/cross-spawn-shim.mjs","../node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"],"sourcesContent":["/**\n * Build-time replacement for the userland process-spawn helper that the\n * MCP SDK's stdio transport depends on. Injected by tsdown via the\n * rolldown alias plugin in `tsdown.config.ts`.\n *\n * Why this exists\n *\n * The upstream spawn helper is CJS and its first line dynamically resolves\n * Node's process-spawn built-in via a bare specifier. When a downstream\n * consumer re-bundles zidane as ESM (esbuild / Vite / tsup with\n * `format: 'esm'` and Node built-ins not externalized), that bare\n * resolution gets wrapped in esbuild's `__require` shim and throws at\n * runtime — every stdio MCP server fails to launch.\n *\n * Aliasing the helper to this file at zidane's own build step replaces\n * the offending bare resolution with explicit `node:`-prefixed imports.\n * Downstream bundlers recognize the `node:` prefix as a Node built-in\n * and externalize it automatically. The upstream MCP SDK is unmodified.\n *\n * Tradeoff\n *\n * The replaced helper does two extra things vs. raw spawn:\n * 1. Windows `.cmd` / `.bat` / `.ps1` resolution via PATHEXT + cmd.exe\n * shelling. Compensated below with `shell: true` on Win32, which\n * routes through cmd.exe and handles the common `npx` / `pnpm` /\n * `yarn` shims.\n * 2. Synthesizes a clean ENOENT error event for missing commands.\n * `node:child_process.spawn` already emits a perfectly usable\n * `error` event with `code === 'ENOENT'`, which the MCP SDK's stdio\n * transport forwards to `onerror`. Functionally equivalent.\n *\n * Net: zero behavioural change on POSIX, near-identical on Windows for\n * MCP-style stdio invocations.\n */\n\nimport { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from 'node:child_process'\nimport process from 'node:process'\n\nconst IS_WIN32 = process.platform === 'win32'\n\nfunction withWin32Shell(options) {\n // Only opt into shell mode on Windows, and only when the caller hasn't\n // explicitly disabled it. POSIX never needs the shell wrapper — args\n // would have to be re-quoted (changes argv semantics) and trap/`set -e`\n // behaviour shifts in subtle ways.\n if (!IS_WIN32)\n return options\n if (options && options.shell !== undefined)\n return options\n return { ...(options ?? {}), shell: true }\n}\n\nexport function spawn(command, args, options) {\n return nodeSpawn(command, args, withWin32Shell(options))\n}\n\nexport function spawnSync(command, args, options) {\n return nodeSpawnSync(command, args, withWin32Shell(options))\n}\n\n// Match cross-spawn's CommonJS interop shape so existing imports keep\n// working byte-for-byte:\n// - default import: `import spawn from 'cross-spawn'` (SDK uses this)\n// - named import: `import { spawn, sync } from 'cross-spawn'`\n// - require pattern: `const cs = require('cross-spawn'); cs.sync(...)`\nspawn.spawn = spawn\nspawn.sync = spawnSync\n\nexport const sync = spawnSync\nexport default spawn\n","import spawn from 'cross-spawn';\nimport process from 'node:process';\nimport { PassThrough } from 'node:stream';\nimport { ReadBuffer, serializeMessage } from '../shared/stdio.js';\n/**\n * Environment variables to inherit by default, if an environment is not explicitly given.\n */\nexport const DEFAULT_INHERITED_ENV_VARS = process.platform === 'win32'\n ? [\n 'APPDATA',\n 'HOMEDRIVE',\n 'HOMEPATH',\n 'LOCALAPPDATA',\n 'PATH',\n 'PROCESSOR_ARCHITECTURE',\n 'SYSTEMDRIVE',\n 'SYSTEMROOT',\n 'TEMP',\n 'USERNAME',\n 'USERPROFILE',\n 'PROGRAMFILES'\n ]\n : /* list inspired by the default env inheritance of sudo */\n ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];\n/**\n * Returns a default environment object including only environment variables deemed safe to inherit.\n */\nexport function getDefaultEnvironment() {\n const env = {};\n for (const key of DEFAULT_INHERITED_ENV_VARS) {\n const value = process.env[key];\n if (value === undefined) {\n continue;\n }\n if (value.startsWith('()')) {\n // Skip functions, which are a security risk.\n continue;\n }\n env[key] = value;\n }\n return env;\n}\n/**\n * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.\n *\n * This transport is only available in Node.js environments.\n */\nexport class StdioClientTransport {\n constructor(server) {\n this._readBuffer = new ReadBuffer();\n this._stderrStream = null;\n this._serverParams = server;\n if (server.stderr === 'pipe' || server.stderr === 'overlapped') {\n this._stderrStream = new PassThrough();\n }\n }\n /**\n * Starts the server process and prepares to communicate with it.\n */\n async start() {\n if (this._process) {\n throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n }\n return new Promise((resolve, reject) => {\n this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], {\n // merge default env with server env because mcp server needs some env vars\n env: {\n ...getDefaultEnvironment(),\n ...this._serverParams.env\n },\n stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],\n shell: false,\n windowsHide: process.platform === 'win32',\n cwd: this._serverParams.cwd\n });\n this._process.on('error', error => {\n reject(error);\n this.onerror?.(error);\n });\n this._process.on('spawn', () => {\n resolve();\n });\n this._process.on('close', _code => {\n this._process = undefined;\n this.onclose?.();\n });\n this._process.stdin?.on('error', error => {\n this.onerror?.(error);\n });\n this._process.stdout?.on('data', chunk => {\n this._readBuffer.append(chunk);\n this.processReadBuffer();\n });\n this._process.stdout?.on('error', error => {\n this.onerror?.(error);\n });\n if (this._stderrStream && this._process.stderr) {\n this._process.stderr.pipe(this._stderrStream);\n }\n });\n }\n /**\n * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to \"pipe\" or \"overlapped\".\n *\n * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to\n * attach listeners before the start method is invoked. This prevents loss of any early\n * error output emitted by the child process.\n */\n get stderr() {\n if (this._stderrStream) {\n return this._stderrStream;\n }\n return this._process?.stderr ?? null;\n }\n /**\n * The child process pid spawned by this transport.\n *\n * This is only available after the transport has been started.\n */\n get pid() {\n return this._process?.pid ?? null;\n }\n processReadBuffer() {\n while (true) {\n try {\n const message = this._readBuffer.readMessage();\n if (message === null) {\n break;\n }\n this.onmessage?.(message);\n }\n catch (error) {\n this.onerror?.(error);\n }\n }\n }\n async close() {\n if (this._process) {\n const processToClose = this._process;\n this._process = undefined;\n const closePromise = new Promise(resolve => {\n processToClose.once('close', () => {\n resolve();\n });\n });\n try {\n processToClose.stdin?.end();\n }\n catch {\n // ignore\n }\n await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n if (processToClose.exitCode === null) {\n try {\n processToClose.kill('SIGTERM');\n }\n catch {\n // ignore\n }\n await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n }\n if (processToClose.exitCode === null) {\n try {\n processToClose.kill('SIGKILL');\n }\n catch {\n // ignore\n }\n }\n }\n this._readBuffer.clear();\n }\n send(message) {\n return new Promise(resolve => {\n if (!this._process?.stdin) {\n throw new Error('Not connected');\n }\n const json = serializeMessage(message);\n if (this._process.stdin.write(json)) {\n resolve();\n }\n else {\n this._process.stdin.once('drain', resolve);\n }\n });\n }\n}\n//# sourceMappingURL=stdio.js.map"],"x_google_ignoreList":[1],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,WAAW,QAAQ,aAAa;AAEtC,SAAS,eAAe,SAAS;CAK/B,IAAI,CAAC,UACH,OAAO;CACT,IAAI,WAAW,QAAQ,UAAU,KAAA,GAC/B,OAAO;CACT,OAAO;EAAE,GAAI,WAAW,CAAC;EAAI,OAAO;CAAK;AAC3C;AAEA,SAAgBA,QAAM,SAAS,MAAM,SAAS;CAC5C,OAAOC,MAAU,SAAS,MAAM,eAAe,OAAO,CAAC;AACzD;AAEA,SAAgBC,YAAU,SAAS,MAAM,SAAS;CAChD,OAAOC,UAAc,SAAS,MAAM,eAAe,OAAO,CAAC;AAC7D;AAOA,QAAM,QAAQH;AACd,QAAM,OAAOE;;;;;;AC3Db,MAAa,6BAA6B,QAAQ,aAAa,UACzD;CACE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ,IAEI;CAAC;CAAQ;CAAW;CAAQ;CAAS;CAAQ;AAAM;;;;AAI3D,SAAgB,wBAAwB;CACpC,MAAM,MAAM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