@nervekit/desktop 0.40.0 → 0.40.1

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 (37) hide show
  1. package/THIRD-PARTY-LICENSES.txt +5087 -463
  2. package/dist/{chunk-D5WJKB4R.js → chunk-24GQ74HM.js} +1 -0
  3. package/dist/{chunk-ET5RYBGZ.js → chunk-3DGBM7UW.js} +1 -1
  4. package/dist/{chunk-5UT23MT6.js → chunk-4MMJDHFX.js} +3 -3
  5. package/dist/{chunk-RWLLVZ7I.js → chunk-55OGZFNA.js} +1 -1
  6. package/dist/{chunk-BPOIFVQO.js → chunk-AJGPULMX.js} +2543 -124
  7. package/dist/{chunk-PUM6UCBT.js → chunk-CKVFGRVV.js} +4 -4
  8. package/dist/{chunk-GCSWN326.js → chunk-CWHAK2HX.js} +3 -3
  9. package/dist/{chunk-V7EAFXAX.js → chunk-D7WIIZAV.js} +4 -4
  10. package/dist/chunk-EJM4HMEL.js +45 -0
  11. package/dist/{chunk-4ZNLXHTH.js → chunk-FOFVPPPV.js} +4 -4
  12. package/dist/{chunk-UN3GLM4U.js → chunk-H5UKINTD.js} +2 -2
  13. package/dist/{chunk-LPCHTKEK.js → chunk-I6NVW4NX.js} +8 -133
  14. package/dist/chunk-JCF3ZRP4.js +481 -0
  15. package/dist/chunk-KAZFF2RD.js +22804 -0
  16. package/dist/{chunk-LZRPWVVJ.js → chunk-KIGB3FK6.js} +3 -3
  17. package/dist/{chunk-JDI4D5EM.js → chunk-KQPEOUCA.js} +4 -4
  18. package/dist/chunk-M7WTH5K5.js +822 -0
  19. package/dist/chunk-MH3SUHI2.js +135 -0
  20. package/dist/{chunk-5R3UAHXF.js → chunk-N5B2RRSS.js} +2 -1
  21. package/dist/{chunk-P2GSKP6N.js → chunk-ONWQH2W6.js} +4 -4
  22. package/dist/{chunk-Q7LPOIKN.js → chunk-OQC3F6JA.js} +3 -471
  23. package/dist/{chunk-H4CDZRIE.js → chunk-OY6PIAR7.js} +2 -2
  24. package/dist/{chunk-HHUSIAK3.js → chunk-QFXKQNMT.js} +4 -4
  25. package/dist/{chunk-U4DBQKHO.js → chunk-QWTKCUIZ.js} +1 -1
  26. package/dist/{chunk-RU6S57LK.js → chunk-TJR6ASRW.js} +4 -4
  27. package/dist/{chunk-YA2WJRUO.js → chunk-TW6FURZ7.js} +2 -2
  28. package/dist/{chunk-7FI3LC3O.js → chunk-V53CETNZ.js} +3 -3
  29. package/dist/{chunk-NSA42OOT.js → chunk-WXRYBXYR.js} +1 -1
  30. package/dist/{chunk-WTHP3VH6.js → chunk-XBHEYY65.js} +1 -1
  31. package/dist/chunk-YYLKI74V.js +8778 -0
  32. package/dist/daemon.js +5 -5
  33. package/dist/main.js +4 -4
  34. package/dist/worker.js +4 -4
  35. package/package.json +7 -7
  36. /package/dist/{chunk-PUM6UCBT.js.LEGAL.txt → chunk-CKVFGRVV.js.LEGAL.txt} +0 -0
  37. /package/dist/{chunk-YA2WJRUO.js.LEGAL.txt → chunk-TW6FURZ7.js.LEGAL.txt} +0 -0
@@ -20,6 +20,9 @@ import {
20
20
  spawnManagedChildProcess,
21
21
  terminateManagedChildProcess
22
22
  } from "./chunk-HKLAYK2Z.js";
23
+ import {
24
+ getProviderEnvValue
25
+ } from "./chunk-FESN7DND.js";
23
26
  import {
24
27
  clampThinkingLevel,
25
28
  createModels,
@@ -30,7 +33,7 @@ import {
30
33
  lazyApi,
31
34
  lazyStream,
32
35
  normalizeContext
33
- } from "./chunk-NSA42OOT.js";
36
+ } from "./chunk-WXRYBXYR.js";
34
37
  import {
35
38
  createAssistantMessageEventStream
36
39
  } from "./chunk-MN7PZ2PH.js";
@@ -30817,6 +30820,9 @@ var importNodeOnlyApi = (specifier) => {
30817
30820
  return import(__rewriteRelativeImportExtension(runtimeSpecifier));
30818
30821
  };
30819
30822
  var bedrockModuleOverride;
30823
+ function setBedrockProviderModule(module) {
30824
+ bedrockModuleOverride = module;
30825
+ }
30820
30826
  var bedrockConverseStreamApi = () => lazyApi(async () => bedrockModuleOverride ?? await importNodeOnlyApi("./bedrock-converse-stream.ts"));
30821
30827
 
30822
30828
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.js
@@ -30906,7 +30912,7 @@ function amazonBedrockProvider() {
30906
30912
  }
30907
30913
 
30908
30914
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
30909
- var openAICompletionsApi = () => lazyApi(() => import("./chunk-5UT23MT6.js"));
30915
+ var openAICompletionsApi = () => lazyApi(() => import("./chunk-4MMJDHFX.js"));
30910
30916
 
