zidane 5.13.9 → 5.13.10

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 (52) hide show
  1. package/dist/acp-cli.js +2 -2
  2. package/dist/acp.d.ts +2 -2
  3. package/dist/{agent-D7ZL8B2X.d.ts → agent-w6htlFlx.d.ts} +2 -2
  4. package/dist/agent-w6htlFlx.d.ts.map +1 -0
  5. package/dist/{auth-BlZUM4yl.js → auth-nA0ZMTbM.js} +21 -8
  6. package/dist/auth-nA0ZMTbM.js.map +1 -0
  7. package/dist/chat/pure.d.ts +3 -3
  8. package/dist/chat.d.ts +6 -6
  9. package/dist/chat.js +2 -2
  10. package/dist/contexts/daytona.d.ts +1 -1
  11. package/dist/contexts/e2b.d.ts +1 -1
  12. package/dist/eval.d.ts +1 -1
  13. package/dist/headless.d.ts +1 -1
  14. package/dist/{index-BsyPeCSL.d.ts → index-BH0lvT7N.d.ts} +2 -2
  15. package/dist/{index-BsyPeCSL.d.ts.map → index-BH0lvT7N.d.ts.map} +1 -1
  16. package/dist/{index-CDcQW-2S.d.ts → index-C4sPfyg6.d.ts} +2 -2
  17. package/dist/{index-CDcQW-2S.d.ts.map → index-C4sPfyg6.d.ts.map} +1 -1
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +1 -1
  20. package/dist/{logger-DItaCwPw.d.ts → logger-MCqSKpby.d.ts} +2 -2
  21. package/dist/{logger-DItaCwPw.d.ts.map → logger-MCqSKpby.d.ts.map} +1 -1
  22. package/dist/mcp.d.ts +1 -1
  23. package/dist/output/stream-json.d.ts +2 -2
  24. package/dist/output/terminal.d.ts +2 -2
  25. package/dist/presets.d.ts +2 -2
  26. package/dist/{providers-CSE9IJ8W.js → providers-OBIysrMe.js} +25 -10
  27. package/dist/providers-OBIysrMe.js.map +1 -0
  28. package/dist/providers.d.ts +1 -1
  29. package/dist/providers.js +1 -1
  30. package/dist/restate.d.ts +1 -1
  31. package/dist/session/sqlite.d.ts +1 -1
  32. package/dist/session.d.ts +1 -1
  33. package/dist/skills.d.ts +2 -2
  34. package/dist/{tool-formatters-CNSMadtp.d.ts → tool-formatters-C7N1Pb1q.d.ts} +7 -2
  35. package/dist/tool-formatters-C7N1Pb1q.d.ts.map +1 -0
  36. package/dist/tools/fetch-url.d.ts +1 -1
  37. package/dist/tools/web-search.d.ts +1 -1
  38. package/dist/tools.d.ts +2 -2
  39. package/dist/{transcript-anchors-D4qAelMs.js → transcript-anchors-BrweEBIo.js} +2 -2
  40. package/dist/{transcript-anchors-D4qAelMs.js.map → transcript-anchors-BrweEBIo.js.map} +1 -1
  41. package/dist/{transcript-anchors-EG-SmZRu.d.ts → transcript-anchors-CJsVfcaq.d.ts} +4 -4
  42. package/dist/{transcript-anchors-EG-SmZRu.d.ts.map → transcript-anchors-CJsVfcaq.d.ts.map} +1 -1
  43. package/dist/tui.d.ts +3 -3
  44. package/dist/tui.js +2 -2
  45. package/dist/{turn-operations-DwtWRYr1.d.ts → turn-operations-BtyfLdPi.d.ts} +3 -3
  46. package/dist/{turn-operations-DwtWRYr1.d.ts.map → turn-operations-BtyfLdPi.d.ts.map} +1 -1
  47. package/dist/types.d.ts +2 -2
  48. package/package.json +2 -2
  49. package/dist/agent-D7ZL8B2X.d.ts.map +0 -1
  50. package/dist/auth-BlZUM4yl.js.map +0 -1
  51. package/dist/providers-CSE9IJ8W.js.map +0 -1
  52. package/dist/tool-formatters-CNSMadtp.d.ts.map +0 -1
package/dist/acp-cli.js CHANGED
@@ -3,9 +3,9 @@ import { b as openaiCompat } from "./messages-DEsLGBB9.js";
3
3
  import { n as createSandboxContext, r as createProcessContext } from "./contexts-DHi8LPCp.js";
4
4
  import { i as basic_default } from "./presets-HDIxliiq.js";
5
5
  import "./session-BDWZZaYa.js";
6
- import { f as arcee, i as openai, l as cerebras, p as anthropic, r as openrouter, t as xai, u as baseten } from "./providers-CSE9IJ8W.js";
6
+ import { f as arcee, i as openai, l as cerebras, p as anthropic, r as openrouter, t as xai, u as baseten } from "./providers-OBIysrMe.js";
7
7
  import { d as buildStartLocalOptions, f as parseStartArgValues, m as startProviderNames, p as startLocalArgOptions, t as runAcpStdioServer, u as StartUsageError } from "./acp-BRQvvdnO.js";
8
- import { a as readCredentials, b as modelsForDescriptor, i as credentialsPath, n as resolveStorageDirs, p as credKeyOf, t as detectAuth, u as BUILTIN_PROVIDERS } from "./auth-BlZUM4yl.js";
8
+ import { a as readCredentials, b as modelsForDescriptor, i as credentialsPath, n as resolveStorageDirs, p as credKeyOf, t as detectAuth, u as BUILTIN_PROVIDERS } from "./auth-nA0ZMTbM.js";
9
9
  import { createDaytonaProvider } from "./contexts/daytona.js";
10
10
  import { createDockerContext } from "./contexts/docker.js";
11
11
  import { createE2BProvider } from "./contexts/e2b.js";
package/dist/acp.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { B as Session, En as PromptPart, Fn as SessionContentBlock, T as ToolDef, U as SessionStore, an as AgentBehavior, i as AgentOptions, qn as ToolResultContent, t as Agent, tr as TurnUsage, yn as McpServerConfig, yt as Provider } from "./agent-D7ZL8B2X.js";
1
+ import { B as Session, En as PromptPart, Fn as SessionContentBlock, T as ToolDef, U as SessionStore, an as AgentBehavior, i as AgentOptions, qn as ToolResultContent, t as Agent, tr as TurnUsage, yn as McpServerConfig, yt as Provider } from "./agent-w6htlFlx.js";
2
2
  import { c as ExecutionContext } from "./types-Bs2oY7Ux.js";
3
- import { t as Preset } from "./index-CDcQW-2S.js";
3
+ import { t as Preset } from "./index-C4sPfyg6.js";
4
4
  import { Readable, Writable } from "node:stream";
5
5
 
6
6
  //#region src/acp/types.d.ts
