pi2dsh 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +31 -11
  2. package/README.zh.md +31 -11
  3. package/dist/all-Rt4K68QA.mjs +28512 -0
  4. package/dist/all-Rt4K68QA.mjs.map +1 -0
  5. package/dist/anthropic-messages-Beym0_aC.mjs +6438 -0
  6. package/dist/anthropic-messages-Beym0_aC.mjs.map +1 -0
  7. package/dist/azure-openai-responses-cHqZTgLD.mjs +209 -0
  8. package/dist/azure-openai-responses-cHqZTgLD.mjs.map +1 -0
  9. package/dist/{build-DsGYAgiT.mjs → build-BG7p2Lbr.mjs} +2 -2
  10. package/dist/{build-DsGYAgiT.mjs.map → build-BG7p2Lbr.mjs.map} +1 -1
  11. package/dist/cli.mjs +1 -1
  12. package/dist/compat/pi-ai.d.mts +25 -3
  13. package/dist/compat/pi-ai.d.mts.map +1 -1
  14. package/dist/compat/pi-ai.mjs +3 -2919
  15. package/dist/compat/pi-coding-agent.d.mts +12 -1
  16. package/dist/compat/pi-coding-agent.d.mts.map +1 -1
  17. package/dist/compat/pi-coding-agent.mjs +2 -2
  18. package/dist/credentials-oauth.d.mts +27 -0
  19. package/dist/credentials-oauth.d.mts.map +1 -0
  20. package/dist/credentials-oauth.mjs +91 -0
  21. package/dist/credentials-oauth.mjs.map +1 -0
  22. package/dist/deferred-tools-BD4g5QUx.mjs +32 -0
  23. package/dist/deferred-tools-BD4g5QUx.mjs.map +1 -0
  24. package/dist/diagnostics-CJye1UFh.mjs +99 -0
  25. package/dist/diagnostics-CJye1UFh.mjs.map +1 -0
  26. package/dist/dist-IQKOgQyt.mjs +10035 -0
  27. package/dist/dist-IQKOgQyt.mjs.map +1 -0
  28. package/dist/dist-QBBA-dL_.mjs +1246 -0
  29. package/dist/dist-QBBA-dL_.mjs.map +1 -0
  30. package/dist/error-body-DKA3lknR.mjs +104 -0
  31. package/dist/error-body-DKA3lknR.mjs.map +1 -0
  32. package/dist/github-copilot-headers-CZo2QHrt.mjs +25 -0
  33. package/dist/github-copilot-headers-CZo2QHrt.mjs.map +1 -0
  34. package/dist/google-generative-ai-B7OZs5lu.mjs +358 -0
  35. package/dist/google-generative-ai-B7OZs5lu.mjs.map +1 -0
  36. package/dist/google-shared-CRsAUItF.mjs +29042 -0
  37. package/dist/google-shared-CRsAUItF.mjs.map +1 -0
  38. package/dist/google-vertex-DmdaHQtB.mjs +402 -0
  39. package/dist/google-vertex-DmdaHQtB.mjs.map +1 -0
  40. package/dist/hash-Dbggamac.mjs +19 -0
  41. package/dist/hash-Dbggamac.mjs.map +1 -0
  42. package/dist/headers-CPzZhJQn.mjs +17 -0
  43. package/dist/headers-CPzZhJQn.mjs.map +1 -0
  44. package/dist/host.d.mts.map +1 -1
  45. package/dist/host.mjs +15 -3
  46. package/dist/host.mjs.map +1 -1
  47. package/dist/images-models-DJtHo9Rp.mjs +1068 -0
  48. package/dist/images-models-DJtHo9Rp.mjs.map +1 -0
  49. package/dist/index.d.mts.map +1 -1
  50. package/dist/index.mjs +1 -1
  51. package/dist/json-parse-CFyFZSLJ.mjs +384 -0
  52. package/dist/json-parse-CFyFZSLJ.mjs.map +1 -0
  53. package/dist/{mcp-config-gqg7GJEE.mjs → mcp-config-D2B3kv-Z.mjs} +34 -16
  54. package/dist/mcp-config-D2B3kv-Z.mjs.map +1 -0
  55. package/dist/mistral-conversations-HHZCcFv_.mjs +42007 -0
  56. package/dist/mistral-conversations-HHZCcFv_.mjs.map +1 -0
  57. package/dist/multipart-parser-CIa5BbwO.mjs +301 -0
  58. package/dist/multipart-parser-CIa5BbwO.mjs.map +1 -0
  59. package/dist/oauth-bridge-C6fL1qSv.mjs +375 -0
  60. package/dist/oauth-bridge-C6fL1qSv.mjs.map +1 -0
  61. package/dist/openai-DkzRh5_G.mjs +6732 -0
  62. package/dist/openai-DkzRh5_G.mjs.map +1 -0
  63. package/dist/openai-codex-responses-vmovNu-q.mjs +1169 -0
  64. package/dist/openai-codex-responses-vmovNu-q.mjs.map +1 -0
  65. package/dist/openai-completions-fXHhRolF.mjs +947 -0
  66. package/dist/openai-completions-fXHhRolF.mjs.map +1 -0
  67. package/dist/openai-prompt-cache-BDWtZRKh.mjs +11 -0
  68. package/dist/openai-prompt-cache-BDWtZRKh.mjs.map +1 -0
  69. package/dist/openai-responses-DKdCYf3h.mjs +247 -0
  70. package/dist/openai-responses-DKdCYf3h.mjs.map +1 -0
  71. package/dist/openai-responses-shared-D0Jq7yVP.mjs +572 -0
  72. package/dist/openai-responses-shared-D0Jq7yVP.mjs.map +1 -0
  73. package/dist/openrouter-images-fG3Aj6M4.mjs +127 -0
  74. package/dist/openrouter-images-fG3Aj6M4.mjs.map +1 -0
  75. package/dist/otel-BQSQRBLF.mjs +24935 -0
  76. package/dist/otel-BQSQRBLF.mjs.map +1 -0
  77. package/dist/pi-ai-DhYGgq4Y.mjs +2984 -0
  78. package/dist/pi-ai-DhYGgq4Y.mjs.map +1 -0
  79. package/dist/{pi-coding-agent-Z1hTs61i.mjs → pi-coding-agent-fPHwKP4d.mjs} +27 -3
  80. package/dist/{pi-coding-agent-Z1hTs61i.mjs.map → pi-coding-agent-fPHwKP4d.mjs.map} +1 -1
  81. package/dist/pi-messages-CV-Ts8An.mjs +306 -0
  82. package/dist/pi-messages-CV-Ts8An.mjs.map +1 -0
  83. package/dist/provider-env-C72pF4vP.mjs +40 -0
  84. package/dist/provider-env-C72pF4vP.mjs.map +1 -0
  85. package/dist/provider-retry-Cw6YJ4cr.mjs +80 -0
  86. package/dist/provider-retry-Cw6YJ4cr.mjs.map +1 -0
  87. package/dist/rolldown-runtime-CTfmNlz1.mjs +44 -0
  88. package/dist/{runtime-oLd2EInK.mjs → runtime-B9R7bDWT.mjs} +838 -345
  89. package/dist/runtime-B9R7bDWT.mjs.map +1 -0
  90. package/dist/runtime.d.mts.map +1 -1
  91. package/dist/runtime.mjs +1 -1
  92. package/dist/sanitize-unicode-wLA11KvZ.mjs +29 -0
  93. package/dist/sanitize-unicode-wLA11KvZ.mjs.map +1 -0
  94. package/dist/src-C3WBfOks.mjs +5031 -0
  95. package/dist/src-C3WBfOks.mjs.map +1 -0
  96. package/dist/transform-messages-DGq9mvhA.mjs +379 -0
  97. package/dist/transform-messages-DGq9mvhA.mjs.map +1 -0
  98. package/dist/uuid-DtFT7tOE.mjs +65 -0
  99. package/dist/uuid-DtFT7tOE.mjs.map +1 -0
  100. package/package.json +11 -1
  101. package/dist/compat/pi-ai.mjs.map +0 -1
  102. package/dist/mcp-config-gqg7GJEE.mjs.map +0 -1
  103. package/dist/rolldown-runtime-D-uZhY3_.mjs +0 -16
  104. package/dist/runtime-oLd2EInK.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"pi-ai.mjs","names":["DEFAULT_POLL_INTERVAL_SECONDS","CLIENT_ID","AUTHORIZE_URL","TOKEN_URL","REDIRECT_URI","DEVICE_CODE_TIMEOUT_SECONDS","parseAuthorizationInput","exchangeAuthorizationCode","decode","CLIENT_ID","values","CLIENT_ID","lazyApiForCompat","codexFlow","anthropicFlow","copilotFlow","kimiFlow"],"sources":["../../src/compat/vendor/pi-ai-overflow.ts","../../src/compat/vendor/pi-ai-retry.ts","../../src/compat/vendor/pi-ai-event-stream.ts","../../src/compat/vendor/pi-ai-lazy.ts","../../src/compat/vendor/pi-ai-provider.ts","../../src/compat/vendor/pi-oauth-flows/provider-env.ts","../../src/compat/vendor/pi-oauth-flows/device-code.ts","../../src/compat/vendor/pi-oauth-flows/oauth-page.ts","../../src/compat/vendor/pi-oauth-flows/pkce.ts","../../src/compat/vendor/pi-oauth-flows/openai-codex.ts","../../src/compat/vendor/pi-oauth-flows/anthropic.ts","../../src/compat/vendor/pi-oauth-flows/data/github-copilot.json","../../src/compat/vendor/pi-oauth-flows/model-catalog.ts","../../src/compat/vendor/pi-oauth-flows/github-copilot.models.ts","../../src/compat/vendor/pi-oauth-flows/github-copilot.ts","../../src/compat/vendor/pi-oauth-flows/kimi-coding.ts","../../src/compat/pi-ai.ts"],"sourcesContent":["// @ts-nocheck — vendored Pi source; checked upstream under Pi's own tsconfig.\nimport type { AssistantMessage } from \"./pi-types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n */\nconst OVERFLOW_PATTERNS = [\n\t/prompt is too long/i, // Anthropic token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds the context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n\t/^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\n];\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n];\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles three cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n * 3. Length-stop overflow: Xiaomi MiMo can return \"length\" with zero output when\n * the input fills the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Check whether a length stop ended below the caller or model's intended output limit.\n * Such responses may be caused by context pressure or provider-side truncation, so callers\n * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original\n * limit before any context-based clamping.\n */\nexport function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn message.stopReason === \"length\" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n","// @ts-nocheck — vendored Pi source; checked upstream under Pi's own tsconfig.\nimport type { AssistantMessage } from \"./pi-types.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t\"524\",\n\t\"service.?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tconst delayMs = policy!.baseDelayMs * 2 ** (attempt - 1);\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n","// @ts-nocheck — vendored Pi source (pi-ai utils/event-stream.js @0.84.1, MIT, see ./PI-LICENSE); unchanged.\n// Generic event stream class for async iteration\nexport class EventStream {\n queue = [];\n waiting = [];\n done = false;\n finalResultPromise;\n resolveFinalResult;\n isComplete;\n extractResult;\n constructor(isComplete, extractResult) {\n this.isComplete = isComplete;\n this.extractResult = extractResult;\n this.finalResultPromise = new Promise((resolve) => {\n this.resolveFinalResult = resolve;\n });\n }\n push(event) {\n if (this.done)\n return;\n if (this.isComplete(event)) {\n this.done = true;\n this.resolveFinalResult(this.extractResult(event));\n }\n // Deliver to waiting consumer or queue it\n const waiter = this.waiting.shift();\n if (waiter) {\n waiter({ value: event, done: false });\n }\n else {\n this.queue.push(event);\n }\n }\n end(result) {\n this.done = true;\n if (result !== undefined) {\n this.resolveFinalResult(result);\n }\n // Notify all waiting consumers that we're done\n while (this.waiting.length > 0) {\n const waiter = this.waiting.shift();\n waiter({ value: undefined, done: true });\n }\n }\n async *[Symbol.asyncIterator]() {\n while (true) {\n if (this.queue.length > 0) {\n yield this.queue.shift();\n }\n else if (this.done) {\n return;\n }\n else {\n const result = await new Promise((resolve) => this.waiting.push(resolve));\n if (result.done)\n return;\n yield result.value;\n }\n }\n }\n result() {\n return this.finalResultPromise;\n }\n}\nexport class AssistantMessageEventStream extends EventStream {\n constructor() {\n super((event) => event.type === \"done\" || event.type === \"error\", (event) => {\n if (event.type === \"done\") {\n return event.message;\n }\n else if (event.type === \"error\") {\n return event.error;\n }\n throw new Error(\"Unexpected event type for final result\");\n });\n }\n}\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream() {\n return new AssistantMessageEventStream();\n}\n//# sourceMappingURL=event-stream.js.map","// @ts-nocheck — vendored Pi source (pi-ai api/lazy.js @0.84.1, MIT, see ./PI-LICENSE); import remapped, logic unchanged.\nimport { AssistantMessageEventStream } from './pi-ai-event-stream.js';\nfunction createSetupErrorMessage(model, error) {\n return {\n role: \"assistant\",\n content: [],\n api: model.api,\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n stopReason: \"error\",\n errorMessage: error instanceof Error ? error.message : String(error),\n timestamp: Date.now(),\n };\n}\nfunction hasResult(source) {\n return typeof source.result === \"function\";\n}\nasync function forwardStream(target, source) {\n for await (const event of source) {\n target.push(event);\n }\n target.end(hasResult(source) ? await source.result() : undefined);\n}\n/**\n * Returns a stream synchronously while running async setup (auth resolution,\n * lazy module loading) behind it. Setup failures terminate the stream with an\n * error event.\n */\nexport function lazyStream(model, setup) {\n const outer = new AssistantMessageEventStream();\n setup()\n .then((inner) => forwardStream(outer, inner))\n .catch((error) => {\n const message = createSetupErrorMessage(model, error);\n outer.push({ type: \"error\", reason: \"error\", error: message });\n outer.end(message);\n });\n return outer;\n}\nexport function lazyApi(load, capabilities) {\n const api = {\n stream: (model, context, options) => lazyStream(model, async () => (await load()).stream(model, context, options)),\n streamSimple: (model, context, options) => lazyStream(model, async () => (await load()).streamSimple(model, context, options)),\n };\n if (capabilities?.fetchDeferred) {\n api.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {\n const implementation = await load();\n if (!implementation.fetchDeferred)\n throw new Error(\"API does not support deferred responses\");\n return implementation.fetchDeferred(model, handle, options);\n });\n }\n if (capabilities?.cancelDeferred) {\n api.cancelDeferred = async (model, handle, options) => {\n const implementation = await load();\n if (!implementation.cancelDeferred)\n throw new Error(\"API cannot cancel deferred responses\");\n await implementation.cancelDeferred(model, handle, options);\n };\n }\n return api;\n}\n//# sourceMappingURL=lazy.js.map","// @ts-nocheck — vendored Pi source excerpts (pi-ai auth/resolve.js ModelsError + models.js createProvider @0.84.1, MIT, see ./PI-LICENSE); logic unchanged.\nimport { lazyStream } from './pi-ai-lazy.js'\nfunction withCauseDetail(message, cause) {\n if (cause === undefined || cause === null)\n return message;\n const detail = formatThrownValue(cause).trim();\n if (!detail || message.includes(detail))\n return message;\n return `${message}: ${detail}`;\n}\nexport class ModelsError extends Error {\n code;\n constructor(code, message, options) {\n super(withCauseDetail(message, options?.cause), options);\n this.name = \"ModelsError\";\n this.code = code;\n }\n}\n/**\n * Builds a provider from parts. Built-in provider factories and models.json\n * custom providers both go through this. A single `api` streams all models;\n * an `api` map dispatches on `model.api`, and a model whose api has no entry\n * produces a stream error.\n */\nexport function createProvider(input) {\n const baselineModels = input.models;\n let dynamicModels = [];\n const fetchModels = input.fetchModels;\n const currentModels = () => {\n const merged = [...baselineModels];\n for (const model of dynamicModels) {\n const index = merged.findIndex((entry) => entry.id === model.id);\n if (index >= 0)\n merged[index] = model;\n else\n merged.push(model);\n }\n return merged;\n };\n const single = typeof input.api.stream === \"function\" ? input.api : undefined;\n const byApi = single ? undefined : input.api;\n const apiFor = (model) => single ?? byApi?.[model.api];\n const dispatch = (model, run) => {\n const streams = apiFor(model);\n if (!streams) {\n return lazyStream(model, async () => {\n throw new ModelsError(\"stream\", `Provider ${input.id} has no API implementation for \"${model.api}\"`);\n });\n }\n return run(streams);\n };\n const provider = {\n id: input.id,\n name: input.name ?? input.id,\n baseUrl: input.baseUrl,\n headers: input.headers,\n auth: input.auth,\n getModels: currentModels,\n refreshModels: fetchModels\n ? async (context) => {\n if (context.stored) {\n const restored = context.stored.models\n .filter((model) => model.provider === input.id)\n .map((model) => model);\n if (!(await context.publish({\n update: () => {\n dynamicModels = restored;\n },\n }))) {\n return;\n }\n }\n if (!context.allowNetwork || context.signal.aborted)\n return;\n const refreshed = await fetchModels(context);\n if (context.signal.aborted)\n return;\n await context.publish({\n persist: { models: refreshed, checkedAt: Date.now() },\n update: () => {\n dynamicModels = refreshed;\n },\n });\n }\n : undefined,\n filterModels: input.filterModels,\n stream: (model, context, options) => dispatch(model, (streams) => streams.stream(model, context, options)),\n streamSimple: (model, context, options) => dispatch(model, (streams) => streams.streamSimple(model, context, options)),\n };\n const streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== undefined);\n if (streams.some((entry) => entry.fetchDeferred !== undefined)) {\n provider.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {\n const implementation = apiFor(model);\n if (!implementation?.fetchDeferred) {\n throw new ModelsError(\"provider\", `Provider ${input.id} does not support deferred responses for \"${model.api}\"`);\n }\n return implementation.fetchDeferred(model, handle, options);\n });\n }\n if (streams.some((entry) => entry.cancelDeferred !== undefined)) {\n provider.cancelDeferred = async (model, handle, options) => {\n const implementation = apiFor(model);\n if (!implementation?.cancelDeferred) {\n throw new ModelsError(\"provider\", `Provider ${input.id} cannot cancel deferred responses for \"${model.api}\"`);\n }\n await implementation.cancelDeferred(model, handle, options);\n };\n }\n return provider;\n}\n","// @ts-nocheck — vendored Pi source (pi-ai utils/provider-env.js @0.84.1, MIT, see ../PI-LICENSE);\n// imports remapped to sibling vendored files, logic byte-identical.\nlet procEnvCache = null;\n/**\n * Fallback for https://github.com/oven-sh/bun/issues/27802.\n * Bun compiled binaries can expose an empty process.env inside Linux sandboxes\n * even though /proc/self/environ contains the environment.\n *\n * This intentionally duplicates restoreSandboxEnv() in\n * packages/coding-agent/src/bun/restore-sandbox-env.ts. The ai package can be\n * used directly, without going through that entrypoint, so provider env lookup\n * must not depend on process.env having been patched.\n */\nfunction getBunSandboxEnvValue(name) {\n if (typeof process === \"undefined\" || !process.versions?.bun || Object.keys(process.env).length > 0) {\n return undefined;\n }\n if (procEnvCache === null) {\n procEnvCache = new Map();\n try {\n const { readFileSync } = require(\"node:fs\");\n const data = readFileSync(\"/proc/self/environ\", \"utf-8\");\n for (const entry of data.split(\"\\0\")) {\n const idx = entry.indexOf(\"=\");\n if (idx > 0) {\n procEnvCache.set(entry.slice(0, idx), entry.slice(idx + 1));\n }\n }\n }\n catch {\n // /proc/self/environ may not exist or may not be readable.\n }\n }\n return procEnvCache.get(name);\n}\n/**\n * Resolve a provider env value from scoped overrides, normal process.env, then\n * the duplicated Bun sandbox fallback for direct pi-ai consumers.\n */\nexport function getProviderEnvValue(name, env) {\n return (env?.[name] ||\n (typeof process !== \"undefined\" ? process.env[name] : undefined) ||\n getBunSandboxEnvValue(name) ||\n undefined);\n}\n//# sourceMappingURL=provider-env.js.map","// @ts-nocheck — vendored Pi source (pi-ai auth/oauth/device-code.js @0.84.1, MIT, see ../PI-LICENSE);\n// imports remapped to sibling vendored files, logic byte-identical.\nconst CANCEL_MESSAGE = \"Login cancelled\";\nconst TIMEOUT_MESSAGE = \"Device flow timed out\";\nconst SLOW_DOWN_TIMEOUT_MESSAGE = \"Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.\";\nconst MINIMUM_INTERVAL_MS = 1000;\n// RFC 8628 section 3.2: if the authorization server omits `interval`, the client must use 5 seconds.\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\n// RFC 8628 section 3.5: `slow_down` means the polling interval must increase by 5 seconds.\nconst SLOW_DOWN_INTERVAL_INCREMENT_MS = 5000;\nfunction abortableSleep(ms, signal, cancelMessage) {\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(new Error(cancelMessage));\n return;\n }\n const onAbort = () => {\n clearTimeout(timeout);\n reject(new Error(cancelMessage));\n };\n const timeout = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\nexport async function pollOAuthDeviceCodeFlow(options) {\n const deadline = typeof options.expiresInSeconds === \"number\"\n ? Date.now() + options.expiresInSeconds * 1000\n : Number.POSITIVE_INFINITY;\n let intervalMs = Math.max(MINIMUM_INTERVAL_MS, Math.floor((options.intervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS) * 1000));\n let slowDownResponses = 0;\n if (options.waitBeforeFirstPoll) {\n const remainingMs = deadline - Date.now();\n if (remainingMs > 0) {\n await abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);\n }\n }\n while (Date.now() < deadline) {\n if (options.signal.aborted) {\n throw new Error(CANCEL_MESSAGE);\n }\n const result = await options.poll();\n if (result.status === \"complete\") {\n return result.value;\n }\n if (result.status === \"failed\") {\n throw new Error(result.message);\n }\n if (result.status === \"slow_down\") {\n slowDownResponses += 1;\n // Use the server-provided interval when given (GitHub reports the new required minimum\n // in `interval`); trusting only a client-tracked value risks polling early forever under\n // WSL/VM clock drift. Otherwise apply RFC 8628 section 3.5: increase by 5 seconds.\n intervalMs =\n typeof result.intervalSeconds === \"number\" &&\n Number.isFinite(result.intervalSeconds) &&\n result.intervalSeconds > 0\n ? Math.max(MINIMUM_INTERVAL_MS, Math.floor(result.intervalSeconds * 1000))\n : Math.max(MINIMUM_INTERVAL_MS, intervalMs + SLOW_DOWN_INTERVAL_INCREMENT_MS);\n }\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) {\n break;\n }\n await abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);\n }\n throw new Error(slowDownResponses > 0 ? SLOW_DOWN_TIMEOUT_MESSAGE : TIMEOUT_MESSAGE);\n}\n//# sourceMappingURL=device-code.js.map","// @ts-nocheck — vendored Pi source (pi-ai auth/oauth/oauth-page.js @0.84.1, MIT, see ../PI-LICENSE);\n// imports remapped to sibling vendored files, logic byte-identical.\nconst LOGO_SVG = `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 800 800\" aria-hidden=\"true\"><path fill=\"#fff\" fill-rule=\"evenodd\" d=\"M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z\"/><path fill=\"#fff\" d=\"M517.36 400 H634.72 V634.72 H517.36 Z\"/></svg>`;\nfunction escapeHtml(value) {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\nfunction renderPage(options) {\n const title = escapeHtml(options.title);\n const heading = escapeHtml(options.heading);\n const message = escapeHtml(options.message);\n const details = options.details ? escapeHtml(options.details) : undefined;\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>${title}</title>\n <style>\n :root {\n --text: #fafafa;\n --text-dim: #a1a1aa;\n --page-bg: #09090b;\n --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, \"Noto Sans\", sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\";\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", 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 text-align: center;\n }\n main {\n width: 100%;\n max-width: 560px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n }\n .logo {\n width: 72px;\n height: 72px;\n display: block;\n margin-bottom: 24px;\n }\n h1 {\n margin: 0 0 10px;\n font-size: 28px;\n line-height: 1.15;\n font-weight: 650;\n color: var(--text);\n }\n p {\n margin: 0;\n line-height: 1.7;\n color: var(--text-dim);\n font-size: 15px;\n }\n .details {\n margin-top: 16px;\n font-family: var(--font-mono);\n font-size: 13px;\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=\"logo\">${LOGO_SVG}</div>\n <h1>${heading}</h1>\n <p>${message}</p>\n ${details ? `<div class=\"details\">${details}</div>` : \"\"}\n </main>\n</body>\n</html>`;\n}\nexport function oauthSuccessHtml(message) {\n return renderPage({\n title: \"Authentication successful\",\n heading: \"Authentication successful\",\n message,\n });\n}\nexport function oauthErrorHtml(message, details) {\n return renderPage({\n title: \"Authentication failed\",\n heading: \"Authentication failed\",\n message,\n details,\n });\n}\n//# sourceMappingURL=oauth-page.js.map","// @ts-nocheck — vendored Pi source (pi-ai auth/oauth/pkce.js @0.84.1, MIT, see ../PI-LICENSE);\n// imports remapped to sibling vendored files, logic byte-identical.\n/**\n * PKCE utilities using Web Crypto API.\n * Works in both Node.js 20+ and browsers.\n */\n/**\n * Encode bytes as base64url string.\n */\nfunction base64urlEncode(bytes) {\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\n/**\n * Generate PKCE code verifier and challenge.\n * Uses Web Crypto API for cross-platform compatibility.\n */\nexport async function generatePKCE() {\n // Generate random verifier\n const verifierBytes = new Uint8Array(32);\n crypto.getRandomValues(verifierBytes);\n const verifier = base64urlEncode(verifierBytes);\n // Compute SHA-256 challenge\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", data);\n const challenge = base64urlEncode(new Uint8Array(hashBuffer));\n return { verifier, challenge };\n}\n//# sourceMappingURL=pkce.js.map","// @ts-nocheck — vendored Pi source (pi-ai auth/oauth/openai-codex.js @0.84.1, MIT, see ../PI-LICENSE);\n// imports remapped to sibling vendored files, logic byte-identical.\n/**\n * OpenAI Codex (ChatGPT OAuth) flow\n *\n * NOTE: This module uses Node.js crypto and http for the OAuth callback.\n * It is only intended for CLI use, not browser environments.\n */\n// NEVER convert to top-level imports - breaks browser/Vite builds\nlet _randomBytes = null;\nlet _http = null;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n import(\"node:crypto\").then((m) => {\n _randomBytes = m.randomBytes;\n });\n import(\"node:http\").then((m) => {\n _http = m;\n });\n}\nimport { getProviderEnvValue } from './provider-env.js';\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.js\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.js\";\nimport { generatePKCE } from \"./pkce.js\";\nconst CLIENT_ID = \"app_EMoamEEZ73f0CkXaXp7hrann\";\nconst AUTH_BASE_URL = \"https://auth.openai.com\";\nconst AUTHORIZE_URL = `${AUTH_BASE_URL}/oauth/authorize`;\nconst TOKEN_URL = `${AUTH_BASE_URL}/oauth/token`;\nconst REDIRECT_URI = \"http://localhost:1455/auth/callback\";\nconst DEVICE_USER_CODE_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`;\nconst DEVICE_TOKEN_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/token`;\nconst DEVICE_VERIFICATION_URI = `${AUTH_BASE_URL}/codex/device`;\nconst DEVICE_REDIRECT_URI = `${AUTH_BASE_URL}/deviceauth/callback`;\nconst DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;\nconst OPENAI_CODEX_BROWSER_LOGIN_METHOD = \"browser\";\nconst OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD = \"device_code\";\nconst SCOPE = \"openid profile email offline_access\";\nconst JWT_CLAIM_PATH = \"https://api.openai.com/auth\";\nfunction getCallbackHost() {\n return getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\n}\nfunction createState() {\n if (!_randomBytes) {\n throw new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n }\n return _randomBytes(16).toString(\"hex\");\n}\nfunction parseAuthorizationInput(input) {\n const value = input.trim();\n if (!value)\n return {};\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 // not a URL\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}\nfunction decodeJwt(token) {\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);\n }\n catch {\n return null;\n }\n}\nasync function fetchWithLoginCancellation(input, init) {\n try {\n return await fetch(input, init);\n }\n catch (error) {\n if (init.signal?.aborted) {\n throw new Error(\"Login cancelled\");\n }\n throw error;\n }\n}\nasync function readTokenResponse(response, operation) {\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`OpenAI Codex token ${operation} failed (${response.status}): ${text || response.statusText}`);\n }\n const rawJson = await response.json();\n const json = rawJson;\n if (!json?.access_token || !json.refresh_token || typeof json.expires_in !== \"number\") {\n throw new Error(`OpenAI Codex token ${operation} response missing fields: ${JSON.stringify(json)}`);\n }\n return {\n access: json.access_token,\n refresh: json.refresh_token,\n expires: Date.now() + json.expires_in * 1000,\n };\n}\nasync function exchangeAuthorizationCode(code, verifier, redirectUri, signal) {\n const response = await fetchWithLoginCancellation(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 signal,\n });\n return readTokenResponse(response, \"exchange\");\n}\nasync function refreshAccessToken(refreshToken, signal) {\n let response;\n try {\n response = await fetch(TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n client_id: CLIENT_ID,\n }),\n signal,\n });\n }\n catch (error) {\n throw new Error(`OpenAI Codex token refresh error: ${error instanceof Error ? error.message : String(error)}`);\n }\n return readTokenResponse(response, \"refresh\");\n}\nasync function startOpenAICodexDeviceAuth(signal) {\n const response = await fetchWithLoginCancellation(DEVICE_USER_CODE_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: CLIENT_ID }),\n signal,\n });\n if (!response.ok) {\n if (response.status === 404) {\n throw new Error(\"OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.\");\n }\n const responseBody = await response.text().catch(() => \"\");\n throw new Error(`OpenAI Codex device code request failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`);\n }\n const rawJson = await response.json();\n const json = rawJson;\n const intervalSeconds = typeof json?.interval === \"string\" ? Number(json.interval.trim()) : json?.interval;\n if (!json?.device_auth_id ||\n !json.user_code ||\n typeof intervalSeconds !== \"number\" ||\n !Number.isFinite(intervalSeconds) ||\n intervalSeconds < 0) {\n throw new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(json)}`);\n }\n return {\n deviceAuthId: json.device_auth_id,\n userCode: json.user_code,\n intervalSeconds,\n };\n}\nasync function pollOpenAICodexDeviceAuth(device, signal) {\n return pollOAuthDeviceCodeFlow({\n intervalSeconds: device.intervalSeconds,\n expiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n signal,\n poll: async () => {\n const response = await fetchWithLoginCancellation(DEVICE_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n device_auth_id: device.deviceAuthId,\n user_code: device.userCode,\n }),\n signal,\n });\n if (response.ok) {\n const rawJson = await response.json();\n const json = rawJson;\n if (!json?.authorization_code || !json.code_verifier) {\n return {\n status: \"failed\",\n message: `Invalid OpenAI Codex device auth token response: ${JSON.stringify(json)}`,\n };\n }\n return {\n status: \"complete\",\n value: { authorizationCode: json.authorization_code, codeVerifier: json.code_verifier },\n };\n }\n if (response.status === 403 || response.status === 404) {\n return { status: \"pending\" };\n }\n const responseBody = await response.text().catch(() => \"\");\n let errorCode;\n try {\n const json = JSON.parse(responseBody);\n const error = json?.error;\n errorCode = typeof error === \"object\" ? error?.code : error;\n }\n catch { }\n if (errorCode === \"deviceauth_authorization_pending\") {\n return { status: \"pending\" };\n }\n if (errorCode === \"slow_down\") {\n return { status: \"slow_down\" };\n }\n return {\n status: \"failed\",\n message: `OpenAI Codex device auth failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`,\n };\n },\n });\n}\nasync function createAuthorizationFlow(originator = \"pi\") {\n const { verifier, challenge } = await generatePKCE();\n const state = createState();\n const url = new URL(AUTHORIZE_URL);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", CLIENT_ID);\n url.searchParams.set(\"redirect_uri\", REDIRECT_URI);\n url.searchParams.set(\"scope\", SCOPE);\n url.searchParams.set(\"code_challenge\", challenge);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n url.searchParams.set(\"state\", state);\n url.searchParams.set(\"id_token_add_organizations\", \"true\");\n url.searchParams.set(\"codex_cli_simplified_flow\", \"true\");\n url.searchParams.set(\"originator\", originator);\n return { verifier, state, url: url.toString() };\n}\nfunction startLocalOAuthServer(state) {\n if (!_http) {\n throw new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n }\n let settleWait;\n const waitForCodePromise = new Promise((resolve) => {\n let settled = false;\n settleWait = (value) => {\n if (settled)\n return;\n settled = true;\n resolve(value);\n };\n });\n const server = _http.createServer((req, res) => {\n try {\n const url = new URL(req.url || \"\", \"http://localhost\");\n if (url.pathname !== \"/auth/callback\") {\n res.statusCode = 404;\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(oauthErrorHtml(\"Callback route not found.\"));\n return;\n }\n if (url.searchParams.get(\"state\") !== state) {\n res.statusCode = 400;\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(oauthErrorHtml(\"State mismatch.\"));\n return;\n }\n const code = url.searchParams.get(\"code\");\n if (!code) {\n res.statusCode = 400;\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(oauthErrorHtml(\"Missing authorization code.\"));\n return;\n }\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(oauthSuccessHtml(\"OpenAI authentication completed. You can close this window.\"));\n settleWait?.({ code });\n }\n catch {\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(oauthErrorHtml(\"Internal error while processing OAuth callback.\"));\n }\n });\n return new Promise((resolve) => {\n server\n .listen(1455, getCallbackHost(), () => {\n resolve({\n close: () => server.close(),\n cancelWait: () => {\n settleWait?.(null);\n },\n waitForCode: () => waitForCodePromise,\n });\n })\n .on(\"error\", (_err) => {\n settleWait?.(null);\n resolve({\n close: () => {\n try {\n server.close();\n }\n catch {\n // ignore\n }\n },\n cancelWait: () => { },\n waitForCode: async () => null,\n });\n });\n });\n}\nfunction getAccountId(accessToken) {\n const payload = decodeJwt(accessToken);\n const auth = payload?.[JWT_CLAIM_PATH];\n const accountId = auth?.chatgpt_account_id;\n return typeof accountId === \"string\" && accountId.length > 0 ? accountId : null;\n}\nfunction credentialsFromToken(token) {\n const accountId = getAccountId(token.access);\n if (!accountId) {\n throw new Error(\"Failed to extract accountId from token\");\n }\n return {\n type: \"oauth\",\n access: token.access,\n refresh: token.refresh,\n expires: token.expires,\n accountId,\n };\n}\nasync function exchangeAuthorizationCodeForCredentials(code, verifier, redirectUri, signal) {\n return credentialsFromToken(await exchangeAuthorizationCode(code, verifier, redirectUri, signal));\n}\nasync function loginOpenAICodexDeviceCode(interaction) {\n const device = await startOpenAICodexDeviceAuth(interaction.signal);\n interaction.notify({\n type: \"device_code\",\n userCode: device.userCode,\n verificationUri: DEVICE_VERIFICATION_URI,\n intervalSeconds: device.intervalSeconds,\n expiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n });\n const code = await pollOpenAICodexDeviceAuth(device, interaction.signal);\n return exchangeAuthorizationCodeForCredentials(code.authorizationCode, code.codeVerifier, DEVICE_REDIRECT_URI, interaction.signal);\n}\nasync function loginOpenAICodex(interaction) {\n const { verifier, state, url } = await createAuthorizationFlow();\n const server = await startLocalOAuthServer(state);\n const manualAbort = new AbortController();\n const onAbort = () => server.cancelWait();\n interaction.signal.addEventListener(\"abort\", onAbort, { once: true });\n if (interaction.signal.aborted)\n onAbort();\n let code;\n let manualCode;\n let manualError;\n interaction.notify({\n type: \"auth_url\",\n url,\n instructions: \"A browser window should open. Complete login to finish.\",\n });\n try {\n const manualPromise = interaction\n .prompt({\n type: \"manual_code\",\n message: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n placeholder: REDIRECT_URI,\n signal: manualAbort.signal,\n })\n .then((input) => {\n manualCode = input;\n server.cancelWait();\n })\n .catch((error) => {\n manualError = error instanceof Error ? error : new Error(String(error));\n server.cancelWait();\n });\n const result = await server.waitForCode();\n if (manualError)\n throw manualError;\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 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 if (!code)\n throw new Error(\"Missing authorization code\");\n return exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI, interaction.signal);\n }\n finally {\n interaction.signal.removeEventListener(\"abort\", onAbort);\n manualAbort.abort();\n server.close();\n }\n}\n/**\n * Refresh OpenAI Codex OAuth token\n */\nasync function refreshOpenAICodexToken(refreshToken, signal) {\n return credentialsFromToken(await refreshAccessToken(refreshToken, signal));\n}\nexport const openaiCodexOAuth = {\n name: \"OpenAI (ChatGPT Plus/Pro)\",\n isSubscription: true,\n async login(interaction) {\n const method = await interaction.prompt({\n type: \"select\",\n message: \"Select OpenAI Codex login method:\",\n options: [\n { id: OPENAI_CODEX_BROWSER_LOGIN_METHOD, label: \"Browser login (default)\" },\n { id: OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD, label: \"Device code login (headless)\" },\n ],\n });\n if (method === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) {\n return loginOpenAICodexDeviceCode(interaction);\n }\n if (method !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {\n throw new Error(`Unknown OpenAI Codex login method: ${method}`);\n }\n return loginOpenAICodex(interaction);\n },\n refresh: (credential, signal) => refreshOpenAICodexToken(credential.refresh, signal),\n async toAuth(credential) {\n return { apiKey: credential.access };\n },\n};\n//# sourceMappingURL=openai-codex.js.map","// @ts-nocheck — vendored Pi source (pi-ai auth/oauth/anthropic.js @0.84.1, MIT, see ../PI-LICENSE);\n// imports remapped to sibling vendored files, logic byte-identical.\n/**\n * Anthropic OAuth flow (Claude Pro/Max)\n *\n * NOTE: This module uses Node.js http.createServer for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\nimport { getProviderEnvValue } from './provider-env.js';\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.js\";\nimport { generatePKCE } from \"./pkce.js\";\nlet nodeApis = null;\nlet nodeApisPromise = null;\nconst decode = (s) => atob(s);\nconst CLIENT_ID = decode(\"OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl\");\nconst AUTHORIZE_URL = \"https://claude.ai/oauth/authorize\";\nconst TOKEN_URL = \"https://platform.claude.com/v1/oauth/token\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 53692;\nconst CALLBACK_PATH = \"/callback\";\nconst REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst SCOPES = \"org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload\";\nasync function getNodeApis() {\n if (nodeApis)\n return nodeApis;\n if (!nodeApisPromise) {\n if (typeof process === \"undefined\" || (!process.versions?.node && !process.versions?.bun)) {\n throw new Error(\"Anthropic OAuth is only available in Node.js environments\");\n }\n nodeApisPromise = import(\"node:http\").then((httpModule) => ({\n createServer: httpModule.createServer,\n }));\n }\n nodeApis = await nodeApisPromise;\n return nodeApis;\n}\nfunction parseAuthorizationInput(input) {\n const value = input.trim();\n if (!value)\n return {};\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 // not a URL\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}\nfunction formatErrorDetails(error) {\n if (error instanceof Error) {\n const details = [`${error.name}: ${error.message}`];\n const errorWithCode = error;\n if (errorWithCode.code)\n details.push(`code=${errorWithCode.code}`);\n if (typeof errorWithCode.errno !== \"undefined\")\n details.push(`errno=${String(errorWithCode.errno)}`);\n if (typeof error.cause !== \"undefined\") {\n details.push(`cause=${formatErrorDetails(error.cause)}`);\n }\n if (error.stack) {\n details.push(`stack=${error.stack}`);\n }\n return details.join(\"; \");\n }\n return String(error);\n}\nasync function startCallbackServer(expectedState) {\n const { createServer } = await getNodeApis();\n return new Promise((resolve, reject) => {\n let settleWait;\n const waitForCodePromise = new Promise((resolveWait) => {\n let settled = false;\n settleWait = (value) => {\n if (settled)\n return;\n settled = true;\n resolveWait(value);\n };\n });\n const server = createServer((req, res) => {\n try {\n const url = new URL(req.url || \"\", \"http://localhost\");\n if (url.pathname !== CALLBACK_PATH) {\n res.writeHead(404, { \"Content-Type\": \"text/html; charset=utf-8\" });\n res.end(oauthErrorHtml(\"Callback route not found.\"));\n return;\n }\n const code = url.searchParams.get(\"code\");\n const state = url.searchParams.get(\"state\");\n const error = url.searchParams.get(\"error\");\n if (error) {\n res.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n res.end(oauthErrorHtml(\"Anthropic authentication did not complete.\", `Error: ${error}`));\n return;\n }\n if (!code || !state) {\n res.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n res.end(oauthErrorHtml(\"Missing code or state parameter.\"));\n return;\n }\n if (state !== expectedState) {\n res.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n res.end(oauthErrorHtml(\"State mismatch.\"));\n return;\n }\n res.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n res.end(oauthSuccessHtml(\"Anthropic authentication completed. You can close this window.\"));\n settleWait?.({ code, state });\n }\n catch {\n res.writeHead(500, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n res.end(\"Internal error\");\n }\n });\n server.on(\"error\", (err) => {\n reject(err);\n });\n server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n resolve({\n server,\n redirectUri: REDIRECT_URI,\n cancelWait: () => {\n settleWait?.(null);\n },\n waitForCode: () => waitForCodePromise,\n });\n });\n });\n}\nasync function postJson(url, body, signal) {\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.any([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 }\n return responseBody;\n}\nasync function exchangeAuthorizationCode(code, state, verifier, redirectUri, signal) {\n let responseBody;\n try {\n 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 }, signal);\n }\n catch (error) {\n throw new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`);\n }\n let tokenData;\n try {\n tokenData = JSON.parse(responseBody);\n }\n catch (error) {\n throw new Error(`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`);\n }\n return {\n type: \"oauth\",\n refresh: tokenData.refresh_token,\n access: tokenData.access_token,\n expires: Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000,\n };\n}\nasync function loginAnthropic(interaction) {\n const { verifier, challenge } = await generatePKCE();\n const server = await startCallbackServer(verifier);\n const manualAbort = new AbortController();\n const onAbort = () => server.cancelWait();\n interaction.signal.addEventListener(\"abort\", onAbort, { once: true });\n if (interaction.signal.aborted)\n onAbort();\n let code;\n let state;\n let manualInput;\n let manualError;\n try {\n const authParams = new URLSearchParams({\n code: \"true\",\n client_id: CLIENT_ID,\n response_type: \"code\",\n redirect_uri: REDIRECT_URI,\n scope: SCOPES,\n code_challenge: challenge,\n code_challenge_method: \"S256\",\n state: verifier,\n });\n interaction.notify({\n type: \"auth_url\",\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 const manualPromise = interaction\n .prompt({\n type: \"manual_code\",\n message: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n placeholder: REDIRECT_URI,\n signal: manualAbort.signal,\n })\n .then((input) => {\n manualInput = input;\n server.cancelWait();\n })\n .catch((error) => {\n manualError = error instanceof Error ? error : new Error(String(error));\n server.cancelWait();\n });\n const result = await server.waitForCode();\n if (manualError)\n throw manualError;\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 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 if (!code)\n throw new Error(\"Missing authorization code\");\n if (!state)\n throw new Error(\"Missing OAuth state\");\n interaction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n return exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI, interaction.signal);\n }\n finally {\n interaction.signal.removeEventListener(\"abort\", onAbort);\n manualAbort.abort();\n server.server.close();\n }\n}\n/**\n * Refresh Anthropic OAuth token\n */\nasync function refreshAnthropicToken(refreshToken, signal) {\n let responseBody;\n try {\n responseBody = await postJson(TOKEN_URL, {\n grant_type: \"refresh_token\",\n client_id: CLIENT_ID,\n refresh_token: refreshToken,\n }, signal);\n }\n catch (error) {\n throw new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);\n }\n let data;\n try {\n data = JSON.parse(responseBody);\n }\n catch (error) {\n throw new Error(`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`);\n }\n return {\n type: \"oauth\",\n refresh: data.refresh_token,\n access: data.access_token,\n expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,\n };\n}\nexport const anthropicOAuth = {\n name: \"Anthropic (Claude Pro/Max)\",\n isSubscription: true,\n login: loginAnthropic,\n refresh: (credential, signal) => refreshAnthropicToken(credential.refresh, signal),\n async toAuth(credential) {\n return { apiKey: credential.access };\n },\n};\n//# sourceMappingURL=anthropic.js.map","","// @ts-nocheck — vendored Pi source (pi-ai model-catalog.js @0.84.1, MIT, see ../PI-LICENSE); unchanged.\nexport function flattenModelCatalog(_provider, groups) {\n return Object.assign({}, ...Object.values(groups));\n}\n//# sourceMappingURL=model-catalog.js.map","// @ts-nocheck — vendored Pi source (pi-ai providers/github-copilot.models.js @0.84.1, MIT, see ../PI-LICENSE);\n// imports remapped to sibling vendored files, logic byte-identical.\n// This file is auto-generated by scripts/generate-models.ts\n// Do not edit manually - run 'npm run generate-models' to update\nimport values from \"./data/github-copilot.json\" with { type: \"json\" };\nimport { flattenModelCatalog } from './model-catalog.js';\nexport const GITHUB_COPILOT_MODELS = flattenModelCatalog(\"github-copilot\", values);\n//# sourceMappingURL=github-copilot.models.js.map","// @ts-nocheck — vendored Pi source (pi-ai auth/oauth/github-copilot.js @0.84.1, MIT, see ../PI-LICENSE);\n// imports remapped to sibling vendored files, logic byte-identical.\n/**\n * GitHub Copilot OAuth flow\n */\nimport { GITHUB_COPILOT_MODELS } from './github-copilot.models.js';\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.js\";\nconst decode = (s) => atob(s);\nconst CLIENT_ID = decode(\"SXYxLmI1MDdhMDhjODdlY2ZlOTg=\");\nconst COPILOT_HEADERS = {\n \"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n \"Editor-Version\": \"vscode/1.107.0\",\n \"Editor-Plugin-Version\": \"copilot-chat/0.35.0\",\n \"Copilot-Integration-Id\": \"vscode-chat\",\n};\nconst COPILOT_API_VERSION = \"2026-06-01\";\nfunction normalizeDomain(input) {\n const trimmed = input.trim();\n if (!trimmed)\n return null;\n try {\n const url = trimmed.includes(\"://\") ? new URL(trimmed) : new URL(`https://${trimmed}`);\n return url.hostname;\n }\n catch {\n return null;\n }\n}\nfunction getUrls(domain) {\n return {\n deviceCodeUrl: `https://${domain}/login/device/code`,\n accessTokenUrl: `https://${domain}/login/oauth/access_token`,\n copilotTokenUrl: `https://api.${domain}/copilot_internal/v2/token`,\n };\n}\n/**\n * Parse the proxy-ep from a Copilot token and convert to API base URL.\n * Token format: tid=...;exp=...;proxy-ep=proxy.individual.githubcopilot.com;...\n * Returns API URL like https://api.individual.githubcopilot.com\n */\nfunction getBaseUrlFromToken(token) {\n const match = token.match(/proxy-ep=([^;]+)/);\n if (!match)\n return null;\n const proxyHost = match[1];\n // Convert proxy.xxx to api.xxx\n const apiHost = proxyHost.replace(/^proxy\\./, \"api.\");\n return `https://${apiHost}`;\n}\nfunction getGitHubCopilotBaseUrl(token, enterpriseDomain) {\n // If we have a token, extract the base URL from proxy-ep\n if (token) {\n const urlFromToken = getBaseUrlFromToken(token);\n if (urlFromToken)\n return urlFromToken;\n }\n // Fallback for enterprise or if token parsing fails\n if (enterpriseDomain)\n return `https://copilot-api.${enterpriseDomain}`;\n return \"https://api.individual.githubcopilot.com\";\n}\nfunction asRecord(value) {\n return value && typeof value === \"object\" ? value : undefined;\n}\nfunction parseAvailableCopilotModelIds(raw, allowPolicyFallback) {\n const data = asRecord(raw)?.data;\n if (!Array.isArray(data)) {\n throw new Error(\"Invalid Copilot models response\");\n }\n const pickerIds = [];\n const policyEnabledIds = [];\n for (const rawItem of data) {\n const item = asRecord(rawItem);\n const id = item?.id;\n if (!item || typeof id !== \"string\")\n continue;\n const capabilities = asRecord(item.capabilities);\n const supports = asRecord(capabilities?.supports);\n if (supports?.tool_calls === false)\n continue;\n const policy = asRecord(item.policy);\n if (item.model_picker_enabled === true && policy?.state !== \"disabled\")\n pickerIds.push(id);\n if (policy?.state === \"enabled\")\n policyEnabledIds.push(id);\n }\n return pickerIds.length > 0 || !allowPolicyFallback ? pickerIds : policyEnabledIds;\n}\nasync function fetchAvailableGitHubCopilotModelIds(copilotToken, enterpriseDomain, signal) {\n const baseUrl = getGitHubCopilotBaseUrl(copilotToken, enterpriseDomain);\n // Some Individual accounts return false for every picker flag despite explicit enabled policies.\n // Limit the fallback to that endpoint so other account types keep strict picker semantics.\n const allowPolicyFallback = baseUrl === \"https://api.individual.githubcopilot.com\";\n const raw = await fetchJson(`${baseUrl}/models`, {\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${copilotToken}`,\n ...COPILOT_HEADERS,\n \"X-GitHub-Api-Version\": COPILOT_API_VERSION,\n },\n signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]),\n });\n return parseAvailableCopilotModelIds(raw, allowPolicyFallback);\n}\nasync function fetchJson(url, init) {\n const response = await fetch(url, init);\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`${response.status} ${response.statusText}: ${text}`);\n }\n return response.json();\n}\nasync function startDeviceFlow(domain, signal) {\n const urls = getUrls(domain);\n const data = await fetchJson(urls.deviceCodeUrl, {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n },\n body: new URLSearchParams({\n client_id: CLIENT_ID,\n scope: \"read:user\",\n }),\n signal,\n });\n if (!data || typeof data !== \"object\") {\n throw new Error(\"Invalid device code response\");\n }\n const deviceCode = data.device_code;\n const userCode = data.user_code;\n const verificationUri = data.verification_uri;\n const interval = data.interval;\n const expiresIn = data.expires_in;\n if (typeof deviceCode !== \"string\" ||\n typeof userCode !== \"string\" ||\n typeof verificationUri !== \"string\" ||\n (interval !== undefined && typeof interval !== \"number\") ||\n typeof expiresIn !== \"number\") {\n throw new Error(\"Invalid device code response fields\");\n }\n // The verification URI is opened in the user's browser and to prevent `open` from\n // opening an executable or similar, we force it to be a URL.\n let parsedUri;\n try {\n parsedUri = new URL(verificationUri);\n }\n catch {\n throw new Error(\"Untrusted verification_uri in device code response\");\n }\n if (parsedUri.protocol !== \"https:\" && parsedUri.protocol !== \"http:\") {\n throw new Error(\"Untrusted verification_uri in device code response\");\n }\n return {\n device_code: deviceCode,\n user_code: userCode,\n verification_uri: parsedUri.href,\n interval,\n expires_in: expiresIn,\n };\n}\nasync function pollForGitHubAccessToken(domain, device, signal) {\n const urls = getUrls(domain);\n return pollOAuthDeviceCodeFlow({\n intervalSeconds: device.interval,\n expiresInSeconds: device.expires_in,\n waitBeforeFirstPoll: true,\n signal,\n poll: async () => {\n const raw = await fetchJson(urls.accessTokenUrl, {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n },\n body: new URLSearchParams({\n client_id: CLIENT_ID,\n device_code: device.device_code,\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n }),\n signal,\n });\n if (raw && typeof raw === \"object\" && typeof raw.access_token === \"string\") {\n return { status: \"complete\", value: raw.access_token };\n }\n if (raw && typeof raw === \"object\" && typeof raw.error === \"string\") {\n const { error, error_description: description, interval } = raw;\n if (error === \"authorization_pending\") {\n return { status: \"pending\" };\n }\n if (error === \"slow_down\") {\n return { status: \"slow_down\", intervalSeconds: typeof interval === \"number\" ? interval : undefined };\n }\n const descriptionSuffix = description ? `: ${description}` : \"\";\n return { status: \"failed\", message: `Device flow failed: ${error}${descriptionSuffix}` };\n }\n return { status: \"failed\", message: \"Invalid device token response\" };\n },\n });\n}\nasync function refreshGitHubCopilotAccessToken(refreshToken, enterpriseDomain, signal) {\n const domain = enterpriseDomain || \"github.com\";\n const urls = getUrls(domain);\n const raw = await fetchJson(urls.copilotTokenUrl, {\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${refreshToken}`,\n ...COPILOT_HEADERS,\n },\n signal,\n });\n if (!raw || typeof raw !== \"object\") {\n throw new Error(\"Invalid Copilot token response\");\n }\n const token = raw.token;\n const expiresAt = raw.expires_at;\n if (typeof token !== \"string\" || typeof expiresAt !== \"number\") {\n throw new Error(\"Invalid Copilot token response fields\");\n }\n return {\n type: \"oauth\",\n refresh: refreshToken,\n access: token,\n expires: expiresAt * 1000 - 5 * 60 * 1000,\n enterpriseUrl: enterpriseDomain,\n };\n}\n/**\n * Refresh GitHub Copilot token\n */\nasync function refreshGitHubCopilotToken(refreshToken, enterpriseDomain, signal) {\n const credentials = await refreshGitHubCopilotAccessToken(refreshToken, enterpriseDomain, signal);\n return {\n ...credentials,\n availableModelIds: await fetchAvailableGitHubCopilotModelIds(credentials.access, enterpriseDomain, signal),\n };\n}\n/**\n * Enable a model for the user's GitHub Copilot account.\n * This is required for some models (like Claude, Grok) before they can be used.\n */\nasync function enableGitHubCopilotModel(token, modelId, enterpriseDomain, signal) {\n const baseUrl = getGitHubCopilotBaseUrl(token, enterpriseDomain);\n const url = `${baseUrl}/models/${modelId}/policy`;\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n ...COPILOT_HEADERS,\n \"openai-intent\": \"chat-policy\",\n \"x-interaction-type\": \"chat-policy\",\n },\n body: JSON.stringify({ state: \"enabled\" }),\n signal,\n });\n return response.ok;\n }\n catch (error) {\n if (signal.aborted)\n throw error;\n return false;\n }\n}\n/**\n * Enable all known GitHub Copilot models that may require policy acceptance.\n * Called after successful login to ensure all models are available.\n */\nasync function enableAllGitHubCopilotModels(token, enterpriseDomain, signal) {\n const models = Object.values(GITHUB_COPILOT_MODELS);\n await Promise.all(models.map(async (model) => {\n await enableGitHubCopilotModel(token, model.id, enterpriseDomain, signal);\n }));\n}\nasync function loginGitHubCopilot(interaction) {\n const input = await interaction.prompt({\n type: \"text\",\n message: \"GitHub Enterprise URL/domain (blank for github.com)\",\n placeholder: \"company.ghe.com\",\n });\n if (interaction.signal.aborted)\n throw new Error(\"Login cancelled\");\n const trimmed = input.trim();\n const enterpriseDomain = normalizeDomain(input);\n if (trimmed && !enterpriseDomain)\n throw new Error(\"Invalid GitHub Enterprise URL/domain\");\n const domain = enterpriseDomain || \"github.com\";\n const device = await startDeviceFlow(domain, interaction.signal);\n interaction.notify({\n type: \"device_code\",\n userCode: device.user_code,\n verificationUri: device.verification_uri,\n intervalSeconds: device.interval,\n expiresInSeconds: device.expires_in,\n });\n const githubAccessToken = await pollForGitHubAccessToken(domain, device, interaction.signal);\n const credentials = await refreshGitHubCopilotAccessToken(githubAccessToken, enterpriseDomain ?? undefined, interaction.signal);\n interaction.notify({ type: \"progress\", message: \"Enabling models...\" });\n await enableAllGitHubCopilotModels(credentials.access, enterpriseDomain ?? undefined, interaction.signal);\n return {\n ...credentials,\n availableModelIds: await fetchAvailableGitHubCopilotModelIds(credentials.access, enterpriseDomain ?? undefined, interaction.signal),\n };\n}\nfunction copilotEnterpriseDomain(credential) {\n const enterpriseUrl = credential.enterpriseUrl;\n if (typeof enterpriseUrl !== \"string\" || !enterpriseUrl)\n return undefined;\n return normalizeDomain(enterpriseUrl) ?? undefined;\n}\nexport const githubCopilotOAuth = {\n name: \"GitHub Copilot\",\n isSubscription: true,\n login: loginGitHubCopilot,\n refresh: (credential, signal) => refreshGitHubCopilotToken(credential.refresh, copilotEnterpriseDomain(credential), signal),\n /** Derive the credential-specific proxy endpoint for each request. */\n async toAuth(credential) {\n return {\n apiKey: credential.access,\n baseUrl: getGitHubCopilotBaseUrl(credential.access, copilotEnterpriseDomain(credential)),\n };\n },\n};\n//# sourceMappingURL=github-copilot.js.map","// @ts-nocheck — vendored Pi source (pi-ai auth/oauth/kimi-coding.js @0.84.1, MIT, see ../PI-LICENSE);\n// imports remapped to sibling vendored files, logic byte-identical.\n/**\n * Kimi Code (subscription) OAuth flow\n *\n * RFC 8628 device authorization grant against https://auth.kimi.com with JSON\n * responses. The access token authenticates requests to\n * https://api.kimi.com/coding as an `Authorization: Bearer` header.\n */\nimport { getProviderEnvValue } from './provider-env.js';\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.js\";\nconst CLIENT_ID = \"17e5f671-d194-4dfb-9706-5516cb48c098\";\nconst DEFAULT_OAUTH_HOST = \"https://auth.kimi.com\";\nconst DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\nconst REQUEST_TIMEOUT_MS = 30 * 1000;\nconst REFRESH_MAX_RETRIES = 3;\nfunction getOauthHost() {\n const override = getProviderEnvValue(\"KIMI_CODE_OAUTH_HOST\") || getProviderEnvValue(\"KIMI_OAUTH_HOST\");\n return (override || DEFAULT_OAUTH_HOST).replace(/\\/+$/, \"\");\n}\nfunction requestSignal(signal) {\n return AbortSignal.any([AbortSignal.timeout(REQUEST_TIMEOUT_MS), signal]);\n}\nfunction formUrlEncode(fields) {\n return new URLSearchParams(fields).toString();\n}\nasync function readJson(response) {\n try {\n const json = await response.json();\n return json && typeof json === \"object\" ? json : null;\n }\n catch {\n return null;\n }\n}\n/** The verification URI is opened in the user's browser; only http(s) URLs are trusted. */\nfunction trustedHttpUrl(value) {\n if (typeof value !== \"string\" || !value)\n return null;\n try {\n const url = new URL(value);\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\")\n return null;\n return url.href;\n }\n catch {\n return null;\n }\n}\nasync function startDeviceAuthorization(oauthHost, signal) {\n const response = await fetch(`${oauthHost}/api/oauth/device_authorization`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: formUrlEncode({ client_id: CLIENT_ID }),\n signal: requestSignal(signal),\n });\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Kimi Code device authorization failed with status ${response.status}${text ? `: ${text}` : \"\"}`);\n }\n const json = await readJson(response);\n const deviceCode = json?.device_code;\n const userCode = json?.user_code;\n const verificationUri = json?.verification_uri;\n const verificationUriComplete = json?.verification_uri_complete;\n if (typeof deviceCode !== \"string\" ||\n typeof userCode !== \"string\" ||\n typeof verificationUri !== \"string\" ||\n typeof verificationUriComplete !== \"string\" ||\n !trustedHttpUrl(verificationUriComplete) ||\n !trustedHttpUrl(verificationUri)) {\n throw new Error(`Invalid Kimi Code device authorization response: ${JSON.stringify(json)}`);\n }\n const interval = json?.interval;\n const expiresIn = json?.expires_in;\n return {\n deviceCode,\n userCode,\n verificationUri,\n verificationUriComplete,\n intervalSeconds: typeof interval === \"number\" && Number.isFinite(interval) && interval > 0\n ? interval\n : DEFAULT_POLL_INTERVAL_SECONDS,\n expiresInSeconds: typeof expiresIn === \"number\" && Number.isFinite(expiresIn) && expiresIn > 0\n ? expiresIn\n : DEVICE_CODE_TIMEOUT_SECONDS,\n };\n}\nfunction parseTokenResponse(json, operation) {\n const accessToken = json?.access_token;\n const refreshToken = json?.refresh_token;\n const expiresIn = json?.expires_in;\n if (typeof accessToken !== \"string\" ||\n !accessToken ||\n typeof refreshToken !== \"string\" ||\n !refreshToken ||\n typeof expiresIn !== \"number\" ||\n !Number.isFinite(expiresIn) ||\n expiresIn <= 0) {\n throw new Error(`Kimi Code token ${operation} response missing fields: ${JSON.stringify(json)}`);\n }\n return {\n access: accessToken,\n refresh: refreshToken,\n expires: Date.now() + expiresIn * 1000,\n };\n}\nasync function pollForToken(oauthHost, device, signal) {\n return pollOAuthDeviceCodeFlow({\n intervalSeconds: device.intervalSeconds,\n expiresInSeconds: device.expiresInSeconds,\n waitBeforeFirstPoll: true,\n signal,\n poll: async () => {\n const response = await fetch(`${oauthHost}/api/oauth/token`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: formUrlEncode({\n client_id: CLIENT_ID,\n device_code: device.deviceCode,\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n }),\n signal: requestSignal(signal),\n });\n if (response.status >= 500) {\n const text = await response.text().catch(() => \"\");\n return {\n status: \"failed\",\n message: `Kimi Code device token request failed with status ${response.status}${text ? `: ${text}` : \"\"}`,\n };\n }\n const json = await readJson(response);\n if (response.ok && typeof json?.access_token === \"string\") {\n try {\n return { status: \"complete\", value: parseTokenResponse(json, \"poll\") };\n }\n catch (error) {\n return { status: \"failed\", message: error instanceof Error ? error.message : String(error) };\n }\n }\n const error = json?.error;\n const description = typeof json?.error_description === \"string\" ? `: ${json.error_description}` : \"\";\n if (error === \"authorization_pending\") {\n return { status: \"pending\" };\n }\n if (error === \"slow_down\") {\n const interval = json?.interval;\n return {\n status: \"slow_down\",\n intervalSeconds: typeof interval === \"number\" && interval > 0 ? interval : undefined,\n };\n }\n if (error === \"expired_token\") {\n return { status: \"failed\", message: \"Kimi Code device authorization expired. Please restart login.\" };\n }\n if (error === \"access_denied\") {\n return { status: \"failed\", message: \"Kimi Code login was denied.\" };\n }\n return {\n status: \"failed\",\n message: `Kimi Code device token request failed (status ${response.status})${typeof error === \"string\" ? `: ${error}${description}` : \"\"}`,\n };\n },\n });\n}\nfunction sleep(ms, signal) {\n return new Promise((resolve, reject) => {\n signal.throwIfAborted();\n const onAbort = () => {\n clearTimeout(timeout);\n reject(signal.reason);\n };\n const timeout = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\nfunction isRetryableRefreshFailure(response) {\n return response.status === 429 || response.status >= 500;\n}\nasync function refreshToken(oauthHost, refreshTokenValue, signal) {\n let lastError;\n for (let attempt = 0; attempt <= REFRESH_MAX_RETRIES; attempt++) {\n if (attempt > 0) {\n await sleep(1000 * 2 ** (attempt - 1), signal);\n }\n if (signal.aborted) {\n throw new Error(\"Kimi Code token refresh aborted\");\n }\n let response;\n try {\n response = await fetch(`${oauthHost}/api/oauth/token`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: formUrlEncode({\n client_id: CLIENT_ID,\n grant_type: \"refresh_token\",\n refresh_token: refreshTokenValue,\n }),\n signal: requestSignal(signal),\n });\n }\n catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n continue;\n }\n const json = await readJson(response);\n if (response.ok) {\n return parseTokenResponse(json, \"refresh\");\n }\n // Unauthorized: the stored credential is dead; Models clears it and prompts re-login.\n if (response.status === 401 || response.status === 403 || json?.error === \"invalid_grant\") {\n const description = typeof json?.error_description === \"string\" ? `: ${json.error_description}` : \"\";\n throw new Error(`Kimi Code token refresh unauthorized (status ${response.status})${description}`);\n }\n if (isRetryableRefreshFailure(response) && attempt < REFRESH_MAX_RETRIES) {\n lastError = new Error(`Kimi Code token refresh failed with status ${response.status}`);\n continue;\n }\n const text = JSON.stringify(json);\n throw new Error(`Kimi Code token refresh failed with status ${response.status}${text ? `: ${text}` : \"\"}`);\n }\n throw lastError ?? new Error(\"Kimi Code token refresh failed\");\n}\nasync function loginKimiCoding(interaction) {\n const oauthHost = getOauthHost();\n const device = await startDeviceAuthorization(oauthHost, interaction.signal);\n interaction.notify({\n type: \"device_code\",\n userCode: device.userCode,\n verificationUri: device.verificationUriComplete,\n intervalSeconds: device.intervalSeconds,\n expiresInSeconds: device.expiresInSeconds,\n });\n const token = await pollForToken(oauthHost, device, interaction.signal);\n return { type: \"oauth\", access: token.access, refresh: token.refresh, expires: token.expires };\n}\nexport const kimiCodingOAuth = {\n name: \"Kimi Code (subscription)\",\n isSubscription: true,\n loginLabel: \"Sign in with Kimi Code\",\n login: loginKimiCoding,\n refresh: async (credential, signal) => {\n const token = await refreshToken(getOauthHost(), credential.refresh, signal);\n return { type: \"oauth\", access: token.access, refresh: token.refresh, expires: token.expires };\n },\n async toAuth(credential) {\n return { headers: { Authorization: `Bearer ${credential.access}` } };\n },\n};\n//# sourceMappingURL=kimi-coding.js.map","// Headless @earendil-works/pi-ai compatibility surface.\n//\n// Provider SDKs, OAuth flows, and streaming transports stay native to DSH;\n// this module carries the schema helpers, error classifiers, and thinking-\n// level math that Pi extensions import for their own logic. Overflow/retry\n// classifiers are vendored byte-identical (see ./vendor/PI-LICENSE) so\n// pattern tables stay in sync with Pi.\n\nexport type { Static, TSchema } from 'typebox'\nexport { Type } from 'typebox'\nexport { isContextOverflow, isRecoverableLength } from './vendor/pi-ai-overflow.js'\nexport { isRetryableAssistantError } from './vendor/pi-ai-retry.js'\nexport { uuidv7 } from './vendor/pi-uuid.js'\nexport type {\n AgentMessage,\n AssistantMessage,\n ImageContent,\n Message,\n TextContent,\n ThinkingContent,\n ToolCallContent,\n ToolResultMessage,\n Usage,\n UserMessage,\n} from './vendor/pi-types.js'\n\nexport type ThinkingLevel = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'\nexport type ModelThinkingLevel = 'off' | ThinkingLevel\nexport type ThinkingLevelMap = Partial<Record<ModelThinkingLevel, string | null>>\nexport type Api = string\n\nexport interface Model<TApi extends Api = Api> {\n id: string\n name?: string\n api?: TApi\n provider?: string\n baseUrl?: string\n reasoning?: boolean\n thinkingLevelMap?: ThinkingLevelMap\n input?: readonly ('text' | 'image')[]\n contextWindow?: number\n maxTokens?: number\n [key: string]: unknown\n}\n\nconst EXTENDED_THINKING_LEVELS: ModelThinkingLevel[] = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']\n\nexport function getSupportedThinkingLevels<TApi extends Api>(model: Model<TApi>): ModelThinkingLevel[] {\n return EXTENDED_THINKING_LEVELS.filter(level => {\n const mapped = model.thinkingLevelMap?.[level]\n if (mapped === null) return false\n if (level === 'xhigh' || level === 'max') return mapped !== undefined\n return true\n })\n}\n\nexport function clampThinkingLevel<TApi extends Api>(\n model: Model<TApi>,\n level: ModelThinkingLevel,\n): ModelThinkingLevel {\n const availableLevels = getSupportedThinkingLevels(model)\n if (availableLevels.includes(level)) return level\n const requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level)\n if (requestedIndex === -1) return availableLevels[0] ?? 'off'\n for (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i += 1) {\n const candidate = EXTENDED_THINKING_LEVELS[i]!\n if (availableLevels.includes(candidate)) return candidate\n }\n for (let i = requestedIndex - 1; i >= 0; i -= 1) {\n const candidate = EXTENDED_THINKING_LEVELS[i]!\n if (availableLevels.includes(candidate)) return candidate\n }\n return availableLevels[0] ?? 'off'\n}\n\nexport function modelsAreEqual<TApi extends Api>(\n a: Model<TApi> | null | undefined,\n b: Model<TApi> | null | undefined,\n): boolean {\n if (a === null || a === undefined || b === null || b === undefined) return false\n return a.id === b.id && a.provider === b.provider\n}\n\ninterface TextishContent {\n type: string\n text?: string\n [key: string]: unknown\n}\n\nexport function contentText(content: string | readonly TextishContent[], separator = '\\n'): string {\n if (typeof content === 'string') return content\n return content\n .filter(block => block.type === 'text')\n .map(block => String(block.text ?? ''))\n .join(separator)\n}\n\n// Legacy pi-ai/compat global-registry API. The registry is bridge-local:\n// providers registered here are visible to the same package but never route\n// real model calls (DSH llm adapters own those).\nconst compatProviders = new Map<string, unknown>()\n\nexport function registerProvider(name: string, provider: unknown): void {\n compatProviders.set(name, provider)\n}\n\n// Pi's compat getProviders() returns provider NAMES (callers iterate and\n// Set() them).\nexport function getProviders(): string[] {\n return [...compatProviders.keys()]\n}\n\nexport function getProvider(name: string): unknown {\n return compatProviders.get(name)\n}\n\nexport function getModel(_provider: string, _id: string): undefined {\n return undefined\n}\n\nexport function getModels(_provider?: string): unknown[] {\n return []\n}\n\n// Provider declaration factory, vendored from Pi (provider packages like\n// pi-provider-litellm build their provider object with it at load time and\n// hand it to pi.registerProvider). Model TRANSPORT stays native to DSH llm:\n// the lazy API factories below return Pi's exact lazy-stream surface, and if\n// a stream is ever actually requested the setup fails through Pi's own error\n// channel (an error event on the stream) instead of pretending to call a model.\nexport { createProvider, ModelsError } from './vendor/pi-ai-provider.js'\nexport { lazyApi, lazyStream } from './vendor/pi-ai-lazy.js'\nexport { AssistantMessageEventStream } from './vendor/pi-ai-event-stream.js'\n\nimport { lazyApi as lazyApiForCompat } from './vendor/pi-ai-lazy.js'\n\nfunction unbridgedTransport(api: string): never {\n throw new Error(`pi2dsh: the ${api} protocol client is not bridged; model transports stay native to DSH llm/credentials`)\n}\n\nexport function openAICompletionsApi(): unknown {\n return lazyApiForCompat(async () => unbridgedTransport('openai-completions'), undefined)\n}\n\nexport function openAIResponsesApi(): unknown {\n return lazyApiForCompat(async () => unbridgedTransport('openai-responses'), { fetchDeferred: true, cancelDeferred: true })\n}\n\nexport function anthropicMessagesApi(): unknown {\n return lazyApiForCompat(async () => unbridgedTransport('anthropic-messages'), undefined)\n}\n\n// Pi's official OAuth flows, vendored byte-identical: OpenAI Codex\n// (PKCE + localhost:1455 callback server, device-code fallback), Anthropic,\n// GitHub Copilot, Kimi Coding. Each exposes pi-ai's native oauth surface\n// (login(interaction)/refresh/toAuth) and runs its real protocol against the\n// real endpoints — account packages like @narumitw/pi-accounts load them\n// through builtinProviders()/the lazy loaders below.\nexport { openaiCodexOAuth } from './vendor/pi-oauth-flows/openai-codex.js'\nexport { anthropicOAuth } from './vendor/pi-oauth-flows/anthropic.js'\nexport { githubCopilotOAuth } from './vendor/pi-oauth-flows/github-copilot.js'\nexport { kimiCodingOAuth } from './vendor/pi-oauth-flows/kimi-coding.js'\nexport { generatePKCE } from './vendor/pi-oauth-flows/pkce.js'\nexport { pollOAuthDeviceCodeFlow } from './vendor/pi-oauth-flows/device-code.js'\n\nimport { openaiCodexOAuth as codexFlow } from './vendor/pi-oauth-flows/openai-codex.js'\nimport { anthropicOAuth as anthropicFlow } from './vendor/pi-oauth-flows/anthropic.js'\nimport { githubCopilotOAuth as copilotFlow } from './vendor/pi-oauth-flows/github-copilot.js'\nimport { kimiCodingOAuth as kimiFlow } from './vendor/pi-oauth-flows/kimi-coding.js'\n\n// The provider catalog surface account packages consume: id + the real OAuth\n// flow. Model catalogs stay empty — model routing is DSH-native in this host.\nexport function builtinProviders(): Array<{ id: string, name: string, api: string, baseUrl: string, models: never[], auth: { oauth: unknown } }> {\n const entry = (id: string, name: string, baseUrl: string, oauth: unknown) => ({\n id, name, api: 'openai-completions', baseUrl, models: [] as never[], auth: { oauth },\n })\n return [\n entry('openai-codex', 'OpenAI (ChatGPT Plus/Pro)', 'https://chatgpt.com/backend-api/codex', codexFlow),\n entry('anthropic', 'Anthropic', 'https://api.anthropic.com', anthropicFlow),\n entry('github-copilot', 'GitHub Copilot', 'https://api.githubcopilot.com', copilotFlow),\n entry('kimi-coding', 'Kimi Code', 'https://api.moonshot.ai/anthropic', kimiFlow),\n ]\n}\n\nexport const loadOpenAICodexOAuth = async (): Promise<unknown> => codexFlow\nexport const loadAnthropicOAuth = async (): Promise<unknown> => anthropicFlow\nexport const loadGitHubCopilotOAuth = async (): Promise<unknown> => copilotFlow\nexport const loadKimiCodingOAuth = async (): Promise<unknown> => kimiFlow\n\nexport function complete(..._args: unknown[]): never {\n throw new Error('pi2dsh: pi-ai complete() routes model calls through Pi provider SDKs; use DSH llm adapters instead')\n}\n\nexport function stream(..._args: unknown[]): never {\n throw new Error('pi2dsh: pi-ai stream() routes model calls through Pi provider SDKs; use DSH llm adapters instead')\n}\n\nexport interface StringEnumOptions<T extends readonly string[]> {\n description?: string\n default?: T[number]\n}\n\nexport function StringEnum<T extends readonly string[]>(\n values: T,\n options: StringEnumOptions<T> = {},\n): { type: 'string'; enum: T; description?: string; default?: T[number] } {\n return {\n type: 'string',\n enum: values,\n ...(options.description !== undefined ? { description: options.description } : {}),\n ...(options.default !== undefined ? { default: options.default } : {}),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,oBAAoB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;;;;;AAWA,MAAM,wBAAwB;CAC7B;CACA;CACA;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,kBAAkB,SAA2B,eAAiC;CAE7F,IAAI,QAAQ,eAAe,WAAW,QAAQ,cAGzC;MAAA,CADkB,sBAAsB,MAAM,MAAM,EAAE,KAAK,QAAQ,YAAa,CACnE,KAAK,kBAAkB,MAAM,MAAM,EAAE,KAAK,QAAQ,YAAa,CAAC,GAChF,OAAO;CAAA;CAKT,IAAI,iBAAiB,QAAQ,eAAe,QACvB;MAAA,QAAQ,MAAM,QAAQ,QAAQ,MAAM,YACtC,eACjB,OAAO;CAAA;CAOT,I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