30911
30917
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/helpers.js
30912
30918
  function envApiKeyAuth(name2, envVars) {
@@ -30962,7 +30968,7 @@ function antLingProvider() {
30962
30968
  }
30963
30969
 
30964
30970
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
30965
- var anthropicMessagesApi = () => lazyApi(() => import("./chunk-7FI3LC3O.js"));
30971
+ var anthropicMessagesApi = () => lazyApi(() => import("./chunk-V53CETNZ.js"));
30966
30972
 
30967
30973
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/load.js
30968
30974
  var __rewriteRelativeImportExtension2 = function(path2, preserveJsx) {
@@ -30978,6 +30984,9 @@ var importOAuthModule = (specifier) => {
30978
30984
  return import(__rewriteRelativeImportExtension2(runtimeSpecifier));
30979
30985
  };
30980
30986
  var bundledLoaders;
30987
+ function registerBundledOAuthFlowLoaders(loaders) {
30988
+ bundledLoaders = loaders;
30989
+ }
30981
30990
  var loadAnthropicOAuth = async () => {
30982
30991
  if (bundledLoaders)
30983
30992
  return bundledLoaders.anthropic();
@@ -31094,7 +31103,7 @@ function anthropicProvider() {
31094
31103
  }
31095
31104
 
31096
31105
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.lazy.js
31097
- var azureOpenAIResponsesApi = () => lazyApi(() => import("./chunk-JDI4D5EM.js"));
31106
+ var azureOpenAIResponsesApi = () => lazyApi(() => import("./chunk-KQPEOUCA.js"));
31098
31107
 
31099
31108
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/azure.js
31100
31109
  function resolveAzureModel(model2, options) {
@@ -31156,7 +31165,7 @@ function cerebrasProvider() {
31156
31165
  }
31157
31166
 
31158
31167
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.lazy.js
31159
- var openAIResponsesApi = () => lazyApi(() => import("./chunk-RU6S57LK.js"));
31168
+ var openAIResponsesApi = () => lazyApi(() => import("./chunk-TJR6ASRW.js"));
31160
31169
 
31161
31170
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-auth.js
31162
31171
  var CLOUDFLARE_API_KEY = "CLOUDFLARE_API_KEY";
@@ -31276,7 +31285,7 @@ function cloudflareAIGatewayProvider() {
31276
31285
 
31277
31286
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-workers-ai-system-one.lazy.js
31278
31287
  var cloudflareWorkersAISystemOneApi = () => ({
31279
- classify: async (model2, context, options) => (await import("./chunk-V7EAFXAX.js")).classify(model2, context, options)
31288
+ classify: async (model2, context, options) => (await import("./chunk-D7WIIZAV.js")).classify(model2, context, options)
31280
31289
  });
31281
31290
 
31282
31291
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-workers-ai.js
@@ -31353,7 +31362,7 @@ function githubCopilotProvider() {
31353
31362
  }
31354
31363
 
31355
31364
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.lazy.js
31356
- var googleGenerativeAIApi = () => lazyApi(() => import("./chunk-HHUSIAK3.js"));
31365
+ var googleGenerativeAIApi = () => lazyApi(() => import("./chunk-QFXKQNMT.js"));
31357
31366
 
31358
31367
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/google.js
31359
31368
  function googleProvider() {
@@ -31368,7 +31377,7 @@ function googleProvider() {
31368
31377
  }
31369
31378
 
31370
31379
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.lazy.js
31371
- var googleVertexApi = () => lazyApi(() => import("./chunk-P2GSKP6N.js"));
31380
+ var googleVertexApi = () => lazyApi(() => import("./chunk-ONWQH2W6.js"));
31372
31381
 
31373
31382
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/google-vertex.js
31374
31383
  var VERTEX_ADC_PATH = "~/.config/gcloud/application_default_credentials.json";
@@ -31542,7 +31551,7 @@ function minimaxCnProvider() {
31542
31551
  }
31543
31552
 
31544
31553
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.lazy.js
31545
- var mistralConversationsApi = () => lazyApi(() => import("./chunk-GCSWN326.js"));
31554
+ var mistralConversationsApi = () => lazyApi(() => import("./chunk-CWHAK2HX.js"));
31546
31555
 
31547
31556
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/mistral.js
31548
31557
  function mistralProvider() {
@@ -31594,7 +31603,7 @@ function nvidiaProvider() {
31594
31603
 
31595
31604
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/openai-decisions.lazy.js
31596
31605
  var openAIDecisionsApi = () => ({
31597
- classify: async (model2, context, options) => (await import("./chunk-LZRPWVVJ.js")).classify(model2, context, options)
31606
+ classify: async (model2, context, options) => (await import("./chunk-KIGB3FK6.js")).classify(model2, context, options)
31598
31607
  });
31599
31608
 
31600
31609
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/openai.js
@@ -31626,7 +31635,7 @@ function openaiProvider() {
31626
31635
  }
31627
31636
 
31628
31637
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.lazy.js
31629
- var openAICodexResponsesApi = () => lazyApi(() => import("./chunk-LPCHTKEK.js"));
31638
+ var openAICodexResponsesApi = () => lazyApi(() => import("./chunk-I6NVW4NX.js"));
31630
31639
 
31631
31640
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/openai-codex.js
31632
31641
  function openaiCodexProvider() {
@@ -31648,7 +31657,7 @@ function openaiCodexProvider() {
31648
31657
 
31649
31658
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/typesafe-system-one.lazy.js
31650
31659
  var typesafeSystemOneApi = () => ({
31651
- classify: async (model2, context, options) => (await import("./chunk-4ZNLXHTH.js")).classify(model2, context, options)
31660
+ classify: async (model2, context, options) => (await import("./chunk-FOFVPPPV.js")).classify(model2, context, options)
31652
31661
  });
31653
31662
 
31654
31663
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/opencode-headers.js
@@ -31709,7 +31718,7 @@ function opencodeGoProvider() {
31709
31718
 
31710
31719
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/openrouter-images.lazy.js
31711
31720
  var openrouterImagesApi = () => ({
31712
- generateImages: async (model2, context, options) => (await import("./chunk-U4DBQKHO.js")).generateImages(model2, context, options)
31721
+ generateImages: async (model2, context, options) => (await import("./chunk-QWTKCUIZ.js")).generateImages(model2, context, options)
31713
31722
  });
31714
31723
 
31715
31724
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/openrouter.js
@@ -31779,7 +31788,7 @@ function qwenTokenPlanIndividualProvider() {
31779
31788
  }
31780
31789
 
31781
31790
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/api/pi-messages.lazy.js
31782
- var piMessagesApi = () => lazyApi(() => import("./chunk-RWLLVZ7I.js"));
31791
+ var piMessagesApi = () => lazyApi(() => import("./chunk-55OGZFNA.js"));
31783
31792
 
31784
31793
  // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/providers/radius-config.js
31785
31794
  var DEFAULT_RADIUS_GATEWAY = "https://radius.pi.dev";
@@ -32558,6 +32567,2416 @@ function fauxProvider(options = {}) {
32558
32567
  };
32559
32568
  }
32560
32569
 
32570
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/callback-server.js
32571
+ import { createServer } from "node:http";
32572
+
32573
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/utils/oauth-page.js
32574
+ var LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>`;
32575
+ function escapeHtml(value) {
32576
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
32577
+ }
32578
+ function renderPage(options) {
32579
+ const title = escapeHtml(options.title);
32580
+ const heading = escapeHtml(options.heading);
32581
+ const message = escapeHtml(options.message);
32582
+ const details = options.details ? escapeHtml(options.details) : void 0;
32583
+ return `<!doctype html>
32584
+ <html lang="en">
32585
+ <head>
32586
+ <meta charset="utf-8" />
32587
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
32588
+ <title>${title}</title>
32589
+ <style>
32590
+ :root {
32591
+ --text: #fafafa;
32592
+ --text-dim: #a1a1aa;
32593
+ --page-bg: #09090b;
32594
+ --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";
32595
+ --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
32596
+ }
32597
+ * { box-sizing: border-box; }
32598
+ html { color-scheme: dark; }
32599
+ body {
32600
+ margin: 0;
32601
+ min-height: 100vh;
32602
+ display: flex;
32603
+ align-items: center;
32604
+ justify-content: center;
32605
+ padding: 24px;
32606
+ background: var(--page-bg);
32607
+ color: var(--text);
32608
+ font-family: var(--font-sans);
32609
+ text-align: center;
32610
+ }
32611
+ main {
32612
+ width: 100%;
32613
+ max-width: 560px;
32614
+ display: flex;
32615
+ flex-direction: column;
32616
+ align-items: center;
32617
+ justify-content: center;
32618
+ }
32619
+ .logo {
32620
+ width: 72px;
32621
+ height: 72px;
32622
+ display: block;
32623
+ margin-bottom: 24px;
32624
+ }
32625
+ h1 {
32626
+ margin: 0 0 10px;
32627
+ font-size: 28px;
32628
+ line-height: 1.15;
32629
+ font-weight: 650;
32630
+ color: var(--text);
32631
+ }
32632
+ p {
32633
+ margin: 0;
32634
+ line-height: 1.7;
32635
+ color: var(--text-dim);
32636
+ font-size: 15px;
32637
+ }
32638
+ .details {
32639
+ margin-top: 16px;
32640
+ font-family: var(--font-mono);
32641
+ font-size: 13px;
32642
+ color: var(--text-dim);
32643
+ white-space: pre-wrap;
32644
+ word-break: break-word;
32645
+ }
32646
+ </style>
32647
+ </head>
32648
+ <body>
32649
+ <main>
32650
+ <div class="logo">${LOGO_SVG}</div>
32651
+ <h1>${heading}</h1>
32652
+ <p>${message}</p>
32653
+ ${details ? `<div class="details">${details}</div>` : ""}
32654
+ </main>
32655
+ </body>
32656
+ </html>`;
32657
+ }
32658
+ function oauthSuccessHtml(message) {
32659
+ return renderPage({
32660
+ title: "Authentication successful",
32661
+ heading: "Authentication successful",
32662
+ message
32663
+ });
32664
+ }
32665
+ function oauthErrorHtml(message, details) {
32666
+ return renderPage({
32667
+ title: "Authentication failed",
32668
+ heading: "Authentication failed",
32669
+ message,
32670
+ details
32671
+ });
32672
+ }
32673
+
32674
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/callback-server.js
32675
+ function sendPage(response, status, html) {
32676
+ response.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
32677
+ response.end(html);
32678
+ }
32679
+ async function startOAuthCallbackServer(options) {
32680
+ const { providerName, signal } = options;
32681
+ if (signal?.aborted)
32682
+ throw new Error("Login cancelled");
32683
+ let resolveWait = () => {
32684
+ };
32685
+ let rejectWait = () => {
32686
+ };
32687
+ const waitPromise = new Promise((resolve7, reject) => {
32688
+ resolveWait = resolve7;
32689
+ rejectWait = reject;
32690
+ });
32691
+ waitPromise.catch(() => void 0);
32692
+ let claimed = false;
32693
+ let settled = false;
32694
+ let timer;
32695
+ const onAbort = () => finish({ error: new Error("Login cancelled") });
32696
+ const finish = (result) => {
32697
+ if (settled)
32698
+ return;
32699
+ settled = true;
32700
+ if (timer)
32701
+ clearTimeout(timer);
32702
+ signal?.removeEventListener("abort", onAbort);
32703
+ if ("error" in result)
32704
+ rejectWait(result.error);
32705
+ else
32706
+ resolveWait(result.value);
32707
+ };
32708
+ const server = createServer((request, response) => {
32709
+ void (async () => {
32710
+ const url2 = new URL(request.url ?? "/", "http://localhost");
32711
+ if (request.method !== "GET" || url2.pathname !== options.path) {
32712
+ sendPage(response, 404, oauthErrorHtml("Callback route not found."));
32713
+ return;
32714
+ }
32715
+ if (options.state !== void 0 && url2.searchParams.get("state") !== options.state) {
32716
+ sendPage(response, 400, oauthErrorHtml("State mismatch."));
32717
+ return;
32718
+ }
32719
+ if (claimed || settled) {
32720
+ sendPage(response, 409, oauthErrorHtml("This sign-in has already been handled."));
32721
+ return;
32722
+ }
32723
+ const error63 = url2.searchParams.get("error");
32724
+ if (error63) {
32725
+ const description = url2.searchParams.get("error_description") ?? error63;
32726
+ sendPage(response, 400, oauthErrorHtml(`${providerName} authorization failed.`, description));
32727
+ finish({ error: new Error(`${providerName} authorization failed: ${description}`) });
32728
+ return;
32729
+ }
32730
+ const code = url2.searchParams.get("code");
32731
+ if (!code) {
32732
+ sendPage(response, 400, oauthErrorHtml("Missing authorization code."));
32733
+ return;
32734
+ }
32735
+ claimed = true;
32736
+ try {
32737
+ const value = await options.complete(code);
32738
+ sendPage(response, 200, oauthSuccessHtml(`Signed in to ${providerName}. You may now close this page.`));
32739
+ finish({ value });
32740
+ } catch (error64) {
32741
+ const failure2 = error64 instanceof Error ? error64 : new Error(String(error64));
32742
+ sendPage(response, 502, oauthErrorHtml(`${providerName} sign-in failed.`, failure2.message));
32743
+ finish({ error: failure2 });
32744
+ }
32745
+ })();
32746
+ });
32747
+ await new Promise((resolve7, reject) => {
32748
+ server.once("error", reject);
32749
+ server.listen(options.port, options.host, () => {
32750
+ server.off("error", reject);
32751
+ resolve7();
32752
+ });
32753
+ });
32754
+ const address = server.address();
32755
+ if (!address || typeof address === "string") {
32756
+ server.close();
32757
+ throw new Error("OAuth callback server did not bind to TCP");
32758
+ }
32759
+ server.on("error", (error63) => finish({ error: error63 }));
32760
+ signal?.addEventListener("abort", onAbort, { once: true });
32761
+ if (options.timeoutMs !== void 0) {
32762
+ timer = setTimeout(() => finish({ error: new Error(`${providerName} sign-in timed out`) }), options.timeoutMs);
32763
+ }
32764
+ const redirectHost = options.redirectHost ?? options.host;
32765
+ return {
32766
+ redirectUri: `http://${redirectHost.includes(":") ? `[${redirectHost}]` : redirectHost}:${address.port}${options.path}`,
32767
+ wait: () => waitPromise,
32768
+ cancel: () => {
32769
+ if (!claimed)
32770
+ finish({ value: void 0 });
32771
+ },
32772
+ close: () => {
32773
+ finish({ error: new Error("OAuth callback server closed") });
32774
+ server.close();
32775
+ }
32776
+ };
32777
+ }
32778
+ async function waitForCallbackOrManualInput(interaction, callback, prompt) {
32779
+ const manualAbort = new AbortController();
32780
+ let manualError;
32781
+ const manual = interaction.prompt({ type: "manual_code", ...prompt, signal: manualAbort.signal }).then((input2) => {
32782
+ callback?.cancel();
32783
+ return input2;
32784
+ }).catch((error63) => {
32785
+ manualError = error63 instanceof Error ? error63 : new Error(String(error63));
32786
+ callback?.cancel();
32787
+ return void 0;
32788
+ });
32789
+ try {
32790
+ const value = await callback?.wait();
32791
+ if (manualError)
32792
+ throw manualError;
32793
+ if (value !== void 0)
32794
+ return { type: "callback", value };
32795
+ const input2 = await manual;
32796
+ if (manualError)
32797
+ throw manualError;
32798
+ return { type: "manual", input: input2 ?? "" };
32799
+ } finally {
32800
+ manualAbort.abort();
32801
+ }
32802
+ }
32803
+
32804
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/pkce.js
32805
+ function base64urlEncode(bytes) {
32806
+ let binary = "";
32807
+ for (const byte of bytes) {
32808
+ binary += String.fromCharCode(byte);
32809
+ }
32810
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
32811
+ }
32812
+ async function generatePKCE() {
32813
+ const verifierBytes = new Uint8Array(32);
32814
+ crypto.getRandomValues(verifierBytes);
32815
+ const verifier = base64urlEncode(verifierBytes);
32816
+ const encoder2 = new TextEncoder();
32817
+ const data = encoder2.encode(verifier);
32818
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
32819
+ const challenge = base64urlEncode(new Uint8Array(hashBuffer));
32820
+ return { verifier, challenge };
32821
+ }
32822
+
32823
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.js
32824
+ var decode3 = (s) => atob(s);
32825
+ var CLIENT_ID = decode3("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
32826
+ var AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
32827
+ var TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
32828
+ var CALLBACK_HOST = getProviderEnvValue("PI_OAUTH_CALLBACK_HOST") || "127.0.0.1";
32829
+ var CALLBACK_PORT = 53692;
32830
+ var CALLBACK_PATH = "/callback";
32831
+ var REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
32832
+ var COPY_CODE_REDIRECT_URI = "https://platform.claude.com/oauth/code/callback";
32833
+ var ANTHROPIC_BROWSER_LOGIN_METHOD = "browser";
32834
+ var ANTHROPIC_COPY_CODE_LOGIN_METHOD = "copy_code";
32835
+ var SCOPES = "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";
32836
+ function parseAuthorizationInput(input2) {
32837
+ const value = input2.trim();
32838
+ if (!value)
32839
+ return {};
32840
+ try {
32841
+ const url2 = new URL(value);
32842
+ return {
32843
+ code: url2.searchParams.get("code") ?? void 0,
32844
+ state: url2.searchParams.get("state") ?? void 0
32845
+ };
32846
+ } catch {
32847
+ }
32848
+ if (value.includes("#")) {
32849
+ const [code, state] = value.split("#", 2);
32850
+ return { code, state };
32851
+ }
32852
+ if (value.includes("code=")) {
32853
+ const params = new URLSearchParams(value);
32854
+ return {
32855
+ code: params.get("code") ?? void 0,
32856
+ state: params.get("state") ?? void 0
32857
+ };
32858
+ }
32859
+ return { code: value };
32860
+ }
32861
+ function formatErrorDetails(error63) {
32862
+ if (error63 instanceof Error) {
32863
+ const details = [`${error63.name}: ${error63.message}`];
32864
+ const errorWithCode = error63;
32865
+ if (errorWithCode.code)
32866
+ details.push(`code=${errorWithCode.code}`);
32867
+ if (typeof errorWithCode.errno !== "undefined")
32868
+ details.push(`errno=${String(errorWithCode.errno)}`);
32869
+ if (typeof error63.cause !== "undefined") {
32870
+ details.push(`cause=${formatErrorDetails(error63.cause)}`);
32871
+ }
32872
+ if (error63.stack) {
32873
+ details.push(`stack=${error63.stack}`);
32874
+ }
32875
+ return details.join("; ");
32876
+ }
32877
+ return String(error63);
32878
+ }
32879
+ async function postJson(url2, body, signal) {
32880
+ const response = await fetch(url2, {
32881
+ method: "POST",
32882
+ headers: {
32883
+ "Content-Type": "application/json",
32884
+ Accept: "application/json"
32885
+ },
32886
+ body: JSON.stringify(body),
32887
+ signal: AbortSignal.any([signal, AbortSignal.timeout(3e4)])
32888
+ });
32889
+ const responseBody = await response.text();
32890
+ if (!response.ok) {
32891
+ throw new Error(`HTTP request failed. status=${response.status}; url=${url2}; body=${responseBody}`);
32892
+ }
32893
+ return responseBody;
32894
+ }
32895
+ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, signal) {
32896
+ let responseBody;
32897
+ try {
32898
+ responseBody = await postJson(TOKEN_URL, {
32899
+ grant_type: "authorization_code",
32900
+ client_id: CLIENT_ID,
32901
+ code,
32902
+ state,
32903
+ redirect_uri: redirectUri,
32904
+ code_verifier: verifier
32905
+ }, signal);
32906
+ } catch (error63) {
32907
+ throw new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error63)}`);
32908
+ }
32909
+ let tokenData;
32910
+ try {
32911
+ tokenData = JSON.parse(responseBody);
32912
+ } catch (error63) {
32913
+ throw new Error(`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error63)}`);
32914
+ }
32915
+ return {
32916
+ type: "oauth",
32917
+ refresh: tokenData.refresh_token,
32918
+ access: tokenData.access_token,
32919
+ expires: Date.now() + tokenData.expires_in * 1e3 - 5 * 60 * 1e3
32920
+ };
32921
+ }
32922
+ async function loginAnthropic(interaction) {
32923
+ const { verifier, challenge } = await generatePKCE();
32924
+ const startCallbackServer2 = (port) => startOAuthCallbackServer({
32925
+ providerName: "Anthropic",
32926
+ host: CALLBACK_HOST,
32927
+ port,
32928
+ path: CALLBACK_PATH,
32929
+ redirectHost: "localhost",
32930
+ state: verifier,
32931
+ complete: async (code) => code,
32932
+ signal: interaction.signal
32933
+ });
32934
+ const callback = await startCallbackServer2(CALLBACK_PORT).catch(() => startCallbackServer2(0)).catch(() => void 0);
32935
+ const redirectUri = callback?.redirectUri ?? REDIRECT_URI;
32936
+ try {
32937
+ const authParams = new URLSearchParams({
32938
+ code: "true",
32939
+ client_id: CLIENT_ID,
32940
+ response_type: "code",
32941
+ redirect_uri: redirectUri,
32942
+ scope: SCOPES,
32943
+ code_challenge: challenge,
32944
+ code_challenge_method: "S256",
32945
+ state: verifier
32946
+ });
32947
+ interaction.notify({
32948
+ type: "auth_url",
32949
+ url: `${AUTHORIZE_URL}?${authParams.toString()}`,
32950
+ instructions: "Complete login in your browser. If the browser is on another machine, paste the final redirect URL here."
32951
+ });
32952
+ const result = await waitForCallbackOrManualInput(interaction, callback, {
32953
+ message: "Complete login in your browser, or paste the authorization code / redirect URL here:",
32954
+ placeholder: redirectUri
32955
+ });
32956
+ let code;
32957
+ let state = verifier;
32958
+ if (result.type === "callback") {
32959
+ code = result.value;
32960
+ } else {
32961
+ const parsed = parseAuthorizationInput(result.input);
32962
+ if (parsed.state && parsed.state !== verifier)
32963
+ throw new Error("OAuth state mismatch");
32964
+ code = parsed.code;
32965
+ state = parsed.state ?? verifier;
32966
+ }
32967
+ if (!code)
32968
+ throw new Error("Missing authorization code");
32969
+ interaction.notify({ type: "progress", message: "Exchanging authorization code for tokens..." });
32970
+ return await exchangeAuthorizationCode(code, state, verifier, redirectUri, interaction.signal);
32971
+ } finally {
32972
+ callback?.close();
32973
+ }
32974
+ }
32975
+ async function loginAnthropicCopyCode(interaction) {
32976
+ const { verifier, challenge } = await generatePKCE();
32977
+ const authParams = new URLSearchParams({
32978
+ code: "true",
32979
+ client_id: CLIENT_ID,
32980
+ response_type: "code",
32981
+ redirect_uri: COPY_CODE_REDIRECT_URI,
32982
+ scope: SCOPES,
32983
+ code_challenge: challenge,
32984
+ code_challenge_method: "S256",
32985
+ state: verifier
32986
+ });
32987
+ interaction.notify({
32988
+ type: "auth_url",
32989
+ url: `${AUTHORIZE_URL}?${authParams.toString()}`,
32990
+ instructions: "Complete login in your browser, then copy the code Anthropic shows and paste it here."
32991
+ });
32992
+ const input2 = await interaction.prompt({
32993
+ type: "manual_code",
32994
+ message: "Paste the code Anthropic shows after you sign in:",
32995
+ placeholder: "code#state",
32996
+ signal: interaction.signal
32997
+ });
32998
+ const parsed = parseAuthorizationInput(input2);
32999
+ if (parsed.state && parsed.state !== verifier)
33000
+ throw new Error("OAuth state mismatch");
33001
+ if (!parsed.code)
33002
+ throw new Error("Missing authorization code");
33003
+ interaction.notify({ type: "progress", message: "Exchanging authorization code for tokens..." });
33004
+ return await exchangeAuthorizationCode(parsed.code, parsed.state ?? verifier, verifier, COPY_CODE_REDIRECT_URI, interaction.signal);
33005
+ }
33006
+ async function refreshAnthropicToken(refreshToken2, signal) {
33007
+ let responseBody;
33008
+ try {
33009
+ responseBody = await postJson(TOKEN_URL, {
33010
+ grant_type: "refresh_token",
33011
+ client_id: CLIENT_ID,
33012
+ refresh_token: refreshToken2
33013
+ }, signal);
33014
+ } catch (error63) {
33015
+ throw new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error63)}`);
33016
+ }
33017
+ let data;
33018
+ try {
33019
+ data = JSON.parse(responseBody);
33020
+ } catch (error63) {
33021
+ throw new Error(`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error63)}`);
33022
+ }
33023
+ return {
33024
+ type: "oauth",
33025
+ refresh: data.refresh_token,
33026
+ access: data.access_token,
33027
+ expires: Date.now() + data.expires_in * 1e3 - 5 * 60 * 1e3
33028
+ };
33029
+ }
33030
+ var anthropicOAuth = {
33031
+ name: "Anthropic (Claude Pro/Max)",
33032
+ isSubscription: true,
33033
+ async login(interaction) {
33034
+ const method = await interaction.prompt({
33035
+ type: "select",
33036
+ message: "Select Anthropic login method:",
33037
+ options: [
33038
+ { id: ANTHROPIC_BROWSER_LOGIN_METHOD, label: "Browser login (default)" },
33039
+ { id: ANTHROPIC_COPY_CODE_LOGIN_METHOD, label: "Copy code login (headless)" }
33040
+ ]
33041
+ });
33042
+ if (method === ANTHROPIC_COPY_CODE_LOGIN_METHOD) {
33043
+ return loginAnthropicCopyCode(interaction);
33044
+ }
33045
+ if (method !== ANTHROPIC_BROWSER_LOGIN_METHOD) {
33046
+ throw new Error(`Unknown Anthropic login method: ${method}`);
33047
+ }
33048
+ return loginAnthropic(interaction);
33049
+ },
33050
+ refresh: (credential, signal) => refreshAnthropicToken(credential.refresh, signal),
33051
+ async toAuth(credential) {
33052
+ return { apiKey: credential.access };
33053
+ }
33054
+ };
33055
+
33056
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/utils/sleep.js
33057
+ function sleep(ms, signal) {
33058
+ return new Promise((resolve7, reject) => {
33059
+ signal.throwIfAborted();
33060
+ const onAbort = () => {
33061
+ clearTimeout(timeout);
33062
+ reject(signal.reason);
33063
+ };
33064
+ const timeout = setTimeout(() => {
33065
+ signal.removeEventListener("abort", onAbort);
33066
+ resolve7();
33067
+ }, ms);
33068
+ signal.addEventListener("abort", onAbort, { once: true });
33069
+ });
33070
+ }
33071
+
33072
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/device-code.js
33073
+ var CANCEL_MESSAGE = "Login cancelled";
33074
+ var TIMEOUT_MESSAGE = "Device flow timed out";
33075
+ var 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.";
33076
+ var MINIMUM_INTERVAL_MS = 1e3;
33077
+ var DEFAULT_POLL_INTERVAL_SECONDS = 5;
33078
+ var SLOW_DOWN_INTERVAL_INCREMENT_MS = 5e3;
33079
+ function abortableSleep(ms, signal, cancelMessage) {
33080
+ return new Promise((resolve7, reject) => {
33081
+ if (signal.aborted) {
33082
+ reject(new Error(cancelMessage));
33083
+ return;
33084
+ }
33085
+ const onAbort = () => {
33086
+ clearTimeout(timeout);
33087
+ reject(new Error(cancelMessage));
33088
+ };
33089
+ const timeout = setTimeout(() => {
33090
+ signal.removeEventListener("abort", onAbort);
33091
+ resolve7();
33092
+ }, ms);
33093
+ signal.addEventListener("abort", onAbort, { once: true });
33094
+ });
33095
+ }
33096
+ async function pollOAuthDeviceCodeFlow(options) {
33097
+ const deadline = typeof options.expiresInSeconds === "number" ? Date.now() + options.expiresInSeconds * 1e3 : Number.POSITIVE_INFINITY;
33098
+ let intervalMs = Math.max(MINIMUM_INTERVAL_MS, Math.floor((options.intervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS) * 1e3));
33099
+ let slowDownResponses = 0;
33100
+ if (options.waitBeforeFirstPoll) {
33101
+ const remainingMs = deadline - Date.now();
33102
+ if (remainingMs > 0) {
33103
+ await abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);
33104
+ }
33105
+ }
33106
+ while (Date.now() < deadline) {
33107
+ if (options.signal.aborted) {
33108
+ throw new Error(CANCEL_MESSAGE);
33109
+ }
33110
+ const result = await options.poll();
33111
+ if (result.status === "complete") {
33112
+ return result.value;
33113
+ }
33114
+ if (result.status === "failed") {
33115
+ throw new Error(result.message);
33116
+ }
33117
+ if (result.status === "slow_down") {
33118
+ slowDownResponses += 1;
33119
+ intervalMs = typeof result.intervalSeconds === "number" && Number.isFinite(result.intervalSeconds) && result.intervalSeconds > 0 ? Math.max(MINIMUM_INTERVAL_MS, Math.floor(result.intervalSeconds * 1e3)) : Math.max(MINIMUM_INTERVAL_MS, intervalMs + SLOW_DOWN_INTERVAL_INCREMENT_MS);
33120
+ }
33121
+ const remainingMs = deadline - Date.now();
33122
+ if (remainingMs <= 0) {
33123
+ break;
33124
+ }
33125
+ await abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);
33126
+ }
33127
+ throw new Error(slowDownResponses > 0 ? SLOW_DOWN_TIMEOUT_MESSAGE : TIMEOUT_MESSAGE);
33128
+ }
33129
+
33130
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.js
33131
+ var decode4 = (s) => atob(s);
33132
+ var CLIENT_ID2 = decode4("SXYxLmI1MDdhMDhjODdlY2ZlOTg=");
33133
+ var COPILOT_HEADERS = {
33134
+ "User-Agent": "GitHubCopilotChat/0.35.0",
33135
+ "Editor-Version": "vscode/1.107.0",
33136
+ "Editor-Plugin-Version": "copilot-chat/0.35.0",
33137
+ "Copilot-Integration-Id": "vscode-chat"
33138
+ };
33139
+ var COPILOT_API_VERSION = "2026-06-01";
33140
+ function normalizeDomain(input2) {
33141
+ const trimmed = input2.trim();
33142
+ if (!trimmed)
33143
+ return null;
33144
+ try {
33145
+ const url2 = trimmed.includes("://") ? new URL(trimmed) : new URL(`https://${trimmed}`);
33146
+ return url2.hostname;
33147
+ } catch {
33148
+ return null;
33149
+ }
33150
+ }
33151
+ function getUrls(domain2) {
33152
+ return {
33153
+ deviceCodeUrl: `https://${domain2}/login/device/code`,
33154
+ accessTokenUrl: `https://${domain2}/login/oauth/access_token`,
33155
+ copilotTokenUrl: `https://api.${domain2}/copilot_internal/v2/token`
33156
+ };
33157
+ }
33158
+ function getBaseUrlFromToken(token) {
33159
+ const match = token.match(/proxy-ep=([^;]+)/);
33160
+ if (!match)
33161
+ return null;
33162
+ const proxyHost = match[1];
33163
+ const apiHost = proxyHost.replace(/^proxy\./, "api.");
33164
+ return `https://${apiHost}`;
33165
+ }
33166
+ function getGitHubCopilotBaseUrl(token, enterpriseDomain) {
33167
+ if (token) {
33168
+ const urlFromToken = getBaseUrlFromToken(token);
33169
+ if (urlFromToken)
33170
+ return urlFromToken;
33171
+ }
33172
+ if (enterpriseDomain)
33173
+ return `https://copilot-api.${enterpriseDomain}`;
33174
+ return "https://api.individual.githubcopilot.com";
33175
+ }
33176
+ function asRecord(value) {
33177
+ return value && typeof value === "object" ? value : void 0;
33178
+ }
33179
+ function parseGitHubCopilotModelCatalog(raw, allowPolicyFallback) {
33180
+ const data = asRecord(raw)?.data;
33181
+ if (!Array.isArray(data)) {
33182
+ throw new Error("Invalid Copilot models response");
33183
+ }
33184
+ const accountModels = data.flatMap((rawItem) => {
33185
+ const item = asRecord(rawItem);
33186
+ const id = item?.id;
33187
+ if (!item || typeof id !== "string")
33188
+ return [];
33189
+ const capabilities = asRecord(item.capabilities);
33190
+ const supports = asRecord(capabilities?.supports);
33191
+ if (supports?.tool_calls === false)
33192
+ return [];
33193
+ return [
33194
+ {
33195
+ id,
33196
+ pickerEnabled: item.model_picker_enabled === true,
33197
+ policyState: asRecord(item.policy)?.state
33198
+ }
33199
+ ];
33200
+ });
33201
+ const pickerModelIds = accountModels.filter((model2) => model2.pickerEnabled && model2.policyState !== "disabled").map((model2) => model2.id);
33202
+ const usePolicyFallback = allowPolicyFallback && pickerModelIds.length === 0;
33203
+ const availableModelIds = pickerModelIds.length > 0 || !allowPolicyFallback ? pickerModelIds : accountModels.filter((model2) => model2.policyState === "enabled").map((model2) => model2.id);
33204
+ const policyModelIds = accountModels.filter((model2) => model2.policyState === "unconfigured" && Object.hasOwn(GITHUB_COPILOT_MODELS, model2.id) && (model2.pickerEnabled || usePolicyFallback)).map((model2) => model2.id);
33205
+ return { availableModelIds, policyModelIds };
33206
+ }
33207
+ async function fetchWithRateLimitRetry(url2, init, signal, retryPolicy) {
33208
+ const retryBudgetSignal = retryPolicy.maxRetries > 0 && retryPolicy.maxElapsedMs > 0 ? AbortSignal.timeout(retryPolicy.maxElapsedMs) : void 0;
33209
+ const requestSignal3 = retryBudgetSignal ? AbortSignal.any([signal, retryBudgetSignal]) : signal;
33210
+ const retryDeadline = retryBudgetSignal ? Date.now() + retryPolicy.maxElapsedMs : void 0;
33211
+ for (let retry2 = 0; ; retry2++) {
33212
+ const response = await fetch(url2, {
33213
+ ...init,
33214
+ signal: AbortSignal.any([requestSignal3, AbortSignal.timeout(5e3)])
33215
+ });
33216
+ if (response.status !== 429 || retry2 === retryPolicy.maxRetries)
33217
+ return response;
33218
+ const retryAfter = response.headers.get("retry-after");
33219
+ let delayMs = 500 * 2 ** retry2;
33220
+ if (retryAfter) {
33221
+ const seconds = Number.parseFloat(retryAfter);
33222
+ delayMs = Number.isNaN(seconds) ? Date.parse(retryAfter) - Date.now() : seconds * 1e3;
33223
+ if (!Number.isFinite(delayMs))
33224
+ return response;
33225
+ }
33226
+ delayMs = Math.max(0, delayMs);
33227
+ if (retryDeadline !== void 0 && delayMs >= retryDeadline - Date.now())
33228
+ return response;
33229
+ await response.body?.cancel();
33230
+ await sleep(delayMs, requestSignal3);
33231
+ }
33232
+ }
33233
+ async function fetchGitHubCopilotModels(copilotToken, enterpriseDomain, signal, retryPolicy) {
33234
+ const baseUrl = getGitHubCopilotBaseUrl(copilotToken, enterpriseDomain);
33235
+ const allowPolicyFallback = baseUrl === "https://api.individual.githubcopilot.com";
33236
+ const response = await fetchWithRateLimitRetry(`${baseUrl}/models`, {
33237
+ headers: {
33238
+ Accept: "application/json",
33239
+ Authorization: `Bearer ${copilotToken}`,
33240
+ ...COPILOT_HEADERS,
33241
+ "X-GitHub-Api-Version": COPILOT_API_VERSION
33242
+ }
33243
+ }, signal, retryPolicy);
33244
+ if (!response.ok) {
33245
+ throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);
33246
+ }
33247
+ return parseGitHubCopilotModelCatalog(await response.json(), allowPolicyFallback);
33248
+ }
33249
+ async function fetchJson(url2, init) {
33250
+ const response = await fetch(url2, init);
33251
+ if (!response.ok) {
33252
+ const text2 = await response.text();
33253
+ throw new Error(`${response.status} ${response.statusText}: ${text2}`);
33254
+ }
33255
+ return response.json();
33256
+ }
33257
+ async function startDeviceFlow(domain2, signal) {
33258
+ const urls2 = getUrls(domain2);
33259
+ const data = await fetchJson(urls2.deviceCodeUrl, {
33260
+ method: "POST",
33261
+ headers: {
33262
+ Accept: "application/json",
33263
+ "Content-Type": "application/x-www-form-urlencoded",
33264
+ "User-Agent": "GitHubCopilotChat/0.35.0"
33265
+ },
33266
+ body: new URLSearchParams({
33267
+ client_id: CLIENT_ID2,
33268
+ scope: "read:user"
33269
+ }),
33270
+ signal
33271
+ });
33272
+ if (!data || typeof data !== "object") {
33273
+ throw new Error("Invalid device code response");
33274
+ }
33275
+ const deviceCode = data.device_code;
33276
+ const userCode = data.user_code;
33277
+ const verificationUri = data.verification_uri;
33278
+ const interval = data.interval;
33279
+ const expiresIn = data.expires_in;
33280
+ if (typeof deviceCode !== "string" || typeof userCode !== "string" || typeof verificationUri !== "string" || interval !== void 0 && typeof interval !== "number" || typeof expiresIn !== "number") {
33281
+ throw new Error("Invalid device code response fields");
33282
+ }
33283
+ let parsedUri;
33284
+ try {
33285
+ parsedUri = new URL(verificationUri);
33286
+ } catch {
33287
+ throw new Error("Untrusted verification_uri in device code response");
33288
+ }
33289
+ if (parsedUri.protocol !== "https:" && parsedUri.protocol !== "http:") {
33290
+ throw new Error("Untrusted verification_uri in device code response");
33291
+ }
33292
+ return {
33293
+ device_code: deviceCode,
33294
+ user_code: userCode,
33295
+ verification_uri: parsedUri.href,
33296
+ interval,
33297
+ expires_in: expiresIn
33298
+ };
33299
+ }
33300
+ async function pollForGitHubAccessToken(domain2, device, signal) {
33301
+ const urls2 = getUrls(domain2);
33302
+ return pollOAuthDeviceCodeFlow({
33303
+ intervalSeconds: device.interval,
33304
+ expiresInSeconds: device.expires_in,
33305
+ waitBeforeFirstPoll: true,
33306
+ signal,
33307
+ poll: async () => {
33308
+ const raw = await fetchJson(urls2.accessTokenUrl, {
33309
+ method: "POST",
33310
+ headers: {
33311
+ Accept: "application/json",
33312
+ "Content-Type": "application/x-www-form-urlencoded",
33313
+ "User-Agent": "GitHubCopilotChat/0.35.0"
33314
+ },
33315
+ body: new URLSearchParams({
33316
+ client_id: CLIENT_ID2,
33317
+ device_code: device.device_code,
33318
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
33319
+ }),
33320
+ signal
33321
+ });
33322
+ if (raw && typeof raw === "object" && typeof raw.access_token === "string") {
33323
+ return { status: "complete", value: raw.access_token };
33324
+ }
33325
+ if (raw && typeof raw === "object" && typeof raw.error === "string") {
33326
+ const { error: error63, error_description: description, interval } = raw;
33327
+ if (error63 === "authorization_pending") {
33328
+ return { status: "pending" };
33329
+ }
33330
+ if (error63 === "slow_down") {
33331
+ return { status: "slow_down", intervalSeconds: typeof interval === "number" ? interval : void 0 };
33332
+ }
33333
+ const descriptionSuffix = description ? `: ${description}` : "";
33334
+ return { status: "failed", message: `Device flow failed: ${error63}${descriptionSuffix}` };
33335
+ }
33336
+ return { status: "failed", message: "Invalid device token response" };
33337
+ }
33338
+ });
33339
+ }
33340
+ async function refreshGitHubCopilotAccessToken(refreshToken2, enterpriseDomain, signal) {
33341
+ const domain2 = enterpriseDomain || "github.com";
33342
+ const urls2 = getUrls(domain2);
33343
+ const raw = await fetchJson(urls2.copilotTokenUrl, {
33344
+ headers: {
33345
+ Accept: "application/json",
33346
+ Authorization: `Bearer ${refreshToken2}`,
33347
+ ...COPILOT_HEADERS
33348
+ },
33349
+ signal
33350
+ });
33351
+ if (!raw || typeof raw !== "object") {
33352
+ throw new Error("Invalid Copilot token response");
33353
+ }
33354
+ const token = raw.token;
33355
+ const expiresAt = raw.expires_at;
33356
+ if (typeof token !== "string" || typeof expiresAt !== "number") {
33357
+ throw new Error("Invalid Copilot token response fields");
33358
+ }
33359
+ return {
33360
+ type: "oauth",
33361
+ refresh: refreshToken2,
33362
+ access: token,
33363
+ expires: expiresAt * 1e3 - 5 * 60 * 1e3,
33364
+ enterpriseUrl: enterpriseDomain
33365
+ };
33366
+ }
33367
+ async function refreshGitHubCopilotToken(refreshToken2, enterpriseDomain, signal) {
33368
+ const credentials = await refreshGitHubCopilotAccessToken(refreshToken2, enterpriseDomain, signal);
33369
+ const { availableModelIds } = await fetchGitHubCopilotModels(credentials.access, enterpriseDomain, signal, {
33370
+ maxRetries: 0,
33371
+ maxElapsedMs: 0
33372
+ });
33373
+ return {
33374
+ ...credentials,
33375
+ availableModelIds
33376
+ };
33377
+ }
33378
+ async function enableGitHubCopilotModel(token, modelId, enterpriseDomain, signal) {
33379
+ const baseUrl = getGitHubCopilotBaseUrl(token, enterpriseDomain);
33380
+ const url2 = `${baseUrl}/models/${modelId}/policy`;
33381
+ let response;
33382
+ try {
33383
+ response = await fetchWithRateLimitRetry(url2, {
33384
+ method: "POST",
33385
+ headers: {
33386
+ "Content-Type": "application/json",
33387
+ Authorization: `Bearer ${token}`,
33388
+ ...COPILOT_HEADERS,
33389
+ "openai-intent": "chat-policy",
33390
+ "x-interaction-type": "chat-policy"
33391
+ },
33392
+ body: JSON.stringify({ state: "enabled" })
33393
+ }, signal, { maxRetries: 2, maxElapsedMs: 5e3 });
33394
+ } catch (error63) {
33395
+ if (signal.aborted)
33396
+ throw error63;
33397
+ return false;
33398
+ }
33399
+ if (response.status === 429) {
33400
+ throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);
33401
+ }
33402
+ return response.ok;
33403
+ }
33404
+ async function enableGitHubCopilotModels(token, modelIds, enterpriseDomain, signal) {
33405
+ const enabledModelIds = [];
33406
+ for (const modelId of modelIds) {
33407
+ try {
33408
+ if (await enableGitHubCopilotModel(token, modelId, enterpriseDomain, signal)) {
33409
+ enabledModelIds.push(modelId);
33410
+ }
33411
+ } catch (error63) {
33412
+ if (signal.aborted)
33413
+ throw error63;
33414
+ break;
33415
+ }
33416
+ }
33417
+ return enabledModelIds;
33418
+ }
33419
+ async function loginGitHubCopilot(interaction) {
33420
+ const input2 = await interaction.prompt({
33421
+ type: "text",
33422
+ message: "GitHub Enterprise URL/domain (blank for github.com)",
33423
+ placeholder: "company.ghe.com"
33424
+ });
33425
+ if (interaction.signal.aborted)
33426
+ throw new Error("Login cancelled");
33427
+ const trimmed = input2.trim();
33428
+ const enterpriseDomain = normalizeDomain(input2);
33429
+ if (trimmed && !enterpriseDomain)
33430
+ throw new Error("Invalid GitHub Enterprise URL/domain");
33431
+ const domain2 = enterpriseDomain || "github.com";
33432
+ const device = await startDeviceFlow(domain2, interaction.signal);
33433
+ interaction.notify({
33434
+ type: "device_code",
33435
+ userCode: device.user_code,
33436
+ verificationUri: device.verification_uri,
33437
+ intervalSeconds: device.interval,
33438
+ expiresInSeconds: device.expires_in
33439
+ });
33440
+ const githubAccessToken = await pollForGitHubAccessToken(domain2, device, interaction.signal);
33441
+ const credentials = await refreshGitHubCopilotAccessToken(githubAccessToken, enterpriseDomain ?? void 0, interaction.signal);
33442
+ const models2 = await fetchGitHubCopilotModels(credentials.access, enterpriseDomain ?? void 0, interaction.signal, {
33443
+ maxRetries: 2,
33444
+ maxElapsedMs: 5e3
33445
+ });
33446
+ let enabledModelIds = [];
33447
+ if (models2.policyModelIds.length > 0) {
33448
+ interaction.notify({ type: "progress", message: "Enabling models..." });
33449
+ enabledModelIds = await enableGitHubCopilotModels(credentials.access, models2.policyModelIds, enterpriseDomain ?? void 0, interaction.signal);
33450
+ }
33451
+ return {
33452
+ ...credentials,
33453
+ availableModelIds: [.../* @__PURE__ */ new Set([...models2.availableModelIds, ...enabledModelIds])]
33454
+ };
33455
+ }
33456
+ function copilotEnterpriseDomain(credential) {
33457
+ const enterpriseUrl = credential.enterpriseUrl;
33458
+ if (typeof enterpriseUrl !== "string" || !enterpriseUrl)
33459
+ return void 0;
33460
+ return normalizeDomain(enterpriseUrl) ?? void 0;
33461
+ }
33462
+ var githubCopilotOAuth = {
33463
+ name: "GitHub Copilot",
33464
+ isSubscription: true,
33465
+ login: loginGitHubCopilot,
33466
+ refresh: (credential, signal) => refreshGitHubCopilotToken(credential.refresh, copilotEnterpriseDomain(credential), signal),
33467
+ /** Derive the credential-specific proxy endpoint for each request. */
33468
+ async toAuth(credential) {
33469
+ return {
33470
+ apiKey: credential.access,
33471
+ baseUrl: getGitHubCopilotBaseUrl(credential.access, copilotEnterpriseDomain(credential))
33472
+ };
33473
+ }
33474
+ };
33475
+
33476
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-coding.js
33477
+ var CLIENT_ID3 = "17e5f671-d194-4dfb-9706-5516cb48c098";
33478
+ var DEFAULT_OAUTH_HOST = "https://auth.kimi.com";
33479
+ var DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;
33480
+ var DEFAULT_POLL_INTERVAL_SECONDS2 = 5;
33481
+ var REQUEST_TIMEOUT_MS = 30 * 1e3;
33482
+ var REFRESH_MAX_RETRIES = 3;
33483
+ function getOauthHost() {
33484
+ const override = getProviderEnvValue("KIMI_CODE_OAUTH_HOST") || getProviderEnvValue("KIMI_OAUTH_HOST");
33485
+ return (override || DEFAULT_OAUTH_HOST).replace(/\/+$/, "");
33486
+ }
33487
+ function requestSignal(signal) {
33488
+ return AbortSignal.any([AbortSignal.timeout(REQUEST_TIMEOUT_MS), signal]);
33489
+ }
33490
+ function formUrlEncode(fields) {
33491
+ return new URLSearchParams(fields).toString();
33492
+ }
33493
+ async function readJson(response) {
33494
+ try {
33495
+ const json2 = await response.json();
33496
+ return json2 && typeof json2 === "object" ? json2 : null;
33497
+ } catch {
33498
+ return null;
33499
+ }
33500
+ }
33501
+ function trustedHttpUrl(value) {
33502
+ if (typeof value !== "string" || !value)
33503
+ return null;
33504
+ try {
33505
+ const url2 = new URL(value);
33506
+ if (url2.protocol !== "https:" && url2.protocol !== "http:")
33507
+ return null;
33508
+ return url2.href;
33509
+ } catch {
33510
+ return null;
33511
+ }
33512
+ }
33513
+ async function startDeviceAuthorization(oauthHost, signal) {
33514
+ const response = await fetch(`${oauthHost}/api/oauth/device_authorization`, {
33515
+ method: "POST",
33516
+ headers: {
33517
+ "Content-Type": "application/x-www-form-urlencoded",
33518
+ Accept: "application/json"
33519
+ },
33520
+ body: formUrlEncode({ client_id: CLIENT_ID3 }),
33521
+ signal: requestSignal(signal)
33522
+ });
33523
+ if (!response.ok) {
33524
+ const text2 = await response.text().catch(() => "");
33525
+ throw new Error(`Kimi Code device authorization failed with status ${response.status}${text2 ? `: ${text2}` : ""}`);
33526
+ }
33527
+ const json2 = await readJson(response);
33528
+ const deviceCode = json2?.device_code;
33529
+ const userCode = json2?.user_code;
33530
+ const verificationUri = json2?.verification_uri;
33531
+ const verificationUriComplete = json2?.verification_uri_complete;
33532
+ if (typeof deviceCode !== "string" || typeof userCode !== "string" || typeof verificationUri !== "string" || typeof verificationUriComplete !== "string" || !trustedHttpUrl(verificationUriComplete) || !trustedHttpUrl(verificationUri)) {
33533
+ throw new Error(`Invalid Kimi Code device authorization response: ${JSON.stringify(json2)}`);
33534
+ }
33535
+ const interval = json2?.interval;
33536
+ const expiresIn = json2?.expires_in;
33537
+ return {
33538
+ deviceCode,
33539
+ userCode,
33540
+ verificationUri,
33541
+ verificationUriComplete,
33542
+ intervalSeconds: typeof interval === "number" && Number.isFinite(interval) && interval > 0 ? interval : DEFAULT_POLL_INTERVAL_SECONDS2,
33543
+ expiresInSeconds: typeof expiresIn === "number" && Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : DEVICE_CODE_TIMEOUT_SECONDS
33544
+ };
33545
+ }
33546
+ function parseTokenResponse(json2, operation) {
33547
+ const accessToken = json2?.access_token;
33548
+ const refreshToken2 = json2?.refresh_token;
33549
+ const expiresIn = json2?.expires_in;
33550
+ if (typeof accessToken !== "string" || !accessToken || typeof refreshToken2 !== "string" || !refreshToken2 || typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0) {
33551
+ throw new Error(`Kimi Code token ${operation} response missing fields: ${JSON.stringify(json2)}`);
33552
+ }
33553
+ return {
33554
+ access: accessToken,
33555
+ refresh: refreshToken2,
33556
+ expires: Date.now() + expiresIn * 1e3
33557
+ };
33558
+ }
33559
+ async function pollForToken(oauthHost, device, signal) {
33560
+ return pollOAuthDeviceCodeFlow({
33561
+ intervalSeconds: device.intervalSeconds,
33562
+ expiresInSeconds: device.expiresInSeconds,
33563
+ waitBeforeFirstPoll: true,
33564
+ signal,
33565
+ poll: async () => {
33566
+ const response = await fetch(`${oauthHost}/api/oauth/token`, {
33567
+ method: "POST",
33568
+ headers: {
33569
+ "Content-Type": "application/x-www-form-urlencoded",
33570
+ Accept: "application/json"
33571
+ },
33572
+ body: formUrlEncode({
33573
+ client_id: CLIENT_ID3,
33574
+ device_code: device.deviceCode,
33575
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
33576
+ }),
33577
+ signal: requestSignal(signal)
33578
+ });
33579
+ if (response.status >= 500) {
33580
+ const text2 = await response.text().catch(() => "");
33581
+ return {
33582
+ status: "failed",
33583
+ message: `Kimi Code device token request failed with status ${response.status}${text2 ? `: ${text2}` : ""}`
33584
+ };
33585
+ }
33586
+ const json2 = await readJson(response);
33587
+ if (response.ok && typeof json2?.access_token === "string") {
33588
+ try {
33589
+ return { status: "complete", value: parseTokenResponse(json2, "poll") };
33590
+ } catch (error64) {
33591
+ return { status: "failed", message: error64 instanceof Error ? error64.message : String(error64) };
33592
+ }
33593
+ }
33594
+ const error63 = json2?.error;
33595
+ const description = typeof json2?.error_description === "string" ? `: ${json2.error_description}` : "";
33596
+ if (error63 === "authorization_pending") {
33597
+ return { status: "pending" };
33598
+ }
33599
+ if (error63 === "slow_down") {
33600
+ const interval = json2?.interval;
33601
+ return {
33602
+ status: "slow_down",
33603
+ intervalSeconds: typeof interval === "number" && interval > 0 ? interval : void 0
33604
+ };
33605
+ }
33606
+ if (error63 === "expired_token") {
33607
+ return { status: "failed", message: "Kimi Code device authorization expired. Please restart login." };
33608
+ }
33609
+ if (error63 === "access_denied") {
33610
+ return { status: "failed", message: "Kimi Code login was denied." };
33611
+ }
33612
+ return {
33613
+ status: "failed",
33614
+ message: `Kimi Code device token request failed (status ${response.status})${typeof error63 === "string" ? `: ${error63}${description}` : ""}`
33615
+ };
33616
+ }
33617
+ });
33618
+ }
33619
+ function isRetryableRefreshFailure(response) {
33620
+ return response.status === 429 || response.status >= 500;
33621
+ }
33622
+ async function refreshToken(oauthHost, refreshTokenValue, signal) {
33623
+ let lastError;
33624
+ for (let attempt = 0; attempt <= REFRESH_MAX_RETRIES; attempt++) {
33625
+ if (attempt > 0) {
33626
+ await sleep(1e3 * 2 ** (attempt - 1), signal);
33627
+ }
33628
+ if (signal.aborted) {
33629
+ throw new Error("Kimi Code token refresh aborted");
33630
+ }
33631
+ let response;
33632
+ try {
33633
+ response = await fetch(`${oauthHost}/api/oauth/token`, {
33634
+ method: "POST",
33635
+ headers: {
33636
+ "Content-Type": "application/x-www-form-urlencoded",
33637
+ Accept: "application/json"
33638
+ },
33639
+ body: formUrlEncode({
33640
+ client_id: CLIENT_ID3,
33641
+ grant_type: "refresh_token",
33642
+ refresh_token: refreshTokenValue
33643
+ }),
33644
+ signal: requestSignal(signal)
33645
+ });
33646
+ } catch (error63) {
33647
+ lastError = error63 instanceof Error ? error63 : new Error(String(error63));
33648
+ continue;
33649
+ }
33650
+ const json2 = await readJson(response);
33651
+ if (response.ok) {
33652
+ return parseTokenResponse(json2, "refresh");
33653
+ }
33654
+ if (response.status === 401 || response.status === 403 || json2?.error === "invalid_grant") {
33655
+ const description = typeof json2?.error_description === "string" ? `: ${json2.error_description}` : "";
33656
+ throw new Error(`Kimi Code token refresh unauthorized (status ${response.status})${description}`);
33657
+ }
33658
+ if (isRetryableRefreshFailure(response) && attempt < REFRESH_MAX_RETRIES) {
33659
+ lastError = new Error(`Kimi Code token refresh failed with status ${response.status}`);
33660
+ continue;
33661
+ }
33662
+ const text2 = JSON.stringify(json2);
33663
+ throw new Error(`Kimi Code token refresh failed with status ${response.status}${text2 ? `: ${text2}` : ""}`);
33664
+ }
33665
+ throw lastError ?? new Error("Kimi Code token refresh failed");
33666
+ }
33667
+ async function loginKimiCoding(interaction) {
33668
+ const oauthHost = getOauthHost();
33669
+ const device = await startDeviceAuthorization(oauthHost, interaction.signal);
33670
+ interaction.notify({
33671
+ type: "device_code",
33672
+ userCode: device.userCode,
33673
+ verificationUri: device.verificationUriComplete,
33674
+ intervalSeconds: device.intervalSeconds,
33675
+ expiresInSeconds: device.expiresInSeconds
33676
+ });
33677
+ const token = await pollForToken(oauthHost, device, interaction.signal);
33678
+ return { type: "oauth", access: token.access, refresh: token.refresh, expires: token.expires };
33679
+ }
33680
+ var kimiCodingOAuth = {
33681
+ name: "Kimi Code (subscription)",
33682
+ isSubscription: true,
33683
+ loginLabel: "Sign in with Kimi Code",
33684
+ login: loginKimiCoding,
33685
+ refresh: async (credential, signal) => {
33686
+ const token = await refreshToken(getOauthHost(), credential.refresh, signal);
33687
+ return { type: "oauth", access: token.access, refresh: token.refresh, expires: token.expires };
33688
+ },
33689
+ async toAuth(credential) {
33690
+ return { headers: { Authorization: `Bearer ${credential.access}` } };
33691
+ }
33692
+ };
33693
+
33694
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/meta.js
33695
+ var CLIENT_ID4 = "1031625952748946";
33696
+ var AUTH_HOST = "https://auth.meta.com";
33697
+ var DEVICE_AUTHORIZATION_URL = `${AUTH_HOST}/oidc/device/authorization/`;
33698
+ var DEVICE_TOKEN_URL = `${AUTH_HOST}/oidc/device/token/`;
33699
+ var API_KEY_MINT_URL = "https://api.meta.ai/muse-code/key";
33700
+ var API_KEY_LIFETIME_MS = 24 * 60 * 60 * 1e3;
33701
+ var REQUEST_TIMEOUT_MS2 = 30 * 1e3;
33702
+ function requestSignal2(signal) {
33703
+ return AbortSignal.any([AbortSignal.timeout(REQUEST_TIMEOUT_MS2), signal]);
33704
+ }
33705
+ async function readJson2(response) {
33706
+ try {
33707
+ const json2 = await response.json();
33708
+ return json2 && typeof json2 === "object" ? json2 : null;
33709
+ } catch {
33710
+ return null;
33711
+ }
33712
+ }
33713
+ function errorDetail(json2) {
33714
+ for (const key2 of ["error_description", "detail", "message", "error"]) {
33715
+ const value = json2?.[key2];
33716
+ if (typeof value === "string" && value.trim())
33717
+ return `: ${value.trim()}`;
33718
+ }
33719
+ return "";
33720
+ }
33721
+ function trustedHttpUrl2(value) {
33722
+ if (typeof value !== "string" || !value)
33723
+ return null;
33724
+ try {
33725
+ const url2 = new URL(value);
33726
+ if (url2.protocol !== "https:" && url2.protocol !== "http:")
33727
+ return null;
33728
+ return url2.href;
33729
+ } catch {
33730
+ return null;
33731
+ }
33732
+ }
33733
+ function positiveNumber(value) {
33734
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
33735
+ }
33736
+ async function startDeviceAuthorization2(signal) {
33737
+ const response = await fetch(DEVICE_AUTHORIZATION_URL, {
33738
+ method: "POST",
33739
+ headers: {
33740
+ "Content-Type": "application/x-www-form-urlencoded",
33741
+ Accept: "application/json"
33742
+ },
33743
+ body: new URLSearchParams({ client_id: CLIENT_ID4 }).toString(),
33744
+ signal: requestSignal2(signal)
33745
+ });
33746
+ const json2 = await readJson2(response);
33747
+ if (!response.ok) {
33748
+ throw new Error(`Meta device authorization failed with status ${response.status}${errorDetail(json2)}`);
33749
+ }
33750
+ const deviceCode = json2?.device_code;
33751
+ const userCode = json2?.user_code;
33752
+ const verificationUri = trustedHttpUrl2(json2?.verification_uri_complete) ?? trustedHttpUrl2(json2?.verification_uri);
33753
+ if (typeof deviceCode !== "string" || !deviceCode || typeof userCode !== "string" || !userCode || !verificationUri) {
33754
+ throw new Error(`Invalid Meta device authorization response: ${JSON.stringify(json2)}`);
33755
+ }
33756
+ return {
33757
+ deviceCode,
33758
+ userCode,
33759
+ verificationUri,
33760
+ intervalSeconds: positiveNumber(json2?.interval),
33761
+ expiresInSeconds: positiveNumber(json2?.expires_in)
33762
+ };
33763
+ }
33764
+ async function pollForIdentityToken(device, signal) {
33765
+ return pollOAuthDeviceCodeFlow({
33766
+ intervalSeconds: device.intervalSeconds,
33767
+ expiresInSeconds: device.expiresInSeconds,
33768
+ waitBeforeFirstPoll: true,
33769
+ signal,
33770
+ poll: async () => {
33771
+ const response = await fetch(DEVICE_TOKEN_URL, {
33772
+ method: "POST",
33773
+ headers: {
33774
+ "Content-Type": "application/x-www-form-urlencoded",
33775
+ Accept: "application/json"
33776
+ },
33777
+ body: new URLSearchParams({
33778
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
33779
+ device_code: device.deviceCode,
33780
+ client_id: CLIENT_ID4
33781
+ }).toString(),
33782
+ signal: requestSignal2(signal)
33783
+ });
33784
+ const json2 = await readJson2(response);
33785
+ if (response.ok && typeof json2?.access_token === "string" && json2.access_token) {
33786
+ return { status: "complete", value: json2.access_token };
33787
+ }
33788
+ switch (json2?.error) {
33789
+ case "authorization_pending":
33790
+ return { status: "pending" };
33791
+ case "slow_down":
33792
+ return { status: "slow_down", intervalSeconds: positiveNumber(json2?.interval) };
33793
+ case "access_denied":
33794
+ return { status: "failed", message: "Meta login was denied." };
33795
+ case "expired_token":
33796
+ return { status: "failed", message: "Meta device authorization expired. Please restart login." };
33797
+ default:
33798
+ return {
33799
+ status: "failed",
33800
+ message: `Meta device token request failed with status ${response.status}${errorDetail(json2)}`
33801
+ };
33802
+ }
33803
+ }
33804
+ });
33805
+ }
33806
+ async function mintApiKey(identityToken, signal) {
33807
+ const response = await fetch(API_KEY_MINT_URL, {
33808
+ method: "POST",
33809
+ headers: {
33810
+ Accept: "application/json",
33811
+ Authorization: `Bearer ${identityToken}`,
33812
+ "Content-Type": "application/json",
33813
+ "x-api-version": "1.0.0"
33814
+ },
33815
+ body: "{}",
33816
+ signal: requestSignal2(signal)
33817
+ });
33818
+ const json2 = await readJson2(response);
33819
+ if (response.status === 401 || response.status === 403) {
33820
+ throw new Error(`Meta session expired (status ${response.status}). Run \`/login meta\` to sign in again.${errorDetail(json2)}`);
33821
+ }
33822
+ if (!response.ok) {
33823
+ throw new Error(`Meta API key mint failed with status ${response.status}${errorDetail(json2)}`);
33824
+ }
33825
+ const apiKey = json2?.api_key;
33826
+ if (typeof apiKey !== "string" || !apiKey) {
33827
+ const actionUrl = trustedHttpUrl2(json2?.action_url);
33828
+ throw new Error(`Meta did not issue an API key.${actionUrl ? ` Complete setup at ${actionUrl}` : ""}`);
33829
+ }
33830
+ return { type: "oauth", refresh: identityToken, access: apiKey, expires: Date.now() + API_KEY_LIFETIME_MS };
33831
+ }
33832
+ async function loginMeta(interaction) {
33833
+ try {
33834
+ const device = await startDeviceAuthorization2(interaction.signal);
33835
+ interaction.notify({
33836
+ type: "device_code",
33837
+ userCode: device.userCode,
33838
+ verificationUri: device.verificationUri,
33839
+ intervalSeconds: device.intervalSeconds,
33840
+ expiresInSeconds: device.expiresInSeconds
33841
+ });
33842
+ const identityToken = await pollForIdentityToken(device, interaction.signal);
33843
+ interaction.notify({ type: "progress", message: "Enabling Meta Model API access..." });
33844
+ return await mintApiKey(identityToken, interaction.signal);
33845
+ } catch (e) {
33846
+ if (interaction.signal.aborted)
33847
+ throw new Error("Login cancelled");
33848
+ throw e;
33849
+ }
33850
+ }
33851
+ var metaOAuth = {
33852
+ name: "Meta (Muse subscription)",
33853
+ isSubscription: true,
33854
+ loginLabel: "Sign in with Meta",
33855
+ login: loginMeta,
33856
+ refresh: (credential, signal) => mintApiKey(credential.refresh, signal),
33857
+ async toAuth(credential) {
33858
+ return { apiKey: credential.access };
33859
+ }
33860
+ };
33861
+
33862
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/openai-chatgpt.js
33863
+ import { randomBytes } from "node:crypto";
33864
+ import { createServer as createServer2 } from "node:http";
33865
+ var DYNAMIC_CLIENT_ID = "dynamic_agent_client";
33866
+ var AGENT_NAME_HINT = "Pi";
33867
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
33868
+ var AUTHORIZE_URL2 = "https://auth.openai.com/api/accounts/authorize";
33869
+ var TOKEN_URL2 = "https://auth.openai.com/api/accounts/oauth/token";
33870
+ var RESOURCE = "https://api.openai.com/v1";
33871
+ var CALLBACK_HOST2 = getProviderEnvValue("PI_OAUTH_CALLBACK_HOST") || "127.0.0.1";
33872
+ var CALLBACK_PORT2 = 1455;
33873
+ var CALLBACK_PATH2 = "/auth/callback";
33874
+ var REDIRECT_URI2 = `http://127.0.0.1:${CALLBACK_PORT2}${CALLBACK_PATH2}`;
33875
+ var DIRECT_TOKEN_SCOPE = "chatgpt.tokens.use.direct";
33876
+ var SCOPE = `openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`;
33877
+ var EXPIRY_MARGIN_MS = 3 * 60 * 1e3;
33878
+ function randomValue() {
33879
+ return randomBytes(32).toString("base64url");
33880
+ }
33881
+ function authorizationResultFromCallback(url2, expectedState) {
33882
+ const code = url2.searchParams.get("code");
33883
+ if (!code)
33884
+ throw new Error("Missing authorization code");
33885
+ const state = url2.searchParams.get("state");
33886
+ if (!state)
33887
+ throw new Error("Missing OAuth state");
33888
+ if (state !== expectedState)
33889
+ throw new Error("OAuth state mismatch");
33890
+ const clientId = url2.searchParams.get("client_id")?.trim();
33891
+ if (!clientId)
33892
+ throw new Error("OpenAI OAuth registration callback did not contain an issued client ID");
33893
+ return { code, clientId };
33894
+ }
33895
+ function authorizationResultFromManualInput(input2, expectedState) {
33896
+ let url2;
33897
+ try {
33898
+ url2 = new URL(input2.trim());
33899
+ } catch {
33900
+ throw new Error("Paste the full callback URL from the browser");
33901
+ }
33902
+ const expected = new URL(REDIRECT_URI2);
33903
+ if (url2.origin !== expected.origin || url2.pathname !== expected.pathname) {
33904
+ throw new Error(`The pasted callback URL must start with ${REDIRECT_URI2}`);
33905
+ }
33906
+ const error63 = url2.searchParams.get("error");
33907
+ if (error63)
33908
+ throw new Error(`ChatGPT authorization failed: ${error63}`);
33909
+ return authorizationResultFromCallback(url2, expectedState);
33910
+ }
33911
+ function sendHtml(response, status, body) {
33912
+ response.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
33913
+ response.end(body);
33914
+ }
33915
+ function startCallbackServer(expectedState) {
33916
+ return new Promise((resolve7, reject) => {
33917
+ let resolveResult;
33918
+ let rejectResult;
33919
+ const result = new Promise((resolveAuthorization, rejectAuthorization) => {
33920
+ resolveResult = resolveAuthorization;
33921
+ rejectResult = rejectAuthorization;
33922
+ });
33923
+ const server = createServer2((request, response) => {
33924
+ try {
33925
+ const url2 = new URL(request.url || "", REDIRECT_URI2);
33926
+ if (url2.pathname !== CALLBACK_PATH2) {
33927
+ sendHtml(response, 404, oauthErrorHtml("Callback route not found."));
33928
+ return;
33929
+ }
33930
+ const error63 = url2.searchParams.get("error");
33931
+ if (error63) {
33932
+ sendHtml(response, 400, oauthErrorHtml("ChatGPT was not connected.", `Error: ${error63}`));
33933
+ rejectResult(new Error(`ChatGPT authorization failed: ${error63}`));
33934
+ return;
33935
+ }
33936
+ let authorizationResult;
33937
+ try {
33938
+ authorizationResult = authorizationResultFromCallback(url2, expectedState);
33939
+ } catch (error64) {
33940
+ const message = error64 instanceof Error ? error64.message : "Invalid callback";
33941
+ sendHtml(response, 400, oauthErrorHtml(message));
33942
+ return;
33943
+ }
33944
+ sendHtml(response, 200, oauthSuccessHtml("ChatGPT authentication completed. You can close this window."));
33945
+ resolveResult(authorizationResult);
33946
+ } catch {
33947
+ sendHtml(response, 500, oauthErrorHtml("Internal error while processing the callback."));
33948
+ }
33949
+ });
33950
+ server.once("error", reject);
33951
+ server.listen(CALLBACK_PORT2, CALLBACK_HOST2, () => {
33952
+ server.removeListener("error", reject);
33953
+ server.on("error", rejectResult);
33954
+ resolve7({ server, result });
33955
+ });
33956
+ });
33957
+ }
33958
+ async function requestToken(body, signal) {
33959
+ const response = await fetch(TOKEN_URL2, {
33960
+ method: "POST",
33961
+ headers: {
33962
+ accept: "application/json",
33963
+ "content-type": "application/x-www-form-urlencoded"
33964
+ },
33965
+ body,
33966
+ signal
33967
+ });
33968
+ if (!response.ok) {
33969
+ const responseBody = await response.text().catch(() => "");
33970
+ throw new Error(`OpenAI OAuth token request failed (${response.status}): ${responseBody || response.statusText}`);
33971
+ }
33972
+ const data = await response.json();
33973
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
33974
+ throw new Error("OpenAI OAuth token response must be an object");
33975
+ }
33976
+ return data;
33977
+ }
33978
+ function requireTokenString(value, field) {
33979
+ if (typeof value !== "string" || value.trim().length === 0) {
33980
+ throw new Error(`OpenAI OAuth token response has invalid ${field}`);
33981
+ }
33982
+ return value;
33983
+ }
33984
+ function credentialFromTokenResponse(token, clientId) {
33985
+ const access6 = requireTokenString(token.access_token, "access_token");
33986
+ const refresh = requireTokenString(token.refresh_token, "refresh_token");
33987
+ const scope = requireTokenString(token.scope, "scope");
33988
+ if (typeof token.expires_in !== "number" || !Number.isFinite(token.expires_in) || token.expires_in <= 0) {
33989
+ throw new Error("OpenAI OAuth token response has invalid expires_in");
33990
+ }
33991
+ const scopes = scope.trim().split(/\s+/).filter(Boolean);
33992
+ if (!scopes.includes(DIRECT_TOKEN_SCOPE)) {
33993
+ throw new Error(`OpenAI OAuth grant did not include ${DIRECT_TOKEN_SCOPE}`);
33994
+ }
33995
+ return {
33996
+ type: "oauth",
33997
+ access: access6,
33998
+ refresh,
33999
+ expires: Date.now() + token.expires_in * 1e3 - EXPIRY_MARGIN_MS,
34000
+ clientId,
34001
+ scopes
34002
+ };
34003
+ }
34004
+ async function exchangeAuthorizationCode2(code, verifier, clientId, signal) {
34005
+ const token = await requestToken(new URLSearchParams({
34006
+ grant_type: "authorization_code",
34007
+ client_id: clientId,
34008
+ code,
34009
+ code_verifier: verifier,
34010
+ redirect_uri: REDIRECT_URI2,
34011
+ resource: RESOURCE
34012
+ }), signal);
34013
+ if (typeof token.id_token !== "string" || token.id_token.trim().length === 0) {
34014
+ throw new Error("OpenAI OAuth token response did not contain an ID token");
34015
+ }
34016
+ return credentialFromTokenResponse(token, clientId);
34017
+ }
34018
+ async function refreshAccessToken(credential, signal) {
34019
+ const clientId = credential.clientId;
34020
+ if (typeof clientId !== "string" || clientId.trim().length === 0) {
34021
+ throw new Error("Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT");
34022
+ }
34023
+ const token = await requestToken(new URLSearchParams({
34024
+ grant_type: "refresh_token",
34025
+ client_id: clientId,
34026
+ refresh_token: credential.refresh,
34027
+ resource: RESOURCE
34028
+ }), signal);
34029
+ return credentialFromTokenResponse(token, clientId);
34030
+ }
34031
+ function agentHostId(deviceId) {
34032
+ if (!deviceId || !UUID_PATTERN.test(deviceId)) {
34033
+ throw new Error("Sign in with ChatGPT requires a device ID (UUID) for this installation");
34034
+ }
34035
+ return `urn:uuid:${deviceId.toLowerCase()}`;
34036
+ }
34037
+ async function loginOpenAIChatGPT(interaction, options) {
34038
+ const hostId = agentHostId(options?.getDeviceId?.());
34039
+ const { verifier, challenge } = await generatePKCE();
34040
+ const state = randomValue();
34041
+ const nonce = randomValue();
34042
+ const callback = await startCallbackServer(state).catch((error63) => {
34043
+ if (!(error63 instanceof Error && "code" in error63 && error63.code === "EADDRINUSE"))
34044
+ throw error63;
34045
+ throw new Error(`Port ${CALLBACK_PORT2} is in use, probably by an unfinished login in another pi session or by the Codex CLI. Cancel that login and try again.`);
34046
+ });
34047
+ const authorizationUrl = new URL(AUTHORIZE_URL2);
34048
+ authorizationUrl.search = new URLSearchParams({
34049
+ client_id: DYNAMIC_CLIENT_ID,
34050
+ agent_name_hint: options?.agentName ?? AGENT_NAME_HINT,
34051
+ ext_agent_host_id: hostId,
34052
+ response_type: "code",
34053
+ redirect_uri: REDIRECT_URI2,
34054
+ resource: RESOURCE,
34055
+ scope: SCOPE,
34056
+ state,
34057
+ code_challenge: challenge,
34058
+ code_challenge_method: "S256",
34059
+ nonce
34060
+ }).toString();
34061
+ interaction.notify({
34062
+ type: "auth_url",
34063
+ url: authorizationUrl.toString(),
34064
+ instructions: "Complete sign-in in your browser. If the callback does not complete, paste the final redirect URL here."
34065
+ });
34066
+ const manualAbort = new AbortController();
34067
+ const manualCode = interaction.prompt({
34068
+ type: "manual_code",
34069
+ message: "Complete login in your browser, or paste the final redirect URL here:",
34070
+ placeholder: REDIRECT_URI2,
34071
+ signal: AbortSignal.any([manualAbort.signal, interaction.signal])
34072
+ }).then((input2) => authorizationResultFromManualInput(input2, state));
34073
+ try {
34074
+ const result = await Promise.race([callback.result, manualCode]);
34075
+ interaction.notify({ type: "progress", message: "Exchanging authorization code for tokens..." });
34076
+ return await exchangeAuthorizationCode2(result.code, verifier, result.clientId, interaction.signal);
34077
+ } catch (error63) {
34078
+ if (interaction.signal.aborted)
34079
+ throw new Error("Login cancelled");
34080
+ throw error63;
34081
+ } finally {
34082
+ manualAbort.abort();
34083
+ callback.server.close();
34084
+ callback.server.closeAllConnections();
34085
+ }
34086
+ }
34087
+ var openaiChatGPTOAuth = {
34088
+ name: "OpenAI (ChatGPT subscription)",
34089
+ isSubscription: true,
34090
+ loginLabel: "Sign in with ChatGPT",
34091
+ login: loginOpenAIChatGPT,
34092
+ refresh: refreshAccessToken,
34093
+ async toAuth(credential) {
34094
+ return { apiKey: credential.access };
34095
+ }
34096
+ };
34097
+
34098
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/openai-codex.js
34099
+ var _randomBytes = null;
34100
+ if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
34101
+ import("node:crypto").then((m2) => {
34102
+ _randomBytes = m2.randomBytes;
34103
+ });
34104
+ }
34105
+ var CLIENT_ID5 = "app_EMoamEEZ73f0CkXaXp7hrann";
34106
+ var AUTH_BASE_URL = "https://auth.openai.com";
34107
+ var AUTHORIZE_URL3 = `${AUTH_BASE_URL}/oauth/authorize`;
34108
+ var TOKEN_URL3 = `${AUTH_BASE_URL}/oauth/token`;
34109
+ var REDIRECT_URI3 = "http://localhost:1455/auth/callback";
34110
+ var DEVICE_USER_CODE_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`;
34111
+ var DEVICE_TOKEN_URL2 = `${AUTH_BASE_URL}/api/accounts/deviceauth/token`;
34112
+ var DEVICE_VERIFICATION_URI = `${AUTH_BASE_URL}/codex/device`;
34113
+ var DEVICE_REDIRECT_URI = `${AUTH_BASE_URL}/deviceauth/callback`;
34114
+ var DEVICE_CODE_TIMEOUT_SECONDS2 = 15 * 60;
34115
+ var OPENAI_CODEX_BROWSER_LOGIN_METHOD = "browser";
34116
+ var OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD = "device_code";
34117
+ var SCOPE2 = "openid profile email offline_access";
34118
+ var JWT_CLAIM_PATH = "https://api.openai.com/auth";
34119
+ function getCallbackHost() {
34120
+ return getProviderEnvValue("PI_OAUTH_CALLBACK_HOST") || "127.0.0.1";
34121
+ }
34122
+ function createState() {
34123
+ if (!_randomBytes) {
34124
+ throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
34125
+ }
34126
+ return _randomBytes(16).toString("hex");
34127
+ }
34128
+ function parseAuthorizationInput2(input2) {
34129
+ const value = input2.trim();
34130
+ if (!value)
34131
+ return {};
34132
+ try {
34133
+ const url2 = new URL(value);
34134
+ return {
34135
+ code: url2.searchParams.get("code") ?? void 0,
34136
+ state: url2.searchParams.get("state") ?? void 0
34137
+ };
34138
+ } catch {
34139
+ }
34140
+ if (value.includes("#")) {
34141
+ const [code, state] = value.split("#", 2);
34142
+ return { code, state };
34143
+ }
34144
+ if (value.includes("code=")) {
34145
+ const params = new URLSearchParams(value);
34146
+ return {
34147
+ code: params.get("code") ?? void 0,
34148
+ state: params.get("state") ?? void 0
34149
+ };
34150
+ }
34151
+ return { code: value };
34152
+ }
34153
+ function decodeJwt(token) {
34154
+ try {
34155
+ const parts2 = token.split(".");
34156
+ if (parts2.length !== 3)
34157
+ return null;
34158
+ const payload3 = parts2[1] ?? "";
34159
+ const decoded = atob(payload3);
34160
+ return JSON.parse(decoded);
34161
+ } catch {
34162
+ return null;
34163
+ }
34164
+ }
34165
+ async function fetchWithLoginCancellation(input2, init) {
34166
+ try {
34167
+ return await fetch(input2, init);
34168
+ } catch (error63) {
34169
+ if (init.signal?.aborted) {
34170
+ throw new Error("Login cancelled");
34171
+ }
34172
+ throw error63;
34173
+ }
34174
+ }
34175
+ async function readTokenResponse(response, operation) {
34176
+ if (!response.ok) {
34177
+ const text2 = await response.text().catch(() => "");
34178
+ throw new Error(`OpenAI Codex token ${operation} failed (${response.status}): ${text2 || response.statusText}`);
34179
+ }
34180
+ const rawJson = await response.json();
34181
+ const json2 = rawJson;
34182
+ if (!json2?.access_token || !json2.refresh_token || typeof json2.expires_in !== "number") {
34183
+ throw new Error(`OpenAI Codex token ${operation} response missing fields: ${JSON.stringify(json2)}`);
34184
+ }
34185
+ return {
34186
+ access: json2.access_token,
34187
+ refresh: json2.refresh_token,
34188
+ expires: Date.now() + json2.expires_in * 1e3
34189
+ };
34190
+ }
34191
+ async function exchangeAuthorizationCode3(code, verifier, redirectUri, signal) {
34192
+ const response = await fetchWithLoginCancellation(TOKEN_URL3, {
34193
+ method: "POST",
34194
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
34195
+ body: new URLSearchParams({
34196
+ grant_type: "authorization_code",
34197
+ client_id: CLIENT_ID5,
34198
+ code,
34199
+ code_verifier: verifier,
34200
+ redirect_uri: redirectUri
34201
+ }),
34202
+ signal
34203
+ });
34204
+ return readTokenResponse(response, "exchange");
34205
+ }
34206
+ async function refreshAccessToken2(refreshToken2, signal) {
34207
+ let response;
34208
+ try {
34209
+ response = await fetch(TOKEN_URL3, {
34210
+ method: "POST",
34211
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
34212
+ body: new URLSearchParams({
34213
+ grant_type: "refresh_token",
34214
+ refresh_token: refreshToken2,
34215
+ client_id: CLIENT_ID5
34216
+ }),
34217
+ signal
34218
+ });
34219
+ } catch (error63) {
34220
+ throw new Error(`OpenAI Codex token refresh error: ${error63 instanceof Error ? error63.message : String(error63)}`);
34221
+ }
34222
+ return readTokenResponse(response, "refresh");
34223
+ }
34224
+ async function startOpenAICodexDeviceAuth(signal) {
34225
+ const response = await fetchWithLoginCancellation(DEVICE_USER_CODE_URL, {
34226
+ method: "POST",
34227
+ headers: { "Content-Type": "application/json" },
34228
+ body: JSON.stringify({ client_id: CLIENT_ID5 }),
34229
+ signal
34230
+ });
34231
+ if (!response.ok) {
34232
+ if (response.status === 404) {
34233
+ throw new Error("OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.");
34234
+ }
34235
+ const responseBody = await response.text().catch(() => "");
34236
+ throw new Error(`OpenAI Codex device code request failed with status ${response.status}${responseBody ? `: ${responseBody}` : ""}`);
34237
+ }
34238
+ const rawJson = await response.json();
34239
+ const json2 = rawJson;
34240
+ const intervalSeconds = typeof json2?.interval === "string" ? Number(json2.interval.trim()) : json2?.interval;
34241
+ if (!json2?.device_auth_id || !json2.user_code || typeof intervalSeconds !== "number" || !Number.isFinite(intervalSeconds) || intervalSeconds < 0) {
34242
+ throw new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(json2)}`);
34243
+ }
34244
+ return {
34245
+ deviceAuthId: json2.device_auth_id,
34246
+ userCode: json2.user_code,
34247
+ intervalSeconds
34248
+ };
34249
+ }
34250
+ async function pollOpenAICodexDeviceAuth(device, signal) {
34251
+ return pollOAuthDeviceCodeFlow({
34252
+ intervalSeconds: device.intervalSeconds,
34253
+ expiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS2,
34254
+ signal,
34255
+ poll: async () => {
34256
+ const response = await fetchWithLoginCancellation(DEVICE_TOKEN_URL2, {
34257
+ method: "POST",
34258
+ headers: { "Content-Type": "application/json" },
34259
+ body: JSON.stringify({
34260
+ device_auth_id: device.deviceAuthId,
34261
+ user_code: device.userCode
34262
+ }),
34263
+ signal
34264
+ });
34265
+ if (response.ok) {
34266
+ const rawJson = await response.json();
34267
+ const json2 = rawJson;
34268
+ if (!json2?.authorization_code || !json2.code_verifier) {
34269
+ return {
34270
+ status: "failed",
34271
+ message: `Invalid OpenAI Codex device auth token response: ${JSON.stringify(json2)}`
34272
+ };
34273
+ }
34274
+ return {
34275
+ status: "complete",
34276
+ value: { authorizationCode: json2.authorization_code, codeVerifier: json2.code_verifier }
34277
+ };
34278
+ }
34279
+ if (response.status === 403 || response.status === 404) {
34280
+ return { status: "pending" };
34281
+ }
34282
+ const responseBody = await response.text().catch(() => "");
34283
+ let errorCode4;
34284
+ try {
34285
+ const json2 = JSON.parse(responseBody);
34286
+ const error63 = json2?.error;
34287
+ errorCode4 = typeof error63 === "object" ? error63?.code : error63;
34288
+ } catch {
34289
+ }
34290
+ if (errorCode4 === "deviceauth_authorization_pending") {
34291
+ return { status: "pending" };
34292
+ }
34293
+ if (errorCode4 === "slow_down") {
34294
+ return { status: "slow_down" };
34295
+ }
34296
+ return {
34297
+ status: "failed",
34298
+ message: `OpenAI Codex device auth failed with status ${response.status}${responseBody ? `: ${responseBody}` : ""}`
34299
+ };
34300
+ }
34301
+ });
34302
+ }
34303
+ async function createAuthorizationFlow(originator = "pi") {
34304
+ const { verifier, challenge } = await generatePKCE();
34305
+ const state = createState();
34306
+ const url2 = new URL(AUTHORIZE_URL3);
34307
+ url2.searchParams.set("response_type", "code");
34308
+ url2.searchParams.set("client_id", CLIENT_ID5);
34309
+ url2.searchParams.set("redirect_uri", REDIRECT_URI3);
34310
+ url2.searchParams.set("scope", SCOPE2);
34311
+ url2.searchParams.set("code_challenge", challenge);
34312
+ url2.searchParams.set("code_challenge_method", "S256");
34313
+ url2.searchParams.set("state", state);
34314
+ url2.searchParams.set("id_token_add_organizations", "true");
34315
+ url2.searchParams.set("codex_cli_simplified_flow", "true");
34316
+ url2.searchParams.set("originator", originator);
34317
+ return { verifier, state, url: url2.toString() };
34318
+ }
34319
+ function getAccountId(accessToken) {
34320
+ const payload3 = decodeJwt(accessToken);
34321
+ const auth = payload3?.[JWT_CLAIM_PATH];
34322
+ const accountId = auth?.chatgpt_account_id;
34323
+ return typeof accountId === "string" && accountId.length > 0 ? accountId : null;
34324
+ }
34325
+ function credentialsFromToken(token) {
34326
+ const accountId = getAccountId(token.access);
34327
+ if (!accountId) {
34328
+ throw new Error("Failed to extract accountId from token");
34329
+ }
34330
+ return {
34331
+ type: "oauth",
34332
+ access: token.access,
34333
+ refresh: token.refresh,
34334
+ expires: token.expires,
34335
+ accountId
34336
+ };
34337
+ }
34338
+ async function exchangeAuthorizationCodeForCredentials(code, verifier, redirectUri, signal) {
34339
+ return credentialsFromToken(await exchangeAuthorizationCode3(code, verifier, redirectUri, signal));
34340
+ }
34341
+ async function loginOpenAICodexDeviceCode(interaction) {
34342
+ const device = await startOpenAICodexDeviceAuth(interaction.signal);
34343
+ interaction.notify({
34344
+ type: "device_code",
34345
+ userCode: device.userCode,
34346
+ verificationUri: DEVICE_VERIFICATION_URI,
34347
+ intervalSeconds: device.intervalSeconds,
34348
+ expiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS2
34349
+ });
34350
+ const code = await pollOpenAICodexDeviceAuth(device, interaction.signal);
34351
+ return exchangeAuthorizationCodeForCredentials(code.authorizationCode, code.codeVerifier, DEVICE_REDIRECT_URI, interaction.signal);
34352
+ }
34353
+ async function loginOpenAICodex(interaction, options) {
34354
+ const { verifier, state, url: url2 } = await createAuthorizationFlow(options?.agentName);
34355
+ const callback = await startOAuthCallbackServer({
34356
+ providerName: "OpenAI",
34357
+ host: getCallbackHost(),
34358
+ port: 1455,
34359
+ path: "/auth/callback",
34360
+ state,
34361
+ complete: async (code) => code,
34362
+ signal: interaction.signal
34363
+ }).catch(() => void 0);
34364
+ interaction.notify({
34365
+ type: "auth_url",
34366
+ url: url2,
34367
+ instructions: "A browser window should open. Complete login to finish."
34368
+ });
34369
+ try {
34370
+ const result = await waitForCallbackOrManualInput(interaction, callback, {
34371
+ message: "Complete login in your browser, or paste the authorization code / redirect URL here:",
34372
+ placeholder: REDIRECT_URI3
34373
+ });
34374
+ let code;
34375
+ if (result.type === "callback") {
34376
+ code = result.value;
34377
+ } else {
34378
+ const parsed = parseAuthorizationInput2(result.input);
34379
+ if (parsed.state && parsed.state !== state)
34380
+ throw new Error("State mismatch");
34381
+ code = parsed.code;
34382
+ }
34383
+ if (!code)
34384
+ throw new Error("Missing authorization code");
34385
+ return await exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI3, interaction.signal);
34386
+ } finally {
34387
+ callback?.close();
34388
+ }
34389
+ }
34390
+ async function refreshOpenAICodexToken(refreshToken2, signal) {
34391
+ return credentialsFromToken(await refreshAccessToken2(refreshToken2, signal));
34392
+ }
34393
+ var openaiCodexOAuth = {
34394
+ name: "OpenAI (ChatGPT Plus/Pro)",
34395
+ isSubscription: true,
34396
+ async login(interaction, options) {
34397
+ const method = await interaction.prompt({
34398
+ type: "select",
34399
+ message: "Select OpenAI Codex login method:",
34400
+ options: [
34401
+ { id: OPENAI_CODEX_BROWSER_LOGIN_METHOD, label: "Browser login (default)" },
34402
+ { id: OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD, label: "Device code login (headless)" }
34403
+ ]
34404
+ });
34405
+ if (method === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) {
34406
+ return loginOpenAICodexDeviceCode(interaction);
34407
+ }
34408
+ if (method !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {
34409
+ throw new Error(`Unknown OpenAI Codex login method: ${method}`);
34410
+ }
34411
+ return loginOpenAICodex(interaction, options);
34412
+ },
34413
+ refresh: (credential, signal) => refreshOpenAICodexToken(credential.refresh, signal),
34414
+ async toAuth(credential) {
34415
+ return { apiKey: credential.access };
34416
+ }
34417
+ };
34418
+
34419
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/openrouter.js
34420
+ var AUTHORIZE_URL4 = "https://openrouter.ai/auth";
34421
+ var TOKEN_URL4 = "https://openrouter.ai/api/v1/auth/keys";
34422
+ var LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
34423
+ var TOKEN_EXCHANGE_TIMEOUT_MS = 3e4;
34424
+ function getCallbackHost2() {
34425
+ return getProviderEnvValue("PI_OAUTH_CALLBACK_HOST") || "127.0.0.1";
34426
+ }
34427
+ function parseAuthorizationInput3(input2) {
34428
+ const value = input2.trim();
34429
+ if (!value)
34430
+ return void 0;
34431
+ try {
34432
+ return new URL(value).searchParams.get("code") ?? void 0;
34433
+ } catch {
34434
+ }
34435
+ if (value.includes("code=")) {
34436
+ return new URLSearchParams(value).get("code") ?? void 0;
34437
+ }
34438
+ return value;
34439
+ }
34440
+ function errorDetail2(body) {
34441
+ if (typeof body.error_description === "string")
34442
+ return body.error_description;
34443
+ if (typeof body.message === "string")
34444
+ return body.message;
34445
+ if (typeof body.error === "string")
34446
+ return body.error;
34447
+ if (body.error && typeof body.error === "object" && !Array.isArray(body.error)) {
34448
+ const message = body.error.message;
34449
+ if (typeof message === "string")
34450
+ return message;
34451
+ }
34452
+ return void 0;
34453
+ }
34454
+ async function exchangeAuthorizationCode4(code, verifier, signal) {
34455
+ if (signal.aborted)
34456
+ throw new Error("Login cancelled");
34457
+ const controller = new AbortController();
34458
+ const onAbort = () => controller.abort(signal.reason);
34459
+ signal.addEventListener("abort", onAbort, { once: true });
34460
+ const timeout = setTimeout(() => controller.abort(new Error("OpenRouter OAuth token exchange timed out")), TOKEN_EXCHANGE_TIMEOUT_MS);
34461
+ let response;
34462
+ let body = {};
34463
+ try {
34464
+ response = await fetch(TOKEN_URL4, {
34465
+ method: "POST",
34466
+ headers: { accept: "application/json", "content-type": "application/json" },
34467
+ body: JSON.stringify({ code, code_verifier: verifier, code_challenge_method: "S256" }),
34468
+ signal: controller.signal
34469
+ });
34470
+ try {
34471
+ const parsed = await response.json();
34472
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
34473
+ body = parsed;
34474
+ } catch {
34475
+ if (response.ok)
34476
+ throw new Error("OpenRouter OAuth returned invalid JSON");
34477
+ }
34478
+ } catch (error63) {
34479
+ if (signal.aborted)
34480
+ throw new Error("Login cancelled");
34481
+ if (controller.signal.aborted)
34482
+ throw new Error("OpenRouter OAuth token exchange timed out");
34483
+ throw error63;
34484
+ } finally {
34485
+ clearTimeout(timeout);
34486
+ signal.removeEventListener("abort", onAbort);
34487
+ }
34488
+ if (!response.ok) {
34489
+ const detail = errorDetail2(body);
34490
+ throw new Error(`OpenRouter OAuth key exchange failed (HTTP ${response.status})${detail ? `: ${detail}` : ""}`);
34491
+ }
34492
+ if (typeof body.key !== "string" || body.key.length === 0) {
34493
+ throw new Error('OpenRouter OAuth response carries no "key"');
34494
+ }
34495
+ return {
34496
+ type: "oauth",
34497
+ access: body.key,
34498
+ refresh: "",
34499
+ expires: Number.MAX_SAFE_INTEGER
34500
+ };
34501
+ }
34502
+ async function loginOpenRouter(interaction) {
34503
+ const { verifier, challenge } = await generatePKCE();
34504
+ const callback = await startOAuthCallbackServer({
34505
+ providerName: "OpenRouter",
34506
+ host: getCallbackHost2(),
34507
+ port: 0,
34508
+ path: `/oauth/callback/${crypto.randomUUID()}`,
34509
+ complete: (code) => exchangeAuthorizationCode4(code, verifier, interaction.signal),
34510
+ signal: interaction.signal,
34511
+ timeoutMs: LOGIN_TIMEOUT_MS
34512
+ });
34513
+ try {
34514
+ const authorizeUrl = new URL(AUTHORIZE_URL4);
34515
+ authorizeUrl.search = new URLSearchParams({
34516
+ callback_url: callback.redirectUri,
34517
+ code_challenge: challenge,
34518
+ code_challenge_method: "S256"
34519
+ }).toString();
34520
+ interaction.notify({
34521
+ type: "progress",
34522
+ message: `Listening for OpenRouter OAuth callback on ${callback.redirectUri}`
34523
+ });
34524
+ interaction.notify({
34525
+ type: "auth_url",
34526
+ url: authorizeUrl.toString(),
34527
+ instructions: "Complete sign-in in your browser. If the browser is on another machine, paste the final redirect URL here."
34528
+ });
34529
+ const result = await waitForCallbackOrManualInput(interaction, callback, {
34530
+ message: "Complete sign-in in your browser, or paste the authorization code / redirect URL here:",
34531
+ placeholder: callback.redirectUri
34532
+ });
34533
+ if (result.type === "callback")
34534
+ return result.value;
34535
+ const code = parseAuthorizationInput3(result.input);
34536
+ if (!code)
34537
+ throw new Error("Missing authorization code");
34538
+ interaction.notify({ type: "progress", message: "Exchanging authorization code for an API key..." });
34539
+ return await exchangeAuthorizationCode4(code, verifier, interaction.signal);
34540
+ } finally {
34541
+ callback.close();
34542
+ }
34543
+ }
34544
+ var openRouterOAuth = {
34545
+ name: "OpenRouter OAuth",
34546
+ loginLabel: "Sign in with OpenRouter",
34547
+ login: loginOpenRouter,
34548
+ async refresh(credential, _signal) {
34549
+ return credential;
34550
+ },
34551
+ async toAuth(credential) {
34552
+ return { apiKey: credential.access };
34553
+ }
34554
+ };
34555
+
34556
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/radius.js
34557
+ var CALLBACK_HOST3 = "127.0.0.1";
34558
+ var CALLBACK_PORT3 = 1456;
34559
+ var CALLBACK_PATH3 = "/oauth/callback";
34560
+ var REDIRECT_URI4 = `http://${CALLBACK_HOST3}:${CALLBACK_PORT3}${CALLBACK_PATH3}`;
34561
+ var TOKEN_EXPIRY_SKEW_MS = 6e4;
34562
+ var LOGIN_METHOD_BROWSER = "browser";
34563
+ var LOGIN_METHOD_DEVICE_CODE = "device-code";
34564
+ var OAUTH_CLIENT_ID = "pi-gateway";
34565
+ var OAUTH_SCOPE = "gateway offline_access";
34566
+ var OAUTH_DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
34567
+ async function loadRadiusOAuthDiscovery(gateway, signal) {
34568
+ const response = await fetch(new URL("/v1/oauth", gateway), {
34569
+ headers: { accept: "application/json" },
34570
+ signal
34571
+ });
34572
+ if (!response.ok) {
34573
+ throw new Error(`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`);
34574
+ }
34575
+ const discovery = await response.json();
34576
+ if (typeof discovery.authorizationEndpoint !== "string") {
34577
+ throw new Error(`Invalid Radius OAuth config from ${gateway}`);
34578
+ }
34579
+ return { authorizationEndpoint: discovery.authorizationEndpoint };
34580
+ }
34581
+ var OAuthResponseError = class extends Error {
34582
+ status;
34583
+ oauthError;
34584
+ constructor(status, oauthError, description, message) {
34585
+ const detail = oauthError ? description ? `${oauthError}: ${description}` : oauthError : description || String(status);
34586
+ super(`${message}: ${detail}`);
34587
+ this.status = status;
34588
+ this.oauthError = oauthError;
34589
+ }
34590
+ };
34591
+ async function readOAuthResponseError(response, message) {
34592
+ const text2 = await response.text().catch(() => "");
34593
+ let oauthError;
34594
+ let description;
34595
+ if (text2) {
34596
+ try {
34597
+ const data = JSON.parse(text2);
34598
+ oauthError = typeof data.error === "string" ? data.error : void 0;
34599
+ description = typeof data.error_description === "string" ? data.error_description : void 0;
34600
+ } catch {
34601
+ description = text2;
34602
+ }
34603
+ }
34604
+ return new OAuthResponseError(response.status, oauthError, description, message);
34605
+ }
34606
+ async function requestOAuthToken(gateway, body, signal) {
34607
+ let response;
34608
+ try {
34609
+ response = await fetch(new URL("/v1/oauth/token", gateway), {
34610
+ method: "POST",
34611
+ headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded" },
34612
+ body,
34613
+ signal
34614
+ });
34615
+ } catch (error63) {
34616
+ if (signal.aborted) {
34617
+ throw new Error("Login cancelled");
34618
+ }
34619
+ throw error63;
34620
+ }
34621
+ if (!response.ok) {
34622
+ throw await readOAuthResponseError(response, "Radius OAuth token request failed");
34623
+ }
34624
+ const data = await response.json();
34625
+ return {
34626
+ type: "oauth",
34627
+ access: data.access_token,
34628
+ refresh: data.refresh_token,
34629
+ expires: Date.now() + data.expires_in * 1e3 - TOKEN_EXPIRY_SKEW_MS,
34630
+ scope: data.scope
34631
+ };
34632
+ }
34633
+ async function loginWithBrowser(gateway, authorizationEndpoint, interaction) {
34634
+ const { verifier, challenge } = await generatePKCE();
34635
+ const state = crypto.randomUUID();
34636
+ const authorizeUrl = new URL(authorizationEndpoint);
34637
+ authorizeUrl.search = new URLSearchParams({
34638
+ response_type: "code",
34639
+ client_id: OAUTH_CLIENT_ID,
34640
+ redirect_uri: REDIRECT_URI4,
34641
+ scope: OAUTH_SCOPE,
34642
+ code_challenge: challenge,
34643
+ code_challenge_method: "S256",
34644
+ handoff: "url",
34645
+ state
34646
+ }).toString();
34647
+ const callback = await startOAuthCallbackServer({
34648
+ providerName: "Radius",
34649
+ host: CALLBACK_HOST3,
34650
+ port: CALLBACK_PORT3,
34651
+ path: CALLBACK_PATH3,
34652
+ state,
34653
+ complete: (code) => requestOAuthToken(gateway, new URLSearchParams({
34654
+ grant_type: "authorization_code",
34655
+ client_id: OAUTH_CLIENT_ID,
34656
+ redirect_uri: REDIRECT_URI4,
34657
+ code,
34658
+ code_verifier: verifier
34659
+ }), interaction.signal),
34660
+ signal: interaction.signal
34661
+ });
34662
+ interaction.notify({ type: "progress", message: `Listening for OAuth callback on ${REDIRECT_URI4}` });
34663
+ interaction.notify({
34664
+ type: "auth_url",
34665
+ url: authorizeUrl.toString(),
34666
+ instructions: "Continue in your browser."
34667
+ });
34668
+ try {
34669
+ const credential = await callback.wait();
34670
+ if (!credential)
34671
+ throw new Error("OAuth callback did not complete.");
34672
+ return credential;
34673
+ } finally {
34674
+ callback.close();
34675
+ }
34676
+ }
34677
+ async function requestDeviceAuthorization(gateway, signal) {
34678
+ let response;
34679
+ try {
34680
+ response = await fetch(new URL("/v1/oauth/device", gateway), {
34681
+ method: "POST",
34682
+ headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded" },
34683
+ body: new URLSearchParams({ client_id: OAUTH_CLIENT_ID, scope: OAUTH_SCOPE }),
34684
+ signal
34685
+ });
34686
+ } catch (error63) {
34687
+ if (signal.aborted) {
34688
+ throw new Error("Login cancelled");
34689
+ }
34690
+ throw error63;
34691
+ }
34692
+ if (!response.ok) {
34693
+ throw await readOAuthResponseError(response, "Radius OAuth device authorization failed");
34694
+ }
34695
+ const data = await response.json();
34696
+ if (!data.device_code || !data.user_code || !data.verification_uri || !data.expires_in) {
34697
+ throw new Error("Radius OAuth device authorization response is missing required fields");
34698
+ }
34699
+ return {
34700
+ device_code: data.device_code,
34701
+ user_code: data.user_code,
34702
+ verification_uri: data.verification_uri,
34703
+ expires_in: data.expires_in,
34704
+ interval: data.interval
34705
+ };
34706
+ }
34707
+ async function loginWithDeviceCode(gateway, interaction) {
34708
+ const device = await requestDeviceAuthorization(gateway, interaction.signal);
34709
+ interaction.notify({
34710
+ type: "device_code",
34711
+ userCode: device.user_code,
34712
+ verificationUri: device.verification_uri,
34713
+ intervalSeconds: device.interval,
34714
+ expiresInSeconds: device.expires_in
34715
+ });
34716
+ return pollOAuthDeviceCodeFlow({
34717
+ intervalSeconds: device.interval,
34718
+ expiresInSeconds: device.expires_in,
34719
+ signal: interaction.signal,
34720
+ poll: async () => {
34721
+ try {
34722
+ const credentials = await requestOAuthToken(gateway, new URLSearchParams({
34723
+ grant_type: OAUTH_DEVICE_CODE_GRANT_TYPE,
34724
+ client_id: OAUTH_CLIENT_ID,
34725
+ device_code: device.device_code
34726
+ }), interaction.signal);
34727
+ return { status: "complete", value: credentials };
34728
+ } catch (error63) {
34729
+ if (!(error63 instanceof OAuthResponseError)) {
34730
+ throw error63;
34731
+ }
34732
+ switch (error63.oauthError) {
34733
+ case "authorization_pending":
34734
+ return { status: "pending" };
34735
+ case "slow_down":
34736
+ return { status: "slow_down" };
34737
+ case "expired_token":
34738
+ return { status: "failed", message: "Device authorization expired." };
34739
+ case "access_denied":
34740
+ return { status: "failed", message: "Device authorization was denied." };
34741
+ default:
34742
+ throw error63;
34743
+ }
34744
+ }
34745
+ }
34746
+ });
34747
+ }
34748
+ function createRadiusOAuth(options) {
34749
+ const gateway = normalizeRadiusGatewayUrl(options.gateway);
34750
+ return {
34751
+ name: options.name,
34752
+ async login(interaction) {
34753
+ const loginMethod = await interaction.prompt({
34754
+ type: "select",
34755
+ message: `Sign in to ${options.name}:`,
34756
+ options: [
34757
+ { id: LOGIN_METHOD_BROWSER, label: "Sign in with browser (recommended)" },
34758
+ {
34759
+ id: LOGIN_METHOD_DEVICE_CODE,
34760
+ label: "Sign in with device code (when signing in from another device)"
34761
+ }
34762
+ ]
34763
+ });
34764
+ if (loginMethod === LOGIN_METHOD_DEVICE_CODE) {
34765
+ return loginWithDeviceCode(gateway, interaction);
34766
+ }
34767
+ if (loginMethod === LOGIN_METHOD_BROWSER) {
34768
+ const discovery = await loadRadiusOAuthDiscovery(gateway, interaction.signal);
34769
+ return loginWithBrowser(gateway, discovery.authorizationEndpoint, interaction);
34770
+ }
34771
+ throw new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);
34772
+ },
34773
+ async refresh(credential, signal) {
34774
+ const refreshed = await requestOAuthToken(gateway, new URLSearchParams({
34775
+ grant_type: "refresh_token",
34776
+ client_id: OAUTH_CLIENT_ID,
34777
+ refresh_token: credential.refresh
34778
+ }), signal);
34779
+ return refreshed;
34780
+ },
34781
+ async toAuth(credential) {
34782
+ return { apiKey: credential.access };
34783
+ }
34784
+ };
34785
+ }
34786
+
34787
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/auth/oauth/xai.js
34788
+ var XAI_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
34789
+ var XAI_SCOPE = "openid profile email offline_access grok-cli:access api:access";
34790
+ var XAI_DEVICE_CODE_URL = "https://auth.x.ai/oauth2/device/code";
34791
+ var XAI_TOKEN_URL = "https://auth.x.ai/oauth2/token";
34792
+ var REFRESH_SKEW_MS = 5 * 60 * 1e3;
34793
+ var DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;
34794
+ function requiredString(body, field) {
34795
+ const value = body[field];
34796
+ if (typeof value !== "string" || value.length === 0) {
34797
+ throw new Error(`Invalid xAI OAuth response field: ${field}`);
34798
+ }
34799
+ return value;
34800
+ }
34801
+ function positiveNumber2(body, field) {
34802
+ const value = body[field];
34803
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
34804
+ throw new Error(`Invalid xAI OAuth response field: ${field}`);
34805
+ }
34806
+ return value;
34807
+ }
34808
+ function validateVerificationUri(raw) {
34809
+ let url2;
34810
+ try {
34811
+ url2 = new URL(raw);
34812
+ } catch {
34813
+ throw new Error("Untrusted verification URI in xAI OAuth response");
34814
+ }
34815
+ if (url2.protocol !== "https:") {
34816
+ throw new Error("Untrusted verification URI in xAI OAuth response");
34817
+ }
34818
+ return url2.href;
34819
+ }
34820
+ async function postForm(url2, fields, signal) {
34821
+ let response;
34822
+ try {
34823
+ response = await fetch(url2, {
34824
+ method: "POST",
34825
+ headers: {
34826
+ Accept: "application/json",
34827
+ "Content-Type": "application/x-www-form-urlencoded"
34828
+ },
34829
+ body: new URLSearchParams(fields),
34830
+ signal
34831
+ });
34832
+ } catch (error63) {
34833
+ if (signal.aborted) {
34834
+ throw new Error("Login cancelled");
34835
+ }
34836
+ throw error63;
34837
+ }
34838
+ let body;
34839
+ try {
34840
+ const parsed = await response.json();
34841
+ body = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
34842
+ } catch {
34843
+ if (signal.aborted) {
34844
+ throw new Error("Login cancelled");
34845
+ }
34846
+ throw new Error(`xAI OAuth returned invalid JSON (HTTP ${response.status})`);
34847
+ }
34848
+ return {
34849
+ ok: response.ok,
34850
+ status: response.status,
34851
+ body
34852
+ };
34853
+ }
34854
+ function requestFailure(action, response) {
34855
+ const error63 = typeof response.body.error === "string" ? response.body.error : void 0;
34856
+ const description = typeof response.body.error_description === "string" ? response.body.error_description : void 0;
34857
+ const detail = [error63, description].filter(Boolean).join(": ");
34858
+ return new Error(`xAI OAuth ${action} failed (HTTP ${response.status})${detail ? `: ${detail}` : ""}`);
34859
+ }
34860
+ function parseDeviceCode(body) {
34861
+ const interval = body.interval;
34862
+ const intervalSeconds = typeof interval === "number" && Number.isFinite(interval) && interval > 0 ? interval : void 0;
34863
+ const verificationUriComplete = typeof body.verification_uri_complete === "string" && body.verification_uri_complete.length > 0 ? validateVerificationUri(body.verification_uri_complete) : void 0;
34864
+ return {
34865
+ deviceCode: requiredString(body, "device_code"),
34866
+ userCode: requiredString(body, "user_code"),
34867
+ verificationUri: validateVerificationUri(requiredString(body, "verification_uri")),
34868
+ verificationUriComplete,
34869
+ intervalSeconds,
34870
+ expiresInSeconds: positiveNumber2(body, "expires_in")
34871
+ };
34872
+ }
34873
+ function credentialsFromTokenResponse(body, previousRefreshToken) {
34874
+ const access6 = requiredString(body, "access_token");
34875
+ const refresh = body.refresh_token === void 0 && previousRefreshToken ? previousRefreshToken : requiredString(body, "refresh_token");
34876
+ const expiresInSeconds = body.expires_in === void 0 ? DEFAULT_TOKEN_LIFETIME_SECONDS : positiveNumber2(body, "expires_in");
34877
+ return {
34878
+ type: "oauth",
34879
+ access: access6,
34880
+ refresh,
34881
+ expires: Date.now() + expiresInSeconds * 1e3 - REFRESH_SKEW_MS
34882
+ };
34883
+ }
34884
+ async function requestDeviceCode(signal) {
34885
+ const response = await postForm(XAI_DEVICE_CODE_URL, {
34886
+ client_id: XAI_CLIENT_ID,
34887
+ scope: XAI_SCOPE,
34888
+ referrer: "pi"
34889
+ }, signal);
34890
+ if (!response.ok) {
34891
+ throw requestFailure("device authorization", response);
34892
+ }
34893
+ return parseDeviceCode(response.body);
34894
+ }
34895
+ async function pollForTokens(device, signal) {
34896
+ return pollOAuthDeviceCodeFlow({
34897
+ intervalSeconds: device.intervalSeconds,
34898
+ expiresInSeconds: device.expiresInSeconds,
34899
+ waitBeforeFirstPoll: true,
34900
+ signal,
34901
+ poll: async () => {
34902
+ const response = await postForm(XAI_TOKEN_URL, {
34903
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
34904
+ client_id: XAI_CLIENT_ID,
34905
+ device_code: device.deviceCode
34906
+ }, signal);
34907
+ if (response.ok) {
34908
+ return { status: "complete", value: credentialsFromTokenResponse(response.body) };
34909
+ }
34910
+ const error63 = response.body.error;
34911
+ if (error63 === "authorization_pending") {
34912
+ return { status: "pending" };
34913
+ }
34914
+ if (error63 === "slow_down") {
34915
+ const interval = response.body.interval;
34916
+ return { status: "slow_down", intervalSeconds: typeof interval === "number" ? interval : void 0 };
34917
+ }
34918
+ if (error63 === "access_denied" || error63 === "authorization_denied") {
34919
+ return { status: "failed", message: "xAI device authorization was denied" };
34920
+ }
34921
+ if (error63 === "expired_token") {
34922
+ return { status: "failed", message: "xAI device code expired" };
34923
+ }
34924
+ return { status: "failed", message: requestFailure("device token polling", response).message };
34925
+ }
34926
+ });
34927
+ }
34928
+ async function loginXai(interaction) {
34929
+ const device = await requestDeviceCode(interaction.signal);
34930
+ interaction.notify({
34931
+ type: "device_code",
34932
+ userCode: device.userCode,
34933
+ verificationUri: device.verificationUriComplete ?? device.verificationUri,
34934
+ intervalSeconds: device.intervalSeconds,
34935
+ expiresInSeconds: device.expiresInSeconds
34936
+ });
34937
+ return pollForTokens(device, interaction.signal);
34938
+ }
34939
+ async function refreshXaiToken(refreshToken2, signal) {
34940
+ const response = await postForm(XAI_TOKEN_URL, {
34941
+ grant_type: "refresh_token",
34942
+ client_id: XAI_CLIENT_ID,
34943
+ refresh_token: refreshToken2
34944
+ }, signal);
34945
+ if (!response.ok) {
34946
+ throw requestFailure("token refresh", response);
34947
+ }
34948
+ return credentialsFromTokenResponse(response.body, refreshToken2);
34949
+ }
34950
+ var xaiOAuth = {
34951
+ name: "xAI (Grok/X subscription)",
34952
+ isSubscription: true,
34953
+ loginLabel: "Sign in with SuperGrok or X Premium",
34954
+ login: loginXai,
34955
+ refresh: (credential, signal) => refreshXaiToken(credential.refresh, signal),
34956
+ async toAuth(credential) {
34957
+ return { apiKey: credential.access };
34958
+ }
34959
+ };
34960
+
34961
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.4.0_@aws-sdk+credential-provider-node@3.972.83_@smithy+signatur_c4dd529f1cf5cdf12d9a6e2070ccac62/node_modules/@earendil-works/pi-ai/dist/bun-oauth.js
34962
+ function registerBunOAuthFlows() {
34963
+ registerBundledOAuthFlowLoaders({
34964
+ anthropic: () => anthropicOAuth,
34965
+ openaiCodex: () => openaiCodexOAuth,
34966
+ openaiChatGPT: () => openaiChatGPTOAuth,
34967
+ githubCopilot: () => githubCopilotOAuth,
34968
+ openrouter: () => openRouterOAuth,
34969
+ kimiCoding: () => kimiCodingOAuth,
34970
+ meta: () => metaOAuth,
34971
+ xai: () => xaiOAuth,
34972
+ radius: createRadiusOAuth
34973
+ });
34974
+ }
34975
+
34976
+ // packages/harness/dist/models/pi-ai-bundle-support.js
34977
+ registerBunOAuthFlows();
34978
+ setBedrockProviderModule(lazyApi(async () => (await import("./chunk-KAZFF2RD.js")).bedrockProviderModule));
34979
+
32561
34980
  // packages/harness/dist/models/model-registry.js