@@ -3347,7 +3347,7 @@ interface OpenRouterParams {
3347
3347
  * Provider capability flags. OpenRouter itself is a router — whether vision,
3348
3348
  * native image-in-tool-result, or document/PDF input are supported depends on
3349
3349
  * the downstream model. Default: `{ vision: true, imageInToolResult: false,
3350
- * documents: true }` — matches the default `anthropic/claude-sonnet-4-6` model
3350
+ * documents: true }` — matches the default `anthropic/claude-sonnet-4.6` model
3351
3351
  * (vision + PDF capable; OpenRouter forwards the OpenAI `file` content part to
3352
3352
  * Anthropic/OpenAI/Gemini routes).
3353
3353
  *
@@ -6613,4 +6613,4 @@ declare function createAgent({
6613
6613
  }: AgentOptions): Agent;
6614
6614
  //#endregion
6615
6615
  export { EnsureToolResultPairingOptions as $, ToolResultVideoContent as $n, planBasetenReasoning as $t, hashContent as A, RepeatGuardToolMatcher as An, SchemaSanitizeOptions as At, Session as B, SpawnHookContext as Bn, classifyOpenAICompatError as Bt, wrapDiscoveredMcpTools as C, PromptAudioPart as Cn, ContextMcpGroup as Cr, TokenCountPayload as Ct, ReadStateEntry as D, PromptTextPart as Dn, TurnResult as Dt, ToolMap as E, PromptPart as En, buildContextBreakdown as Er, ToolSpec as Et, SkillDiagnostic as F, SessionContentBlock as Fn, OpenRouterParams as Ft, demoteStaleRunningStatus as G, ToolOutcome as Gn, LocalParams as Gt, SessionRun as H, ThinkingLevel as Hn, openaiCompat as Ht, SkillResource as I, SessionEndStatus as In, openrouter as It, createRemoteStore as J, ToolResultDocumentContent as Jn, cursor as Jt, loadSession as K, ToolResultAudioContent as Kn, local as Kt, SkillSource as L, SessionHookContext as Ln, OpenAICompatAuthHeader as Lt, resolveReadStateMap as M, ResolveContentRefBlock as Mn, SchemaSanitizeResult as Mt, ShellInterpolationApproval as N, RetryConfig as Nn, sanitizeToolSchema as Nt, ReadStateMap as O, PromptVideoPart as On, XaiParams as Ot, SkillConfig as P, RunHookMap as Pn, sanitizeToolSpecs as Pt, createFileMapStore as Q, ToolResultTextContent as Qn, baseten as Qt, SkillsConfig as R, SessionMessage as Rn, OpenAICompatHttpError as Rt, resultToString as S, OAuthRefreshHookContext as Sn, ContextItem as Sr, StreamOptions as St, ToolDef as T, PromptImagePart as Tn, ContextUsageSplit as Tr, ToolResult as Tt, SessionStore as U, ToolBatchExecutor as Un, OpenAIParams as Ut, SessionData as V, StreamHookContext as Vn, mapOAIFinishReason as Vt, createSession as W, ToolHookContext as Wn, openai as Wt, FileMapAdapter as X, ToolResultImageContent as Xn, cerebras as Xt, createMemoryStore as Y, ToolResultDocumentRefContent as Yn, CerebrasParams as Yt, FileMapStoreOptions as Z, ToolResultImageRefContent as Zn, BasetenParams as Zt, attachStderrWarnPump as _, DedupHasher as _n, ContextBreakdown as _r, toOpenAI as _t, McpConnector as a, AgentBehavior as an, AgentAbortedError as ar, TOOL_USE_INTERRUPTED_MARKER as at, normalizeMcpBlocks as b, McpToolHookContext as bn, ContextCategoryId as br, ProviderCapabilities as bt, createAgent as c, AgentStats as cn, AgentProviderError as cr, autoDetectAndConvert as ct, DeactivationReason as d, ChildRunStats as dn, CONTEXT_EXCEEDED_MESSAGE_PATTERNS as dr, ensureToolResultPairing as dt, ArceeParams as en, TurnFinishReason as er, ORPHANED_TOOL_RESULT_MARKER as et, SkillActivationState as f, CompactEndHookContext as fn, ClassifiedError as fr, filterUnresolvedToolUses as ft, McpConnection as g, DEFAULT_AGENT_CLOCK as gn, toTypedError as gr, toAnthropic as gt, ConnectMcpServersOptions as h, CompactStartHookContext as hn, matchesContextExceeded as hr, remintDuplicateToolCallIds as ht, AgentOptions as i, applyAnthropicCacheBreakpoints as in, toolResultToText as ir, SYNTHETIC_TOOL_RESULT_PLACEHOLDER as it, readStateKey as j, ResolveContentRef as jn, SchemaSanitizeProfile as jt, getReadState as k, RepeatGuardConfig as kn, xai as kt, ActivationVia as l, AutoCompact as ln, AgentToolNotAllowedError as lr, detectTurnInterruption as lt, createSkillActivationState as m, CompactHookContext as mn, errorMessage as mr, fromOpenAI as mt, AgentHookMap as n, AnthropicParams as nn, toolOutputBudgetByteLength as nr, PairingRepairMode as nt, McpToolMeta as o, AgentClock as on, AgentBudgetExceededError as or, ToWireMessagesOptions as ot, SkillActivationStateOptions as p, CompactFunction as pn, ClassifiedErrorKind as pr, fromAnthropic as pt, RemoteStoreOptions as q, ToolResultContent as qn, CursorParams as qt, AgentHooks as r, anthropic as rn, toolOutputByteLength as rr, RemintResult as rt, McpToolWrap as s, AgentRunOptions as sn, AgentContextExceededError as sr, TurnInterruptionState as st, Agent as t, arcee as tn, TurnUsage as tr, PairingRepair as tt, ActiveSkill as u, AutoCompactConfig as un, AgentToolPairingError as ur, ensureEndsWithUserMessage as ut, connectMcpServers as v, DedupToolConfig as vn, ContextBreakdownOptions as vr, toWireMessages as vt, ToolContext as w, PromptDocumentPart as wn, ContextSnapshot as wr, ToolCall as wt, normalizeMcpServers as x, McpToolSchema as xn, ContextExactCounts as xr, StreamCallbacks as xt, deriveMcpToolMeta as y, McpServerConfig as yn, ContextCategory as yr, Provider as yt, CreateSessionOptions as z, SessionTurn as zn, OpenAICompatParams as zt };
6616
- //# sourceMappingURL=agent-D7ZL8B2X.d.ts.map
6616
+ //# sourceMappingURL=agent-w6htlFlx.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-w6htlFlx.d.ts","names":[],"sources":["../src/chat/context-breakdown.ts","../src/errors.ts","../src/types.ts","../src/providers/oauth.ts","../src/providers/anthropic.ts","../src/providers/arcee.ts","../src/providers/baseten.ts","../src/providers/cerebras.ts","../src/providers/cursor.ts","../src/providers/local.ts","../src/providers/openai.ts","../src/providers/openai-compat.ts","../src/providers/openrouter.ts","../src/providers/schema-sanitize.ts","../src/providers/xai.ts","../src/providers/index.ts","../src/session/messages.ts","../src/session/file-map.ts","../src/session/memory.ts","../src/session/remote.ts","../src/session/index.ts","../src/skills/types.ts","../src/tools/read-state.ts","../src/tools/types.ts","../src/mcp/index.ts","../src/skills/activation.ts","../src/agent.ts"],"mappings":";;;;;;;;;;;;;;;;;AA+BA;;;;AAA6B;AAmB7B;;;;;;;;;AAQQ;AAIR;;;;KA/BY,iBAAA;;;;;AAuCD;UApBM,iBAAA;EAwBe;EAtB9B,KAAA;EAqCmB;EAnCnB,SAAA;EAqBI;EAnBJ,aAAA;EAuBA;EArBA,MAAA;AAAA;;UAIe,WAAA;EA2BI;EAzBnB,EAAA;EA6Be;EA3Bf,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AAa,OAAA;EX16DM;AAAA;AAGrB;;EW46DE,OAAA,QAAe,OAAA;EXz6DF;;;;;;EWg7Db,aAAA,GAAgB,IAAA,aAAiB,OAAA;EX76DlB;;;;EWk7Df,eAAA,GAAkB,IAAA,aAAiB,OAAA;EXz6DnC;;;;AAmBO;AAYT;;;;;EWq5DE,MAAA,QAAc,OAAA;EAAA,SACL,SAAA;EAAA,SACA,KAAA,EAAO,WAAA;EAAA,SACP,SAAA,EAAW,gBAAA;EAAA,SACX,MAAA,EAAQ,eAAA;EAAA,SACR,OAAA,EAAS,OAAA;EXn2DT;EAAA,SWq2DA,YAAA,WAAuB,WAAA;EXj2DjB;;;;;;EAAA,SWw2DN,IAAA,EAAM,QAAA,CAAS,MAAA;EX51D2C;;;;;;;;;;;;;;;;;;;EWg3DnE,mBAAA,GAAsB,IAAA,GAAO,uBAAA,KAA4B,OAAA,CAAQ,gBAAA;EX91DjE;;AAAe;AAGjB;;;;;;;;;;;EAHE,CW62DC,MAAA,CAAO,YAAA,SAAqB,OAAA;AAAA;AAAA,iBAybf,WAAA,CAAA;EAAc,QAAA;EAAU,IAAA,EAAM,SAAA;EAAW,MAAA,EAAQ,WAAA;EAAa,KAAA,EAAO,UAAA;EAAY,WAAA;EAAa,QAAA,EAAU,aAAA;EAAe,SAAA;EAAW,UAAA;EAAY,OAAA;EAAS,SAAA,EAAW,cAAA;EAAgB,MAAA,EAAQ,WAAA;EAAa,YAAA;EAAc,WAAA;EAAa,KAAA;EAAO,KAAA,EAAO,YAAA;EAAc,KAAA,EAAO;AAAA,GAAc,YAAA,GAAe,KAAA"}
@@ -1,5 +1,5 @@
1
1
  import { t as writeFileAtomic } from "./atomic-write-Bgtr5JPu.js";
2
- import { a as local, c as generatePkce, f as arcee, g as FAST_MODE_OPTIONS, h as ANTHROPIC_EXTRA_MODELS, i as openai, l as cerebras, n as createXaiOAuthProvider, p as anthropic, r as openrouter, s as createCursorOAuthProvider, t as xai, u as baseten } from "./providers-CSE9IJ8W.js";
2
+ import { a as local, c as generatePkce, f as arcee, g as FAST_MODE_OPTIONS, h as ANTHROPIC_EXTRA_MODELS, i as openai, l as cerebras, n as createXaiOAuthProvider, p as anthropic, r as openrouter, s as createCursorOAuthProvider, t as xai, u as baseten } from "./providers-OBIysrMe.js";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import { existsSync, readFileSync, realpathSync } from "node:fs";
5
5
  import { randomBytes } from "node:crypto";
@@ -676,15 +676,27 @@ const openaiDescriptor = {
676
676
  credentialFileKey: "openai-codex",
677
677
  piProviderId: "openai-codex",
678
678
  apiKeyPlaceholder: "sk-… or eyJ… (Codex)",
679
- oauthProvider: openaiCodexOAuthProvider
679
+ oauthProvider: openaiCodexOAuthProvider,
680
+ optionsFor: (id) => id === "gpt-5.5" ? [{
681
+ id: "fast",
682
+ label: "Fast mode",
683
+ description: "Priority tier at 2.5× pricing",
684
+ costMultiplier: {
685
+ input: 2.5,
686
+ output: 2.5,
687
+ cacheRead: 2.5,
688
+ cacheWrite: 2.5
689
+ }
690
+ }] : void 0
680
691
  };
681
692
  const openrouterDescriptor = {
682
693
  key: "openrouter",
683
694
  label: "OpenRouter",
684
695
  factory: openrouter,
685
- defaultModel: "anthropic/claude-sonnet-4-6",
696
+ defaultModel: "anthropic/claude-sonnet-4.6",
686
697
  envKey: "OPENROUTER_API_KEY",
687
- apiKeyPlaceholder: "sk-or-…"
698
+ apiKeyPlaceholder: "sk-or-…",
699
+ modelAliases: { "anthropic/claude-sonnet-4-6": "anthropic/claude-sonnet-4.6" }
688
700
  };
689
701
  const cerebrasDescriptor = {
690
702
  key: "cerebras",
@@ -1012,12 +1024,13 @@ function decorateOptions(model, descriptor) {
1012
1024
  * known.
1013
1025
  */
1014
1026
  function getModelInfo(descriptor, modelId) {
1015
- if (descriptor.models) return descriptor.models.find((m) => m.id === modelId) ?? null;
1027
+ const lookupId = descriptor.modelAliases?.[modelId] ?? modelId;
1028
+ if (descriptor.models) return descriptor.models.find((m) => m.id === lookupId) ?? null;
1016
1029
  try {
1017
- const bundled = getModel(piIdOf(descriptor), modelId);
1030
+ const bundled = getModel(piIdOf(descriptor), lookupId);
1018
1031
  if (bundled) return decorateOptions(bundled, descriptor);
1019
1032
  } catch {}
1020
- const extra = descriptor.extraModels?.find((m) => m.id === modelId);
1033
+ const extra = descriptor.extraModels?.find((m) => m.id === lookupId);
1021
1034
  return extra ? decorateOptions(extra, descriptor) : null;
1022
1035
  }
1023
1036
  /**
@@ -1464,4 +1477,4 @@ function detectAuth(dataDir, registry, env = process.env) {
1464
1477
  //#endregion
1465
1478
  export { piIdOf as C, openrouterDescriptor as S, localDescriptor as _, readCredentials as a, modelsForDescriptor as b, setProviderCredential as c, anthropicDescriptor as d, cerebrasDescriptor as f, getModelInfo as g, getContextWindow as h, credentialsPath as i, writeCredentials as l, enabledModelOptions as m, resolveStorageDirs as n, readProviderCredential as o, credKeyOf as p, applyApiKeyEnv as r, removeProviderCredential as s, detectAuth as t, BUILTIN_PROVIDERS as u, modelOptionsFor as v, restoreModelOptions as w, openaiDescriptor as x, modelSupportsReasoning as y };
1466
1479
 
1467
- //# sourceMappingURL=auth-BlZUM4yl.js.map
1480
+ //# sourceMappingURL=auth-nA0ZMTbM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-nA0ZMTbM.js","names":["CLIENT_ID","AUTHORIZE_URL","TOKEN_URL","CALLBACK_PORT","CALLBACK_PATH","PROVIDER_NAME","parseAuthorizationInput","exchangeAuthorizationCode"],"sources":["../src/chat/oauth-page/server.ts","../src/chat/oauth-page/anthropic.ts","../src/chat/oauth-page/openai-codex.ts","../src/chat/oauth-page/render.ts","../src/chat/oauth-page/index.ts","../src/chat/providers.ts","../src/chat/credentials.ts","../src/chat/xdg.ts","../src/chat/auth.ts"],"sourcesContent":["/**\n * Local HTTP callback server primitive shared by the Anthropic + Codex\n * login flows. Owns three concerns:\n *\n * 1. Bind a loopback listener (configurable port + host via\n * `PI_OAUTH_CALLBACK_HOST`, matching pi-ai's semantics).\n * 2. Parse the redirect query string into `{ code, state }` or surface\n * a structured error.\n * 3. Render the result page through the caller-supplied renderer.\n *\n * Each provider clones the lifecycle wrapper (`waitForCode` / `cancelWait`\n * / `close`) so the higher-level login code reads the same on either\n * side. The only thing the server itself decides is the HTML.\n */\n\nimport type { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport type { OAuthCallbackPageRenderer } from './render'\nimport { createServer } from 'node:http'\n\nconst CALLBACK_HOST = process.env.PI_OAUTH_CALLBACK_HOST || '127.0.0.1'\n\nexport interface CallbackServerOptions {\n /** Loopback port. Must match the `redirect_uri` registered with the provider. */\n port: number\n /** Path component of the redirect URI (e.g. `/callback`, `/auth/callback`). */\n path: string\n /**\n * Expected `state` value. The server rejects any callback whose `state`\n * doesn't match, exactly. For Anthropic this is the PKCE verifier; for\n * Codex it's a random 16-byte hex string.\n */\n expectedState: string\n /** Display name passed through to {@link OAuthCallbackPageRenderer}. */\n providerName: string\n /** HTML renderer for both success + error pages. */\n renderPage: OAuthCallbackPageRenderer\n /** Success-page body shown after a clean redirect. */\n successMessage: string\n /**\n * How to react when `server.listen` itself fails (typically `EADDRINUSE`\n * when another instance is mid-flow). `\"reject\"` propagates the error to\n * the awaiting `start` caller; `\"resolveWithStub\"` returns a degraded\n * handle whose `waitForCode` immediately resolves to `null`, so the\n * caller can fall back to manual paste. Anthropic uses `\"reject\"`,\n * Codex uses `\"resolveWithStub\"` to match pi-ai's per-provider behavior.\n */\n onListenError?: 'reject' | 'resolveWithStub'\n}\n\nexport interface CallbackServerHandle {\n /** Fully-qualified redirect URI to advertise to the provider. */\n redirectUri: string\n /**\n * Resolves when the redirect lands (with `{ code, state? }`) or when\n * {@link cancelWait} is invoked (with `null`). Never throws.\n */\n waitForCode: () => Promise<{ code: string, state?: string } | null>\n /** Unblock `waitForCode` early (e.g. manual paste won the race). */\n cancelWait: () => void\n /** Close the listener. Idempotent. */\n close: () => void\n}\n\ninterface PendingResolution {\n settle: (value: { code: string, state?: string } | null) => void\n}\n\nfunction buildRequestHandler(opts: CallbackServerOptions, pending: PendingResolution) {\n return (req: IncomingMessage, res: ServerResponse) => {\n try {\n const url = new URL(req.url || '', 'http://localhost')\n\n if (url.pathname !== opts.path) {\n respondError(res, 404, opts, 'Callback route not found.')\n return\n }\n\n const error = url.searchParams.get('error')\n if (error) {\n respondError(res, 400, opts, `${opts.providerName} authentication did not complete.`, `Error: ${error}`)\n return\n }\n\n const code = url.searchParams.get('code')\n const state = url.searchParams.get('state')\n\n if (!code || !state) {\n respondError(res, 400, opts, 'Missing code or state parameter.')\n return\n }\n\n if (state !== opts.expectedState) {\n respondError(res, 400, opts, 'State mismatch.')\n return\n }\n\n res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })\n res.end(opts.renderPage({\n kind: 'success',\n provider: opts.providerName,\n message: opts.successMessage,\n }))\n pending.settle({ code, state })\n }\n catch {\n // We intentionally swallow the actual error here: surfacing a stack\n // to the user's browser would leak internals, and the login flow\n // is about to fall back to manual paste anyway.\n respondError(res, 500, opts, 'Internal error while processing the callback.')\n }\n }\n}\n\nfunction respondError(\n res: ServerResponse,\n status: number,\n opts: CallbackServerOptions,\n message: string,\n details?: string,\n) {\n res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' })\n res.end(opts.renderPage({\n kind: 'error',\n provider: opts.providerName,\n message,\n details,\n }))\n}\n\nfunction buildStubHandle(redirectUri: string, server: Server | null): CallbackServerHandle {\n return {\n redirectUri,\n waitForCode: async () => null,\n cancelWait: () => {},\n close: () => {\n try { server?.close() }\n catch { /* already closed */ }\n },\n }\n}\n\n/**\n * Start the loopback HTTP callback server. The returned handle is the\n * caller's contract — they `await waitForCode()`, race it against manual\n * paste, then `close()` in a `finally`.\n */\nexport async function startCallbackServer(opts: CallbackServerOptions): Promise<CallbackServerHandle> {\n const onListenError = opts.onListenError ?? 'reject'\n const redirectUri = `http://localhost:${opts.port}${opts.path}`\n\n return new Promise<CallbackServerHandle>((resolve, reject) => {\n let settled = false\n const pending: PendingResolution = {\n settle: () => {},\n }\n const waitPromise = new Promise<{ code: string, state?: string } | null>((resolveWait) => {\n pending.settle = (value) => {\n if (settled)\n return\n settled = true\n resolveWait(value)\n }\n })\n\n const server = createServer(buildRequestHandler(opts, pending))\n\n server.on('error', (err) => {\n if (onListenError === 'resolveWithStub') {\n pending.settle(null)\n resolve(buildStubHandle(redirectUri, server))\n return\n }\n reject(err)\n })\n\n server.listen(opts.port, CALLBACK_HOST, () => {\n resolve({\n redirectUri,\n waitForCode: () => waitPromise,\n cancelWait: () => pending.settle(null),\n close: () => {\n try { server.close() }\n catch { /* already closed */ }\n },\n })\n })\n })\n}\n","/**\n * Anthropic OAuth flow with a customisable callback page.\n *\n * Mirrors `loginAnthropic` from `@earendil-works/pi-ai/oauth` 1:1 except:\n *\n * 1. The HTTP callback server's response HTML routes through\n * {@link OAuthCallbackPageRenderer} instead of pi-ai's baked-in page.\n * 2. The lifecycle is delegated to {@link startCallbackServer} so the\n * Codex sibling and any future loopback provider share one HTTP impl.\n *\n * Refresh + `getApiKey` delegate straight to pi-ai's exports — those don't\n * touch HTML and there's no upside to forking them.\n *\n * Endpoints / client id / port / scopes match pi-ai `0.79.10`. Bump in\n * lockstep on the next `@earendil-works/pi-ai` upgrade, or delete this\n * file once pi-ai exposes a `renderCallbackPage` callback upstream.\n */\n\nimport type {\n OAuthCredentials,\n OAuthLoginCallbacks,\n OAuthProviderInterface,\n} from '@earendil-works/pi-ai/oauth'\nimport type { OAuthCallbackPageRenderer } from './render'\nimport { refreshAnthropicToken } from '@earendil-works/pi-ai/oauth'\nimport { generatePkce } from './pkce'\nimport { startCallbackServer } from './server'\n\n// Pulled verbatim from pi-ai 0.79.10 — `dist/utils/oauth/anthropic.js`.\nconst CLIENT_ID = atob('OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl')\nconst AUTHORIZE_URL = 'https://claude.ai/oauth/authorize'\nconst TOKEN_URL = 'https://platform.claude.com/v1/oauth/token'\nconst CALLBACK_PORT = 53692\nconst CALLBACK_PATH = '/callback'\nconst SCOPES = 'org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload'\nconst PROVIDER_NAME = 'Anthropic'\n\n/**\n * Parse what the user pasted into the manual-code prompt. Accepts:\n * - the bare authorization code\n * - the full `redirect_uri?code=...&state=...` URL\n * - the `code#state` shorthand Anthropic surfaces on the page\n * - a raw query string with `code=...&state=...`\n *\n * Matches pi-ai's parse table so an existing user's muscle memory still works.\n */\nfunction parseAuthorizationInput(input: string): { code?: string, state?: string } {\n const value = input.trim()\n if (!value)\n return {}\n\n try {\n const url = new URL(value)\n return {\n code: url.searchParams.get('code') ?? undefined,\n state: url.searchParams.get('state') ?? undefined,\n }\n }\n catch {\n // fall through to non-URL parsing below\n }\n\n if (value.includes('#')) {\n const [code, state] = value.split('#', 2)\n return { code, state }\n }\n if (value.includes('code=')) {\n const params = new URLSearchParams(value)\n return {\n code: params.get('code') ?? undefined,\n state: params.get('state') ?? undefined,\n }\n }\n return { code: value }\n}\n\nasync function postJson(url: string, body: Record<string, unknown>): Promise<string> {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(30_000),\n })\n const responseBody = await response.text()\n if (!response.ok)\n throw new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`)\n return responseBody\n}\n\nasync function exchangeAuthorizationCode(\n code: string,\n state: string,\n verifier: string,\n redirectUri: string,\n): Promise<OAuthCredentials> {\n const responseBody = await postJson(TOKEN_URL, {\n grant_type: 'authorization_code',\n client_id: CLIENT_ID,\n code,\n state,\n redirect_uri: redirectUri,\n code_verifier: verifier,\n })\n\n const tokenData = JSON.parse(responseBody) as {\n refresh_token: string\n access_token: string\n expires_in: number\n }\n\n return {\n refresh: tokenData.refresh_token,\n access: tokenData.access_token,\n // -5min so a refresh fires before the upstream expiry; matches pi-ai.\n expires: Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000,\n }\n}\n\nexport interface LoginAnthropicWithPageOptions extends Pick<\n OAuthLoginCallbacks,\n 'onAuth' | 'onPrompt' | 'onProgress' | 'onManualCodeInput'\n> {\n renderPage: OAuthCallbackPageRenderer\n}\n\nexport async function loginAnthropicWithCustomPage(\n options: LoginAnthropicWithPageOptions,\n): Promise<OAuthCredentials> {\n const { verifier, challenge } = await generatePkce()\n const server = await startCallbackServer({\n port: CALLBACK_PORT,\n path: CALLBACK_PATH,\n expectedState: verifier,\n providerName: PROVIDER_NAME,\n renderPage: options.renderPage,\n successMessage: 'Anthropic authentication completed. You can close this window.',\n onListenError: 'reject',\n })\n\n let code: string | undefined\n let state: string | undefined\n\n try {\n const authParams = new URLSearchParams({\n code: 'true',\n client_id: CLIENT_ID,\n response_type: 'code',\n redirect_uri: server.redirectUri,\n scope: SCOPES,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n state: verifier,\n })\n\n options.onAuth({\n url: `${AUTHORIZE_URL}?${authParams.toString()}`,\n instructions: 'Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.',\n })\n\n if (options.onManualCodeInput) {\n let manualInput: string | undefined\n let manualError: Error | undefined\n const manualPromise = options\n .onManualCodeInput()\n .then((input) => {\n manualInput = input\n server.cancelWait()\n })\n .catch((err) => {\n manualError = err instanceof Error ? err : new Error(String(err))\n server.cancelWait()\n })\n\n const result = await server.waitForCode()\n if (manualError)\n throw manualError\n\n if (result?.code) {\n code = result.code\n state = result.state\n }\n else if (manualInput) {\n const parsed = parseAuthorizationInput(manualInput)\n if (parsed.state && parsed.state !== verifier)\n throw new Error('OAuth state mismatch')\n code = parsed.code\n state = parsed.state ?? verifier\n }\n\n if (!code) {\n await manualPromise\n if (manualError)\n throw manualError\n if (manualInput) {\n const parsed = parseAuthorizationInput(manualInput)\n if (parsed.state && parsed.state !== verifier)\n throw new Error('OAuth state mismatch')\n code = parsed.code\n state = parsed.state ?? verifier\n }\n }\n }\n else {\n const result = await server.waitForCode()\n if (result?.code) {\n code = result.code\n state = result.state\n }\n }\n\n if (!code) {\n const input = await options.onPrompt({\n message: 'Paste the authorization code or full redirect URL:',\n placeholder: server.redirectUri,\n })\n const parsed = parseAuthorizationInput(input)\n if (parsed.state && parsed.state !== verifier)\n throw new Error('OAuth state mismatch')\n code = parsed.code\n state = parsed.state ?? verifier\n }\n\n if (!code)\n throw new Error('Missing authorization code')\n if (!state)\n throw new Error('Missing OAuth state')\n\n options.onProgress?.('Exchanging authorization code for tokens...')\n return await exchangeAuthorizationCode(code, state, verifier, server.redirectUri)\n }\n finally {\n server.close()\n }\n}\n\n/**\n * Build an `OAuthProviderInterface` that behaves identically to pi-ai's\n * `anthropicOAuthProvider` except for the callback page HTML. Drop this\n * onto `ProviderDescriptor.oauthProvider` to override.\n */\nexport function createAnthropicOAuthProviderWithCustomPage(\n renderPage: OAuthCallbackPageRenderer,\n): OAuthProviderInterface {\n return {\n id: 'anthropic',\n name: 'Anthropic (Claude Pro/Max)',\n usesCallbackServer: true,\n async login(callbacks: OAuthLoginCallbacks) {\n return loginAnthropicWithCustomPage({\n renderPage,\n onAuth: callbacks.onAuth,\n onPrompt: callbacks.onPrompt,\n onProgress: callbacks.onProgress,\n onManualCodeInput: callbacks.onManualCodeInput,\n })\n },\n async refreshToken(credentials: OAuthCredentials) {\n return refreshAnthropicToken(credentials.refresh)\n },\n getApiKey(credentials: OAuthCredentials) {\n return credentials.access\n },\n }\n}\n","/**\n * OpenAI Codex (ChatGPT Plus/Pro) OAuth flow with a customisable callback\n * page. 1:1 mirror of pi-ai `0.79.10`'s `loginOpenAICodex` except the HTTP\n * callback server routes through {@link OAuthCallbackPageRenderer}.\n *\n * Refresh delegates to pi-ai's exported `refreshOpenAICodexToken` —\n * Codex's refresh path involves JWT decoding for `accountId`, and we don't\n * want to duplicate it. The HTML override is purely about the landing page.\n */\n\nimport type {\n OAuthCredentials,\n OAuthLoginCallbacks,\n OAuthProviderInterface,\n} from '@earendil-works/pi-ai/oauth'\nimport type { OAuthCallbackPageRenderer } from './render'\nimport { randomBytes } from 'node:crypto'\nimport { refreshOpenAICodexToken } from '@earendil-works/pi-ai/oauth'\nimport { generatePkce } from './pkce'\nimport { startCallbackServer } from './server'\n\n// Pulled verbatim from pi-ai 0.79.10 — `dist/utils/oauth/openai-codex.js`.\nconst CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann'\nconst AUTHORIZE_URL = 'https://auth.openai.com/oauth/authorize'\nconst TOKEN_URL = 'https://auth.openai.com/oauth/token'\nconst CALLBACK_PORT = 1455\nconst CALLBACK_PATH = '/auth/callback'\nconst SCOPE = 'openid profile email offline_access'\nconst JWT_CLAIM_PATH = 'https://api.openai.com/auth'\nconst PROVIDER_NAME = 'OpenAI'\n\nfunction createState(): string {\n return randomBytes(16).toString('hex')\n}\n\nfunction parseAuthorizationInput(input: string): { code?: string, state?: string } {\n const value = input.trim()\n if (!value)\n return {}\n\n try {\n const url = new URL(value)\n return {\n code: url.searchParams.get('code') ?? undefined,\n state: url.searchParams.get('state') ?? undefined,\n }\n }\n catch {\n // fall through\n }\n\n if (value.includes('#')) {\n const [code, state] = value.split('#', 2)\n return { code, state }\n }\n if (value.includes('code=')) {\n const params = new URLSearchParams(value)\n return {\n code: params.get('code') ?? undefined,\n state: params.get('state') ?? undefined,\n }\n }\n return { code: value }\n}\n\ninterface JwtPayload {\n [key: string]: unknown\n [JWT_CLAIM_PATH]?: { chatgpt_account_id?: string }\n}\n\nfunction decodeJwt(token: string): JwtPayload | null {\n try {\n const parts = token.split('.')\n if (parts.length !== 3)\n return null\n const payload = parts[1] ?? ''\n const decoded = atob(payload)\n return JSON.parse(decoded) as JwtPayload\n }\n catch {\n return null\n }\n}\n\nfunction getAccountId(accessToken: string): string | null {\n const payload = decodeJwt(accessToken)\n const claim = payload?.[JWT_CLAIM_PATH] as { chatgpt_account_id?: string } | undefined\n const accountId = claim?.chatgpt_account_id\n return typeof accountId === 'string' && accountId.length > 0 ? accountId : null\n}\n\ninterface TokenExchangeSuccess {\n type: 'success'\n access: string\n refresh: string\n expires: number\n}\n\ninterface TokenExchangeFailure {\n type: 'failed'\n message: string\n}\n\nasync function exchangeAuthorizationCode(\n code: string,\n verifier: string,\n redirectUri: string,\n): Promise<TokenExchangeSuccess | TokenExchangeFailure> {\n const response = await fetch(TOKEN_URL, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: CLIENT_ID,\n code,\n code_verifier: verifier,\n redirect_uri: redirectUri,\n }),\n })\n\n if (!response.ok) {\n const text = await response.text().catch(() => '')\n return {\n type: 'failed',\n message: `OpenAI Codex token exchange failed (${response.status}): ${text || response.statusText}`,\n }\n }\n\n const json = await response.json() as {\n access_token?: string\n refresh_token?: string\n expires_in?: number\n }\n if (!json.access_token || !json.refresh_token || typeof json.expires_in !== 'number') {\n return {\n type: 'failed',\n message: `OpenAI Codex token exchange response missing fields: ${JSON.stringify(json)}`,\n }\n }\n return {\n type: 'success',\n access: json.access_token,\n refresh: json.refresh_token,\n expires: Date.now() + json.expires_in * 1000,\n }\n}\n\nexport interface LoginOpenAICodexWithPageOptions extends Pick<\n OAuthLoginCallbacks,\n 'onAuth' | 'onPrompt' | 'onProgress' | 'onManualCodeInput'\n> {\n renderPage: OAuthCallbackPageRenderer\n /** OAuth `originator` parameter. Defaults to `\"pi\"` to stay observable upstream. */\n originator?: string\n}\n\nexport async function loginOpenAICodexWithCustomPage(\n options: LoginOpenAICodexWithPageOptions,\n): Promise<OAuthCredentials> {\n const { verifier, challenge } = await generatePkce()\n const state = createState()\n const originator = options.originator ?? 'pi'\n\n const server = await startCallbackServer({\n port: CALLBACK_PORT,\n path: CALLBACK_PATH,\n expectedState: state,\n providerName: PROVIDER_NAME,\n renderPage: options.renderPage,\n successMessage: 'OpenAI authentication completed. You can close this window.',\n // Matches pi-ai: Codex falls back to manual paste on port collision.\n onListenError: 'resolveWithStub',\n })\n\n const authUrl = new URL(AUTHORIZE_URL)\n authUrl.searchParams.set('response_type', 'code')\n authUrl.searchParams.set('client_id', CLIENT_ID)\n authUrl.searchParams.set('redirect_uri', server.redirectUri)\n authUrl.searchParams.set('scope', SCOPE)\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('id_token_add_organizations', 'true')\n authUrl.searchParams.set('codex_cli_simplified_flow', 'true')\n authUrl.searchParams.set('originator', originator)\n\n options.onAuth({\n url: authUrl.toString(),\n instructions: 'A browser window should open. Complete login to finish.',\n })\n\n let code: string | undefined\n\n try {\n if (options.onManualCodeInput) {\n let manualCode: string | undefined\n let manualError: Error | undefined\n const manualPromise = options\n .onManualCodeInput()\n .then((input) => {\n manualCode = input\n server.cancelWait()\n })\n .catch((err) => {\n manualError = err instanceof Error ? err : new Error(String(err))\n server.cancelWait()\n })\n\n const result = await server.waitForCode()\n if (manualError)\n throw manualError\n\n if (result?.code) {\n code = result.code\n }\n else if (manualCode) {\n const parsed = parseAuthorizationInput(manualCode)\n if (parsed.state && parsed.state !== state)\n throw new Error('State mismatch')\n code = parsed.code\n }\n\n if (!code) {\n await manualPromise\n if (manualError)\n throw manualError\n if (manualCode) {\n const parsed = parseAuthorizationInput(manualCode)\n if (parsed.state && parsed.state !== state)\n throw new Error('State mismatch')\n code = parsed.code\n }\n }\n }\n else {\n const result = await server.waitForCode()\n if (result?.code)\n code = result.code\n }\n\n if (!code) {\n const input = await options.onPrompt({\n message: 'Paste the authorization code (or full redirect URL):',\n })\n const parsed = parseAuthorizationInput(input)\n if (parsed.state && parsed.state !== state)\n throw new Error('State mismatch')\n code = parsed.code\n }\n\n if (!code)\n throw new Error('Missing authorization code')\n\n const tokenResult = await exchangeAuthorizationCode(code, verifier, server.redirectUri)\n if (tokenResult.type !== 'success')\n throw new Error(tokenResult.message)\n\n const accountId = getAccountId(tokenResult.access)\n if (!accountId)\n throw new Error('Failed to extract accountId from token')\n\n return {\n access: tokenResult.access,\n refresh: tokenResult.refresh,\n expires: tokenResult.expires,\n accountId,\n }\n }\n finally {\n server.close()\n }\n}\n\n/**\n * Build an `OAuthProviderInterface` that behaves identically to pi-ai's\n * `openaiCodexOAuthProvider` except for the callback page HTML.\n */\nexport function createOpenAICodexOAuthProviderWithCustomPage(\n renderPage: OAuthCallbackPageRenderer,\n): OAuthProviderInterface {\n return {\n id: 'openai-codex',\n name: 'ChatGPT Plus/Pro (Codex Subscription)',\n usesCallbackServer: true,\n async login(callbacks: OAuthLoginCallbacks) {\n return loginOpenAICodexWithCustomPage({\n renderPage,\n onAuth: callbacks.onAuth,\n onPrompt: callbacks.onPrompt,\n onProgress: callbacks.onProgress,\n onManualCodeInput: callbacks.onManualCodeInput,\n })\n },\n async refreshToken(credentials: OAuthCredentials) {\n return refreshOpenAICodexToken(credentials.refresh)\n },\n getApiKey(credentials: OAuthCredentials) {\n return credentials.access\n },\n }\n}\n","/**\n * HTML rendered by the local OAuth callback server when the browser hits\n * `redirect_uri`. This is the page the user sees the moment authentication\n * finishes — by default pi-ai bakes in its own dark page; this module lets\n * a host swap it for something branded without forking the package.\n *\n * Renderer is a single pure function — `(page) => string` — so a host can\n * inline a literal template, pull from a theme registry, or proxy a static\n * asset built at compile time. Anything that returns a `string`.\n */\n\n/**\n * Outcome rendered on the callback page. `kind` drives status code on the\n * underlying HTTP response (`200` for success, `4xx` for error); the rest\n * is content. `provider` is the human-readable name of the OAuth provider\n * (e.g. `\"Anthropic\"`, `\"OpenAI Codex\"`) so a renderer can swap copy or\n * logos per provider.\n */\nexport interface OAuthCallbackPage {\n kind: 'success' | 'error'\n /** Headline message — usually one sentence. Safe to include user-visible details. */\n message: string\n /** Optional secondary details (e.g. provider error code). Rendered in mono. */\n details?: string\n /** Provider display name passed through from the login function. */\n provider: string\n}\n\nexport type OAuthCallbackPageRenderer = (page: OAuthCallbackPage) => string\n\nfunction escapeHtml(value: string): string {\n return value\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll('\\'', '&#39;')\n}\n\n/**\n * Default zidane-themed page. Visually neutral but distinguishable from\n * pi-ai's stock page — dark background, mono headings, no logo (host can\n * pass a custom renderer to add one).\n */\nexport const renderDefaultCallbackPage: OAuthCallbackPageRenderer = (page) => {\n const title = page.kind === 'success'\n ? `Signed in to ${page.provider}`\n : `Could not sign in to ${page.provider}`\n const heading = escapeHtml(title)\n const message = escapeHtml(page.message)\n const details = page.details ? escapeHtml(page.details) : undefined\n\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${heading}</title>\n <style>\n :root {\n --text: #f4f4f5;\n --text-dim: #a1a1aa;\n --accent: ${page.kind === 'success' ? '#22d3ee' : '#f87171'};\n --page-bg: #0a0a0a;\n --panel-bg: #131316;\n --border: #27272a;\n --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n }\n * { box-sizing: border-box; }\n html { color-scheme: dark; }\n body {\n margin: 0;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: var(--page-bg);\n color: var(--text);\n font-family: var(--font-sans);\n }\n main {\n width: 100%;\n max-width: 520px;\n padding: 32px;\n background: var(--panel-bg);\n border: 1px solid var(--border);\n border-radius: 12px;\n }\n .label {\n font-family: var(--font-mono);\n font-size: 12px;\n letter-spacing: 0.08em;\n text-transform: uppercase;\n color: var(--accent);\n margin-bottom: 12px;\n }\n h1 {\n margin: 0 0 12px;\n font-size: 22px;\n font-weight: 600;\n letter-spacing: -0.01em;\n color: var(--text);\n }\n p {\n margin: 0;\n line-height: 1.6;\n color: var(--text-dim);\n font-size: 14px;\n }\n .details {\n margin-top: 18px;\n padding: 12px 14px;\n background: var(--page-bg);\n border: 1px solid var(--border);\n border-radius: 8px;\n font-family: var(--font-mono);\n font-size: 12px;\n color: var(--text-dim);\n white-space: pre-wrap;\n word-break: break-word;\n }\n </style>\n</head>\n<body>\n <main>\n <div class=\"label\">zidane · OAuth · ${escapeHtml(page.provider)}</div>\n <h1>${heading}</h1>\n <p>${message}</p>\n ${details ? `<div class=\"details\">${details}</div>` : ''}\n </main>\n</body>\n</html>`\n}\n\n/**\n * Tiny helper kept private to the module so renderer authors can reuse\n * the same escaping rules as the default theme. Re-exported in case a\n * host wants to embed user-supplied messages safely.\n */\nexport const escapeHtmlForCallbackPage: (value: string) => string = escapeHtml\n","/**\n * Custom OAuth callback page — drop-in replacements for pi-ai's built-in\n * Anthropic + OpenAI Codex providers that route the post-redirect HTML\n * through your own renderer.\n *\n * Why this module exists\n * ----------------------\n * `@earendil-works/pi-ai` (as of `0.79.10`) bakes its callback page into\n * `loginAnthropic` / `loginOpenAICodex` with no override. The upstream\n * fix is a tiny `renderCallbackPage` hook on `OAuthLoginCallbacks`; until\n * that lands this module forks the two flows in one self-contained place\n * — everything else (token refresh, `getApiKey`, env handling) delegates\n * back to pi-ai unchanged.\n *\n * How to use\n * ----------\n *\n * ```ts\n * import { createCustomCallbackOAuthProviders, renderDefaultCallbackPage } from './chat/oauth-page'\n * import { BUILTIN_PROVIDERS } from './chat/providers'\n *\n * const { anthropic, openaiCodex } = createCustomCallbackOAuthProviders(renderDefaultCallbackPage)\n *\n * const providers = {\n * ...BUILTIN_PROVIDERS,\n * anthropic: { ...BUILTIN_PROVIDERS.anthropic, oauthProvider: anthropic },\n * openai: { ...BUILTIN_PROVIDERS.openai, oauthProvider: openaiCodex },\n * }\n * ```\n *\n * Or override per provider with `createAnthropicOAuthProviderWithCustomPage`\n * / `createOpenAICodexOAuthProviderWithCustomPage` directly.\n *\n * Deleting this module\n * --------------------\n * When pi-ai exposes `renderCallbackPage` on `OAuthLoginCallbacks`:\n *\n * 1. Delete this folder.\n * 2. Surface the upstream callback through `OAuthFlowOptions` in\n * `src/chat/oauth.ts` (one optional pass-through field).\n * 3. Re-point any descriptors that imported from here to pi-ai's\n * `anthropicOAuthProvider` / `openaiCodexOAuthProvider` directly.\n *\n * Pinned to pi-ai `0.79.10`. Re-verify endpoints + ports on every pi-ai\n * bump (auth URLs, client IDs, callback ports are duplicated verbatim\n * here; see `anthropic.ts` and `openai-codex.ts` for the source-of-truth\n * pointers).\n */\n\nimport type { OAuthProviderInterface } from '@earendil-works/pi-ai/oauth'\nimport type { OAuthCallbackPageRenderer } from './render'\nimport { registerOAuthProvider } from '@earendil-works/pi-ai/oauth'\nimport { createAnthropicOAuthProviderWithCustomPage } from './anthropic'\nimport { createCursorOAuthProvider } from './cursor'\nimport { createOpenAICodexOAuthProviderWithCustomPage } from './openai-codex'\nimport { createXaiOAuthProvider } from './xai'\n\nexport type {\n LoginAnthropicWithPageOptions,\n} from './anthropic'\nexport {\n createAnthropicOAuthProviderWithCustomPage,\n loginAnthropicWithCustomPage,\n} from './anthropic'\nexport {\n createCursorOAuthProvider,\n CURSOR_OAUTH_PROVIDER_ID,\n loginCursor,\n refreshCursorToken,\n} from './cursor'\nexport type {\n LoginOpenAICodexWithPageOptions,\n} from './openai-codex'\nexport {\n createOpenAICodexOAuthProviderWithCustomPage,\n loginOpenAICodexWithCustomPage,\n} from './openai-codex'\nexport type {\n OAuthCallbackPage,\n OAuthCallbackPageRenderer,\n} from './render'\nexport {\n escapeHtmlForCallbackPage,\n renderDefaultCallbackPage,\n} from './render'\nexport {\n createXaiOAuthProvider,\n loginXai,\n refreshXaiToken,\n XAI_OAUTH_PROVIDER_ID,\n xaiBaseUrl,\n} from './xai'\nexport type { XaiOAuthCredentials } from './xai'\n\nexport interface CustomCallbackOAuthProviders {\n anthropic: OAuthProviderInterface\n openaiCodex: OAuthProviderInterface\n}\n\n/**\n * Bundle helper — returns both Anthropic + OpenAI Codex providers wired\n * with the same renderer. Hosts that want different renderers per provider\n * should call the individual `create…WithCustomPage` factories instead.\n */\nexport function createCustomCallbackOAuthProviders(\n renderPage: OAuthCallbackPageRenderer,\n): CustomCallbackOAuthProviders {\n return {\n anthropic: createAnthropicOAuthProviderWithCustomPage(renderPage),\n openaiCodex: createOpenAICodexOAuthProviderWithCustomPage(renderPage),\n }\n}\n\nlet cursorRegistered = false\n\n/**\n * Register Cursor with pi-ai's OAuth registry.\n *\n * Unlike Anthropic / Codex, Cursor is **not** built into pi-ai, so\n * `getOAuthApiKey('cursor', …)` (used by `resolveOAuthApiKey` for lazy\n * token refresh) would throw \"Unknown OAuth provider\" until we register it.\n * Call once at startup from both the CLI auth path and the TUI. Idempotent.\n */\nexport function registerCursorOAuthProvider(): OAuthProviderInterface {\n const provider = createCursorOAuthProvider()\n if (!cursorRegistered) {\n registerOAuthProvider(provider)\n cursorRegistered = true\n }\n return provider\n}\n\nlet xaiRegistered = false\n\n/**\n * Register xAI Grok with pi-ai's OAuth registry.\n *\n * pi-ai ships an xAI *API-key* provider, but no OAuth one — so\n * `getOAuthApiKey('xai-oauth', …)` (lazy refresh in `resolveOAuthApiKey`)\n * would throw \"Unknown OAuth provider\" until we register our flow. The\n * callback page routes through the supplied renderer so the post-redirect\n * HTML matches zidane's theme. Call once at startup; idempotent.\n */\nexport function registerXaiOAuthProvider(\n renderPage: OAuthCallbackPageRenderer,\n): OAuthProviderInterface {\n const provider = createXaiOAuthProvider(renderPage)\n if (!xaiRegistered) {\n registerOAuthProvider(provider)\n xaiRegistered = true\n }\n return provider\n}\n","/**\n * Provider registry — the customization seam for the TUI.\n *\n * A {@link ProviderDescriptor} carries everything the TUI needs to know about\n * a provider in one place: how to instantiate it, what to show in the UI,\n * how to detect credentials, how to OAuth (if applicable), and where to look\n * up its models. Hosts can ship their own descriptors instead of the built-in\n * four — see {@link BUILTIN_PROVIDERS}.\n */\n\nimport type { OAuthProviderInterface } from '@earendil-works/pi-ai/oauth'\nimport type { Provider } from '../providers'\nimport { getModel, getModels } from '@earendil-works/pi-ai'\nimport { anthropic, arcee, baseten, cerebras, cursor, local, openai, openrouter, xai } from '../providers'\nimport { ANTHROPIC_EXTRA_MODELS, FAST_MODE_OPTIONS } from './anthropic-models'\nimport { createCustomCallbackOAuthProviders, registerCursorOAuthProvider, registerXaiOAuthProvider, renderDefaultCallbackPage } from './oauth-page'\n\n/**\n * pi-ai's stock Anthropic + Codex OAuth providers bake their own callback\n * HTML; we route both through `renderDefaultCallbackPage` so the post-redirect\n * page matches zidane's theme. The override lives in `src/chat/oauth-page/`\n * — see that folder's `index.ts` for the deletion path once pi-ai exposes\n * a `renderCallbackPage` hook upstream.\n */\nconst { anthropic: anthropicOAuthProvider, openaiCodex: openaiCodexOAuthProvider }\n = createCustomCallbackOAuthProviders(renderDefaultCallbackPage)\n\n/**\n * Cursor isn't built into pi-ai, so registering it makes lazy token refresh\n * (`getOAuthApiKey('cursor', …)` inside `resolveOAuthApiKey`) resolve to our\n * Cursor flow. The poll-based login has no callback server, so no themed page.\n */\nconst cursorOAuthProvider = registerCursorOAuthProvider()\n\n/**\n * xAI Grok isn't built into pi-ai's OAuth registry (only its API-key provider\n * is), so register our loopback-PKCE flow — themed via `renderDefaultCallbackPage`\n * — so lazy token refresh resolves through it.\n */\nconst xaiOAuthProvider = registerXaiOAuthProvider(renderDefaultCallbackPage)\n\n/**\n * Structural model metadata — compatible with pi-ai's `Model` interface but\n * not coupled to it, so hosts can pass either pi-ai-shaped objects or a\n * custom registry of their own.\n *\n * Deliberately a structural duplicate of pi-ai's `Model` rather than a\n * re-export: keeps the public API stable when pi-ai bumps shape, and lets\n * hosts implement their own registry without depending on pi-ai's types.\n *\n * Lives here (rather than `./config`) because `ProviderDescriptor.models`\n * needs it — pushing it to `config.tsx` created an import cycle.\n */\nexport interface ModelInfo {\n id: string\n name?: string\n contextWindow: number\n maxTokens?: number\n reasoning?: boolean\n input?: readonly ('text' | 'image')[]\n cost?: { input: number, output: number, cacheRead?: number, cacheWrite?: number }\n provider?: string\n /**\n * Model-specific toggleable knobs surfaced in the UI (e.g. Anthropic's\n * \"fast mode\"). Each option is an independent boolean the user flips on the\n * active model; enabled options are collected into `StreamOptions.modelOptions`\n * keyed by {@link ModelOption.id} and applied to the wire by the provider.\n * Omitted / empty → the model has no custom options and the picker is hidden.\n */\n options?: readonly ModelOption[]\n}\n\n/**\n * A single toggleable model option. Declarative metadata only — the provider\n * owns the actual request-body translation (keyed on {@link id}). Kept generic\n * (not \"fast mode\"-specific) so new per-model knobs land without a type change.\n */\nexport interface ModelOption {\n /** Stable identifier; the key under which the toggle persists + reaches the provider. */\n id: string\n /** Short label shown in the picker (e.g. \"Fast mode\"). */\n label: string\n /** One-line description of the trade-off (shown in the picker row). */\n description?: string\n /**\n * Optional cost multipliers applied to the model's base rates while the\n * option is enabled. `{ input: 2, output: 2 }` doubles both. Used by the\n * cost estimator so the footer reflects premium-priced modes (fast mode).\n */\n costMultiplier?: { input?: number, output?: number, cacheRead?: number, cacheWrite?: number }\n}\n\n/**\n * Free-form configuration field that a provider needs the user to supply\n * alongside (or instead of) an API key — e.g. a self-hosted base URL, an\n * Azure deployment name, a default model id.\n *\n * The wizard prompts for each field in order. Submitted values are persisted\n * into the apikey credential (as `customFields[key]`) and mirrored into\n * `process.env[envVar]` so the provider's factory can read them via the same\n * env-var convention as `envKey`.\n *\n * Descriptors without an `envKey` use `customFields` as the sole credential\n * mechanism — the wizard skips its API-key step in that case.\n */\nexport interface CustomField {\n /** Storage key inside the credential's `customFields` record. */\n key: string\n /** Human-readable label shown in the wizard step's title. */\n label: string\n /** Env var name to mirror this field into at TUI launch + on submit. */\n envVar: string\n /** Optional placeholder shown in the wizard input. */\n placeholder?: string\n /** Optional helper copy rendered above the input. */\n hint?: string\n /** When true, an empty submission is rejected by the wizard. Default: false. */\n required?: boolean\n}\n\nexport interface ProviderDescriptor {\n /**\n * Unique identifier. Used as the registry key, persisted in `state.json`\n * as the resumed provider, and (by default) as the credential-file key.\n */\n key: string\n /** Display name shown in the TUI's provider picker and labels. */\n label: string\n /**\n * Factory that builds a fresh `Provider` instance. Called on every session\n * activation. Some factories (e.g. zidane's built-in `anthropic`) eagerly\n * resolve credentials at construction time and throw when none are\n * configured — set {@link defaultModel} on the descriptor to avoid the TUI\n * calling the factory before the user has picked + authed a provider.\n */\n factory: () => Provider\n /**\n * Default model id to seed the picker with. When omitted, the TUI falls\n * back to `descriptor.factory().meta.defaultModel`, which constructs the\n * provider — fine for lazy-credential factories, but breaks for factories\n * that throw on missing credentials before the wizard runs. Setting this\n * eagerly lets the TUI render the auth wizard without ever instantiating\n * the provider.\n */\n defaultModel?: string\n /**\n * Env var checked when detecting whether the user has an API key\n * configured for this provider. Optional — set to `undefined` when the\n * provider only supports OAuth (or only credentials via a custom path).\n */\n envKey?: string\n /**\n * Key under which credentials live in `credentials.json`. Defaults to\n * `key`. The only built-in that overrides this is OpenAI Codex\n * (`openai` → `openai-codex`) to stay compatible with the harness\n * provider's existing lookup.\n */\n credentialFileKey?: string\n /** Placeholder shown in the wizard's API-key input. */\n apiKeyPlaceholder?: string\n /**\n * pi-ai (or compat) OAuth provider. When present, the wizard offers an\n * OAuth option in addition to API key.\n */\n oauthProvider?: OAuthProviderInterface\n /**\n * Optional copy appended to the wizard's \"OAuth\" method description.\n * Use to communicate why a user might pick OAuth (e.g. subscription tier,\n * org-wide SSO). Shown after `browser-based sign-in`. Skip the leading\n * space — the wizard adds it. Example: `'Claude Pro/Max subscription'`.\n */\n oauthHint?: string\n /**\n * pi-ai provider id used to look up models in pi-ai's built-in registry.\n * Defaults to `key`. Only Codex differs (`openai` → `openai-codex`).\n */\n piProviderId?: string\n /**\n * Back-compat aliases for persisted model ids whose upstream slug changed.\n * Used for metadata lookups only; aliases are not surfaced as picker rows.\n */\n modelAliases?: Readonly<Record<string, string>>\n /**\n * Override the model list returned for this provider's picker. When set,\n * skips pi-ai's registry entirely. Useful for hosts maintaining their\n * own model catalogue or for custom providers pi-ai doesn't know about.\n */\n models?: readonly ModelInfo[]\n /**\n * Additional free-form fields the wizard should collect from the user\n * (e.g. base URL for a self-hosted endpoint, default model slug for a\n * provider with no fixed catalogue). Each field is persisted in the\n * apikey credential's `customFields` map and mirrored into the matching\n * `envVar` at TUI launch.\n *\n * When `envKey` is also set, the wizard collects custom fields **before**\n * the API key. When `envKey` is omitted, the wizard skips the API-key\n * step entirely — `customFields` becomes the sole credential mechanism\n * (used by the `local` provider, which authenticates via baseURL only).\n */\n customFields?: readonly CustomField[]\n /**\n * Extra models merged AHEAD of pi-ai's registry list (de-duped by id, pi-ai\n * wins on collision). Unlike {@link models} this augments rather than\n * replaces — used to surface freshly-shipped models pi-ai hasn't bundled\n * yet without losing the rest of the registry. Ignored when {@link models}\n * is set.\n */\n extraModels?: readonly ModelInfo[]\n /**\n * Resolve the custom {@link ModelOption}s a given model id supports. Used to\n * attach options (e.g. fast mode) to models that come from pi-ai's registry —\n * which {@link extraModels} can't reach because pi-ai wins the id collision.\n * Returns `undefined` / `[]` for models with no options. Models that already\n * carry `options` (e.g. via {@link extraModels}) keep theirs.\n */\n optionsFor?: (modelId: string) => readonly ModelOption[] | undefined\n /**\n * Env var holding a user-supplied context window (in tokens) for providers\n * that have no model registry to advertise one — chiefly the `local`\n * provider, whose runtime (Ollama, vLLM, …) doesn't expose its loaded\n * model's window over the OpenAI-compat API. When set, {@link getContextWindow}\n * falls back to resolving this env var (via {@link resolveContextWindow})\n * after the registry lookup comes up empty. The value is either a single\n * window (`\"32768\"`, applied to every model) or a per-model map\n * (`\"llama3.1:8b=32768, qwen=128k, 64k\"`, with an optional bare fallback).\n * Pair it with a {@link CustomField} that mirrors the user's value into the\n * same `envVar` so the footer's context indicator and auto-compaction work\n * for local models.\n */\n contextWindowEnvVar?: string\n}\n\n/** Convenience accessor — returns `credentialFileKey ?? key`. */\nexport function credKeyOf(desc: ProviderDescriptor): string {\n return desc.credentialFileKey ?? desc.key\n}\n\n/** Convenience accessor — returns `piProviderId ?? key`. */\nexport function piIdOf(desc: ProviderDescriptor): string {\n return desc.piProviderId ?? desc.key\n}\n\n// ---------------------------------------------------------------------------\n// Built-in descriptors\n// ---------------------------------------------------------------------------\n\nexport const anthropicDescriptor: ProviderDescriptor = {\n key: 'anthropic',\n label: 'Anthropic',\n factory: anthropic,\n defaultModel: 'claude-opus-4-8',\n envKey: 'ANTHROPIC_API_KEY',\n apiKeyPlaceholder: 'sk-ant-…',\n oauthProvider: anthropicOAuthProvider,\n oauthHint: 'Claude Pro/Max subscription',\n extraModels: ANTHROPIC_EXTRA_MODELS,\n optionsFor: id => FAST_MODE_OPTIONS[id] ? [FAST_MODE_OPTIONS[id]] : undefined,\n}\n\nexport const openaiDescriptor: ProviderDescriptor = {\n key: 'openai',\n label: 'OpenAI',\n factory: openai,\n defaultModel: 'gpt-5.5',\n envKey: 'OPENAI_CODEX_API_KEY',\n credentialFileKey: 'openai-codex',\n piProviderId: 'openai-codex',\n apiKeyPlaceholder: 'sk-… or eyJ… (Codex)',\n oauthProvider: openaiCodexOAuthProvider,\n optionsFor: id => id === 'gpt-5.5'\n ? [{\n id: 'fast',\n label: 'Fast mode',\n description: 'Priority tier at 2.5× pricing',\n costMultiplier: { input: 2.5, output: 2.5, cacheRead: 2.5, cacheWrite: 2.5 },\n }]\n : undefined,\n}\n\nexport const openrouterDescriptor: ProviderDescriptor = {\n key: 'openrouter',\n label: 'OpenRouter',\n factory: openrouter,\n defaultModel: 'anthropic/claude-sonnet-4.6',\n envKey: 'OPENROUTER_API_KEY',\n apiKeyPlaceholder: 'sk-or-…',\n // Metadata-side mirror of the OpenRouter provider's wire alias (see\n // `MODEL_ALIASES` in `src/providers/openrouter.ts`). Keeps context-window /\n // reasoning lookups resolving for sessions persisted with the old slug.\n modelAliases: {\n 'anthropic/claude-sonnet-4-6': 'anthropic/claude-sonnet-4.6',\n },\n}\n\nexport const cerebrasDescriptor: ProviderDescriptor = {\n key: 'cerebras',\n label: 'Cerebras',\n factory: cerebras,\n defaultModel: 'zai-glm-4.7',\n envKey: 'CEREBRAS_API_KEY',\n apiKeyPlaceholder: 'csk-…',\n}\n\n/**\n * xAI Grok. Supports BOTH a static API key (`XAI_API_KEY`) and the\n * SuperGrok / X Premium+ OAuth subscription, so the wizard offers both methods.\n * Models come from pi-ai's `xai` registry (OpenAI-compatible endpoint), shared\n * by both auth modes.\n */\nexport const xaiDescriptor: ProviderDescriptor = {\n key: 'xai',\n label: 'xAI Grok',\n factory: xai,\n defaultModel: 'grok-4.3',\n envKey: 'XAI_API_KEY',\n apiKeyPlaceholder: 'xai-…',\n oauthProvider: xaiOAuthProvider,\n oauthHint: 'SuperGrok / X Premium+ subscription',\n // pi-ai stores the OAuth credential under the provider id, distinct from the\n // `xai` descriptor key so the API-key and OAuth credentials never collide.\n credentialFileKey: 'xai-oauth',\n piProviderId: 'xai',\n}\n\n/**\n * Arcee Trinity models (Platform API slugs). pi-ai has no Arcee registry, so we\n * ship a curated list. `reasoning: true` surfaces the effort/thinking UI — the\n * `arcee()` factory round-trips Trinity's `reasoning_content` across turns so the\n * model resumes its chain-of-thought through tool calls.\n *\n * Costs/context per Arcee's published Trinity catalogue.\n */\nconst ARCEE_MODELS: readonly ModelInfo[] = [\n { id: 'trinity-large-thinking', name: 'Trinity Large (Thinking)', contextWindow: 256_000, reasoning: true, input: ['text'], cost: { input: 0.25, output: 0.8 } },\n { id: 'trinity-large-preview', name: 'Trinity Large (Preview)', contextWindow: 128_000, input: ['text'], cost: { input: 0.45, output: 0.15 } },\n { id: 'trinity-mini', name: 'Trinity Mini', contextWindow: 128_000, input: ['text'], cost: { input: 0.045, output: 0.15 } },\n]\n\nexport const arceeDescriptor: ProviderDescriptor = {\n key: 'arcee',\n label: 'Arcee',\n factory: arcee,\n defaultModel: 'trinity-large-thinking',\n envKey: 'ARCEE_API_KEY',\n apiKeyPlaceholder: 'arcee-…',\n models: ARCEE_MODELS,\n}\n\n/**\n * Baseten Model APIs catalogue. pi-ai has no Baseten registry, so we ship a\n * curated list mirroring https://docs.baseten.co/inference/model-apis/overview\n * (context windows) and Baseten's published per-MTok rates. Models without a\n * `cost` (GLM 5.1, Nemotron Ultra) have no published rate yet — the footer\n * cost indicator hides for those. `/v1/models` is the live source of truth.\n *\n * All listed models support reasoning (`reasoning_content`); the `baseten()`\n * factory maps the thinking level to `reasoning_effort` / `chat_template_args`\n * per model.\n */\nconst BASETEN_MODELS: readonly ModelInfo[] = [\n { id: 'zai-org/GLM-5.2', name: 'GLM 5.2', contextWindow: 1_000_000, reasoning: true, input: ['text'] },\n { id: 'zai-org/GLM-5.1', name: 'GLM 5.1', contextWindow: 200_000, reasoning: true, input: ['text'] },\n { id: 'zai-org/GLM-5', name: 'GLM 5', contextWindow: 200_000, reasoning: true, input: ['text'], cost: { input: 0.95, output: 3.15, cacheRead: 0.2 } },\n { id: 'zai-org/GLM-4.7', name: 'GLM 4.7', contextWindow: 200_000, reasoning: true, input: ['text'], cost: { input: 0.6, output: 2.2, cacheRead: 0.12 } },\n { id: 'moonshotai/Kimi-K2.6', name: 'Kimi K2.6', contextWindow: 256_000, reasoning: true, input: ['text', 'image'], cost: { input: 1, output: 3.9, cacheRead: 0.2 } },\n { id: 'moonshotai/Kimi-K2.5', name: 'Kimi K2.5', contextWindow: 256_000, reasoning: true, input: ['text', 'image'], cost: { input: 0.6, output: 3, cacheRead: 0.12 } },\n { id: 'deepseek-ai/DeepSeek-V4-Pro', name: 'DeepSeek V4 Pro', contextWindow: 131_000, reasoning: true, input: ['text'], cost: { input: 1.74, output: 3.48, cacheRead: 0.145 } },\n { id: 'nvidia/Nemotron-120B-A12B', name: 'Nemotron Super', contextWindow: 200_000, reasoning: true, input: ['text'], cost: { input: 0.3, output: 0.75, cacheRead: 0.06 } },\n { id: 'nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B', name: 'Nemotron Ultra', contextWindow: 200_000, reasoning: true, input: ['text'] },\n { id: 'openai/gpt-oss-120b', name: 'GPT-OSS 120B', contextWindow: 128_000, reasoning: true, input: ['text'], cost: { input: 0.1, output: 0.5 } },\n]\n\nexport const basetenDescriptor: ProviderDescriptor = {\n key: 'baseten',\n label: 'Baseten',\n factory: baseten,\n defaultModel: 'zai-org/GLM-5.1',\n envKey: 'BASETEN_API_KEY',\n apiKeyPlaceholder: 'baseten-api-key…',\n models: BASETEN_MODELS,\n}\n\n/**\n * Conservative context-window assumption for a user-configured local model.\n * Local runtimes expose no reliable per-model metadata over the OpenAI-compat\n * `/v1/models` endpoint (it returns ids, not context sizes), so we pick a\n * floor that fits the smallest mainstream OSS models (Llama 3.x 8B, Qwen2.5)\n * without over-promising. The footer's context indicator and auto-compaction\n * lean on this — under-estimating is the safe direction (compact early rather\n * than overflow the server's real window).\n *\n * Users running larger-context models (e.g. a 128K Qwen) can raise it via the\n * `LOCAL_LLM_CONTEXT_WINDOW` env var / customField, which supports a single\n * value or a per-model map (resolved by {@link resolveContextWindow}).\n */\nconst LOCAL_DEFAULT_CONTEXT_WINDOW = 8_192\n\n/**\n * Local OpenAI-compatible LLM (Ollama, vLLM, LM Studio, Lemonade, llama.cpp).\n *\n * No fixed base URL or model catalogue — both come from the user via\n * `customFields`. No `envKey`, so the wizard skips the API-key prompt and\n * treats the customFields-only credential as the auth signal (see\n * `applyApiKeyEnv` + `detectAuth`).\n *\n * Vision / cache / reasoning are off by default in the factory — flip them\n * by passing a custom descriptor that calls `local({ capabilities })`.\n *\n * `models` is a getter, not a static list: there's no fixed catalogue to ship,\n * but once the user has configured a default model (mirrored into\n * `LOCAL_LLM_DEFAULT_MODEL` by `applyApiKeyEnv`), we surface it as a\n * single-entry list so the model picker + footer aren't empty. Resolved at\n * access time because the env var is populated at TUI launch, after this\n * module loads. Empty list when unconfigured — the picker hides, the user\n * types a slug at the prompt as before.\n */\nexport const localDescriptor: ProviderDescriptor = {\n key: 'local',\n label: 'Local LLM',\n factory: local,\n get models(): readonly ModelInfo[] {\n const configured = process.env.LOCAL_LLM_DEFAULT_MODEL?.trim()\n if (!configured)\n return []\n // Resolve the window from the user's `LOCAL_LLM_CONTEXT_WINDOW` (single\n // value or per-model map), falling back to the conservative default. Uses\n // the same parser as `getContextWindow`'s `contextWindowEnvVar` path so\n // both surfaces agree on the number.\n const resolved = resolveContextWindow(process.env.LOCAL_LLM_CONTEXT_WINDOW, configured)\n return [{\n id: configured,\n name: configured,\n contextWindow: resolved ?? LOCAL_DEFAULT_CONTEXT_WINDOW,\n input: ['text'],\n }]\n },\n customFields: [\n {\n key: 'baseURL',\n label: 'Base URL',\n envVar: 'LOCAL_LLM_BASE_URL',\n placeholder: 'http://localhost:11434/v1',\n hint: 'Where your local LLM server is reachable. Examples: Ollama → http://localhost:11434/v1, vLLM → http://localhost:8000/v1, LM Studio → http://localhost:1234/v1.',\n required: true,\n },\n {\n key: 'apiKey',\n label: 'API key',\n envVar: 'LOCAL_LLM_API_KEY',\n placeholder: 'leave blank if your server is unauthenticated',\n },\n {\n key: 'model',\n label: 'Default model',\n envVar: 'LOCAL_LLM_DEFAULT_MODEL',\n placeholder: 'e.g. llama3.1:8b, qwen2.5-coder, mistral-small',\n hint: 'Model id your server exposes. Leave blank to pick later from the model picker.',\n },\n {\n key: 'contextWindow',\n label: 'Context window (tokens)',\n envVar: 'LOCAL_LLM_CONTEXT_WINDOW',\n placeholder: 'e.g. 32768 · or per-model: llama3.1:8b=32768, qwen2.5-coder=128k, 64k',\n hint: 'Context length(s) for your local model(s) — local runtimes don\\'t advertise this, so set it here to enable the context indicator and auto-compaction. Use a single value (32768, 128k) for all models, or a comma-separated map of `model=window` with an optional bare value as the fallback. Press',\n },\n ],\n contextWindowEnvVar: 'LOCAL_LLM_CONTEXT_WINDOW',\n}\n\n/**\n * Cursor models. pi-ai has no Cursor registry, so we ship a small curated\n * list (Cursor proxies these). Context windows are nominal — Cursor inference\n * isn't wired yet (the provider's `stream()` throws), so these only drive the\n * picker once the protobuf transport lands.\n */\nconst CURSOR_MODELS: readonly ModelInfo[] = [\n { id: 'claude-4.6-sonnet', name: 'Claude Sonnet 4.6', contextWindow: 200_000, reasoning: true, input: ['text', 'image'] },\n { id: 'claude-4.8-opus', name: 'Claude Opus 4.8', contextWindow: 200_000, reasoning: true, input: ['text', 'image'] },\n { id: 'gpt-5.5', name: 'GPT-5.5', contextWindow: 272_000, reasoning: true, input: ['text', 'image'] },\n { id: 'composer-2', name: 'Composer 2', contextWindow: 200_000, input: ['text'] },\n { id: 'composer-2.5', name: 'Composer 2.5', contextWindow: 200_000, input: ['text'] },\n]\n\nexport const cursorDescriptor: ProviderDescriptor = {\n key: 'cursor',\n label: 'Cursor',\n factory: cursor,\n defaultModel: 'claude-4.6-sonnet',\n // OAuth-only: no API-key env var.\n envKey: undefined,\n oauthProvider: cursorOAuthProvider,\n oauthHint: 'Cursor subscription',\n models: CURSOR_MODELS,\n}\n\n/**\n * Default provider registry. Passed verbatim when `runTui` is invoked without\n * an explicit `providers` option. Hosts that want to override per-provider\n * metadata can spread this and replace specific entries:\n *\n * ```ts\n * runTui({ providers: { ...BUILTIN_PROVIDERS, anthropic: myOwnAnthropicDescriptor } })\n * ```\n *\n * `cursor` is intentionally NOT registered here: OAuth works, but inference\n * isn't wired (`cursor.stream()` throws — Cursor speaks a protobuf/HTTP-2\n * agent protocol, not OpenAI-compat). Shipping it in the picker only lets users\n * select a model that errors every turn. The descriptor stays exported so a\n * host can opt in (`{ ...BUILTIN_PROVIDERS, cursor: cursorDescriptor }`) once\n * the transport lands — re-add it here at that point.\n */\nexport const BUILTIN_PROVIDERS: Readonly<Record<string, ProviderDescriptor>> = {\n anthropic: anthropicDescriptor,\n openai: openaiDescriptor,\n openrouter: openrouterDescriptor,\n cerebras: cerebrasDescriptor,\n xai: xaiDescriptor,\n arcee: arceeDescriptor,\n baseten: basetenDescriptor,\n local: localDescriptor,\n}\n\n// ---------------------------------------------------------------------------\n// Model registry helper\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the model list for a given provider. Honors `descriptor.models`\n * when set; otherwise queries pi-ai via `descriptor.piProviderId`. Returns\n * `[]` for descriptors with no known mapping (custom providers without a\n * model list) — callers should hide the model picker in that case.\n */\nexport function modelsForDescriptor(descriptor: ProviderDescriptor): readonly ModelInfo[] {\n if (descriptor.models)\n return descriptor.models\n let bundled: readonly ModelInfo[]\n try {\n bundled = getModels(piIdOf(descriptor) as never) as readonly ModelInfo[]\n }\n catch {\n bundled = []\n }\n if (descriptor.extraModels?.length) {\n // Merge extras ahead of the bundled list, de-duped by id (bundled wins, so a\n // model that lands in pi-ai later transparently supersedes the local entry).\n const bundledIds = new Set(bundled.map(m => m.id))\n const extras = descriptor.extraModels.filter(m => !bundledIds.has(m.id))\n bundled = [...extras, ...bundled]\n }\n return descriptor.optionsFor ? bundled.map(m => decorateOptions(m, descriptor)) : bundled\n}\n\n/**\n * Attach descriptor-resolved {@link ModelOption}s to a model that doesn't\n * already declare its own. Pure / non-mutating — returns the input untouched\n * when the model has options already or the descriptor resolves none.\n */\nfunction decorateOptions(model: ModelInfo, descriptor: ProviderDescriptor): ModelInfo {\n if (model.options?.length || !descriptor.optionsFor)\n return model\n const options = descriptor.optionsFor(model.id)\n return options?.length ? { ...model, options } : model\n}\n\n/**\n * Resolve a single model's metadata via the descriptor's model source.\n * Mirrors {@link modelsForDescriptor} routing: descriptor's own list wins,\n * pi-ai's registry is the fallback. Returns `null` when the model isn't\n * known.\n */\nexport function getModelInfo(descriptor: ProviderDescriptor, modelId: string): ModelInfo | null {\n const lookupId = descriptor.modelAliases?.[modelId] ?? modelId\n if (descriptor.models)\n return descriptor.models.find(m => m.id === lookupId) ?? null\n try {\n const bundled = getModel(piIdOf(descriptor) as never, lookupId as never) as ModelInfo | undefined\n if (bundled)\n return decorateOptions(bundled, descriptor)\n }\n catch {\n // fall through to extras\n }\n const extra = descriptor.extraModels?.find(m => m.id === lookupId)\n return extra ? decorateOptions(extra, descriptor) : null\n}\n\n/**\n * Parse a user-supplied context-window string into a token count.\n *\n * Accepts a plain integer (`\"32768\"`), or a number with a `k`/`m` suffix\n * (×1_000 / ×1_000_000, case-insensitive, optional space) — so `\"128k\"`\n * yields `128_000`, matching how the footer renders windows (`fmtTokens`).\n * Fractional values are floored (`\"1.5k\"` → `1500`). Returns `null` for\n * empty, malformed, zero, or negative input so callers fall through to\n * \"window unknown\" rather than a bogus ceiling.\n */\nexport function parseContextWindow(raw: string | undefined | null): number | null {\n if (raw == null)\n return null\n const trimmed = raw.trim()\n if (trimmed.length === 0)\n return null\n const match = /^(\\d+(?:\\.\\d+)?)\\s*([km])?$/i.exec(trimmed)\n if (!match)\n return null\n const suffix = match[2]?.toLowerCase()\n const mult = suffix === 'k' ? 1_000 : suffix === 'm' ? 1_000_000 : 1\n const value = Math.floor(Number.parseFloat(match[1]) * mult)\n return value >= 1 ? value : null\n}\n\n/**\n * Resolve a per-model context window from a user-supplied spec string.\n *\n * A spec is a comma-separated list of entries. An entry is either:\n * - `model=window` — a per-model override (split on the **first** `=`, so\n * model ids containing `:` or `/` survive), or\n * - a bare `window` — the fallback applied to any model not named above.\n *\n * Windows are parsed by {@link parseContextWindow} (plain int or k/m suffix).\n * Whitespace around entries and the `=` is ignored; malformed entries are\n * skipped rather than poisoning the whole spec; a later duplicate key wins.\n *\n * Lookup order for `modelId`: exact map entry → bare fallback → `null`. A\n * lone bare value (`\"32768\"`) therefore behaves as a single global window,\n * keeping the simple single-model config working.\n *\n * @example resolveContextWindow('llama3.1:8b=32768, qwen=128k, 64k', 'qwen') // 128000\n */\nexport function resolveContextWindow(spec: string | undefined | null, modelId: string): number | null {\n if (spec == null)\n return null\n const overrides = new Map<string, number>()\n let fallback: number | null = null\n for (const entry of spec.split(',')) {\n const eq = entry.indexOf('=')\n if (eq === -1) {\n const bare = parseContextWindow(entry)\n if (bare != null)\n fallback = bare\n continue\n }\n const key = entry.slice(0, eq).trim()\n const window = parseContextWindow(entry.slice(eq + 1))\n if (key.length > 0 && window != null)\n overrides.set(key, window)\n }\n return overrides.get(modelId) ?? fallback\n}\n\n/**\n * Look up the model's max context window via the descriptor's model source.\n * Falls back to {@link ProviderDescriptor.contextWindowEnvVar} (parsed via\n * {@link resolveContextWindow}, which supports a per-model map) when the\n * registry has nothing — this is how local LLMs, whose runtimes don't\n * advertise a window, get one. Returns `null` when neither source resolves a\n * value (custom slugs, providers without a registry or a configured window);\n * callers should hide the context indicator and skip auto-compaction then.\n */\nexport function getContextWindow(descriptor: ProviderDescriptor, modelId: string): number | null {\n const fromRegistry = getModelInfo(descriptor, modelId)?.contextWindow\n if (fromRegistry != null)\n return fromRegistry\n if (descriptor.contextWindowEnvVar)\n return resolveContextWindow(process.env[descriptor.contextWindowEnvVar], modelId)\n return null\n}\n\n// `OUTPUT_RESERVE_TOKENS` + `effectiveContextWindow` moved to the core\n// `src/compact/policy.ts` so the agent loop (which can't import `src/chat/`)\n// shares the same window math as the chat footer + auto-compact trigger.\n// Re-exported here so existing `chat/providers` importers keep working.\nexport { effectiveContextWindow, OUTPUT_RESERVE_TOKENS } from '../compact/policy'\n\n/**\n * Whether the given model exposes a reasoning / extended-thinking knob.\n * Drives the TUI's effort picker visibility — the `ctrl+n` shortcut and\n * the bottom-bar `effortName` segment only surface when this is `true`.\n * Returns `false` for unknown models (no registry entry → no advertised\n * capability).\n */\nexport function modelSupportsReasoning(descriptor: ProviderDescriptor, modelId: string): boolean {\n return getModelInfo(descriptor, modelId)?.reasoning === true\n}\n\n/**\n * Custom {@link ModelOption}s the given model supports (e.g. fast mode), or `[]`\n * when none. Drives the TUI/GUI options picker visibility — surfaces only when\n * non-empty.\n */\nexport function modelOptionsFor(descriptor: ProviderDescriptor, modelId: string): readonly ModelOption[] {\n return getModelInfo(descriptor, modelId)?.options ?? []\n}\n\n/**\n * Normalize a model-options blob to an enabled-only `{ id: true }` map.\n *\n * Single source of truth shared by every surface that reads or persists model\n * options — the TUI run path, the GUI engine reader, and the GUI IPC handlers.\n * Tolerant of arbitrary input (persisted JSON metadata may be anything): a\n * non-object → `{}`, and only entries strictly equal to `true` survive. This\n * keeps the persisted shape minimal (no `{ fast: false }` noise) and means\n * callers never forward a disabled option to `agent.run`.\n */\nexport function enabledModelOptions(raw: unknown): Record<string, boolean> {\n if (!raw || typeof raw !== 'object')\n return {}\n const out: Record<string, boolean> = {}\n for (const [id, on] of Object.entries(raw as Record<string, unknown>)) {\n if (on === true)\n out[id] = true\n }\n return out\n}\n\n/**\n * Resolve a model's remembered options for a (re)pick: keep only options the\n * model still declares AND that are enabled, dropping any that no longer apply\n * (e.g. switching away from a model that supported `fast`). Returns `undefined`\n * when nothing applies so callers can omit the field entirely.\n *\n * Shared by the TUI pick path and the launch-time resume path so \"which options\n * survive a model switch / relaunch\" is decided in exactly one place.\n */\nexport function restoreModelOptions(\n descriptor: ProviderDescriptor,\n modelId: string,\n remembered: Record<string, Record<string, boolean>> | undefined,\n): Record<string, boolean> | undefined {\n const validIds = new Set(modelOptionsFor(descriptor, modelId).map(o => o.id))\n if (validIds.size === 0)\n return undefined\n const enabled = enabledModelOptions(remembered?.[modelId])\n const filtered: Record<string, boolean> = {}\n for (const id of Object.keys(enabled)) {\n if (validIds.has(id))\n filtered[id] = true\n }\n return Object.keys(filtered).length > 0 ? filtered : undefined\n}\n","/**\n * Credential storage for the TUI.\n *\n * Lives at `<dataDir>/credentials.json` (default `~/.zidane/credentials.json`,\n * overridable via `ZIDANE_STORAGE_DIR`). Owner-only (0o600) so refresh tokens\n * and API keys don't leak on shared boxes.\n *\n * Two credential kinds:\n * - `apikey` — a plain API key entered by the user (e.g. via the setup wizard).\n * - `oauth` — tokens obtained via a provider's OAuth flow (refresh-aware).\n *\n * **Schema note.** File keys come from {@link ProviderDescriptor.credentialFileKey}\n * (falling back to `descriptor.key`). They must match what the harness providers\n * look up at runtime — for built-ins this is `anthropic`, `openai-codex`,\n * `openrouter`, `cerebras`. Hosts that ship custom providers control the file\n * key via the descriptor.\n *\n * The legacy `cwd/.credentials.json` (written by `bun run auth` in older\n * versions) is migrated on first read if the new file doesn't exist yet. The\n * legacy file is left in place — we don't delete user data behind their back.\n */\n\nimport type { ProviderDescriptor } from './providers'\nimport { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, resolve } from 'node:path'\nimport { writeFileAtomic } from '../atomic-write'\nimport { credKeyOf } from './providers'\n\n/** POSIX mode for the credentials file. Ignored on Windows. */\nconst FILE_MODE = 0o600\n\nexport interface ApiKeyCredential {\n kind: 'apikey'\n /**\n * Bearer API key. May be empty when the descriptor has no `envKey` and\n * authenticates entirely via {@link customFields} (e.g. the `local`\n * provider, where the auth signal is the configured base URL).\n */\n value: string\n /**\n * Free-form fields collected by the wizard from the descriptor's\n * `customFields` definitions. Keys match the descriptor field's `key`.\n * Mirrored into `process.env[field.envVar]` by `applyApiKeyEnv` so the\n * provider's factory can read them via the existing env-var convention.\n */\n customFields?: Record<string, string>\n}\nexport interface OAuthCredential {\n kind: 'oauth'\n access: string\n refresh?: string\n expires?: number\n /** Provider-specific extras (e.g. OpenAI Codex `accountId`). */\n [extra: string]: unknown\n}\nexport type ProviderCredential = ApiKeyCredential | OAuthCredential\n\n/** Top-level shape of `credentials.json` — keys are credential-file keys. */\nexport type CredentialsFile = Record<string, ProviderCredential>\n\n/**\n * Resolve the credentials file path given the resolved TUI data directory\n * (typically `~/.zidane`, i.e. `config.paths.dir`).\n *\n * Matches the convention used elsewhere in the TUI (sessions.db, state.json)\n * so a single `ZIDANE_STORAGE_DIR` override moves the entire data root.\n */\nexport function credentialsPath(dataDir: string): string {\n return resolve(dataDir, 'credentials.json')\n}\n\n/**\n * Read credentials from disk.\n *\n * Returns `{}` when the file is missing or corrupt (last-ditch tolerance —\n * a hand-edit gone wrong shouldn't lock the user out of re-authing). On first\n * call with no file present, attempts a migration from `cwd/.credentials.json`\n * (the legacy location used by `bun run auth`).\n */\nexport function readCredentials(dataDir: string): CredentialsFile {\n const path = credentialsPath(dataDir)\n\n if (!existsSync(path)) {\n const migrated = migrateLegacyFile(path)\n if (migrated)\n return migrated\n return {}\n }\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 return parsed as CredentialsFile\n }\n catch {\n return {}\n }\n}\n\n/** Read a single provider's credential (translating via the descriptor). */\nexport function readProviderCredential(dataDir: string, descriptor: ProviderDescriptor): ProviderCredential | undefined {\n return readCredentials(dataDir)[credKeyOf(descriptor)]\n}\n\n/**\n * Write credentials atomically (write-then-rename) with mode 0o600.\n *\n * Atomic on the same filesystem — readers either see the previous file or the\n * new one, never a half-written intermediate. Creates the parent dir if needed\n * (first launch on a fresh machine: `~/.zidane/` may not exist yet).\n */\nexport function writeCredentials(dataDir: string, creds: CredentialsFile): void {\n writeFileAtomic(\n credentialsPath(dataDir),\n `${JSON.stringify(creds, null, 2)}\\n`,\n { ensureDir: true, mode: FILE_MODE },\n )\n}\n\nexport function setProviderCredential(\n dataDir: string,\n descriptor: ProviderDescriptor,\n cred: ProviderCredential,\n): void {\n const all = readCredentials(dataDir)\n all[credKeyOf(descriptor)] = cred\n writeCredentials(dataDir, all)\n}\n\nexport function removeProviderCredential(dataDir: string, descriptor: ProviderDescriptor): void {\n const all = readCredentials(dataDir)\n const fileKey = credKeyOf(descriptor)\n if (!(fileKey in all))\n return\n delete all[fileKey]\n writeCredentials(dataDir, all)\n}\n\n/**\n * Reconcile `process.env` with the stored credentials so the harness providers\n * pick up the wizard's output via their existing env-var resolution. Called\n * once at TUI launch after the credentials file has been resolved.\n *\n * **Precedence: stored credential > ambient env.** When the user has run the\n * auth wizard, that's an explicit, recent action — it MUST win over whatever\n * ambient value is already in `process.env`. Otherwise an upgrade reliably\n * breaks for anyone whose cwd happens to contain a stale `.env`: Bun\n * auto-loads `.env` from cwd into `process.env` before our code runs, the\n * legacy `bun run auth` used to upsert tokens into `cwd/.env`, and even a\n * one-off `export ANTHROPIC_API_KEY=…` from months ago in the user's shell rc\n * can outlive its usefulness. None of those should override a key the user\n * just typed into the wizard.\n *\n * Three cases per registered provider with an `envKey`:\n *\n * 1. Stored `kind: 'apikey'` → overwrite env with the stored value. Wizard\n * wins. A debug log fires when this clobbers a different ambient value.\n * 2. Stored `kind: 'oauth'` → DELETE env, so {@link resolveOAuthApiKey}\n * falls through to the file-read + refresh path. A stale OAuth token\n * in env would otherwise short-circuit refresh and get rejected.\n * 3. No stored entry → leave env alone. Env-only setups (no wizard run yet,\n * hosts driving zidane purely from secrets management) keep working.\n *\n * To opt out and force ambient env to win again, the user signs the provider\n * out via the wizard (which deletes the stored entry → case 3 above).\n *\n * Descriptors without an `envKey` (OAuth-only providers, custom providers\n * that bypass env-var resolution) are skipped silently.\n */\nexport function applyApiKeyEnv(\n dataDir: string,\n registry: Readonly<Record<string, ProviderDescriptor>>,\n): void {\n const creds = readCredentials(dataDir)\n for (const descriptor of Object.values(registry)) {\n const cred = creds[credKeyOf(descriptor)]\n\n // Mirror customFields → env regardless of whether the descriptor has an\n // envKey. Same \"stored beats ambient\" semantics as the API-key path.\n if (cred?.kind === 'apikey' && descriptor.customFields) {\n const stored = cred.customFields ?? {}\n for (const field of descriptor.customFields) {\n const value = stored[field.key]\n if (typeof value === 'string' && value.length > 0) {\n const ambient = process.env[field.envVar]\n if (ambient && ambient !== value && process.env.ZIDANE_DEBUG) {\n process.stderr.write(\n `[zidane/chat] applyApiKeyEnv: overriding ambient \\`${field.envVar}\\` `\n + `with stored value from credentials.json (provider=${descriptor.key}, field=${field.key}).\\n`,\n )\n }\n process.env[field.envVar] = value\n }\n }\n }\n\n if (!descriptor.envKey)\n continue\n const envKey = descriptor.envKey\n const ambient = process.env[envKey]\n\n if (cred?.kind === 'apikey' && cred.value) {\n if (ambient && ambient !== cred.value && process.env.ZIDANE_DEBUG) {\n process.stderr.write(\n `[zidane/chat] applyApiKeyEnv: overriding ambient \\`${envKey}\\` `\n + `with stored API key from credentials.json (provider=${descriptor.key}). `\n + `Sign out via the auth wizard if the ambient value was intended to win.\\n`,\n )\n }\n process.env[envKey] = cred.value\n continue\n }\n\n if (cred?.kind === 'oauth' && cred.access) {\n if (ambient !== undefined && process.env.ZIDANE_DEBUG) {\n process.stderr.write(\n `[zidane/chat] applyApiKeyEnv: clearing ambient \\`${envKey}\\` because `\n + `credentials.json has stored OAuth for ${descriptor.key} — refresh path needs the file.\\n`,\n )\n }\n delete process.env[envKey]\n continue\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Legacy migration\n// ---------------------------------------------------------------------------\n\n/**\n * `bun run auth` (pre-TUI) wrote `cwd/.credentials.json` with an entry per\n * provider mapping directly to an OAuthCredentials payload, e.g.:\n *\n * {\n * \"anthropic\": { \"access\": \"...\", \"refresh\": \"...\", \"expires\": 123 },\n * \"openai-codex\": { \"access\": \"...\", \"refresh\": \"...\", \"expires\": 123, \"accountId\": \"...\" }\n * }\n *\n * We don't delete the legacy file — it might still be used by a host that\n * imports the harness directly. We just copy its contents into the new\n * location under the kind-tagged shape so the TUI picks them up.\n *\n * Migration is provider-agnostic: any top-level entry with an `access` field\n * is preserved verbatim (extras included), under the same key. The TUI's\n * detection then looks them up via the matching descriptor's `credentialFileKey`.\n *\n * Returns the migrated credentials when the migration ran, or `null` when\n * there's no legacy file to migrate.\n */\nfunction migrateLegacyFile(targetPath: string): CredentialsFile | null {\n const legacyPath = resolve(process.cwd(), '.credentials.json')\n // Only trust a legacy file that sits directly in the user's home dir (where\n // `bun run auth` was typically run) or next to the migration target. A\n // cwd-relative read from an arbitrary checkout would let an untrusted repo\n // plant a `.credentials.json` that gets persisted as the USER-LEVEL\n // credential file. Compared via realpath so symlinked dirs (e.g. macOS\n // `/var` → `/private/var`) don't defeat the check.\n const real = (p: string): string => {\n try {\n return realpathSync(p)\n }\n catch {\n return p\n }\n }\n const legacyDir = real(dirname(legacyPath))\n if (legacyDir !== real(homedir()) && legacyDir !== real(dirname(resolve(targetPath))))\n return null\n if (!existsSync(legacyPath))\n return null\n\n let legacy: Record<string, unknown>\n try {\n legacy = JSON.parse(readFileSync(legacyPath, 'utf-8'))\n }\n catch {\n return null\n }\n if (!legacy || typeof legacy !== 'object' || Array.isArray(legacy))\n return null\n\n const migrated: CredentialsFile = {}\n for (const [fileKey, value] of Object.entries(legacy)) {\n if (!isOAuthLegacy(value))\n continue\n const { access, refresh, expires, ...extras } = value\n migrated[fileKey] = {\n kind: 'oauth',\n access,\n ...(typeof refresh === 'string' ? { refresh } : {}),\n ...(typeof expires === 'number' ? { expires } : {}),\n ...extras,\n }\n }\n\n if (Object.keys(migrated).length === 0)\n return null\n\n // Persist immediately so subsequent reads use the new file directly.\n writeFileAtomic(\n targetPath,\n `${JSON.stringify(migrated, null, 2)}\\n`,\n { ensureDir: true, mode: FILE_MODE },\n )\n\n return migrated\n}\n\nfunction isOAuthLegacy(value: unknown): value is { access: string, refresh?: string, expires?: number, [extra: string]: unknown } {\n return (\n typeof value === 'object'\n && value !== null\n && 'access' in value\n && typeof (value as { access: unknown }).access === 'string'\n )\n}\n","/**\n * XDG Base Directory resolution for zidane.\n *\n * The user's storage spreads across four logical slots:\n *\n * - **config** — credentials, mcp-credentials, keybindings, config.json,\n * mcps.json, skills (user-editable surface).\n * - **data** — sessions.db (long-lived chat history).\n * - **state** — state.json (per-machine UI bookkeeping: last provider,\n * last model, last agent, settings).\n * - **cache** — persisted tool results, background-task logs,\n * auto-update registry cache (regenerable, safe to wipe).\n *\n * Historically all four collapsed to `~/.zidane/`. This module adds\n * XDG-Base-Directory-aware defaults so a Linux user with no existing\n * `~/.zidane/` lands in the conventional `~/.config/zidane/`,\n * `~/.local/share/zidane/`, `~/.local/state/zidane/`, `~/.cache/zidane/`\n * trio. Existing setups (anyone with a `~/.zidane/` directory or\n * `ZIDANE_STORAGE_DIR` set) keep the single-dir layout unchanged.\n *\n * Resolution flow — applied in this order:\n *\n * 1. Caller passed an explicit `storageDir` (`ChatOptions.storageDir`)\n * OR `ZIDANE_STORAGE_DIR` is set → **legacy-explicit** single-dir\n * layout under `<storageDir>/<prefix>`. The four slots collapse to\n * the same directory.\n * 2. `~/<prefix>/` already exists on disk → **legacy-existing**\n * single-dir layout under that directory. Upgrades never silently\n * shift files around.\n * 3. Any `XDG_*_HOME` env var is set OR `process.platform === 'linux'`\n * → **XDG split**. Each slot lands in its own dir. Per-slot\n * `ZIDANE_{CONFIG,DATA,CACHE,STATE}_DIR` overrides beat the XDG\n * vars for surgical tweaks.\n * 4. Otherwise (macOS/Windows, no XDG signal, no existing dir) →\n * **default** single-dir layout at `~/<prefix>/`. Day-one behavior\n * on these platforms is unchanged.\n *\n * The `userDir` legacy alias always equals `configDir` so existing code\n * that still references `paths.userDir` keeps reading credentials, mcps,\n * etc. from the right place.\n */\n\nimport { existsSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { resolve } from 'node:path'\n\n/** The four slot kinds we resolve. Names match the XDG spec. */\nexport type StorageSlot = 'config' | 'data' | 'state' | 'cache'\n\n/** Which resolution branch produced the layout — surfaced for debugging + tests. */\nexport type StorageMode = 'legacy-explicit' | 'legacy-existing' | 'xdg' | 'default'\n\n/**\n * Per-slot directories. In legacy / default modes the four fields all\n * point at the same path; in XDG mode they fan out into their\n * spec-conventional locations.\n *\n * `mode` carries the resolution branch so a host that wants to print\n * a startup banner (\"zidane is using XDG paths\") can detect the\n * layout without re-running the logic.\n */\nexport interface StorageDirs {\n configDir: string\n dataDir: string\n stateDir: string\n cacheDir: string\n mode: StorageMode\n}\n\nexport interface ResolveStorageDirsOptions {\n /** Storage prefix. Leading dot tolerated. Default: `'.zidane'`. */\n prefix?: string\n /**\n * Explicit storage root (`ChatOptions.storageDir`). When set, forces\n * legacy-explicit mode regardless of the platform / XDG signals.\n */\n storageDir?: string\n /** Override `os.homedir()` for tests. */\n home?: string\n /** Override `process.platform` for tests. */\n platform?: NodeJS.Platform\n /** Override `process.env` for tests. */\n env?: Readonly<Record<string, string | undefined>>\n}\n\n/**\n * Resolve the four storage slots according to the precedence above.\n *\n * Pure aside from one filesystem probe (`existsSync(home/<prefix>)`)\n * — the same probe `resolveStoragePaths` would do anyway when\n * computing `paths.userDir`. No directories are created here; the\n * relevant write paths (state store, credentials writer, persist\n * dir) handle their own lazy `mkdirSync` already.\n */\nexport function resolveStorageDirs(opts: ResolveStorageDirsOptions = {}): StorageDirs {\n const env = opts.env ?? process.env\n const home = opts.home ?? homedir()\n const platform = opts.platform ?? process.platform\n // Two prefix forms — legacy mode preserves whatever the caller\n // passed (no implicit dot insertion, so `prefix: 'myapp'` lands at\n // `<storageDir>/myapp` not `<storageDir>/.myapp` — matches the\n // pre-XDG behavior tests already rely on). XDG mode uses the de-\n // dotted form (`'.zidane'` → `'zidane'`) because the XDG dir itself\n // is already the dotfile container — `~/.config/.zidane/` would be\n // a double-dot offense.\n const rawPrefix = opts.prefix ?? '.zidane'\n const prefixBare = rawPrefix.replace(/^\\./, '')\n\n // Branch 1 — explicit storage root → legacy-explicit.\n // Host-supplied `storageDir` beats env so SDK callers can pin a\n // location for embedded usage; otherwise `ZIDANE_STORAGE_DIR` wins.\n const explicitStorageDir = opts.storageDir ?? env.ZIDANE_STORAGE_DIR\n if (explicitStorageDir) {\n const base = resolve(explicitStorageDir, rawPrefix)\n return single(base, 'legacy-explicit')\n }\n\n // Branch 2 — `~/<prefix>/` already exists → legacy-existing.\n // Detect ANY of the legacy locations the user might have:\n // - `~/.zidane/` (default prefix)\n // - `~/.<prefix>/` (custom prefix)\n // The probe is a single existsSync (cheap) and skipping it for a\n // user with a customized prefix would leak their data into XDG dirs\n // on next launch.\n const legacyHomeDir = resolve(home, rawPrefix)\n if (existsSync(legacyHomeDir))\n return single(legacyHomeDir, 'legacy-existing')\n\n // Branch 3 — XDG signals present → split layout.\n // The signal is generous: Linux always qualifies, any platform\n // where the user has set any `XDG_*_HOME` var opts in (a savvy\n // mac user can put zidane in their XDG hierarchy too), AND any\n // `ZIDANE_{CONFIG,DATA,STATE,CACHE}_DIR` per-slot override also\n // opts in — otherwise a user pinning JUST `ZIDANE_CACHE_DIR` on\n // macOS would have it silently ignored because none of the\n // `XDG_*_HOME` vars are set.\n const hasXdgSignal = platform === 'linux'\n || !!env.XDG_CONFIG_HOME\n || !!env.XDG_DATA_HOME\n || !!env.XDG_CACHE_HOME\n || !!env.XDG_STATE_HOME\n || !!env.ZIDANE_CONFIG_DIR\n || !!env.ZIDANE_DATA_DIR\n || !!env.ZIDANE_STATE_DIR\n || !!env.ZIDANE_CACHE_DIR\n\n if (hasXdgSignal) {\n return {\n configDir: env.ZIDANE_CONFIG_DIR\n ?? resolve(env.XDG_CONFIG_HOME || resolve(home, '.config'), prefixBare),\n dataDir: env.ZIDANE_DATA_DIR\n ?? resolve(env.XDG_DATA_HOME || resolve(home, '.local', 'share'), prefixBare),\n stateDir: env.ZIDANE_STATE_DIR\n ?? resolve(env.XDG_STATE_HOME || resolve(home, '.local', 'state'), prefixBare),\n cacheDir: env.ZIDANE_CACHE_DIR\n ?? resolve(env.XDG_CACHE_HOME || resolve(home, '.cache'), prefixBare),\n mode: 'xdg',\n }\n }\n\n // Branch 4 — default (mac/windows, no XDG signal, no existing dir).\n // Same as the day-one experience: everything under `~/<prefix>/`.\n return single(legacyHomeDir, 'default')\n}\n\nfunction single(base: string, mode: StorageMode): StorageDirs {\n return {\n configDir: base,\n dataDir: base,\n stateDir: base,\n cacheDir: base,\n mode,\n }\n}\n","import type { ProviderCredential } from './credentials'\nimport type { ProviderDescriptor } from './providers'\nimport { readCredentials } from './credentials'\nimport { credKeyOf } from './providers'\n\n/**\n * Provider identifier as known to the TUI. Built-in keys are `anthropic`,\n * `openai`, `openrouter`, `cerebras`, but hosts can register additional\n * keys via {@link ProviderDescriptor} — so the type is open.\n */\nexport type ProviderKey = string\n\nexport interface AuthMethod {\n source: 'env' | 'oauth' | 'apikey'\n /** Human-readable detail (env var name, expiry timestamp, …). */\n detail: string\n}\n\nexport interface ProviderAuth {\n key: ProviderKey\n label: string\n /** True when at least one credential source is present. */\n available: boolean\n methods: AuthMethod[]\n}\n\n/**\n * Detect available auth for every registered provider.\n *\n * Resolution order per provider (a method appears in `methods` for each\n * layer that has a credential — the agent itself resolves them in the same\n * order via its provider factories):\n *\n * 1. `kind: 'apikey'` from `credentials.json` (injected into env at TUI launch)\n * 2. explicit env var (descriptor's `envKey`)\n * 3. `kind: 'oauth'` from `credentials.json` (or legacy `cwd/.credentials.json`)\n *\n * Pure read — never refreshes or rewrites the credentials file.\n */\nexport function detectAuth(\n dataDir: string,\n registry: Readonly<Record<string, ProviderDescriptor>>,\n env: Record<string, string | undefined> = process.env,\n): ProviderAuth[] {\n const creds = readCredentials(dataDir)\n\n return Object.values(registry).map((descriptor) => {\n const methods: AuthMethod[] = []\n const fileEntry = creds[credKeyOf(descriptor)] as ProviderCredential | undefined\n\n // 1. Stored API key\n if (fileEntry?.kind === 'apikey' && fileEntry.value)\n methods.push({ source: 'apikey', detail: 'credentials.json' })\n\n // 1b. customFields-only credential (descriptor has no `envKey` and is\n // authenticated entirely by configuration — e.g. the `local` provider,\n // where the auth signal is the configured base URL). The credential\n // is \"present\" when every required field has a stored value.\n if (\n fileEntry?.kind === 'apikey'\n && !fileEntry.value\n && descriptor.customFields\n && descriptor.customFields.length > 0\n ) {\n const stored = fileEntry.customFields ?? {}\n const required = descriptor.customFields.filter(f => f.required)\n const allRequiredPresent = required.every(\n f => typeof stored[f.key] === 'string' && (stored[f.key] as string).length > 0,\n )\n if (allRequiredPresent) {\n methods.push({ source: 'apikey', detail: 'credentials.json (configured)' })\n }\n }\n\n // 2. Env var (may be set by `applyApiKeyEnv` from a stored key, or by the\n // user's shell. Either way, treated as the same observable signal.)\n if (descriptor.envKey && env[descriptor.envKey])\n methods.push({ source: 'env', detail: descriptor.envKey })\n\n // 3. Stored OAuth\n if (fileEntry?.kind === 'oauth' && fileEntry.access) {\n const detail = typeof fileEntry.expires === 'number'\n ? `oauth · expires ${new Date(fileEntry.expires).toLocaleString()}`\n : 'oauth · credentials.json'\n methods.push({ source: 'oauth', detail })\n }\n\n return {\n key: descriptor.key,\n label: descriptor.label,\n available: methods.length > 0,\n methods,\n }\n })\n}\n"],"mappings":";;;;;;;;;;AAmBA,MAAM,gBAAgB,QAAQ,IA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
- import { Cr as ContextMcpGroup, Er as buildContextBreakdown, Sr as ContextItem, Tr as ContextUsageSplit, _r as ContextBreakdown, br as ContextCategoryId, vr as ContextBreakdownOptions, wr as ContextSnapshot, xr as ContextExactCounts, yr as ContextCategory } from "../agent-D7ZL8B2X.js";
2
- import { B as collectReferences, F as CompletionContext, H as mergeReferences, I as CompletionItem, L as CompletionProvider, P as ActiveTrigger, R as CompletionReference, V as findActiveTrigger, _ as isEditErrorResult, a as formatToolCall, b as selectableTurnIds, c as splitPromptSegments, g as EDIT_TOOL_NAMES, i as displayNameFor, n as ToolDisplayMeta, o as PromptSegment, r as ToolFormatLine, s as PromptSegmentRef, t as TOOL_DISPLAY, v as isTurnHighlighted, x as turnSelectionOwnership, y as isVisible, z as applyInsert } from "../tool-formatters-CNSMadtp.js";
3
- import { $ as uniqueFilesFromReferences, A as buildUnifiedDiff, C as EditSummary, D as PreviewResult, E as InlineSegment, F as previewEditPayload, I as splitLines, J as SKILLS_TRIGGER, L as summarizeEditPayload, M as computeLineDiff, N as extractEditPayload, O as applyEditPayload, P as filetypeFromPath, Q as createFilesCompletionProvider, R as tokenize, S as EditHunkSummary, T as InlineDiff, X as uniqueSkillNamesFromReferences, Y as createSkillsCompletionProvider, Z as FILES_TRIGGER, _ as formatTaskSummary, a as finalizeStreamingMarkdown, b as DiffLine, c as CatalogEntry, d as indexOfEntry, f as ageString, g as formatTaskStatus, h as formatDuration, i as turnAsText, it as buildLinearRamp, j as computeInlineDiff, k as buildContextualDiff, l as buildModelCatalog, m as fmtTokens, n as deleteTurnSafely, o as finalizeStreamingMarkdownForOwner, p as compactPath, q as summarizeOutcomes, r as truncateTurnsAt, rt as blendHsl, s as turnContextSize, t as countNeighbors, u as filterModelCatalog, v as previewLine, w as HunkResolution, x as DiffOp, y as shortId } from "../turn-operations-DwtWRYr1.js";
1
+ import { Cr as ContextMcpGroup, Er as buildContextBreakdown, Sr as ContextItem, Tr as ContextUsageSplit, _r as ContextBreakdown, br as ContextCategoryId, vr as ContextBreakdownOptions, wr as ContextSnapshot, xr as ContextExactCounts, yr as ContextCategory } from "../agent-w6htlFlx.js";
2
+ import { B as collectReferences, F as CompletionContext, H as mergeReferences, I as CompletionItem, L as CompletionProvider, P as ActiveTrigger, R as CompletionReference, V as findActiveTrigger, _ as isEditErrorResult, a as formatToolCall, b as selectableTurnIds, c as splitPromptSegments, g as EDIT_TOOL_NAMES, i as displayNameFor, n as ToolDisplayMeta, o as PromptSegment, r as ToolFormatLine, s as PromptSegmentRef, t as TOOL_DISPLAY, v as isTurnHighlighted, x as turnSelectionOwnership, y as isVisible, z as applyInsert } from "../tool-formatters-C7N1Pb1q.js";
3
+ import { $ as uniqueFilesFromReferences, A as buildUnifiedDiff, C as EditSummary, D as PreviewResult, E as InlineSegment, F as previewEditPayload, I as splitLines, J as SKILLS_TRIGGER, L as summarizeEditPayload, M as computeLineDiff, N as extractEditPayload, O as applyEditPayload, P as filetypeFromPath, Q as createFilesCompletionProvider, R as tokenize, S as EditHunkSummary, T as InlineDiff, X as uniqueSkillNamesFromReferences, Y as createSkillsCompletionProvider, Z as FILES_TRIGGER, _ as formatTaskSummary, a as finalizeStreamingMarkdown, b as DiffLine, c as CatalogEntry, d as indexOfEntry, f as ageString, g as formatTaskStatus, h as formatDuration, i as turnAsText, it as buildLinearRamp, j as computeInlineDiff, k as buildContextualDiff, l as buildModelCatalog, m as fmtTokens, n as deleteTurnSafely, o as finalizeStreamingMarkdownForOwner, p as compactPath, q as summarizeOutcomes, r as truncateTurnsAt, rt as blendHsl, s as turnContextSize, t as countNeighbors, u as filterModelCatalog, v as previewLine, w as HunkResolution, x as DiffOp, y as shortId } from "../turn-operations-BtyfLdPi.js";
4
4
  export { type ActiveTrigger, type CatalogEntry, type CompletionContext, type CompletionItem, type CompletionProvider, type CompletionReference, type ContextBreakdown, type ContextBreakdownOptions, type ContextCategory, type ContextCategoryId, type ContextExactCounts, type ContextItem, type ContextMcpGroup, type ContextSnapshot, type ContextUsageSplit, type DiffLine, type DiffOp, EDIT_TOOL_NAMES, type EditHunkSummary, type EditSummary, FILES_TRIGGER, type HunkResolution, type InlineDiff, type InlineSegment, type PreviewResult, type PromptSegment, type PromptSegmentRef, SKILLS_TRIGGER, TOOL_DISPLAY, type ToolDisplayMeta, type ToolFormatLine, ageString, applyEditPayload, applyInsert, blendHsl, buildContextBreakdown, buildContextualDiff, buildLinearRamp, buildModelCatalog, buildUnifiedDiff, collectReferences, compactPath, computeInlineDiff, computeLineDiff, countNeighbors, createFilesCompletionProvider, createSkillsCompletionProvider, deleteTurnSafely, displayNameFor, extractEditPayload, filetypeFromPath, filterModelCatalog, finalizeStreamingMarkdown, finalizeStreamingMarkdownForOwner, findActiveTrigger, fmtTokens, formatDuration, formatTaskStatus, formatTaskSummary, formatToolCall, indexOfEntry, isEditErrorResult, isTurnHighlighted, isVisible, mergeReferences, previewEditPayload, previewLine, selectableTurnIds, shortId, splitLines, splitPromptSegments, summarizeEditPayload, summarizeOutcomes, tokenize, truncateTurnsAt, turnAsText, turnContextSize, turnSelectionOwnership, uniqueFilesFromReferences, uniqueSkillNamesFromReferences };
package/dist/chat.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { B as Session, Cr as ContextMcpGroup, Er as buildContextBreakdown, P as SkillConfig, R as SkillsConfig, Sr as ContextItem, Tr as ContextUsageSplit, _r as ContextBreakdown, br as ContextCategoryId, ln as AutoCompact, r as AgentHooks, vr as ContextBreakdownOptions, wr as ContextSnapshot, xn as McpToolSchema, xr as ContextExactCounts, yn as McpServerConfig, yr as ContextCategory, yt as Provider, zn as SessionTurn } from "./agent-D7ZL8B2X.js";
2
- import { J as McpCredentialStore, q as McpCredentialEntry, t as Preset } from "./index-CDcQW-2S.js";
1
+ import { B as Session, Cr as ContextMcpGroup, Er as buildContextBreakdown, P as SkillConfig, R as SkillsConfig, Sr as ContextItem, Tr as ContextUsageSplit, _r as ContextBreakdown, br as ContextCategoryId, ln as AutoCompact, r as AgentHooks, vr as ContextBreakdownOptions, wr as ContextSnapshot, xn as McpToolSchema, xr as ContextExactCounts, yn as McpServerConfig, yr as ContextCategory, yt as Provider, zn as SessionTurn } from "./agent-w6htlFlx.js";
2
+ import { J as McpCredentialStore, q as McpCredentialEntry, t as Preset } from "./index-C4sPfyg6.js";
3
3
  import { a as effectiveContextWindow, i as OUTPUT_RESERVE_TOKENS, n as AutoCompactDecision, o as shouldAutoCompact, r as AutoCompactInput, t as AUTO_COMPACT_MIN_GROWTH_FRACTION } from "./policy-DcGlpaNs.js";