32562
34981
  var models = builtinModels();
32563
34982
  var builtinProviderIds = new Set(models.getProviders().map((provider) => provider.id));
@@ -34680,7 +37099,7 @@ var storageInfoSchema = external_exports.object({
34680
37099
  });
34681
37100
 
34682
37101
  // packages/workbench-server/dist/infrastructure/storage-bootstrap/file-mutations.js
34683
- import { randomBytes } from "node:crypto";
37102
+ import { randomBytes as randomBytes2 } from "node:crypto";
34684
37103
  import { mkdir as mkdir2, open as open2, rename, rm as rm2 } from "node:fs/promises";
34685
37104
  import path from "node:path";
34686
37105
  var RENAME_ATTEMPTS = 8;
@@ -34761,7 +37180,7 @@ function isRetriableRenameError(error63) {
34761
37180
  }
34762
37181
  function temporaryFilePath(filePath) {
34763
37182
  temporaryFileCounter += 1;
34764
- return path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${temporaryFileCounter}.${randomBytes(4).toString("hex")}.tmp`);
37183
+ return path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${temporaryFileCounter}.${randomBytes2(4).toString("hex")}.tmp`);
34765
37184
  }
34766
37185
  function errorCode(error63) {
34767
37186
  return typeof error63 === "object" && error63 !== null && "code" in error63 ? String(error63.code) : void 0;
@@ -35954,15 +38373,15 @@ function Get2() {
35954
38373
 
35955
38374
  // node_modules/.pnpm/typebox@1.3.7/node_modules/typebox/build/type/types/_codec.mjs
35956
38375
  var EncodeBuilder = class {
35957
- constructor(type, decode3) {
38376
+ constructor(type, decode5) {
35958
38377
  this.type = type;
35959
- this.decode = decode3;
38378
+ this.decode = decode5;
35960
38379
  }
35961
38380
  Encode(callback) {
35962
38381
  const type = this.type;
35963
- const decode3 = IsCodec(type) ? (value) => this.decode(type["~codec"].decode(value)) : this.decode;
38382
+ const decode5 = IsCodec(type) ? (value) => this.decode(type["~codec"].decode(value)) : this.decode;
35964
38383
  const encode3 = IsCodec(type) ? (value) => type["~codec"].encode(callback(value)) : callback;
35965
- const codec2 = { decode: decode3, encode: encode3 };
38384
+ const codec2 = { decode: decode5, encode: encode3 };
35966
38385
  return memory_exports.Update(this.type, { "~codec": codec2 }, {});
35967
38386
  }
35968
38387
  };
@@ -41975,7 +44394,7 @@ function isRecord2(value) {
41975
44394
  }
41976
44395
 
41977
44396
  // packages/tools/dist/execution/atlassian/arguments.js
41978
- function requiredString(value, name2) {
44397
+ function requiredString2(value, name2) {
41979
44398
  if (typeof value !== "string" || value.trim().length === 0) {
41980
44399
  throw new Error(`${name2} must be a non-empty string.`);
41981
44400
  }
@@ -42405,13 +44824,13 @@ function displayLimitNotice({ noun, total, displayed, artifactPath }) {
42405
44824
  return artifactPath ? `Showing first ${displayed} of ${total} ${plural2}; full Confluence response is saved to ${artifactPath}.` : `Showing first ${displayed} of ${total} ${plural2}; narrow the query or save raw JSON for full details.`;
42406
44825
  }
42407
44826
  function summarizeConfluenceSpace(value) {
42408
- const record5 = asRecord(value);
44827
+ const record5 = asRecord2(value);
42409
44828
  if (!record5)
42410
44829
  return void 0;
42411
44830
  const id = stringField(record5.id);
42412
44831
  if (!id)
42413
44832
  return void 0;
42414
- const homepage = asRecord(record5.homepage);
44833
+ const homepage = asRecord2(record5.homepage);
42415
44834
  return compactRecord2({
42416
44835
  id,
42417
44836
  key: truncateField(stringField(record5.key)),
@@ -42422,18 +44841,18 @@ function summarizeConfluenceSpace(value) {
42422
44841
  });
42423
44842
  }
42424
44843
  function summarizeConfluencePage(value) {
42425
- const record5 = asRecord(value);
44844
+ const record5 = asRecord2(value);
42426
44845
  if (!record5)
42427
44846
  return void 0;
42428
- const content = asRecord(record5.content);
44847
+ const content = asRecord2(record5.content);
42429
44848
  const source = content ?? record5;
42430
44849
  const id = stringField(source.id);
42431
44850
  if (!id)
42432
44851
  return void 0;
42433
- const space = asRecord(source.space);
42434
- const version2 = asRecord(source.version);
42435
- const links = asRecord(source.links) ?? asRecord(source._links);
42436
- const parent = asRecord(source.parent);
44852
+ const space = asRecord2(source.space);
44853
+ const version2 = asRecord2(source.version);
44854
+ const links = asRecord2(source.links) ?? asRecord2(source._links);
44855
+ const parent = asRecord2(source.parent);
42437
44856
  const ancestors = Array.isArray(source.ancestors) ? source.ancestors : void 0;
42438
44857
  const lastAncestor = ancestors?.at(-1);
42439
44858
  return compactRecord2({
@@ -42441,7 +44860,7 @@ function summarizeConfluencePage(value) {
42441
44860
  title: truncateField(stringField(source.title)),
42442
44861
  spaceId: stringField(source.spaceId) ?? stringField(space?.id),
42443
44862
  spaceKey: truncateField(stringField(source.spaceKey) ?? stringField(space?.key)),
42444
- parentId: stringField(source.parentId) ?? stringField(parent?.id) ?? stringField(asRecord(lastAncestor)?.id),
44863
+ parentId: stringField(source.parentId) ?? stringField(parent?.id) ?? stringField(asRecord2(lastAncestor)?.id),
42445
44864
  status: truncateField(stringField(source.status)),
42446
44865
  versionNumber: numberField(version2?.number ?? source.versionNumber),
42447
44866
  created: truncateField(stringField(source.createdAt)),
@@ -42454,12 +44873,12 @@ function summarizeConfluencePage(value) {
42454
44873
  });
42455
44874
  }
42456
44875
  function summarizeConfluenceAttachment(value) {
42457
- const record5 = asRecord(value);
44876
+ const record5 = asRecord2(value);
42458
44877
  if (!record5)
42459
44878
  return void 0;
42460
44879
  const id = stringField(record5.id);
42461
44880
  const fileId = stringField(record5.fileId);
42462
- const version2 = asRecord(record5.version);
44881
+ const version2 = asRecord2(record5.version);
42463
44882
  const filename = stringField(record5.filename) ?? stringField(record5.title) ?? stringField(record5.name) ?? stringField(record5.fileName);
42464
44883
  if (!id && !fileId && !filename)
42465
44884
  return void 0;
@@ -42477,13 +44896,13 @@ function summarizeConfluenceAttachment(value) {
42477
44896
  });
42478
44897
  }
42479
44898
  function summarizeConfluenceComment(value, kind) {
42480
- const record5 = asRecord(value);
44899
+ const record5 = asRecord2(value);
42481
44900
  if (!record5)
42482
44901
  return void 0;
42483
- const version2 = asRecord(record5.version);
42484
- const body = asRecord(record5.body);
42485
- const storage = asRecord(body?.storage);
42486
- const author = asRecord(record5.author);
44902
+ const version2 = asRecord2(record5.version);
44903
+ const body = asRecord2(record5.body);
44904
+ const storage = asRecord2(body?.storage);
44905
+ const author = asRecord2(record5.author);
42487
44906
  const id = stringField(record5.id);
42488
44907
  if (!id && Object.keys(record5).length === 0)
42489
44908
  return void 0;
@@ -42498,10 +44917,10 @@ function summarizeConfluenceComment(value, kind) {
42498
44917
  });
42499
44918
  }
42500
44919
  function summarizeConfluenceProperty(value) {
42501
- const record5 = asRecord(value);
44920
+ const record5 = asRecord2(value);
42502
44921
  if (!record5)
42503
44922
  return void 0;
42504
- const version2 = asRecord(record5.version);
44923
+ const version2 = asRecord2(record5.version);
42505
44924
  const key2 = stringField(record5.key) ?? stringField(record5.name);
42506
44925
  if (!key2)
42507
44926
  return void 0;
@@ -42528,7 +44947,7 @@ function collectPropertyScalars(value, path2, output3, depth) {
42528
44947
  value.slice(0, 3).forEach((item, index) => collectPropertyScalars(item, path2 ? `${path2}[${index}]` : String(index), output3, depth + 1));
42529
44948
  return;
42530
44949
  }
42531
- const record5 = asRecord(value);
44950
+ const record5 = asRecord2(value);
42532
44951
  if (!record5)
42533
44952
  return;
42534
44953
  for (const [key2, item] of Object.entries(record5).slice(0, 6)) {
@@ -42538,7 +44957,7 @@ function collectPropertyScalars(value, path2, output3, depth) {
42538
44957
  function summarizeConfluenceLabel(value) {
42539
44958
  if (typeof value === "string")
42540
44959
  return { name: truncateField(value) ?? value };
42541
- const record5 = asRecord(value);
44960
+ const record5 = asRecord2(value);
42542
44961
  if (!record5)
42543
44962
  return void 0;
42544
44963
  const name2 = stringField(record5.name) ?? stringField(record5.label);
@@ -42552,11 +44971,11 @@ function summarizeConfluenceLabel(value) {
42552
44971
  function summarizeConfluenceRestrictions(value) {
42553
44972
  const records = valuesFromConfluenceList(value);
42554
44973
  return records.flatMap((item) => {
42555
- const record5 = asRecord(item);
44974
+ const record5 = asRecord2(item);
42556
44975
  const operation = stringField(record5?.operation) ?? stringField(record5?.key);
42557
44976
  if (operation !== "read" && operation !== "update")
42558
44977
  return [];
42559
- const restrictions = asRecord(record5?.restrictions);
44978
+ const restrictions = asRecord2(record5?.restrictions);
42560
44979
  const users = valuesFromConfluenceList(restrictions?.user);
42561
44980
  const groups = valuesFromConfluenceList(restrictions?.group);
42562
44981
  const subjects = [
@@ -42566,7 +44985,7 @@ function summarizeConfluenceRestrictions(value) {
42566
44985
  if (subjects.length === 0)
42567
44986
  return [{ operation }];
42568
44987
  return subjects.map(({ subject, subjectType }) => {
42569
- const subjectRecord = asRecord(subject);
44988
+ const subjectRecord = asRecord2(subject);
42570
44989
  return compactRecord2({
42571
44990
  operation,
42572
44991
  subjectType,
@@ -42597,7 +45016,7 @@ function formatPageSummaryLine(summary) {
42597
45016
  function valuesFromConfluenceList(value) {
42598
45017
  if (Array.isArray(value))
42599
45018
  return value;
42600
- const record5 = asRecord(value);
45019
+ const record5 = asRecord2(value);
42601
45020
  if (!record5)
42602
45021
  return [];
42603
45022
  if (Array.isArray(record5.results))
@@ -42607,8 +45026,8 @@ function valuesFromConfluenceList(value) {
42607
45026
  return [];
42608
45027
  }
42609
45028
  function nextCursorFromResponse(value) {
42610
- const record5 = asRecord(value);
42611
- const links = asRecord(record5?._links) ?? asRecord(record5?.links);
45029
+ const record5 = asRecord2(value);
45030
+ const links = asRecord2(record5?._links) ?? asRecord2(record5?.links);
42612
45031
  const next = stringField(links?.next);
42613
45032
  if (!next)
42614
45033
  return stringField(record5?.nextCursor);
@@ -42620,7 +45039,7 @@ function nextCursorFromResponse(value) {
42620
45039
  }
42621
45040
  }
42622
45041
  function extractBodyValue(page2) {
42623
- const body = asRecord(asRecord(page2)?.body);
45042
+ const body = asRecord2(asRecord2(page2)?.body);
42624
45043
  if (!body)
42625
45044
  return void 0;
42626
45045
  const direct = stringField(body.value);
@@ -42635,7 +45054,7 @@ function extractBodyValue(page2) {
42635
45054
  "styled_view",
42636
45055
  "editor"
42637
45056
  ]) {
42638
- const nested = asRecord(body[key2]);
45057
+ const nested = asRecord2(body[key2]);
42639
45058
  const value = stringField(nested?.value);
42640
45059
  if (value !== void 0)
42641
45060
  return value;
@@ -42643,7 +45062,7 @@ function extractBodyValue(page2) {
42643
45062
  return void 0;
42644
45063
  }
42645
45064
  function extractBodyRepresentation(page2, fallback = "storage") {
42646
- const body = asRecord(asRecord(page2)?.body);
45065
+ const body = asRecord2(asRecord2(page2)?.body);
42647
45066
  if (!body)
42648
45067
  return fallback;
42649
45068
  const direct = stringField(body.representation);
@@ -42658,7 +45077,7 @@ function extractBodyRepresentation(page2, fallback = "storage") {
42658
45077
  "styled_view",
42659
45078
  "editor"
42660
45079
  ]) {
42661
- if (asRecord(body[key2]))
45080
+ if (asRecord2(body[key2]))
42662
45081
  return key2;
42663
45082
  }
42664
45083
  return fallback;
@@ -42686,7 +45105,7 @@ function stringField(value) {
42686
45105
  function numberField(value) {
42687
45106
  return typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : void 0;
42688
45107
  }
42689
- function asRecord(value) {
45108
+ function asRecord2(value) {
42690
45109
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
42691
45110
  }
42692
45111
  function compactRecord2(record5) {
@@ -42986,10 +45405,10 @@ async function writeDownloadBundle(context, options) {
42986
45405
  };
42987
45406
  }
42988
45407
  function pageLinks(page2) {
42989
- const links = asRecord2(page2.links) ?? asRecord2(page2._links);
45408
+ const links = asRecord3(page2.links) ?? asRecord3(page2._links);
42990
45409
  return links ? compactRecord3({ webui: links.webui }) : void 0;
42991
45410
  }
42992
- function asRecord2(value) {
45411
+ function asRecord3(value) {
42993
45412
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
42994
45413
  }
42995
45414
  function compactRecord3(record5) {
@@ -43169,13 +45588,13 @@ function parseJsonRecord(text2, label) {
43169
45588
  } catch (error63) {
43170
45589
  throw new ToolExecutionError("CONFLUENCE_PAGE_FILE_INVALID_JSON", guideErrorMessage(`Invalid JSON in ${label}: ${error63 instanceof Error ? error63.message : String(error63)}`));
43171
45590
  }
43172
- const record5 = asRecord(parsed);
45591
+ const record5 = asRecord2(parsed);
43173
45592
  if (!record5)
43174
45593
  throw new ToolExecutionError("CONFLUENCE_PAGE_FILE_INVALID", guideErrorMessage(`${label} must contain a JSON object.`));
43175
45594
  return record5;
43176
45595
  }
43177
45596
  function pageRowBody(row) {
43178
- const body = asRecord(row.body);
45597
+ const body = asRecord2(row.body);
43179
45598
  const value = optionalString(body?.value);
43180
45599
  if (!value)
43181
45600
  return void 0;
@@ -43185,7 +45604,7 @@ function pageRowBody(row) {
43185
45604
  };
43186
45605
  }
43187
45606
  function pageRowVersionNumber(row) {
43188
- const value = asRecord(row.version)?.number;
45607
+ const value = asRecord2(row.version)?.number;
43189
45608
  return typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : void 0;
43190
45609
  }
43191
45610
 
@@ -43333,7 +45752,7 @@ async function resolveBody(args, row, context, options = {}) {
43333
45752
  import { readFile as readFile5 } from "node:fs/promises";
43334
45753
  import { basename as basename4 } from "node:path";
43335
45754
  function actionOf(args) {
43336
- return requiredString(args.action, "action");
45755
+ return requiredString2(args.action, "action");
43337
45756
  }
43338
45757
  function kindPath(kind) {
43339
45758
  return kind === "inline" ? "inline-comments" : "footer-comments";
@@ -43352,8 +45771,8 @@ function dry(context, text2, details) {
43352
45771
  async function executeConfluenceManageComment(args, context) {
43353
45772
  const connection = await requireConfluenceConnection(context);
43354
45773
  const action = actionOf(args);
43355
- const kind = requiredString(args.kind, "kind");
43356
- const pageId = action === "create" ? requiredString(args.page_id, "page_id") : optionalString(args.page_id);
45774
+ const kind = requiredString2(args.kind, "kind");
45775
+ const pageId = action === "create" ? requiredString2(args.page_id, "page_id") : optionalString(args.page_id);
43357
45776
  const commentId = optionalString(args.comment_id);
43358
45777
  if (action !== "create" && !commentId)
43359
45778
  throw new ToolExecutionError("CONFLUENCE_COMMENT_ID_REQUIRED", guideErrorMessage("comment_id is required."));
@@ -43367,7 +45786,7 @@ async function executeConfluenceManageComment(args, context) {
43367
45786
  });
43368
45787
  let payload3;
43369
45788
  if (action === "create" || action === "update") {
43370
- const body = requiredString(args.body, "body");
45789
+ const body = requiredString2(args.body, "body");
43371
45790
  const representation = optionalString(args.body_representation) ?? "storage";
43372
45791
  payload3 = { body: { representation, value: body } };
43373
45792
  if (pageId)
@@ -43426,7 +45845,7 @@ async function executeConfluenceManageComment(args, context) {
43426
45845
  async function executeConfluenceManagePage(args, context) {
43427
45846
  const connection = await requireConfluenceConnection(context);
43428
45847
  const action = actionOf(args);
43429
- const pageId = requiredString(args.page_id, "page_id");
45848
+ const pageId = requiredString2(args.page_id, "page_id");
43430
45849
  const page2 = await confluenceRequest(connection, {
43431
45850
  parse: jsonObject,
43432
45851
  path: `/pages/${pathSegment(pageId)}`,
@@ -43493,8 +45912,8 @@ async function executeConfluenceManagePage(args, context) {
43493
45912
  async function executeConfluenceManageLabel(args, context) {
43494
45913
  const connection = await requireConfluenceConnection(context);
43495
45914
  const action = actionOf(args);
43496
- const pageId = requiredString(args.page_id, "page_id");
43497
- const label = requiredString(args.label, "label");
45915
+ const pageId = requiredString2(args.page_id, "page_id");
45916
+ const label = requiredString2(args.label, "label");
43498
45917
  const prefix = optionalString(args.prefix) ?? "global";
43499
45918
  if (args.dry_run === true)
43500
45919
  return dry(context, `would ${action} label '${label}' on page ${pageId}.`, {
@@ -43545,8 +45964,8 @@ async function executeConfluenceManageLabel(args, context) {
43545
45964
  async function executeConfluenceManageRestriction(args, context) {
43546
45965
  const connection = await requireConfluenceConnection(context);
43547
45966
  const action = actionOf(args);
43548
- const pageId = requiredString(args.page_id, "page_id");
43549
- const operation = requiredString(args.operation, "operation");
45967
+ const pageId = requiredString2(args.page_id, "page_id");
45968
+ const operation = requiredString2(args.operation, "operation");
43550
45969
  const current = await confluenceRequest(connection, {
43551
45970
  api: "v1",
43552
45971
  path: `/content/${pathSegment(pageId)}/restriction/byOperation`,
@@ -43600,7 +46019,7 @@ async function executeConfluenceManageAttachment(args, context) {
43600
46019
  const action = actionOf(args);
43601
46020
  const connection = await requireConfluenceConnection(context);
43602
46021
  if (action === "upload") {
43603
- const pageId2 = requiredString(args.page_id, "page_id");
46022
+ const pageId2 = requiredString2(args.page_id, "page_id");
43604
46023
  const filePath = resolveToolPath(context.cwd, args.file_path);
43605
46024
  const filename = optionalString(args.filename) ?? basename4(filePath);
43606
46025
  const bytes = await readFile5(filePath);
@@ -43650,8 +46069,8 @@ async function executeConfluenceManageAttachment(args, context) {
43650
46069
  }
43651
46070
  });
43652
46071
  }
43653
- const pageId = requiredString(args.page_id, "page_id");
43654
- const attachmentId = requiredString(args.attachment_id, "attachment_id");
46072
+ const pageId = requiredString2(args.page_id, "page_id");
46073
+ const attachmentId = requiredString2(args.attachment_id, "attachment_id");
43655
46074
  const attachment = await confluenceRequest(connection, {
43656
46075
  parse: jsonObject,
43657
46076
  path: `/attachments/${pathSegment(attachmentId)}`,
@@ -43673,7 +46092,7 @@ async function executeConfluenceManageAttachment(args, context) {
43673
46092
  signal: context.signal
43674
46093
  });
43675
46094
  else {
43676
- const newFilename = requiredString(args.new_filename, "new_filename");
46095
+ const newFilename = requiredString2(args.new_filename, "new_filename");
43677
46096
  await confluenceRequest(connection, {
43678
46097
  api: "v1",
43679
46098
  method: "PUT",
@@ -43886,7 +46305,7 @@ async function executeConfluenceSearchPages(args, context) {
43886
46305
  }
43887
46306
  async function executeConfluenceGetPage(args, context) {
43888
46307
  const connection = await requireConfluenceConnection(context);
43889
- const pageId = requiredString(args.page_id, "page_id");
46308
+ const pageId = requiredString2(args.page_id, "page_id");
43890
46309
  const bodyFormat = enumString(args.body_format, PAGE_BODY_FORMATS, "storage");
43891
46310
  const include = enumSet(args.include, [
43892
46311
  "labels",
@@ -44075,7 +46494,7 @@ function formatConfluenceCommentPreview(item) {
44075
46494
  }
44076
46495
  async function executeConfluenceDownloadPage(args, context) {
44077
46496
  const connection = await requireConfluenceConnection(context);
44078
- const pageId = requiredString(args.page_id, "page_id");
46497
+ const pageId = requiredString2(args.page_id, "page_id");
44079
46498
  const bodyFormat = enumString(args.body_format, READ_BODY_FORMATS, "storage");
44080
46499
  const page2 = await confluenceRequest(connection, {
44081
46500
  parse: jsonObject,
@@ -46310,13 +48729,13 @@ async function runRg(args, scope, limit, contextLines, signal) {
46310
48729
  failAndKill(new Error(`ripgrep returned invalid JSON output: ${line.slice(0, 200)}`));
46311
48730
  return;
46312
48731
  }
46313
- const record5 = asRecord3(event);
48732
+ const record5 = asRecord4(event);
46314
48733
  const type = record5?.type;
46315
48734
  if (type !== "match" && type !== "context")
46316
48735
  return;
46317
- const data = asRecord3(record5?.data);
46318
- const pathData = asRecord3(data?.path);
46319
- const linesData = asRecord3(data?.lines);
48736
+ const data = asRecord4(record5?.data);
48737
+ const pathData = asRecord4(data?.path);
48738
+ const linesData = asRecord4(data?.lines);
46320
48739
  const pathText = stringValue(pathData?.text);
46321
48740
  const lineNumber = data?.line_number;
46322
48741
  const text2 = stringValue(linesData?.text)?.replace(/\r?\n$/, "");
@@ -46569,7 +48988,7 @@ function displayPath(displayRoot, path2) {
46569
48988
  function stripDisplayFlag(line) {
46570
48989
  return { path: line.path, line: line.line, text: line.text };
46571
48990
  }
46572
- function asRecord3(value) {
48991
+ function asRecord4(value) {
46573
48992
  return value && typeof value === "object" ? value : void 0;
46574
48993
  }
46575
48994
  function stringValue(value) {
@@ -47404,7 +49823,7 @@ function summarizeJiraIssue(issue2) {
47404
49823
  if (!issue2 || typeof issue2 !== "object")
47405
49824
  return void 0;
47406
49825
  const record5 = issue2;
47407
- const fields = asRecord4(record5.fields);
49826
+ const fields = asRecord5(record5.fields);
47408
49827
  const key2 = stringField2(record5.key) ?? stringField2(record5.id);
47409
49828
  if (!key2)
47410
49829
  return void 0;
@@ -47474,7 +49893,7 @@ function summarizeJiraField(value, fallbackId) {
47474
49893
  if (!value || typeof value !== "object")
47475
49894
  return void 0;
47476
49895
  const record5 = value;
47477
- const schema = asRecord4(record5.schema);
49896
+ const schema = asRecord5(record5.schema);
47478
49897
  const id = stringField2(record5.id) ?? stringField2(record5.key) ?? fallbackId;
47479
49898
  if (!id)
47480
49899
  return void 0;
@@ -47489,7 +49908,7 @@ function summarizeJiraField(value, fallbackId) {
47489
49908
  });
47490
49909
  }
47491
49910
  function summarizeJiraIssueType(value) {
47492
- const record5 = asRecord4(value);
49911
+ const record5 = asRecord5(value);
47493
49912
  const idValue = record5.id;
47494
49913
  const id = typeof idValue === "number" ? String(idValue) : stringField2(idValue);
47495
49914
  if (!id)
@@ -47521,12 +49940,12 @@ function summarizeJiraAttachment(value) {
47521
49940
  });
47522
49941
  }
47523
49942
  function summarizeJiraBoard(value) {
47524
- const record5 = asRecord4(value);
49943
+ const record5 = asRecord5(value);
47525
49944
  const idValue = record5.id;
47526
49945
  const id = typeof idValue === "number" ? String(idValue) : stringField2(idValue);
47527
49946
  if (!id)
47528
49947
  return void 0;
47529
- const location = asRecord4(record5.location);
49948
+ const location = asRecord5(record5.location);
47530
49949
  return compactRecord4({
47531
49950
  id,
47532
49951
  name: truncateField2(stringField2(record5.name)),
@@ -47536,7 +49955,7 @@ function summarizeJiraBoard(value) {
47536
49955
  });
47537
49956
  }
47538
49957
  function summarizeJiraSprint(value) {
47539
- const record5 = asRecord4(value);
49958
+ const record5 = asRecord5(value);
47540
49959
  const idValue = record5.id;
47541
49960
  const id = typeof idValue === "number" ? String(idValue) : stringField2(idValue);
47542
49961
  if (!id)
@@ -47554,7 +49973,7 @@ function summarizeJiraSprint(value) {
47554
49973
  });
47555
49974
  }
47556
49975
  function summarizeJiraComment(value) {
47557
- const record5 = asRecord4(value);
49976
+ const record5 = asRecord5(value);
47558
49977
  const id = stringField2(record5.id);
47559
49978
  if (!id && Object.keys(record5).length === 0)
47560
49979
  return void 0;
@@ -47568,7 +49987,7 @@ function summarizeJiraComment(value) {
47568
49987
  });
47569
49988
  }
47570
49989
  function summarizeJiraWorklog(value) {
47571
- const record5 = asRecord4(value);
49990
+ const record5 = asRecord5(value);
47572
49991
  const id = stringField2(record5.id);
47573
49992
  if (!id && Object.keys(record5).length === 0)
47574
49993
  return void 0;
@@ -47582,10 +50001,10 @@ function summarizeJiraWorklog(value) {
47582
50001
  });
47583
50002
  }
47584
50003
  function summarizeJiraChangelog(value) {
47585
- const record5 = asRecord4(value);
50004
+ const record5 = asRecord5(value);
47586
50005
  const items = Array.isArray(record5.items) ? record5.items : [];
47587
50006
  const changes = items.flatMap((item) => {
47588
- const change = asRecord4(item);
50007
+ const change = asRecord5(item);
47589
50008
  const field = stringField2(change.field) ?? stringField2(change.fieldId);
47590
50009
  if (!field)
47591
50010
  return [];
@@ -47604,8 +50023,8 @@ function summarizeJiraChangelog(value) {
47604
50023
  });
47605
50024
  }
47606
50025
  function summarizeJiraRemoteLink(value) {
47607
- const record5 = asRecord4(value);
47608
- const object2 = asRecord4(record5.object);
50026
+ const record5 = asRecord5(value);
50027
+ const object2 = asRecord5(record5.object);
47609
50028
  const id = stringField2(record5.id);
47610
50029
  const url2 = stringField2(object2.url) ?? stringField2(record5.url);
47611
50030
  if (!id && !url2)
@@ -47618,10 +50037,10 @@ function summarizeJiraRemoteLink(value) {
47618
50037
  });
47619
50038
  }
47620
50039
  function summarizeJiraIssueLink(value) {
47621
- const record5 = asRecord4(value);
47622
- const type = asRecord4(record5.type);
47623
- const outward = asRecord4(record5.outwardIssue);
47624
- const inward = asRecord4(record5.inwardIssue);
50040
+ const record5 = asRecord5(value);
50041
+ const type = asRecord5(record5.type);
50042
+ const outward = asRecord5(record5.outwardIssue);
50043
+ const inward = asRecord5(record5.inwardIssue);
47625
50044
  const other = Object.keys(outward).length > 0 ? outward : inward;
47626
50045
  return compactRecord4({
47627
50046
  id: stringField2(record5.id),
@@ -47713,7 +50132,7 @@ function truncateField2(value) {
47713
50132
  function stringField2(value) {
47714
50133
  return typeof value === "string" && value.length > 0 ? value : void 0;
47715
50134
  }
47716
- function asRecord4(value) {
50135
+ function asRecord5(value) {
47717
50136
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
47718
50137
  }
47719
50138
  function displayNameOf(value) {
@@ -47861,7 +50280,7 @@ function normalize2(value) {
47861
50280
  }
47862
50281
  async function executeJiraSearchUsers(args, context) {
47863
50282
  const connection = await requireJiraConnection(context);
47864
- const query = requiredString(args.query, "query");
50283
+ const query = requiredString2(args.query, "query");
47865
50284
  const maxResults = boundedNumber(args.max_results, 10, 1, 50);
47866
50285
  const projectKey = optionalString(args.project_key) ?? connection.defaultProjectKey;
47867
50286
  const issueKey = optionalString(args.issue_key);
@@ -48197,7 +50616,7 @@ var parseSearchResponse = objectWithFields({
48197
50616
  });
48198
50617
  async function executeJiraSearchIssues(args, context) {
48199
50618
  const connection = await requireJiraConnection(context);
48200
- const jql = requiredString(args.jql, "jql");
50619
+ const jql = requiredString2(args.jql, "jql");
48201
50620
  const maxResults = boundedNumber(args.max_results, 25, 1, 100);
48202
50621
  const fields = optionalStringArray(args.fields) ?? DEFAULT_SEARCH_FIELDS;
48203
50622
  const body = {
@@ -48316,7 +50735,7 @@ function dryResult(context, text2, details) {
48316
50735
  }
48317
50736
  async function executeJiraGetBoard(args, context) {
48318
50737
  const connection = await requireJiraConnection(context);
48319
- const boardId = requiredString(args.board_id, "board_id");
50738
+ const boardId = requiredString2(args.board_id, "board_id");
48320
50739
  const include = enumSet(args.include, ["sprints", "backlog"]);
48321
50740
  const board = await jiraRequest(connection, {
48322
50741
  parse: jsonObject,
@@ -48378,7 +50797,7 @@ Raw JSON saved to: ${artifact.path}`,
48378
50797
  }
48379
50798
  async function executeJiraGetSprint(args, context) {
48380
50799
  const connection = await requireJiraConnection(context);
48381
- const sprintId = requiredString(args.sprint_id, "sprint_id");
50800
+ const sprintId = requiredString2(args.sprint_id, "sprint_id");
48382
50801
  const sprint = await jiraRequest(connection, {
48383
50802
  parse: jsonObject,
48384
50803
  api: "agile",
@@ -48420,7 +50839,7 @@ Raw JSON saved to: ${artifact.path}`,
48420
50839
  }
48421
50840
  async function executeJiraDownloadAttachment(args, context) {
48422
50841
  const connection = await requireJiraConnection(context);
48423
- const attachmentId = requiredString(args.attachment_id, "attachment_id");
50842
+ const attachmentId = requiredString2(args.attachment_id, "attachment_id");
48424
50843
  const metadata2 = await jiraRequest(connection, {
48425
50844
  parse: jsonObject,
48426
50845
  path: `/attachment/${pathSegment2(attachmentId)}`,
@@ -48465,12 +50884,12 @@ async function executeJiraDownloadAttachment(args, context) {
48465
50884
  });
48466
50885
  }
48467
50886
  async function executeJiraManageAttachment(args, context) {
48468
- const action = requiredString(args.action, "action");
50887
+ const action = requiredString2(args.action, "action");
48469
50888
  if (action !== "upload" && action !== "delete")
48470
50889
  throw new ToolExecutionError("JIRA_ATTACHMENT_ACTION_INVALID", guideErrorMessage2("action must be upload or delete."));
48471
50890
  const connection = await requireJiraConnection(context);
48472
50891
  if (action === "delete") {
48473
- const attachmentId = requiredString(args.attachment_id, "attachment_id");
50892
+ const attachmentId = requiredString2(args.attachment_id, "attachment_id");
48474
50893
  if (args.dry_run === true)
48475
50894
  return dryResult(context, `would delete Jira attachment ${attachmentId}.`, {
48476
50895
  action,
@@ -48492,7 +50911,7 @@ async function executeJiraManageAttachment(args, context) {
48492
50911
  }
48493
50912
  });
48494
50913
  }
48495
- const issueKey = requiredString(args.issue_key, "issue_key");
50914
+ const issueKey = requiredString2(args.issue_key, "issue_key");
48496
50915
  const filePath = resolveToolPath(context.cwd, args.file_path);
48497
50916
  const bytes = await readFile8(filePath);
48498
50917
  if (bytes.byteLength > 25 * 1024 * 1024)
@@ -48529,8 +50948,8 @@ async function executeJiraManageAttachment(args, context) {
48529
50948
  }
48530
50949
  async function executeJiraManageComment(args, context) {
48531
50950
  const connection = await requireJiraConnection(context);
48532
- const action = requiredString(args.action, "action");
48533
- const issueKey = requiredString(args.issue_key, "issue_key");
50951
+ const action = requiredString2(args.action, "action");
50952
+ const issueKey = requiredString2(args.issue_key, "issue_key");
48534
50953
  const commentId = optionalString(args.comment_id);
48535
50954
  let payload3;
48536
50955
  if (action !== "delete") {
@@ -48578,8 +50997,8 @@ async function executeJiraManageComment(args, context) {
48578
50997
  }
48579
50998
  async function executeJiraManageWorklog(args, context) {
48580
50999
  const connection = await requireJiraConnection(context);
48581
- const action = requiredString(args.action, "action");
48582
- const issueKey = requiredString(args.issue_key, "issue_key");
51000
+ const action = requiredString2(args.action, "action");
51001
+ const issueKey = requiredString2(args.issue_key, "issue_key");
48583
51002
  const worklogId = optionalString(args.worklog_id);
48584
51003
  if (action !== "create" && !worklogId)
48585
51004
  throw new ToolExecutionError("JIRA_WORKLOG_ID_REQUIRED", guideErrorMessage2("worklog_id is required."));
@@ -48643,8 +51062,8 @@ async function executeJiraManageWorklog(args, context) {
48643
51062
  }
48644
51063
  async function executeJiraManageIssueLink(args, context) {
48645
51064
  const connection = await requireJiraConnection(context);
48646
- const action = requiredString(args.action, "action");
48647
- const issueKey = requiredString(args.issue_key, "issue_key");
51065
+ const action = requiredString2(args.action, "action");
51066
+ const issueKey = requiredString2(args.issue_key, "issue_key");
48648
51067
  const linkId = optionalString(args.link_id);
48649
51068
  if (action === "delete") {
48650
51069
  if (!linkId)
@@ -48668,9 +51087,9 @@ async function executeJiraManageIssueLink(args, context) {
48668
51087
  }
48669
51088
  });
48670
51089
  }
48671
- const otherIssueKey = requiredString(args.other_issue_key, "other_issue_key");
48672
- const linkType = requiredString(args.link_type, "link_type");
48673
- const direction = requiredString(args.direction, "direction");
51090
+ const otherIssueKey = requiredString2(args.other_issue_key, "other_issue_key");
51091
+ const linkType = requiredString2(args.link_type, "link_type");
51092
+ const direction = requiredString2(args.direction, "direction");
48674
51093
  const types = await jiraRequest(connection, {
48675
51094
  parse: parseLinkTypes,
48676
51095
  path: "/issueLinkType",
@@ -48727,7 +51146,7 @@ async function executeJiraManageIssueLink(args, context) {
48727
51146
  }
48728
51147
  async function executeJiraManageSprint(args, context) {
48729
51148
  const connection = await requireJiraConnection(context);
48730
- const action = requiredString(args.action, "action");
51149
+ const action = requiredString2(args.action, "action");
48731
51150
  const sprintId = optionalString(args.sprint_id);
48732
51151
  if (action !== "create" && !sprintId)
48733
51152
  throw new ToolExecutionError("JIRA_SPRINT_ID_REQUIRED", guideErrorMessage2("sprint_id is required."));
@@ -48761,8 +51180,8 @@ async function executeJiraManageSprint(args, context) {
48761
51180
  throw new ToolExecutionError("JIRA_EMPTY_SPRINT_UPDATE", guideErrorMessage2("Provide at least one sprint field to update."));
48762
51181
  }
48763
51182
  if (action === "create") {
48764
- payload3.name = requiredString(args.name, "name");
48765
- const boardId = Number(requiredString(args.board_id, "board_id"));
51183
+ payload3.name = requiredString2(args.name, "name");
51184
+ const boardId = Number(requiredString2(args.board_id, "board_id"));
48766
51185
  if (!Number.isSafeInteger(boardId) || boardId <= 0) {
48767
51186
  throw new ToolExecutionError("JIRA_BOARD_ID_INVALID", guideErrorMessage2("board_id must be a positive numeric Jira board id."));
48768
51187
  }
@@ -48797,8 +51216,8 @@ async function executeJiraManageSprint(args, context) {
48797
51216
  }
48798
51217
  async function executeJiraManageBacklog(args, context) {
48799
51218
  const connection = await requireJiraConnection(context);
48800
- const action = requiredString(args.action, "action");
48801
- const issueKey = requiredString(args.issue_key, "issue_key");
51219
+ const action = requiredString2(args.action, "action");
51220
+ const issueKey = requiredString2(args.issue_key, "issue_key");
48802
51221
  let path2;
48803
51222
  let method = "POST";
48804
51223
  let payload3;
@@ -48806,7 +51225,7 @@ async function executeJiraManageBacklog(args, context) {
48806
51225
  path2 = "/backlog/issue";
48807
51226
  payload3 = { issues: [issueKey] };
48808
51227
  } else if (action === "move_to_sprint") {
48809
- const sprintId = requiredString(args.sprint_id, "sprint_id");
51228
+ const sprintId = requiredString2(args.sprint_id, "sprint_id");
48810
51229
  path2 = `/sprint/${pathSegment2(sprintId)}/issue`;
48811
51230
  payload3 = { issues: [issueKey] };
48812
51231
  } else {
@@ -48867,7 +51286,7 @@ var parseTransitions = objectWithFields({
48867
51286
  });
48868
51287
  async function executeJiraGetIssue(args, context) {
48869
51288
  const connection = await requireJiraConnection(context);
48870
- const issueKey = requiredString(args.issue_key, "issue_key");
51289
+ const issueKey = requiredString2(args.issue_key, "issue_key");
48871
51290
  const include = enumSet(args.include, [
48872
51291
  "comments",
48873
51292
  "transitions",
@@ -49056,8 +51475,8 @@ async function executeJiraCreateIssue(args, context) {
49056
51475
  const projectKey = optionalString(args.project_key) ?? connection.defaultProjectKey;
49057
51476
  if (!projectKey)
49058
51477
  throw new ToolExecutionError("JIRA_PROJECT_REQUIRED", guideErrorMessage2("project_key is required because no default Jira project key is configured."));
49059
- const issueType = requiredString(args.issue_type, "issue_type");
49060
- const summary = requiredString(args.summary, "summary");
51478
+ const issueType = requiredString2(args.issue_type, "issue_type");
51479
+ const summary = requiredString2(args.summary, "summary");
49061
51480
  const fields = rawFields(args.fields);
49062
51481
  fields.project = { key: projectKey };
49063
51482
  fields.issuetype = { name: issueType };
@@ -49129,7 +51548,7 @@ async function executeJiraCreateIssue(args, context) {
49129
51548
  }
49130
51549
  async function executeJiraUpdateIssue(args, context) {
49131
51550
  const connection = await requireJiraConnection(context);
49132
- const issueKey = requiredString(args.issue_key, "issue_key");
51551
+ const issueKey = requiredString2(args.issue_key, "issue_key");
49133
51552
  const fields = rawFields(args.fields);
49134
51553
  if (typeof args.summary === "string" && args.summary.trim().length > 0)
49135
51554
  fields.summary = args.summary;
@@ -49201,7 +51620,7 @@ async function executeJiraUpdateIssue(args, context) {
49201
51620
  }
49202
51621
  async function executeJiraTransitionIssue(args, context) {
49203
51622
  const connection = await requireJiraConnection(context);
49204
- const issueKey = requiredString(args.issue_key, "issue_key");
51623
+ const issueKey = requiredString2(args.issue_key, "issue_key");
49205
51624
  const transitionsResponse = await getTransitions(connection, issueKey, context);
49206
51625
  const transitions = Array.isArray(transitionsResponse.transitions) ? transitionsResponse.transitions : [];
49207
51626
  const transitionArg = optionalString(args.transition);
@@ -56076,7 +58495,7 @@ async function acquireStorageHomeLock(home, options = {}) {
56076
58495
  }
56077
58496
  }
56078
58497
  async function assertNoLiveDaemon(home, alive) {
56079
- const value = await readJson(join22(home, "daemon.json"));
58498
+ const value = await readJson3(join22(home, "daemon.json"));
56080
58499
  const parsed = daemonFileSchema.safeParse(value);
56081
58500
  if (parsed.success && parsed.data.pid !== process.pid && alive(parsed.data.pid)) {
56082
58501
  throw new StorageHomeLockedError(`A live Nerve daemon (${parsed.data.pid}) is using this home.`);
@@ -56112,7 +58531,7 @@ async function releaseOwnedLock(path2, token) {
56112
58531
  if (current?.token === token)
56113
58532
  await rm6(path2, { force: true });
56114
58533
  }
56115
- async function readJson(path2) {
58534
+ async function readJson3(path2) {
56116
58535
  try {
56117
58536
  return JSON.parse(await readFile14(path2, "utf8"));
56118
58537
  } catch {