4
- import { _ as SourcedScanPath } from "./index-BsyPeCSL.js";
5
- import { $ as useInteractionsQueue, $t as mergeKeybindings, A as InteractionsProvider, At as loadState, B as QuestionPayload, Bt as KEYBINDING_DEFS, C as ASK_USER_TOOL, Ct as TuiState, D as InteractionRequest, Dt as eventsFromTurns, E as CreateInteractionToolsOptions, Et as deriveSessionTitle, F as PlanRequest, Ft as titleFromTurns, G as TextQuestion, Gt as KeyBindingSection, H as QuestionResponse, Ht as KEYBINDING_KEY_COL_WIDTH, I as PlanResponse, It as toolCallPreview, J as isInteractionTool, Jt as ensureKeybindingsFile, K as buildResumedToolResultsTurn, Kt as KeyBindings, L as PlanStep, Lt as toolResultText, M as PendingInteractionEntry, Mt as saveState, N as PlanDecision, Nt as stripSpawnTokensLine, O as InteractionResponse, Ot as lastContextSizeFromTurns, P as PlanPayload, Pt as sumRunCosts, Q as useInteractionsActions, Qt as matchesBinding, R as Question, Rt as updateToolEventOutcomes, S as splitMarkdownCodeBlocks, St as StateStoreApi, T as ConfirmQuestion, Tt as createStateStore, U as QuestionType, Ut as KeyAction, V as QuestionRequest, Vt as KEYBINDING_DEF_BY_ACTION, W as SelectQuestion, Wt as KeyBindingDef, X as pendingInteractionsFromTurns, Xt as groupBindings, Y as makeRequestInteraction, Yt as formatBindingForDisplay, Z as serializeInteractionResponse, Zt as keybindingsPath, _ as SessionExportTarget, _n as DEFAULT_PERSIST_EXCLUDE_TOOLS, _t as ResolveStorageDirsOptions, a as ChipColorMap, an as EMPTY_HINTS, at as DiscoveryResult, b as writeSessionExport, bn as resolveAgentId, bt as StorageSlot, c as SyntaxTokenStyle, cn as hintsLength, ct as discoverProjectMcps, d as ThemeSelect, dn as AgentProfile, dt as ChatOptions, en as parseBindingSpec, et as EnabledAllowlistKey, f as ThemeSurfaces, fn as AgentRegistry, ft as ProviderRegistry, g as SessionExportFormat, gn as DEFAULT_BUDGET_EXCLUDE_TOOLS, gt as resolveStoragePaths, h as SessionExportAnchor, hn as DEFAULT_AGENT_ID, ht as resolveConfig, i as ChipColor, in as useCompletion, it as DiscoveryError, j as PRESENT_PLAN_TOOL, jt as marginTopFor, k as InteractionsActions, kt as listSessionMeta, l as Theme, ln as truncateTrailing, lt as parseMcpsFile, m as resolveTheme, mn as BUILTIN_AGENTS, mt as ResolvedPaths, n as computeTurnAnchors, nn as stripJsonComments, nt as useEnabledToggleSet, o as DEFAULT_THEME, on as Hint, ot as buildMcpServers, p as resolveChipColor, pn as BUILD_AGENT, pt as ResolvedConfig, q as createInteractionTools, qt as ParsedBinding, r as BUILTIN_THEMES, rn as CompletionState, rt as DiscoveredMcp, s as SyntaxStyles, sn as clipHintsToWidth, st as defaultMcpsConfigPaths, t as TranscriptItem, tn as readKeybindings, tt as EnabledToggleSet, u as ThemeColors, un as AgentAccent, ut as AutoUpdateConfig, v as renderSession, vn as PLAN_AGENT, vt as StorageDirs, w as AnswerValue, wt as compactSummaryEvent, x as MarkdownSegment, xn as singleAgentRegistry, xt as resolveStorageDirs, y as resolveSessionExportTarget, yn as accentColor, yt as StorageMode, z as QuestionChoice, zt as DEFAULT_KEYBINDINGS } from "./transcript-anchors-EG-SmZRu.js";
6
- import { $ as cerebrasDescriptor, A as SessionMeta, B as collectReferences, C as EditHunk, D as Owner, E as EditPayload, F as CompletionContext, G as ProviderKey, H as mergeReferences, I as CompletionItem, J as CustomField, K as detectAuth, L as CompletionProvider, M as StreamEvent, N as ToolCallDisplay, O as Picked, P as ActiveTrigger, Q as anthropicDescriptor, R as CompletionReference, S as EditDiffDisplay, T as EditOutcomeKind, U as AuthMethod, V as findActiveTrigger, W as ProviderAuth, X as ModelOption, Y as ModelInfo, Z as ProviderDescriptor, _ as isEditErrorResult, a as formatToolCall, at as modelOptionsFor, b as selectableTurnIds, c as splitPromptSegments, ct as openaiDescriptor, d as RequestApproval, dt as restoreModelOptions, et as credKeyOf, f as SafeModeActions, h as useSafeModeQueue, i as displayNameFor, it as localDescriptor, j as Settings, k as Screen, l as ApprovalDecision, lt as openrouterDescriptor, m as useSafeModeActions, n as ToolDisplayMeta, nt as getContextWindow, o as PromptSegment, ot as modelSupportsReasoning, p as SafeModeProvider, q as BUILTIN_PROVIDERS, r as ToolFormatLine, rt as getModelInfo, s as PromptSegmentRef, st as modelsForDescriptor, t as TOOL_DISPLAY, tt as enabledModelOptions, u as ApprovalRequest, ut as piIdOf, v as isTurnHighlighted, w as EditOutcome, x as turnSelectionOwnership, y as isVisible, z as applyInsert } from "./tool-formatters-CNSMadtp.js";
7
- import { $ as uniqueFilesFromReferences, A as buildUnifiedDiff, B as buildEditOutcomesAnnotation, C as EditSummary, D as PreviewResult, E as InlineSegment, F as previewEditPayload, G as rewriteMultiEditHeader, H as mergeApprovalAndBodyOutcomes, I as splitLines, J as SKILLS_TRIGGER, K as stripEditOutcomesAnnotation, L as summarizeEditPayload, M as computeLineDiff, N as extractEditPayload, O as applyEditPayload, P as filetypeFromPath, Q as createFilesCompletionProvider, R as tokenize, S as EditHunkSummary, T as InlineDiff, U as parseEditOutcomesFromResult, V as maskToOutcomeKinds, W as resolveApprovalForPayload, X as uniqueSkillNamesFromReferences, Y as createSkillsCompletionProvider, Z as FILES_TRIGGER, _ as formatTaskSummary, a as finalizeStreamingMarkdown, b as DiffLine, c as CatalogEntry, d as indexOfEntry, et as FileEntry, f as ageString, g as formatTaskStatus, h as formatDuration, i as turnAsText, it as buildLinearRamp, j as computeInlineDiff, k as buildContextualDiff, l as buildModelCatalog, m as fmtTokens, n as deleteTurnSafely, nt as listProjectFiles, o as finalizeStreamingMarkdownForOwner, p as compactPath, q as summarizeOutcomes, r as truncateTurnsAt, rt as blendHsl, s as turnContextSize, t as countNeighbors, tt as ListProjectFilesOptions, u as filterModelCatalog, v as previewLine, w as HunkResolution, x as DiffOp, y as shortId, z as ResolvedApproval } from "./turn-operations-DwtWRYr1.js";
4
+ import { _ as SourcedScanPath } from "./index-BH0lvT7N.js";
5
+ import { $ as useInteractionsQueue, $t as mergeKeybindings, A as InteractionsProvider, At as loadState, B as QuestionPayload, Bt as KEYBINDING_DEFS, C as ASK_USER_TOOL, Ct as TuiState, D as InteractionRequest, Dt as eventsFromTurns, E as CreateInteractionToolsOptions, Et as deriveSessionTitle, F as PlanRequest, Ft as titleFromTurns, G as TextQuestion, Gt as KeyBindingSection, H as QuestionResponse, Ht as KEYBINDING_KEY_COL_WIDTH, I as PlanResponse, It as toolCallPreview, J as isInteractionTool, Jt as ensureKeybindingsFile, K as buildResumedToolResultsTurn, Kt as KeyBindings, L as PlanStep, Lt as toolResultText, M as PendingInteractionEntry, Mt as saveState, N as PlanDecision, Nt as stripSpawnTokensLine, O as InteractionResponse, Ot as lastContextSizeFromTurns, P as PlanPayload, Pt as sumRunCosts, Q as useInteractionsActions, Qt as matchesBinding, R as Question, Rt as updateToolEventOutcomes, S as splitMarkdownCodeBlocks, St as StateStoreApi, T as ConfirmQuestion, Tt as createStateStore, U as QuestionType, Ut as KeyAction, V as QuestionRequest, Vt as KEYBINDING_DEF_BY_ACTION, W as SelectQuestion, Wt as KeyBindingDef, X as pendingInteractionsFromTurns, Xt as groupBindings, Y as makeRequestInteraction, Yt as formatBindingForDisplay, Z as serializeInteractionResponse, Zt as keybindingsPath, _ as SessionExportTarget, _n as DEFAULT_PERSIST_EXCLUDE_TOOLS, _t as ResolveStorageDirsOptions, a as ChipColorMap, an as EMPTY_HINTS, at as DiscoveryResult, b as writeSessionExport, bn as resolveAgentId, bt as StorageSlot, c as SyntaxTokenStyle, cn as hintsLength, ct as discoverProjectMcps, d as ThemeSelect, dn as AgentProfile, dt as ChatOptions, en as parseBindingSpec, et as EnabledAllowlistKey, f as ThemeSurfaces, fn as AgentRegistry, ft as ProviderRegistry, g as SessionExportFormat, gn as DEFAULT_BUDGET_EXCLUDE_TOOLS, gt as resolveStoragePaths, h as SessionExportAnchor, hn as DEFAULT_AGENT_ID, ht as resolveConfig, i as ChipColor, in as useCompletion, it as DiscoveryError, j as PRESENT_PLAN_TOOL, jt as marginTopFor, k as InteractionsActions, kt as listSessionMeta, l as Theme, ln as truncateTrailing, lt as parseMcpsFile, m as resolveTheme, mn as BUILTIN_AGENTS, mt as ResolvedPaths, n as computeTurnAnchors, nn as stripJsonComments, nt as useEnabledToggleSet, o as DEFAULT_THEME, on as Hint, ot as buildMcpServers, p as resolveChipColor, pn as BUILD_AGENT, pt as ResolvedConfig, q as createInteractionTools, qt as ParsedBinding, r as BUILTIN_THEMES, rn as CompletionState, rt as DiscoveredMcp, s as SyntaxStyles, sn as clipHintsToWidth, st as defaultMcpsConfigPaths, t as TranscriptItem, tn as readKeybindings, tt as EnabledToggleSet, u as ThemeColors, un as AgentAccent, ut as AutoUpdateConfig, v as renderSession, vn as PLAN_AGENT, vt as StorageDirs, w as AnswerValue, wt as compactSummaryEvent, x as MarkdownSegment, xn as singleAgentRegistry, xt as resolveStorageDirs, y as resolveSessionExportTarget, yn as accentColor, yt as StorageMode, z as QuestionChoice, zt as DEFAULT_KEYBINDINGS } from "./transcript-anchors-CJsVfcaq.js";
6
+ import { $ as cerebrasDescriptor, A as SessionMeta, B as collectReferences, C as EditHunk, D as Owner, E as EditPayload, F as CompletionContext, G as ProviderKey, H as mergeReferences, I as CompletionItem, J as CustomField, K as detectAuth, L as CompletionProvider, M as StreamEvent, N as ToolCallDisplay, O as Picked, P as ActiveTrigger, Q as anthropicDescriptor, R as CompletionReference, S as EditDiffDisplay, T as EditOutcomeKind, U as AuthMethod, V as findActiveTrigger, W as ProviderAuth, X as ModelOption, Y as ModelInfo, Z as ProviderDescriptor, _ as isEditErrorResult, a as formatToolCall, at as modelOptionsFor, b as selectableTurnIds, c as splitPromptSegments, ct as openaiDescriptor, d as RequestApproval, dt as restoreModelOptions, et as credKeyOf, f as SafeModeActions, h as useSafeModeQueue, i as displayNameFor, it as localDescriptor, j as Settings, k as Screen, l as ApprovalDecision, lt as openrouterDescriptor, m as useSafeModeActions, n as ToolDisplayMeta, nt as getContextWindow, o as PromptSegment, ot as modelSupportsReasoning, p as SafeModeProvider, q as BUILTIN_PROVIDERS, r as ToolFormatLine, rt as getModelInfo, s as PromptSegmentRef, st as modelsForDescriptor, t as TOOL_DISPLAY, tt as enabledModelOptions, u as ApprovalRequest, ut as piIdOf, v as isTurnHighlighted, w as EditOutcome, x as turnSelectionOwnership, y as isVisible, z as applyInsert } from "./tool-formatters-C7N1Pb1q.js";
7
+ import { $ as uniqueFilesFromReferences, A as buildUnifiedDiff, B as buildEditOutcomesAnnotation, C as EditSummary, D as PreviewResult, E as InlineSegment, F as previewEditPayload, G as rewriteMultiEditHeader, H as mergeApprovalAndBodyOutcomes, I as splitLines, J as SKILLS_TRIGGER, K as stripEditOutcomesAnnotation, L as summarizeEditPayload, M as computeLineDiff, N as extractEditPayload, O as applyEditPayload, P as filetypeFromPath, Q as createFilesCompletionProvider, R as tokenize, S as EditHunkSummary, T as InlineDiff, U as parseEditOutcomesFromResult, V as maskToOutcomeKinds, W as resolveApprovalForPayload, X as uniqueSkillNamesFromReferences, Y as createSkillsCompletionProvider, Z as FILES_TRIGGER, _ as formatTaskSummary, a as finalizeStreamingMarkdown, b as DiffLine, c as CatalogEntry, d as indexOfEntry, et as FileEntry, f as ageString, g as formatTaskStatus, h as formatDuration, i as turnAsText, it as buildLinearRamp, j as computeInlineDiff, k as buildContextualDiff, l as buildModelCatalog, m as fmtTokens, n as deleteTurnSafely, nt as listProjectFiles, o as finalizeStreamingMarkdownForOwner, p as compactPath, q as summarizeOutcomes, r as truncateTurnsAt, rt as blendHsl, s as turnContextSize, t as countNeighbors, tt as ListProjectFilesOptions, u as filterModelCatalog, v as previewLine, w as HunkResolution, x as DiffOp, y as shortId, z as ResolvedApproval } from "./turn-operations-BtyfLdPi.js";
8
8
  import { Hookable } from "hookable";
9
9
  import { OAuthCredentials, OAuthDeviceCodeInfo, OAuthPrompt, OAuthPrompt as OAuthPrompt$1, OAuthSelectPrompt } from "@earendil-works/pi-ai/oauth";
10
10
  import { spawn } from "node:child_process";
package/dist/chat.js CHANGED
@@ -1,8 +1,8 @@
1
- import { $ as useMcpAuthDispatch, $n as singleAgentRegistry, $t as createStateStore, A as runOAuthLogin, An as bootTick, At as SettingsProvider, B as refreshMcpToolsCatalog, Bn as resolvePlatformPackage, Bt as CATPPUCCIN_FRAPPE, C as projectsFilePath, Cn as mergeKeybindings, Cr as TOKEN_DISCIPLINE_DOCTRINE, Ct as shortChord, D as formatPathForCwd, Dn as useCompletion, Dt as SETTINGS_CATEGORIES, E as writeProjects, En as stripJsonComments, Er as envSection, Et as DEFAULT_SETTINGS, F as parseMcpsFile, Fn as detectLibc, Ft as resolveChipColor, G as useMcpToolToggleSet, Gn as BUILD_AGENT, Gt as DiscoveryProvider, H as subscribeMcpToolsCache, Hn as discoverAgentsMd, Ht as CATPPUCCIN_MACCHIATO, I as projectUserPaths, In as detectPackageManager, It as resolveTheme, J as parentServerName, Jn as DEFAULT_BUDGET_EXCLUDE_TOOLS, Jt as ConfigProvider, K as buildVisibleMcpRows, Kn as BUILTIN_AGENTS, Kt as useDiscovery, L as clearMcpToolsCache, Ln as parseSemver, Lt as VAPORWAVE_THEME, M as buildMcpServers, Mn as useUpdateCheck, Mt as useSettings, N as defaultMcpsConfigPaths, Nn as checkForUpdate, Nt as BUILTIN_THEMES, O as fetchOAuthRedirect, On as tryOpenBrowser, Ot as SETTINGS_CHOICES, P as discoverProjectMcps, Pn as compareSemver, Pt as DEFAULT_THEME, Q as McpAuthProvider, Qn as resolveAgentId, Qt as compactSummaryEvent, R as loadMcpToolsCache, Rn as performInPlaceSelfUpdate, Rt as GRUVBOX_DARK, S as matchesSafelistEntry, Sn as matchesBinding, Sr as SUBAGENT_GUIDANCE, St as buildHints, T as suggestSafelistEntry, Tn as readKeybindings, Tr as buildPlanSystem, Tt as useEnabledToggleSet, U as buildToolToggle, Un as renderAgentsMdBlock, Ut as CATPPUCCIN_MOCHA, V as saveMcpToolsCache, Vn as chatAutoCompactBehavior, Vt as CATPPUCCIN_LATTE, W as useMcpToolToggleMap, Wn as findGitRoot, Wt as createDiscoverySlot, X as mcpCredentialsPath, Xn as PLAN_AGENT, Xt as resolveConfig, Y as createFileMcpCredentialStore, Yn as DEFAULT_PERSIST_EXCLUDE_TOOLS, Yt as useConfig, Z as patchMcpCredential, Zn as accentColor, Zt as resolveStoragePaths, _ as useSafeModeQueue, _n as KEYBINDING_KEY_COL_WIDTH, _r as IDENTITY_PREFIX, _t as clipHintsToWidth, a as useSurfaces, an as marginTopFor, ar as createTodoTools, at as ASK_USER_TOOL, b as getSafelist, bn as groupBindings, br as PLAN_MODE_DOCTRINE, bt as cleanTitle, c as useStreamBuffer, cn as stripSpawnTokensLine, cr as isTodoTool, ct as buildResumedToolResultsTurn, d as discoverProjectSkills, dn as toolCallPreview, dr as selectActiveTodos, dt as makeRequestInteraction, en as deriveSessionTitle, er as TODOREAD_TOOL, et as useMcpAuthState, f as renderSession, fn as toolResultText, fr as setTodosForRun, ft as pendingInteractionsFromTurns, g as useSafeModeActions, gn as KEYBINDING_DEF_BY_ACTION, gr as DOING_TASKS_DOCTRINE, gt as EMPTY_HINTS, h as SafeModeProvider, hn as KEYBINDING_DEFS, hr as COMMUNICATION_DOCTRINE, ht as useInteractionsQueue, i as useSelectStyle, in as loadState, ir as TODO_WRITE_COUNTS_METADATA_KEY, it as splitMarkdownCodeBlocks, j as supportsOAuth, jn as buildUpdateHint, k as oauthUsesManualCodePaste, kn as bootProfileEnabled, kt as SETTINGS_TOGGLES, l as buildSkillsConfig, ln as sumRunCosts, lr as pickActiveRunId, lt as createInteractionTools, m as writeSessionExport, mn as DEFAULT_KEYBINDINGS, mr as ACTIONS_WITH_CARE_DOCTRINE, mt as useInteractionsActions, n as ThemeProvider, nn as lastContextSizeFromTurns, nr as TODOWRITE_TOOL, nt as reduceMcpAuth, o as useSyntaxStyles, on as saveState, or as getArchivedTodosForRun, ot as InteractionsProvider, p as resolveSessionExportTarget, pn as updateToolEventOutcomes, pr as useActiveTodos, pt as serializeInteractionResponse, q as indexOfServerRow, qn as DEFAULT_AGENT_ID, qt as useDiscoveryOptional, r as useColors, rn as listSessionMeta, rr as TODO_STATUS_GLYPHS, s as useTheme, sr as getTodosForRun, st as PRESENT_PLAN_TOOL, t as computeTurnAnchors, tn as eventsFromTurns, tr as TODOS_METADATA_KEY, tt as getMcpAuthStatus, u as defaultSkillScanPaths, un as titleFromTurns, ur as pruneTodosByRun, ut as isInteractionTool, v as IMPLICITLY_SAFE_TOOLS, vn as ensureKeybindingsFile, vr as INTERACTION_GUIDANCE, vt as hintsLength, w as readProjects, wn as parseBindingSpec, wr as buildBuildSystem, wt as listProjectFiles, x as isOnSafelist, xn as keybindingsPath, xr as PLAN_MODE_DOCTRINE_NO_PROMPTS, xt as generateSessionTitle, y as addToSafelist, yn as formatBindingForDisplay, yr as INTERACTION_GUIDANCE_NO_PROMPTS, yt as truncateTrailing, z as mcpToolsCachePath, zn as performSelfUpdate, zt as GRUVBOX_LIGHT } from "./transcript-anchors-D4qAelMs.js";
1
+ import { $ as useMcpAuthDispatch, $n as singleAgentRegistry, $t as createStateStore, A as runOAuthLogin, An as bootTick, At as SettingsProvider, B as refreshMcpToolsCatalog, Bn as resolvePlatformPackage, Bt as CATPPUCCIN_FRAPPE, C as projectsFilePath, Cn as mergeKeybindings, Cr as TOKEN_DISCIPLINE_DOCTRINE, Ct as shortChord, D as formatPathForCwd, Dn as useCompletion, Dt as SETTINGS_CATEGORIES, E as writeProjects, En as stripJsonComments, Er as envSection, Et as DEFAULT_SETTINGS, F as parseMcpsFile, Fn as detectLibc, Ft as resolveChipColor, G as useMcpToolToggleSet, Gn as BUILD_AGENT, Gt as DiscoveryProvider, H as subscribeMcpToolsCache, Hn as discoverAgentsMd, Ht as CATPPUCCIN_MACCHIATO, I as projectUserPaths, In as detectPackageManager, It as resolveTheme, J as parentServerName, Jn as DEFAULT_BUDGET_EXCLUDE_TOOLS, Jt as ConfigProvider, K as buildVisibleMcpRows, Kn as BUILTIN_AGENTS, Kt as useDiscovery, L as clearMcpToolsCache, Ln as parseSemver, Lt as VAPORWAVE_THEME, M as buildMcpServers, Mn as useUpdateCheck, Mt as useSettings, N as defaultMcpsConfigPaths, Nn as checkForUpdate, Nt as BUILTIN_THEMES, O as fetchOAuthRedirect, On as tryOpenBrowser, Ot as SETTINGS_CHOICES, P as discoverProjectMcps, Pn as compareSemver, Pt as DEFAULT_THEME, Q as McpAuthProvider, Qn as resolveAgentId, Qt as compactSummaryEvent, R as loadMcpToolsCache, Rn as performInPlaceSelfUpdate, Rt as GRUVBOX_DARK, S as matchesSafelistEntry, Sn as matchesBinding, Sr as SUBAGENT_GUIDANCE, St as buildHints, T as suggestSafelistEntry, Tn as readKeybindings, Tr as buildPlanSystem, Tt as useEnabledToggleSet, U as buildToolToggle, Un as renderAgentsMdBlock, Ut as CATPPUCCIN_MOCHA, V as saveMcpToolsCache, Vn as chatAutoCompactBehavior, Vt as CATPPUCCIN_LATTE, W as useMcpToolToggleMap, Wn as findGitRoot, Wt as createDiscoverySlot, X as mcpCredentialsPath, Xn as PLAN_AGENT, Xt as resolveConfig, Y as createFileMcpCredentialStore, Yn as DEFAULT_PERSIST_EXCLUDE_TOOLS, Yt as useConfig, Z as patchMcpCredential, Zn as accentColor, Zt as resolveStoragePaths, _ as useSafeModeQueue, _n as KEYBINDING_KEY_COL_WIDTH, _r as IDENTITY_PREFIX, _t as clipHintsToWidth, a as useSurfaces, an as marginTopFor, ar as createTodoTools, at as ASK_USER_TOOL, b as getSafelist, bn as groupBindings, br as PLAN_MODE_DOCTRINE, bt as cleanTitle, c as useStreamBuffer, cn as stripSpawnTokensLine, cr as isTodoTool, ct as buildResumedToolResultsTurn, d as discoverProjectSkills, dn as toolCallPreview, dr as selectActiveTodos, dt as makeRequestInteraction, en as deriveSessionTitle, er as TODOREAD_TOOL, et as useMcpAuthState, f as renderSession, fn as toolResultText, fr as setTodosForRun, ft as pendingInteractionsFromTurns, g as useSafeModeActions, gn as KEYBINDING_DEF_BY_ACTION, gr as DOING_TASKS_DOCTRINE, gt as EMPTY_HINTS, h as SafeModeProvider, hn as KEYBINDING_DEFS, hr as COMMUNICATION_DOCTRINE, ht as useInteractionsQueue, i as useSelectStyle, in as loadState, ir as TODO_WRITE_COUNTS_METADATA_KEY, it as splitMarkdownCodeBlocks, j as supportsOAuth, jn as buildUpdateHint, k as oauthUsesManualCodePaste, kn as bootProfileEnabled, kt as SETTINGS_TOGGLES, l as buildSkillsConfig, ln as sumRunCosts, lr as pickActiveRunId, lt as createInteractionTools, m as writeSessionExport, mn as DEFAULT_KEYBINDINGS, mr as ACTIONS_WITH_CARE_DOCTRINE, mt as useInteractionsActions, n as ThemeProvider, nn as lastContextSizeFromTurns, nr as TODOWRITE_TOOL, nt as reduceMcpAuth, o as useSyntaxStyles, on as saveState, or as getArchivedTodosForRun, ot as InteractionsProvider, p as resolveSessionExportTarget, pn as updateToolEventOutcomes, pr as useActiveTodos, pt as serializeInteractionResponse, q as indexOfServerRow, qn as DEFAULT_AGENT_ID, qt as useDiscoveryOptional, r as useColors, rn as listSessionMeta, rr as TODO_STATUS_GLYPHS, s as useTheme, sr as getTodosForRun, st as PRESENT_PLAN_TOOL, t as computeTurnAnchors, tn as eventsFromTurns, tr as TODOS_METADATA_KEY, tt as getMcpAuthStatus, u as defaultSkillScanPaths, un as titleFromTurns, ur as pruneTodosByRun, ut as isInteractionTool, v as IMPLICITLY_SAFE_TOOLS, vn as ensureKeybindingsFile, vr as INTERACTION_GUIDANCE, vt as hintsLength, w as readProjects, wn as parseBindingSpec, wr as buildBuildSystem, wt as listProjectFiles, x as isOnSafelist, xn as keybindingsPath, xr as PLAN_MODE_DOCTRINE_NO_PROMPTS, xt as generateSessionTitle, y as addToSafelist, yn as formatBindingForDisplay, yr as INTERACTION_GUIDANCE_NO_PROMPTS, yt as truncateTrailing, z as mcpToolsCachePath, zn as performSelfUpdate, zt as GRUVBOX_LIGHT } from "./transcript-anchors-BrweEBIo.js";
2
2
  import { ct as effectiveContextWindow, lt as shouldAutoCompact, ot as AUTO_COMPACT_MIN_GROWTH_FRACTION, st as OUTPUT_RESERVE_TOKENS } from "./tools-DhzKzB1y.js";
3
3
  import { t as buildContextBreakdown } from "./context-breakdown-kO-pDsay.js";
4
4
  import { a as formatTaskStatus, c as shortId, i as formatDuration, n as compactPath, o as formatTaskSummary, r as fmtTokens, s as previewLine, t as ageString } from "./format-BNOXpl-1.js";
5
- import { C as piIdOf, S as openrouterDescriptor, _ as localDescriptor, a as readCredentials, b as modelsForDescriptor, c as setProviderCredential, d as anthropicDescriptor, f as cerebrasDescriptor, g as getModelInfo, h as getContextWindow, i as credentialsPath, l as writeCredentials, m as enabledModelOptions, n as resolveStorageDirs, o as readProviderCredential, p as credKeyOf, r as applyApiKeyEnv, s as removeProviderCredential, t as detectAuth, u as BUILTIN_PROVIDERS, v as modelOptionsFor, w as restoreModelOptions, x as openaiDescriptor, y as modelSupportsReasoning } from "./auth-BlZUM4yl.js";
5
+ import { C as piIdOf, S as openrouterDescriptor, _ as localDescriptor, a as readCredentials, b as modelsForDescriptor, c as setProviderCredential, d as anthropicDescriptor, f as cerebrasDescriptor, g as getModelInfo, h as getContextWindow, i as credentialsPath, l as writeCredentials, m as enabledModelOptions, n as resolveStorageDirs, o as readProviderCredential, p as credKeyOf, r as applyApiKeyEnv, s as removeProviderCredential, t as detectAuth, u as BUILTIN_PROVIDERS, v as modelOptionsFor, w as restoreModelOptions, x as openaiDescriptor, y as modelSupportsReasoning } from "./auth-nA0ZMTbM.js";
6
6
  import { A as splitLines, B as summarizeOutcomes, C as buildContextualDiff, D as extractEditPayload, E as computeLineDiff, F as mergeApprovalAndBodyOutcomes, G as createFilesCompletionProvider, H as createSkillsCompletionProvider, I as parseEditOutcomesFromResult, J as collectReferences, K as uniqueFilesFromReferences, L as resolveApprovalForPayload, M as tokenize, N as buildEditOutcomesAnnotation, O as filetypeFromPath, P as maskToOutcomeKinds, Q as buildLinearRamp, R as rewriteMultiEditHeader, S as applyEditPayload, T as computeInlineDiff, U as uniqueSkillNamesFromReferences, V as SKILLS_TRIGGER, W as FILES_TRIGGER, X as mergeReferences, Y as findActiveTrigger, Z as blendHsl, _ as isEditErrorResult, a as TOOL_DISPLAY, b as selectableTurnIds, c as finalizeStreamingMarkdown, d as turnContextSize, f as splitPromptSegments, h as indexOfEntry, i as turnAsText, j as summarizeEditPayload, k as previewEditPayload, l as finalizeStreamingMarkdownForOwner, m as filterModelCatalog, n as deleteTurnSafely, o as displayNameFor, p as buildModelCatalog, q as applyInsert, r as truncateTurnsAt, s as formatToolCall, t as countNeighbors, v as isTurnHighlighted, w as buildUnifiedDiff, x as turnSelectionOwnership, y as isVisible, z as stripEditOutcomesAnnotation } from "./turn-operations-DLWN2J7f.js";
7
7
  //#region src/chat/auto-update-cli.ts
8
8
  const UPGRADE_HELP = `Usage: zidane upgrade [options]