github-router 0.3.356 → 0.3.367

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 (121) hide show
  1. package/dist/ado-tools-rysFZDws.js +1 -0
  2. package/dist/{aic-ledger-BuFrsGur.js → aic-ledger-_mvGW2Ev.js} +42 -7
  3. package/dist/aic-ledger-_mvGW2Ev.js.map +1 -0
  4. package/dist/{aic-statusline-settings-DBS9sEGC.js → aic-statusline-settings-B5EMMSFC.js} +2 -2
  5. package/dist/{aic-statusline-settings-DBS9sEGC.js.map → aic-statusline-settings-B5EMMSFC.js.map} +1 -1
  6. package/dist/{attribution-settings-CnmV9MSv.js → attribution-settings-wVzQvIdL.js} +188 -64
  7. package/dist/attribution-settings-wVzQvIdL.js.map +1 -0
  8. package/dist/{auth-DFawaLJU.js → auth-B3UvYB2r.js} +3 -3
  9. package/dist/{auth-DFawaLJU.js.map → auth-B3UvYB2r.js.map} +1 -1
  10. package/dist/browser-ext/manifest.json +1 -1
  11. package/dist/{check-usage-BkVEl-Su.js → check-usage-45vyaLfl.js} +4 -4
  12. package/dist/{check-usage-BkVEl-Su.js.map → check-usage-45vyaLfl.js.map} +1 -1
  13. package/dist/{claude-DvR3Y7fu.js → claude-B3pIageM.js} +89 -41
  14. package/dist/claude-B3pIageM.js.map +1 -0
  15. package/dist/{claude-md-injection-Cpzolxin.js → claude-md-injection-BV4tPUWo.js} +126 -35
  16. package/dist/claude-md-injection-BV4tPUWo.js.map +1 -0
  17. package/dist/{codex-DQpSPjpQ.js → codex-B_AMB6JM.js} +7 -7
  18. package/dist/{codex-DQpSPjpQ.js.map → codex-B_AMB6JM.js.map} +1 -1
  19. package/dist/{copilot-discount-Bsmv_3OX.js → copilot-discount-BuDbQOHq.js} +2 -2
  20. package/dist/{copilot-discount-Bsmv_3OX.js.map → copilot-discount-BuDbQOHq.js.map} +1 -1
  21. package/dist/{debug-DkNTuErv.js → debug-DL2JsRqY.js} +2 -2
  22. package/dist/{debug-DkNTuErv.js.map → debug-DL2JsRqY.js.map} +1 -1
  23. package/dist/engine-D3oNrF6Z.js +1 -0
  24. package/dist/{gate-discovery-B2x_8hNL.js → gate-discovery-CXE-7VcM.js} +5 -5
  25. package/dist/{gate-discovery-B2x_8hNL.js.map → gate-discovery-CXE-7VcM.js.map} +1 -1
  26. package/dist/{get-copilot-usage-P9chc-X2.js → get-copilot-usage-BbGmK03C.js} +2 -2
  27. package/dist/{get-copilot-usage-P9chc-X2.js.map → get-copilot-usage-BbGmK03C.js.map} +1 -1
  28. package/dist/hooks.mjs +200 -117
  29. package/dist/hooks.sha256 +1 -1
  30. package/dist/{index-cmd-BkfYr9FH.js → index-cmd-CjRcmYk3.js} +4 -4
  31. package/dist/{index-cmd-BkfYr9FH.js.map → index-cmd-CjRcmYk3.js.map} +1 -1
  32. package/dist/{internal-aic-status-C6L4-ncP.js → internal-aic-status-BAVomi5A.js} +4 -4
  33. package/dist/{internal-aic-status-C6L4-ncP.js.map → internal-aic-status-BAVomi5A.js.map} +1 -1
  34. package/dist/{internal-artifact-open-DgJ3PCtt.js → internal-artifact-open-NAGn9Mgt.js} +2 -2
  35. package/dist/{internal-artifact-open-DgJ3PCtt.js.map → internal-artifact-open-NAGn9Mgt.js.map} +1 -1
  36. package/dist/{internal-fast-dispatch-guard-CicGz6oM.js → internal-fast-dispatch-guard-DP25L_Bx.js} +1 -1
  37. package/dist/{internal-fast-dispatch-guard-CgBtUsQI.js → internal-fast-dispatch-guard-DbrgO9Ab.js} +2 -2
  38. package/dist/{internal-fast-dispatch-guard-CgBtUsQI.js.map → internal-fast-dispatch-guard-DbrgO9Ab.js.map} +1 -1
  39. package/dist/{internal-first-mate-guard-DTXPT7JW.js → internal-first-mate-guard-C8GwLbaX.js} +1 -1
  40. package/dist/{internal-first-mate-guard-BfWYN6Jb.js → internal-first-mate-guard-GufCUMl3.js} +3 -3
  41. package/dist/{internal-first-mate-guard-BfWYN6Jb.js.map → internal-first-mate-guard-GufCUMl3.js.map} +1 -1
  42. package/dist/{internal-max-dispatch-guard-mNl9CCir.js → internal-max-dispatch-guard-BB0vwiPx.js} +1 -1
  43. package/dist/{internal-max-dispatch-guard-CY8l9SDw.js → internal-max-dispatch-guard-BodVFHRC.js} +2 -2
  44. package/dist/{internal-max-dispatch-guard-CY8l9SDw.js.map → internal-max-dispatch-guard-BodVFHRC.js.map} +1 -1
  45. package/dist/{internal-plan-review-2OHTs8Nk.js → internal-plan-review-ChFx8wTX.js} +3 -3
  46. package/dist/{internal-plan-review-2OHTs8Nk.js.map → internal-plan-review-ChFx8wTX.js.map} +1 -1
  47. package/dist/{internal-prompt-submit-CkfUcu34.js → internal-prompt-submit-BaccW_CC.js} +4 -4
  48. package/dist/{internal-prompt-submit-CkfUcu34.js.map → internal-prompt-submit-BaccW_CC.js.map} +1 -1
  49. package/dist/{internal-prompt-submit-DZ_-2A6a.js → internal-prompt-submit-DPUBQZtG.js} +2 -2
  50. package/dist/{internal-rebrief-EhBHAHsz.js → internal-rebrief-NjSlx5QY.js} +4 -4
  51. package/dist/{internal-rebrief-EhBHAHsz.js.map → internal-rebrief-NjSlx5QY.js.map} +1 -1
  52. package/dist/{internal-session-bind-Bv50ju2n.js → internal-session-bind-dsUOcKxU.js} +2 -2
  53. package/dist/{internal-session-bind-Bv50ju2n.js.map → internal-session-bind-dsUOcKxU.js.map} +1 -1
  54. package/dist/{internal-stop-hook-Dm-m8RoA.js → internal-stop-hook-B2TTl6Zp.js} +5 -5
  55. package/dist/{internal-stop-hook-Dm-m8RoA.js.map → internal-stop-hook-B2TTl6Zp.js.map} +1 -1
  56. package/dist/{internal-stop-review-K6f8xsCh.js → internal-stop-review-D_KEV_04.js} +2 -2
  57. package/dist/{internal-stop-review-K6f8xsCh.js.map → internal-stop-review-D_KEV_04.js.map} +1 -1
  58. package/dist/{internal-worker-guard-GVhTjVlR.js → internal-worker-guard-DB6shBIn.js} +2 -2
  59. package/dist/{internal-worker-guard-GVhTjVlR.js.map → internal-worker-guard-DB6shBIn.js.map} +1 -1
  60. package/dist/{internal-workspace-header-d2hFf9Jy.js → internal-workspace-header-DBg5Y7oN.js} +2 -2
  61. package/dist/{internal-workspace-header-d2hFf9Jy.js.map → internal-workspace-header-DBg5Y7oN.js.map} +1 -1
  62. package/dist/{lifecycle-C6cxM_Nk.js → lifecycle-9nX09dBl.js} +2 -2
  63. package/dist/{lifecycle-C6cxM_Nk.js.map → lifecycle-9nX09dBl.js.map} +1 -1
  64. package/dist/lifecycle-C_CT13c9.js +1 -0
  65. package/dist/lifecycle-DibiH857.js +1 -0
  66. package/dist/{lifecycle-pl9QpvqD.js → lifecycle-Gge2Dadd.js} +2 -2
  67. package/dist/{lifecycle-pl9QpvqD.js.map → lifecycle-Gge2Dadd.js.map} +1 -1
  68. package/dist/main.js +23 -23
  69. package/dist/{mcp-workspace-header-Su8uUxJg.js → mcp-workspace-header-Xw9B1W6T.js} +2 -2
  70. package/dist/{mcp-workspace-header-Su8uUxJg.js.map → mcp-workspace-header-Xw9B1W6T.js.map} +1 -1
  71. package/dist/{models-D8v8OTbN.js → models-BR6i348u.js} +3 -3
  72. package/dist/{models-D8v8OTbN.js.map → models-BR6i348u.js.map} +1 -1
  73. package/dist/{orchestration-Bov4rZEi.js → orchestration-D3-2ulhX.js} +2 -2
  74. package/dist/{orchestration-Bov4rZEi.js.map → orchestration-D3-2ulhX.js.map} +1 -1
  75. package/dist/{paths-BSI_EtDT.js → paths-C5477RGC.js} +48 -4
  76. package/dist/paths-C5477RGC.js.map +1 -0
  77. package/dist/paths-CEswtFj5.js +1 -0
  78. package/dist/{peer-mcp-personas-CVxXq1Q-.js → peer-mcp-personas-BOgR46nM.js} +641 -270
  79. package/dist/peer-mcp-personas-BOgR46nM.js.map +1 -0
  80. package/dist/{pi-D-BgxVhx.js → pi-DcWp83mx.js} +377 -602
  81. package/dist/pi-DcWp83mx.js.map +1 -0
  82. package/dist/{plan-review-hook-CHK1wL3-.js → plan-review-hook-C9K-em4D.js} +3 -3
  83. package/dist/{plan-review-hook-CHK1wL3-.js.map → plan-review-hook-C9K-em4D.js.map} +1 -1
  84. package/dist/{provision-DYmZgZDr.js → provision-DkWR9B6I.js} +5 -5
  85. package/dist/{provision-DYmZgZDr.js.map → provision-DkWR9B6I.js.map} +1 -1
  86. package/dist/{self-invocation-Dk_UHD_v.js → self-invocation-BtcGj-lY.js} +2 -2
  87. package/dist/{self-invocation-Dk_UHD_v.js.map → self-invocation-BtcGj-lY.js.map} +1 -1
  88. package/dist/{serve-DfxxKLFl.js → serve-BGwEVDdc.js} +14 -14
  89. package/dist/{serve-DfxxKLFl.js.map → serve-BGwEVDdc.js.map} +1 -1
  90. package/dist/{server-setup-VYf8ptCH.js → server-setup-DVPL9iph.js} +911 -100
  91. package/dist/server-setup-DVPL9iph.js.map +1 -0
  92. package/dist/{service-backend-DHyd9vjW.js → service-backend-B6D_DY1Z.js} +3 -3
  93. package/dist/{service-backend-DHyd9vjW.js.map → service-backend-B6D_DY1Z.js.map} +1 -1
  94. package/dist/{start-BsY1d26G.js → start-BUWx3nSr.js} +4 -4
  95. package/dist/{start-BsY1d26G.js.map → start-BUWx3nSr.js.map} +1 -1
  96. package/dist/{static-context-pack-dKrzbfIN.js → static-context-pack-ChHuxBpk.js} +232 -61
  97. package/dist/static-context-pack-ChHuxBpk.js.map +1 -0
  98. package/dist/{stop-gate-hook-CC7VWkZM.js → stop-gate-hook-DnLC09Lg.js} +3 -3
  99. package/dist/{stop-gate-hook-CC7VWkZM.js.map → stop-gate-hook-DnLC09Lg.js.map} +1 -1
  100. package/dist/{stop-gate-policy-CoR8xKNQ.js → stop-gate-policy-Dx9c98_d.js} +2 -2
  101. package/dist/{stop-gate-policy-CoR8xKNQ.js.map → stop-gate-policy-Dx9c98_d.js.map} +1 -1
  102. package/dist/{token-CA2s70qj.js → token-OTb61rOC.js} +2 -2
  103. package/dist/{token-CA2s70qj.js.map → token-OTb61rOC.js.map} +1 -1
  104. package/dist/{worker-dispatch-B_rriT7z.js → worker-dispatch-B1w2qfjX.js} +2 -2
  105. package/dist/{worker-dispatch-B_rriT7z.js.map → worker-dispatch-B1w2qfjX.js.map} +1 -1
  106. package/docs/azure-mcp.md +29 -31
  107. package/package.json +1 -1
  108. package/dist/ado-tools-DokE2DbX.js +0 -1
  109. package/dist/aic-ledger-BuFrsGur.js.map +0 -1
  110. package/dist/attribution-settings-CnmV9MSv.js.map +0 -1
  111. package/dist/claude-DvR3Y7fu.js.map +0 -1
  112. package/dist/claude-md-injection-Cpzolxin.js.map +0 -1
  113. package/dist/engine-DgmsdkCe.js +0 -1
  114. package/dist/lifecycle-BU_d2QMs.js +0 -1
  115. package/dist/lifecycle-ByFyew_w.js +0 -1
  116. package/dist/paths-BSI_EtDT.js.map +0 -1
  117. package/dist/paths-BYxX9DfA.js +0 -1
  118. package/dist/peer-mcp-personas-CVxXq1Q-.js.map +0 -1
  119. package/dist/pi-D-BgxVhx.js.map +0 -1
  120. package/dist/server-setup-VYf8ptCH.js.map +0 -1
  121. package/dist/static-context-pack-dKrzbfIN.js.map +0 -1
@@ -1,22 +1,22 @@
1
- import { I as provisionTreeSitterAssets, L as withInstallLock } from "./service-backend-DHyd9vjW.js";
1
+ import { I as provisionTreeSitterAssets, L as withInstallLock } from "./service-backend-B6D_DY1Z.js";
2
2
  import { t as getPackageVersion } from "./version-C8x2hQrZ.js";
3
- import { i as ensurePaths, t as PATHS } from "./paths-BSI_EtDT.js";
3
+ import { i as ensurePaths, t as PATHS } from "./paths-C5477RGC.js";
4
4
  import { t as state } from "./state-CiwCLVDZ.js";
5
- import { _ as forwardError, a as cacheCopilotVersion, b as copilotBaseUrl, c as filterBetaHeader, d as resolveModel, f as sleep, g as HTTPError, i as tryRefreshAndRetry, l as isNullish, n as setupGitHubAgentToken, o as cacheModels, r as setupGitHubToken, s as cacheVSCodeVersion, t as setupCopilotToken, x as copilotHeaders } from "./token-CA2s70qj.js";
5
+ import { _ as forwardError, a as cacheCopilotVersion, b as copilotBaseUrl, c as filterBetaHeader, d as resolveModel, f as sleep, g as HTTPError, i as tryRefreshAndRetry, l as isNullish, n as setupGitHubAgentToken, o as cacheModels, r as setupGitHubToken, s as cacheVSCodeVersion, t as setupCopilotToken, x as copilotHeaders } from "./token-OTb61rOC.js";
6
6
  import { r as fetchWithTransientRetry } from "./upstream-retry-i1k1Xai2.js";
7
- import { t as getCopilotUsage } from "./get-copilot-usage-P9chc-X2.js";
7
+ import { t as getCopilotUsage } from "./get-copilot-usage-BbGmK03C.js";
8
8
  import { a as parseBoolEnv, c as runCommandCapture, i as killManagedTree, s as resolveExecutable, u as runCommandVoid } from "./exec-Bf8g_bIR.js";
9
9
  import { c as FAST_PROFILE_MODELS, l as FAST_PROFILE_NATIVE_AGENT_NAMES, r as FAST_PROFILE_ADVISOR_MODEL } from "./fast-profile-contract-JOnZBgFB.js";
10
- import { $ as readIteratorWithTimeout, $t as getTokenCount, B as injectAdvisorTool, Bn as catalogAdvertises1M, D as toolbeltEnabled, En as BUDGET_SMALL_FAST_SLUG, F as ADVISOR_TOOL_INSTRUCTIONS, G as formatThinkingRepairDecline, Gn as CHEAP_PROFILE_MODELS, H as resolveAdvisorEffort, Hn as withOneMSuffix, I as CHEAPEST_ADVISOR_TOOL_INSTRUCTIONS, J as repairRejectedThinkingHistory, K as rememberThinkingHistoryRepair, Kn as CHEAP_PROFILE_NATIVE_AGENT_NAMES, L as CHEAPEST_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, Ln as upstreamAllowH2, Mn as UPSTREAM_INACTIVITY_TIMEOUT_MS, N as searchWeb, Nn as generateRandomPort, P as ADVISOR_INTERNAL_TOOL_NAME, Pn as isBudgetClaudeLead, Q as logStreamError, Qt as getTextTokenCount, R as FAST_ADVISOR_TOOL_INSTRUCTIONS, Rn as upstreamMaxConnections, U as resolveAdvisorModel, Un as withOneMSuffixForLead, V as isAdvisorRequested, Vn as oneMContextDisabled, W as resolveCheapestAdvisorModel, Wn as CHEAP_PROFILE_ADVISOR_CLIENT_MODEL, X as buildOpenAIErrorEvent, Xt as countTokens, Y as buildAnthropicErrorEvent, Yn as CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS, Yt as shimDefaultsToXhigh, Z as isControllerClosedError, Zt as createMessages, an as warnOnTokenPriceDrift, at as handleMcpDelete, cn as createChatCompletions, dn as parseJsonOrDiagnose, dt as ADO_DEFAULT_TOOLSETS, en as getTokenizerFromModel, et as relayAnthropicStream, fn as normalizeOpenAIUsage, ft as normalizeAdoToolsets, gn as normalizeKustoClusterUri, hn as normalizeCloudAgentEnvironment, i as assertMcpToolSurfaceConsistent, in as assembleResponsesPayload, it as clampEffort, jn as UPSTREAM_FETCH_TIMEOUT_MS, ln as MAX_RESPONSE_BODY_BYTES, mt as agentToolsEnabled, nt as UNKNOWN_EFFORT_ANCHOR, on as resolveMcpToolTimeoutMs, ot as handleMcpPost, q as repairKnownThinkingHistory, rt as bucketEffort, sn as createResponses, tn as findLaunchBySecret, tt as EFFORT_ORDER, un as readResponseBodyCapped, ut as provisionAdoTools, wn as toolbeltPathOverride, z as buildAdvisorStream, zn as classifyMessagesRoute } from "./peer-mcp-personas-CVxXq1Q-.js";
11
- import { D as CHEAPEST_PROFILE_MODELS, O as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, S as CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL, _ as isBalancedFamily, g as displayModelName, m as cheapestContractFor, p as balancedContractFor, v as isCheapestFamily, y as isPinnedLaunchProfile } from "./static-context-pack-dKrzbfIN.js";
10
+ import { $ as isControllerClosedError, $t as createMessages, An as toolbeltPathOverride, B as LOCAL_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, Bn as isBudgetClaudeLead, D as toolbeltEnabled, F as ADVISOR_TOOL_INSTRUCTIONS, G as resolveAdvisorModel, Gn as classifyMessagesRoute, H as injectAdvisorTool, I as CHEAPEST_ADVISOR_TOOL_INSTRUCTIONS, J as rememberThinkingHistoryRepair, Jn as withOneMSuffix, K as resolveCheapestAdvisorModel, Kn as catalogAdvertises1M, L as CHEAPEST_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, Ln as UPSTREAM_FETCH_TIMEOUT_MS, Mn as BUDGET_SMALL_FAST_SLUG, N as searchWeb, P as ADVISOR_INTERNAL_TOOL_NAME, Q as buildOpenAIErrorEvent, Qn as CHEAP_PROFILE_NATIVE_AGENT_NAMES, Qt as countTokens, R as FAST_ADVISOR_TOOL_INSTRUCTIONS, Rn as UPSTREAM_INACTIVITY_TIMEOUT_MS, Sn as normalizeKustoClusterUri, U as isAdvisorRequested, Un as upstreamAllowH2, V as buildAdvisorStream, W as resolveAdvisorEffort, Wn as upstreamMaxConnections, X as repairRejectedThinkingHistory, Xn as CHEAP_PROFILE_ADVISOR_CLIENT_MODEL, Y as repairKnownThinkingHistory, Yn as withOneMSuffixForLead, Z as buildAnthropicErrorEvent, Zn as CHEAP_PROFILE_MODELS, Zt as shimDefaultsToXhigh, _n as effectiveLocalProfile, at as bucketEffort, cn as assembleResponsesPayload, ct as handleMcpPost, dn as createResponses, en as getTextTokenCount, et as logStreamError, fn as createChatCompletions, ft as provisionAdoTools, gn as assertCopilotModelAllowed, gt as agentToolsEnabled, hn as parseJsonOrDiagnose, i as assertMcpToolSurfaceConsistent, in as findLaunchBySecret, it as UNKNOWN_EFFORT_ANCHOR, ln as warnOnTokenPriceDrift, mn as readResponseBodyCapped, mt as normalizeAdoToolsets, nn as getTokenizerFromModel, nt as relayAnthropicStream, ot as clampEffort, pn as MAX_RESPONSE_BODY_BYTES, pt as ADO_DEFAULT_TOOLSETS, q as formatThinkingRepairDecline, qn as oneMContextDisabled, rn as LAUNCH_BOUND_TOKEN_PREFIX, rt as EFFORT_ORDER, st as handleMcpDelete, tn as getTokenCount, tr as CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS, tt as readIteratorWithTimeout, un as resolveMcpToolTimeoutMs, vn as normalizeOpenAIUsage, xn as normalizeCloudAgentEnvironment, z as LOCAL_ADVISOR_TOOL_INSTRUCTIONS, zn as generateRandomPort } from "./peer-mcp-personas-BOgR46nM.js";
11
+ import { E as LOCAL_PROFILE_TIER_MODELS, N as CHEAPEST_PROFILE_MODELS, O as CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL, P as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, _ as isCheapestFamily, b as local2AdvisorContract, f as balancedContractFor, g as isBalancedFamily, h as displayModelName, p as cheapestContractFor, v as isLocalFamily, x as localContractFor, y as isPinnedLaunchProfile } from "./static-context-pack-ChHuxBpk.js";
12
12
  import { i as BALANCED_PROFILE_NATIVE_AGENT_NAMES, r as BALANCED_PROFILE_MODELS } from "./balanced-profile-contract-DtnTIBjL.js";
13
13
  import { A as normalizeTrailingOneMSuffix, a as MAX_PROFILE_NATIVE_AGENT_NAMES, d as maxAdvisorPinIsValid, h as maxOpusModel, i as MAX_PROFILE_MODELS, j as stripTrailingOneMSuffix, k as fastEndpointForModel, l as maxAdvisorEffortForModel, n as MAX_PROFILE_ALLOWED_LEAD_MODEL_IDS, t as MAX_PROFILE_ADVISOR_INSTRUCTIONS, u as maxAdvisorModelFromPin, y as validateMaxProfilePrerequisites } from "./max-profile-contract-Cx5_Z1Y7.js";
14
14
  import { f as getAzureRepoFromGit } from "./bluebird-client-C29-JOkG.js";
15
- import { a as extractAndRecordPricedAic, f as copilotUsageToWire, h as nanoAiuToCredits, i as extractAndRecordAic, l as recordAic, m as formatAic, p as extractCopilotUsage } from "./aic-ledger-BuFrsGur.js";
15
+ import { a as extractAndRecordPricedAic, g as nanoAiuToCredits, h as formatAic, i as extractAndRecordAic, l as recordAic, m as extractCopilotUsage, p as copilotUsageToWire, u as recordZeroCostRequest } from "./aic-ledger-_mvGW2Ev.js";
16
16
  import consola from "consola";
17
17
  import fs, { existsSync } from "node:fs";
18
18
  import path from "node:path";
19
- import { createHash, randomUUID } from "node:crypto";
19
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
20
20
  import fs$1 from "node:fs/promises";
21
21
  import os from "node:os";
22
22
  import process$1 from "node:process";
@@ -30,21 +30,21 @@ import { Hono } from "hono";
30
30
  import { cors } from "hono/cors";
31
31
  //#region src/lib/claude-version-check.ts
32
32
  const NPM_PACKAGE$1 = "@anthropic-ai/claude-code";
33
- const THROTTLE_HOURS$1 = 1;
34
- const NPM_VIEW_TIMEOUT_MS$1 = 5e3;
33
+ const THROTTLE_HOURS$2 = 1;
34
+ const NPM_VIEW_TIMEOUT_MS$2 = 5e3;
35
35
  const CLAUDE_VERSION_TIMEOUT_MS = 3e3;
36
- const NPM_INSTALL_TIMEOUT_MS = 12e4;
36
+ const NPM_INSTALL_TIMEOUT_MS$1 = 12e4;
37
37
  /** Path to the throttle cache. Created on demand. */
38
- function cacheFilePath$1() {
38
+ function cacheFilePath$2() {
39
39
  return path.join(os.homedir(), ".local", "share", "github-router", "last-update-check");
40
40
  }
41
41
  /**
42
42
  * Read the throttle cache. Returns null on missing/corrupt file —
43
43
  * triggers a fresh check.
44
44
  */
45
- async function readCache$1() {
45
+ async function readCache$2() {
46
46
  try {
47
- const raw = await fs$1.readFile(cacheFilePath$1(), "utf8");
47
+ const raw = await fs$1.readFile(cacheFilePath$2(), "utf8");
48
48
  const parsed = JSON.parse(raw);
49
49
  if (typeof parsed.checkedAt !== "string" || parsed.installedVersion !== null && typeof parsed.installedVersion !== "string" || parsed.latestVersion !== null && typeof parsed.latestVersion !== "string") return null;
50
50
  return parsed;
@@ -52,20 +52,20 @@ async function readCache$1() {
52
52
  return null;
53
53
  }
54
54
  }
55
- async function writeCache$1(cache) {
55
+ async function writeCache$2(cache) {
56
56
  try {
57
- await fs$1.mkdir(path.dirname(cacheFilePath$1()), { recursive: true });
58
- await fs$1.writeFile(cacheFilePath$1(), JSON.stringify(cache), { mode: 384 });
57
+ await fs$1.mkdir(path.dirname(cacheFilePath$2()), { recursive: true });
58
+ await fs$1.writeFile(cacheFilePath$2(), JSON.stringify(cache), { mode: 384 });
59
59
  } catch (err) {
60
60
  consola.debug("Failed to write claude version-check cache:", err);
61
61
  }
62
62
  }
63
63
  /** Check if it's been more than THROTTLE_HOURS since the last check. */
64
- function shouldCheckNow$1(cache) {
64
+ function shouldCheckNow$2(cache) {
65
65
  if (!cache) return true;
66
66
  const lastCheck = new Date(cache.checkedAt).getTime();
67
67
  if (Number.isNaN(lastCheck)) return true;
68
- return (Date.now() - lastCheck) / 1e3 / 3600 >= THROTTLE_HOURS$1;
68
+ return (Date.now() - lastCheck) / 1e3 / 3600 >= THROTTLE_HOURS$2;
69
69
  }
70
70
  /**
71
71
  * Read the installed `claude` version. Returns null if claude is not
@@ -106,7 +106,7 @@ async function getLatestVersion$1() {
106
106
  NPM_PACKAGE$1,
107
107
  "version",
108
108
  "--silent"
109
- ], { timeoutMs: NPM_VIEW_TIMEOUT_MS$1 });
109
+ ], { timeoutMs: NPM_VIEW_TIMEOUT_MS$2 });
110
110
  if (code !== 0) return null;
111
111
  const v = stdout.trim();
112
112
  return /^\d+\.\d+\.\d+/.test(v) ? v : null;
@@ -145,8 +145,8 @@ async function checkClaudeVersion(opts = {}) {
145
145
  skipped: true,
146
146
  skipReason: "disabled"
147
147
  };
148
- const cache = await readCache$1();
149
- if (!opts.force && !shouldCheckNow$1(cache)) return {
148
+ const cache = await readCache$2();
149
+ if (!opts.force && !shouldCheckNow$2(cache)) return {
150
150
  installed: cache?.installedVersion !== null,
151
151
  installedVersion: cache?.installedVersion ?? null,
152
152
  latestVersion: cache?.latestVersion ?? null,
@@ -164,7 +164,7 @@ async function checkClaudeVersion(opts = {}) {
164
164
  skipReason: "no-claude"
165
165
  };
166
166
  const latestVersion = await getLatestVersion$1();
167
- await writeCache$1({
167
+ await writeCache$2({
168
168
  checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
169
169
  installedVersion,
170
170
  latestVersion
@@ -207,7 +207,7 @@ async function updateClaude(latestVersion, deps = {}) {
207
207
  if (!claudePath) throw new Error("claude not found on PATH");
208
208
  if (!await _lock("claude-update.lock", async () => {
209
209
  consola.info(`Updating Claude Code to ${latestVersion} via \`claude update\`...`);
210
- const { code, stdout, stderr } = await _capture([claudePath, "update"], { timeoutMs: NPM_INSTALL_TIMEOUT_MS });
210
+ const { code, stdout, stderr } = await _capture([claudePath, "update"], { timeoutMs: NPM_INSTALL_TIMEOUT_MS$1 });
211
211
  const combined = `${stdout}${stderr}`;
212
212
  const trimmed = combined.trim();
213
213
  if (trimmed) process.stdout.write(trimmed.endsWith("\n") ? trimmed : `${trimmed}\n`);
@@ -225,7 +225,7 @@ async function updateClaude(latestVersion, deps = {}) {
225
225
  "-g",
226
226
  `${NPM_PACKAGE$1}@latest`,
227
227
  "--silent"
228
- ], { timeoutMs: NPM_INSTALL_TIMEOUT_MS });
228
+ ], { timeoutMs: NPM_INSTALL_TIMEOUT_MS$1 });
229
229
  if (npmCode !== 0) throw new Error(`npm install failed: ${npmStderr.trim() || `exit ${npmCode}`}`);
230
230
  consola.success(`${NPM_PACKAGE$1} updated to ${latestVersion}`);
231
231
  })) consola.debug("Claude Code update already in progress in another process; skipping.");
@@ -249,33 +249,33 @@ async function updateClaude(latestVersion, deps = {}) {
249
249
  * delay the proxy from serving.
250
250
  */
251
251
  const NPM_PACKAGE = "github-router";
252
- const THROTTLE_HOURS = 1;
253
- const NPM_VIEW_TIMEOUT_MS = 5e3;
254
- function cacheFilePath() {
252
+ const THROTTLE_HOURS$1 = 1;
253
+ const NPM_VIEW_TIMEOUT_MS$1 = 5e3;
254
+ function cacheFilePath$1() {
255
255
  return path.join(os.homedir(), ".local", "share", "github-router", "last-self-update-check");
256
256
  }
257
- async function readCache() {
257
+ async function readCache$1() {
258
258
  try {
259
- const parsed = JSON.parse(await fs$1.readFile(cacheFilePath(), "utf8"));
259
+ const parsed = JSON.parse(await fs$1.readFile(cacheFilePath$1(), "utf8"));
260
260
  if (typeof parsed.checkedAt !== "string") return null;
261
261
  return parsed;
262
262
  } catch {
263
263
  return null;
264
264
  }
265
265
  }
266
- async function writeCache(cache) {
266
+ async function writeCache$1(cache) {
267
267
  try {
268
- await fs$1.mkdir(path.dirname(cacheFilePath()), { recursive: true });
269
- await fs$1.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 384 });
268
+ await fs$1.mkdir(path.dirname(cacheFilePath$1()), { recursive: true });
269
+ await fs$1.writeFile(cacheFilePath$1(), JSON.stringify(cache), { mode: 384 });
270
270
  } catch (err) {
271
271
  consola.debug("Failed to write self-update cache:", err);
272
272
  }
273
273
  }
274
- function shouldCheckNow(cache) {
274
+ function shouldCheckNow$1(cache) {
275
275
  if (!cache) return true;
276
276
  const last = new Date(cache.checkedAt).getTime();
277
277
  if (Number.isNaN(last)) return true;
278
- return (Date.now() - last) / 1e3 / 3600 >= THROTTLE_HOURS;
278
+ return (Date.now() - last) / 1e3 / 3600 >= THROTTLE_HOURS$1;
279
279
  }
280
280
  async function getLatestVersion(npmPath) {
281
281
  try {
@@ -285,7 +285,7 @@ async function getLatestVersion(npmPath) {
285
285
  NPM_PACKAGE,
286
286
  "version",
287
287
  "--silent"
288
- ], { timeoutMs: NPM_VIEW_TIMEOUT_MS });
288
+ ], { timeoutMs: NPM_VIEW_TIMEOUT_MS$1 });
289
289
  if (code !== 0) return null;
290
290
  const v = stdout.trim();
291
291
  return /^\d+\.\d+\.\d+/.test(v) ? v : null;
@@ -356,14 +356,14 @@ async function runSelfUpdate(opts) {
356
356
  if (!opts.selfUpdate) return;
357
357
  if (parseBoolEnv(process.env.GH_ROUTER_NO_SELF_UPDATE) === true) return;
358
358
  try {
359
- const cache = await readCache();
360
- if (!opts.force && !shouldCheckNow(cache)) return;
359
+ const cache = await readCache$1();
360
+ if (!opts.force && !shouldCheckNow$1(cache)) return;
361
361
  const installed = getPackageVersion();
362
362
  if (installed === "unknown") return;
363
363
  const npmPath = resolveExecutable("npm");
364
364
  if (!npmPath) return;
365
365
  const latest = await getLatestVersion(npmPath);
366
- await writeCache({
366
+ await writeCache$1({
367
367
  checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
368
368
  installedVersion: installed,
369
369
  latestVersion: latest
@@ -533,6 +533,59 @@ const BALANCED2_PROFILE = Object.freeze({
533
533
  hasCoordinator: false
534
534
  });
535
535
  /**
536
+ * The `-m local` roster: the cheapest surface (same three-agent roster, no
537
+ * coordinator), with every role's model swapped for the local endpoint's tier
538
+ * id.
539
+ *
540
+ * No agent turn on a local launch reaches a Copilot model, so every group
541
+ * whose tools spawn one is absent: `workers` (the Pi workers resolve Copilot
542
+ * models) and every group built for model ties. `peers` is permitted only
543
+ * because the artifact tools live there and human review is not model
544
+ * inference, and the empty allow-list means no persona is listed or callable:
545
+ * with the artifact panel off the group holds nothing and neither launcher
546
+ * publishes it. What remains is the surface that is not an agent model call —
547
+ * `search` (in-process lexical/ColBERT plus the PAT-backed web search),
548
+ * `browser` (a local extension, whose page compressor is the one model-backed
549
+ * exception and carries its own fixed chain), and the three Azure data groups.
550
+ * The egress guard in `copilot-model-policy.ts` enforces the same rule from
551
+ * the other side, so a path that somehow reaches Copilot still refuses.
552
+ */
553
+ const LOCAL_PROFILE = Object.freeze({
554
+ id: "local",
555
+ nativeRoster: new Set(localContractFor("local").nativeAgentNames),
556
+ personaAllowlist: /* @__PURE__ */ new Set(),
557
+ allowedGroups: /* @__PURE__ */ new Set([
558
+ "peers",
559
+ "search",
560
+ "browser",
561
+ "ado",
562
+ "kusto",
563
+ "cloudagent"
564
+ ]),
565
+ hasCoordinator: false
566
+ });
567
+ /**
568
+ * The `-m local2` roster: `local` plus the curated `gpt-6.1-sol`/high Advisor.
569
+ * The Advisor and the Oracle are the only two Copilot consumers the profile
570
+ * has, so `peers` gains the Oracle persona next to the model-free artifact
571
+ * tools. `workers` stays absent as on `local`: a Pi worker is neither of the
572
+ * two exceptions.
573
+ */
574
+ const LOCAL2_PROFILE = Object.freeze({
575
+ id: "local2",
576
+ nativeRoster: new Set(localContractFor("local2").nativeAgentNames),
577
+ personaAllowlist: /* @__PURE__ */ new Set(["oracle"]),
578
+ allowedGroups: /* @__PURE__ */ new Set([
579
+ "peers",
580
+ "search",
581
+ "browser",
582
+ "ado",
583
+ "kusto",
584
+ "cloudagent"
585
+ ]),
586
+ hasCoordinator: false
587
+ });
588
+ /**
536
589
  * The `-m max` profile: Sol/Luna-led, browse-only workers, and explicit
537
590
  * cross-lab peer names. The descriptor is a hard projection for bound launch
538
591
  * requests; unbound/BYO traffic remains standard because it has no registry
@@ -574,6 +627,8 @@ function profileDescriptor(id) {
574
627
  if (id === "cheapest2") return CHEAPEST2_PROFILE;
575
628
  if (id === "balanced") return BALANCED_PROFILE;
576
629
  if (id === "balanced2") return BALANCED2_PROFILE;
630
+ if (id === "local") return LOCAL_PROFILE;
631
+ if (id === "local2") return LOCAL2_PROFILE;
577
632
  return STANDARD_PROFILE;
578
633
  }
579
634
  /**
@@ -597,6 +652,8 @@ function resolveLaunchProfile(modelArg) {
597
652
  if (arg === "cheapest2") return "cheapest2";
598
653
  if (arg === "balanced") return "balanced";
599
654
  if (arg === "balanced2") return "balanced2";
655
+ if (arg === "local") return "local";
656
+ if (arg === "local2") return "local2";
600
657
  return "standard";
601
658
  }
602
659
  function validateMaxProfileLaunch(catalog) {
@@ -1229,6 +1286,61 @@ function validateBalancedProfilePrerequisites(catalog, opts = {}, profileId = "b
1229
1286
  function formatBalancedPrerequisiteFailure(missing, profileId = "balanced") {
1230
1287
  return `github-router claude -m ${profileId} requires the following live-catalog capabilities, which this account's catalog does not fully provide:\n` + missing.map((m) => ` - ${m}`).join("\n") + `\n\nFalling back or silently dropping an agent is not supported for the ${profileId} profile's exact roster. Run plain \`github-router claude\` instead.`;
1231
1288
  }
1289
+ /**
1290
+ * Validate the launch prerequisites for the `local` family.
1291
+ *
1292
+ * The LOCAL roster needs nothing from the Copilot catalog: its lead and its
1293
+ * native roles are the bare tier ids `opus` / `sonnet` / `haiku`, which the
1294
+ * local server resolves, and this profile deliberately makes no claim about
1295
+ * what that server can do (no context, effort, tool-call or endpoint check —
1296
+ * we do not know, and refusing to launch on a guess would be worse than
1297
+ * letting the server answer for itself).
1298
+ *
1299
+ * The ONE Copilot model the family still consumes is `local2`'s Advisor:
1300
+ * `gpt-6.1-sol`, server-side, at its default context and `high` effort. That
1301
+ * model is checked here, and only for `local2`. `local` has no advisor at the
1302
+ * type level, so passing its contract would be a programming error rather
1303
+ * than a launch to validate.
1304
+ *
1305
+ * Contrast with `validateCheapestProfilePrerequisites`: there the whole roster
1306
+ * IS the catalog, so every role is checked.
1307
+ */
1308
+ function validateLocalProfilePrerequisites(catalog, profileId = "local") {
1309
+ if (profileId !== "local2") return {
1310
+ ok: true,
1311
+ missing: []
1312
+ };
1313
+ const contract = local2AdvisorContract();
1314
+ const advisorModel = contract.advisorModel;
1315
+ const missing = [];
1316
+ const advisor = findModel(catalog, advisorModel);
1317
+ if (!advisor) {
1318
+ missing.push(`${advisorModel}: absent from the live catalog (the ${profileId} Advisor)`);
1319
+ return {
1320
+ ok: false,
1321
+ missing
1322
+ };
1323
+ }
1324
+ if (!hasToolCalls(advisor)) missing.push(`${advisorModel}: does not advertise tool_calls`);
1325
+ if (!hasContextAtLeast(advisor, contract.subagentContextTokens)) missing.push(`${advisorModel}: advertised context window is below the 200K subagent floor`);
1326
+ if (!supportsEffort(advisor, contract.advisorEffort)) missing.push(`${advisorModel}: does not advertise a "${contract.advisorEffort}" reasoning effort`);
1327
+ if (!supportsEndpoint(advisor, "responses")) missing.push(`${advisorModel}: does not advertise a supported Responses endpoint`);
1328
+ return {
1329
+ ok: missing.length === 0,
1330
+ missing
1331
+ };
1332
+ }
1333
+ /**
1334
+ * Format `validateLocalProfilePrerequisites`'s failure list. The local roles
1335
+ * themselves are never in the list — they need no catalog entry — so the
1336
+ * message names the Advisor explicitly rather than implying the roster failed.
1337
+ *
1338
+ * `command` is the subcommand whose launch failed (`claude` or `pi`), so the
1339
+ * remedy the message prints is one the user can actually type.
1340
+ */
1341
+ function formatLocalPrerequisiteFailure(missing, profileId = "local", command = "claude") {
1342
+ return `github-router ${command} -m ${profileId} requires the following Copilot capabilities for its server-side Advisor, which this account's catalog does not fully provide:\n` + missing.map((m) => ` - ${m}`).join("\n") + "\n\nThe lead and native roles run on the local endpoint and need no catalog entry; only the Advisor is served by Copilot. Drop the Advisor by launching `-m local` instead.";
1343
+ }
1232
1344
  //#endregion
1233
1345
  //#region src/lib/file-log-reporter.ts
1234
1346
  const MAX_LOG_BYTES = 1048576;
@@ -1653,6 +1765,34 @@ const CHEAPEST2_PICKER_MODELS = pinnedRows(cheapestContractFor("cheapest2").advi
1653
1765
  const BALANCED_PICKER_MODELS = pinnedRows(balancedContractFor("balanced").models.lead, balancedContractFor("balanced").oracleModel);
1654
1766
  const BALANCED2_PICKER_MODELS = pinnedRows(balancedContractFor("balanced2").models.lead, balancedContractFor("balanced2").oracleModel);
1655
1767
  /**
1768
+ * The `local` / `local2` rows: the three tier ids the local endpoint itself
1769
+ * resolves, emitted BARE and never catalog-filtered.
1770
+ *
1771
+ * These are not Copilot ids and must never be resolved through the catalog:
1772
+ * the proxy deliberately knows nothing about what is loaded behind the port.
1773
+ * `behavesAs` exists only because Claude Code 2.1.260 does not OFFER an
1774
+ * otherwise-unknown picker row without it; it supplies the closest
1775
+ * client-known capability profile and changes neither the label nor the id
1776
+ * that is sent.
1777
+ */
1778
+ const LOCAL_PICKER_MODELS = Object.freeze([
1779
+ {
1780
+ id: "opus",
1781
+ label: "Opus",
1782
+ behavesAs: "claude-opus-5.5"
1783
+ },
1784
+ {
1785
+ id: "sonnet",
1786
+ label: "Sonnet",
1787
+ behavesAs: "claude-sonnet-5"
1788
+ },
1789
+ {
1790
+ id: "haiku",
1791
+ label: "Haiku",
1792
+ behavesAs: "claude-haiku-4-5"
1793
+ }
1794
+ ]);
1795
+ /**
1656
1796
  * Return the ordered, profile-specific `/model` rows supported by the live
1657
1797
  * Copilot catalog. Fast intentionally shares Standard's four-row inventory;
1658
1798
  * Max replaces Grok with Opus because Grok is not an allowed Max lead.
@@ -1666,6 +1806,11 @@ const BALANCED2_PICKER_MODELS = pinnedRows(balancedContractFor("balanced2").mode
1666
1806
  * each profile's actual model/effort contract.
1667
1807
  */
1668
1808
  function selectableModelsInCatalog(profile) {
1809
+ if (isLocalFamily(profile)) return LOCAL_PICKER_MODELS.map((entry) => ({
1810
+ model: entry.id,
1811
+ label: entry.label,
1812
+ behavesAs: entry.behavesAs
1813
+ }));
1669
1814
  const catalog = state.models?.data;
1670
1815
  if (!catalog || catalog.length === 0) return [];
1671
1816
  const present = new Set(catalog.map((entry) => entry.id));
@@ -1707,7 +1852,7 @@ async function renameSettingsWithRetry(temp, target) {
1707
1852
  * 200K session's `/model` UI.
1708
1853
  */
1709
1854
  function routerWinsPicker(profile) {
1710
- return profile === "fast" || profile === "cheap" || profile === "cheap1m" || isCheapestFamily(profile) || isBalancedFamily(profile);
1855
+ return profile === "fast" || profile === "cheap" || profile === "cheap1m" || isCheapestFamily(profile) || isBalancedFamily(profile) || isLocalFamily(profile);
1711
1856
  }
1712
1857
  function modelIdsFromExistingPicker(value) {
1713
1858
  if (!value || typeof value !== "object" || Array.isArray(value)) return [];
@@ -2605,6 +2750,413 @@ function deriveAutoCompactWindowTokens(maxPromptTokens, maxOutputTokens) {
2605
2750
  return Math.min(ENV_WINDOW_MAX_TOKENS, Math.max(ENV_WINDOW_MIN_TOKENS, window));
2606
2751
  }
2607
2752
  //#endregion
2753
+ //#region src/lib/pi-paths.ts
2754
+ function appDir() {
2755
+ return path.join(os.homedir(), ".local", "share", "github-router");
2756
+ }
2757
+ /** Where the user's real Pi agent dir lives (`PI_CODING_AGENT_DIR` wins). */
2758
+ function userPiAgentDir() {
2759
+ const override = (process.env.PI_CODING_AGENT_DIR ?? "").trim();
2760
+ if (override.length > 0) return override;
2761
+ return path.join(os.homedir(), ".pi", "agent");
2762
+ }
2763
+ /**
2764
+ * Per-launch suffix for the Pi mirror. Lazily generated once per process
2765
+ * so every path getter in this module agrees on the directory.
2766
+ */
2767
+ let launchSuffix;
2768
+ function perLaunchSuffix() {
2769
+ launchSuffix ??= `pi-agent-${process.pid}-${randomBytes(4).toString("hex")}`;
2770
+ return launchSuffix;
2771
+ }
2772
+ /** Router-owned, per-launch Pi agent dir for the spawned `pi` child. */
2773
+ function piMirrorDir() {
2774
+ return path.join(appDir(), "pi-mirrors", perLaunchSuffix());
2775
+ }
2776
+ /**
2777
+ * Router-owned, durable Pi session store, shared by every launch.
2778
+ *
2779
+ * Pi's default session root is `<agent dir>/sessions/`, and the agent dir is
2780
+ * the per-launch mirror we delete on shutdown, so quitting used to take the
2781
+ * whole transcript history with it and `--continue` / `--resume` had nothing
2782
+ * left to resume. One stable root, handed to the child as
2783
+ * `PI_CODING_AGENT_SESSION_DIR`, outlives every launch. Pi groups sessions by
2784
+ * working directory under that root, so per-workspace history stays separate
2785
+ * and `--continue` still picks the right one.
2786
+ *
2787
+ * Deliberately outside `sweepStalePiAgentMirrors`: that sweep reaps mirrors by
2788
+ * PID because they are scratch, and this directory is history. Nothing here
2789
+ * ages it out either — Pi documents no retention policy, and the session
2790
+ * picker's delete is the user-facing pruning surface.
2791
+ */
2792
+ function piSessionsDir() {
2793
+ return path.join(appDir(), "pi-sessions");
2794
+ }
2795
+ /**
2796
+ * Provision the per-launch Pi mirror: snapshot-copy the user's real Pi
2797
+ * agent dir (settings, models, skills, prompts, extensions the user owns)
2798
+ * so the spawned `pi` starts from the user's own setup, then let the
2799
+ * launcher overlay the mode's generated files on top.
2800
+ *
2801
+ * Copy failures of individual user files are debug-logged and skipped —
2802
+ * a corrupt user file must not strand the launch. Throws only when the
2803
+ * mirror directory itself cannot be created.
2804
+ */
2805
+ async function ensurePiAgentMirror() {
2806
+ const mirror = piMirrorDir();
2807
+ await fs$1.mkdir(mirror, { recursive: true });
2808
+ await fs$1.mkdir(piSessionsDir(), { recursive: true });
2809
+ const source = userPiAgentDir();
2810
+ let entries;
2811
+ try {
2812
+ entries = await fs$1.readdir(source);
2813
+ } catch {
2814
+ return mirror;
2815
+ }
2816
+ const keepUserExtensions = process.env.GH_ROUTER_PI_KEEP_USER_EXTENSIONS === "1";
2817
+ const SKIP = /* @__PURE__ */ new Set([
2818
+ "auth.json",
2819
+ "sessions",
2820
+ "models-store.json",
2821
+ ...keepUserExtensions ? [] : ["extensions"]
2822
+ ]);
2823
+ await Promise.all(entries.filter((e) => !SKIP.has(e)).map(async (entry) => {
2824
+ try {
2825
+ await fs$1.cp(path.join(source, entry), path.join(mirror, entry), { recursive: true });
2826
+ } catch (err) {
2827
+ consola.debug(`Pi mirror: skipping ${entry}:`, err);
2828
+ }
2829
+ }));
2830
+ return mirror;
2831
+ }
2832
+ /** Remove THIS launch's Pi mirror on shutdown. Best-effort, never throws. */
2833
+ async function removeOwnPiAgentMirror() {
2834
+ try {
2835
+ await fs$1.rm(piMirrorDir(), {
2836
+ recursive: true,
2837
+ force: true
2838
+ });
2839
+ } catch (err) {
2840
+ consola.debug("Pi mirror cleanup failed:", err);
2841
+ }
2842
+ }
2843
+ /**
2844
+ * Sweep stale Pi mirrors left behind by crashed launches (dirs whose PID
2845
+ * no longer exists, or older than 24h). Best-effort, never throws.
2846
+ */
2847
+ async function sweepStalePiAgentMirrors() {
2848
+ const root = path.join(appDir(), "pi-mirrors");
2849
+ let entries;
2850
+ try {
2851
+ entries = await fs$1.readdir(root);
2852
+ } catch {
2853
+ return;
2854
+ }
2855
+ await Promise.all(entries.map(async (entry) => {
2856
+ const dir = path.join(root, entry);
2857
+ try {
2858
+ const stat = await fs$1.stat(dir);
2859
+ const ageMs = Date.now() - stat.mtimeMs;
2860
+ const pidMatch = /^pi-agent-(\d+)-[0-9a-f]+$/.exec(entry);
2861
+ let dead = ageMs > 864e5;
2862
+ if (pidMatch && !dead) {
2863
+ const pid = Number.parseInt(pidMatch[1], 10);
2864
+ try {
2865
+ process.kill(pid, 0);
2866
+ } catch {
2867
+ dead = true;
2868
+ }
2869
+ }
2870
+ if (dead) await fs$1.rm(dir, {
2871
+ recursive: true,
2872
+ force: true
2873
+ });
2874
+ } catch (err) {
2875
+ consola.debug(`Pi mirror sweep: skipping ${entry}:`, err);
2876
+ }
2877
+ }));
2878
+ }
2879
+ //#endregion
2880
+ //#region src/lib/pi-version-check.ts
2881
+ const PI_NPM_PACKAGE = "@earendil-works/pi-coding-agent";
2882
+ /**
2883
+ * Minimum Pi version the `pi` launcher supports.
2884
+ *
2885
+ * The floor is pinned to the first release whose `before_agent_start` event
2886
+ * carries the `messageType` discriminator (present at 1.3.0, absent at 1.1.0).
2887
+ * The generated extension's prompt hook stands down for non-user events using
2888
+ * that field, and without it the hook would fire on subagent and system turns
2889
+ * the user never typed, which is a wrong brief rather than a missing one.
2890
+ * Below-floor Pi hard-exits at the launcher (`src/pi.ts`), but only where the
2891
+ * gate actually runs: the install probe, the background refresh, and this floor
2892
+ * check all sit inside `--update-check` (default on), so `--no-update-check`
2893
+ * (documented for offline/CI) skips the floor as well. That path is still
2894
+ * fail-closed rather than silently wrong: the generated extension's own shape
2895
+ * probe sees the missing `messageType`, warns once with the fix, and injects
2896
+ * nothing.
2897
+ */
2898
+ const PI_MIN_VERSION = "1.3.0";
2899
+ /**
2900
+ * Registry used for the PI PACKAGE ONLY.
2901
+ *
2902
+ * Pi must come from a registry that actually carries it. A corporate npm mirror
2903
+ * can lag npmjs far enough that its `latest` sits below `PI_MIN_VERSION`, and
2904
+ * the launcher then fail-closes on an upgrade command the user cannot satisfy
2905
+ * (their `npm install -g` resolves through the same lagging mirror). Pointing
2906
+ * the Pi probe and install at npmjs by default keeps the floor reachable;
2907
+ * `GH_ROUTER_NPM_REGISTRY` overrides it for a mirror that does carry the
2908
+ * package. Everything else this repo installs still resolves through the user's
2909
+ * configured registry.
2910
+ */
2911
+ const PI_DEFAULT_REGISTRY = "https://registry.npmjs.org/";
2912
+ /**
2913
+ * Resolve the registry for Pi package operations. Accepts `GH_ROUTER_NPM_REGISTRY`
2914
+ * when it is an http(s) URL and falls back to `PI_DEFAULT_REGISTRY` with a
2915
+ * warning otherwise, so a typo degrades to the working default rather than
2916
+ * bricking the launcher.
2917
+ */
2918
+ function resolvePiRegistry() {
2919
+ const raw = process.env.GH_ROUTER_NPM_REGISTRY?.trim();
2920
+ if (!raw) return PI_DEFAULT_REGISTRY;
2921
+ if (!/^https?:\/\//i.test(raw)) {
2922
+ consola.warn(`Ignoring GH_ROUTER_NPM_REGISTRY=${JSON.stringify(raw)}: expected an http(s) URL. Using ${PI_DEFAULT_REGISTRY}.`);
2923
+ return PI_DEFAULT_REGISTRY;
2924
+ }
2925
+ return raw.endsWith("/") ? raw : `${raw}/`;
2926
+ }
2927
+ /** `npm` args that pin an operation to the resolved Pi registry. */
2928
+ function piRegistryArgs(registry = resolvePiRegistry()) {
2929
+ return [`--registry=${registry}`];
2930
+ }
2931
+ const THROTTLE_HOURS = 1;
2932
+ const NPM_VIEW_TIMEOUT_MS = 5e3;
2933
+ const PI_VERSION_TIMEOUT_MS = 3e3;
2934
+ const NPM_INSTALL_TIMEOUT_MS = 3e5;
2935
+ /** Path to the throttle cache. Created on demand. Separate file from the Claude check. */
2936
+ function cacheFilePath() {
2937
+ return path.join(os.homedir(), ".local", "share", "github-router", "last-pi-update-check");
2938
+ }
2939
+ async function readCache() {
2940
+ try {
2941
+ const raw = await fs$1.readFile(cacheFilePath(), "utf8");
2942
+ const parsed = JSON.parse(raw);
2943
+ if (typeof parsed.checkedAt !== "string" || parsed.installedVersion !== null && typeof parsed.installedVersion !== "string" || parsed.latestVersion !== null && typeof parsed.latestVersion !== "string") return null;
2944
+ return parsed;
2945
+ } catch {
2946
+ return null;
2947
+ }
2948
+ }
2949
+ async function writeCache(cache) {
2950
+ try {
2951
+ await fs$1.mkdir(path.dirname(cacheFilePath()), { recursive: true });
2952
+ await fs$1.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 384 });
2953
+ } catch (err) {
2954
+ consola.debug("Failed to write pi version-check cache:", err);
2955
+ }
2956
+ }
2957
+ function shouldCheckNow(cache) {
2958
+ if (!cache) return true;
2959
+ const lastCheck = new Date(cache.checkedAt).getTime();
2960
+ if (Number.isNaN(lastCheck)) return true;
2961
+ return (Date.now() - lastCheck) / 1e3 / 3600 >= THROTTLE_HOURS;
2962
+ }
2963
+ /**
2964
+ * Read the installed `pi` version. Returns null if pi is not on PATH
2965
+ * or the version probe fails.
2966
+ *
2967
+ * Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path
2968
+ * (excluding the cwd) before invocation via the shared exec helper.
2969
+ */
2970
+ async function getInstalledPiVersion() {
2971
+ const piPath = resolveExecutable("pi");
2972
+ if (!piPath) return null;
2973
+ try {
2974
+ const { stdout, code } = await runCommandCapture([piPath, "--version"], { timeoutMs: PI_VERSION_TIMEOUT_MS });
2975
+ if (code !== 0) return null;
2976
+ const match = stdout.match(/(\d+\.\d+\.\d+)/);
2977
+ return match ? match[1] : null;
2978
+ } catch {
2979
+ return null;
2980
+ }
2981
+ }
2982
+ /** Fetch the latest Pi version from npm. Null on network/npm failure. */
2983
+ async function getLatestPiVersion() {
2984
+ const npmPath = resolveExecutable("npm");
2985
+ if (!npmPath) return null;
2986
+ try {
2987
+ const { stdout, code } = await runCommandCapture([
2988
+ npmPath,
2989
+ "view",
2990
+ PI_NPM_PACKAGE,
2991
+ "version",
2992
+ "--silent",
2993
+ ...piRegistryArgs()
2994
+ ], { timeoutMs: NPM_VIEW_TIMEOUT_MS });
2995
+ if (code !== 0) return null;
2996
+ const v = stdout.trim();
2997
+ return /^\d+\.\d+\.\d+/.test(v) ? v : null;
2998
+ } catch {
2999
+ return null;
3000
+ }
3001
+ }
3002
+ /**
3003
+ * Compare two semver-shaped strings (leading X.Y.Z only). True when
3004
+ * `latest` is strictly higher than `installed`.
3005
+ */
3006
+ function isPiNewer(installed, latest) {
3007
+ if (!installed || !latest) return false;
3008
+ const a = installed.split(".").map((n) => parseInt(n, 10));
3009
+ const b = latest.split(".").map((n) => parseInt(n, 10));
3010
+ for (let i = 0; i < 3; i++) {
3011
+ const av = a[i] ?? 0;
3012
+ const bv = b[i] ?? 0;
3013
+ if (av < bv) return true;
3014
+ if (av > bv) return false;
3015
+ }
3016
+ return false;
3017
+ }
3018
+ /** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */
3019
+ function meetsPiMinVersion(version) {
3020
+ if (!version) return false;
3021
+ return !isPiNewer(version, PI_MIN_VERSION);
3022
+ }
3023
+ /** Run a version check (subject to throttle). Side-effect: updates the cache. */
3024
+ async function checkPiVersion(opts = {}) {
3025
+ if (opts.noCheck) return {
3026
+ installed: false,
3027
+ installedVersion: null,
3028
+ latestVersion: null,
3029
+ needsUpdate: false,
3030
+ needsMinUpgrade: false,
3031
+ skipped: true,
3032
+ skipReason: "disabled"
3033
+ };
3034
+ const cache = await readCache();
3035
+ if (!opts.force && !shouldCheckNow(cache)) {
3036
+ const installedVersion = cache?.installedVersion ?? null;
3037
+ const latestVersion = cache?.latestVersion ?? null;
3038
+ return {
3039
+ installed: installedVersion !== null,
3040
+ installedVersion,
3041
+ latestVersion,
3042
+ needsUpdate: isPiNewer(installedVersion, latestVersion),
3043
+ needsMinUpgrade: !meetsPiMinVersion(installedVersion),
3044
+ skipped: true,
3045
+ skipReason: "throttled"
3046
+ };
3047
+ }
3048
+ const installedVersion = await getInstalledPiVersion();
3049
+ if (installedVersion === null) return {
3050
+ installed: false,
3051
+ installedVersion: null,
3052
+ latestVersion: null,
3053
+ needsUpdate: false,
3054
+ needsMinUpgrade: true,
3055
+ skipped: true,
3056
+ skipReason: "no-pi"
3057
+ };
3058
+ const latestVersion = await getLatestPiVersion();
3059
+ await writeCache({
3060
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
3061
+ installedVersion,
3062
+ latestVersion
3063
+ });
3064
+ if (latestVersion === null) return {
3065
+ installed: true,
3066
+ installedVersion,
3067
+ latestVersion: null,
3068
+ needsUpdate: false,
3069
+ needsMinUpgrade: !meetsPiMinVersion(installedVersion),
3070
+ skipped: true,
3071
+ skipReason: "no-npm"
3072
+ };
3073
+ return {
3074
+ installed: true,
3075
+ installedVersion,
3076
+ latestVersion,
3077
+ needsUpdate: isPiNewer(installedVersion, latestVersion),
3078
+ needsMinUpgrade: !meetsPiMinVersion(installedVersion),
3079
+ skipped: false
3080
+ };
3081
+ }
3082
+ /**
3083
+ * Install (or upgrade) Pi from npm under the cross-process install lock.
3084
+ * Returns `true` when this call performed the install, `false` when
3085
+ * another process holds the lock (caller skips — its install will land
3086
+ * for a later launch). Best-effort: throws on failure; callers fall
3087
+ * back to the installed version with a visible warning rather than
3088
+ * stranding the launch.
3089
+ */
3090
+ function updatePi(version, opts = {}) {
3091
+ const npmPath = resolveExecutable("npm");
3092
+ if (!npmPath) throw new Error("npm not found on PATH; cannot install Pi automatically");
3093
+ return withInstallLock("pi-install.lock", async () => {
3094
+ const registry = resolvePiRegistry();
3095
+ consola.info(`Installing ${PI_NPM_PACKAGE}@${version} from ${registry}...`);
3096
+ await runCommandVoid([
3097
+ npmPath,
3098
+ "install",
3099
+ "-g",
3100
+ `${PI_NPM_PACKAGE}@${version}`,
3101
+ ...piRegistryArgs(registry)
3102
+ ], {
3103
+ timeoutMs: NPM_INSTALL_TIMEOUT_MS,
3104
+ signal: opts.signal
3105
+ });
3106
+ });
3107
+ }
3108
+ /**
3109
+ * Blocking fresh install for when Pi is absent entirely. Installs
3110
+ * `@latest`, then force re-checks; throws when Pi still is not on PATH
3111
+ * (caller exits with the install command). Only used when there is no
3112
+ * usable Pi at all — the healthy path never blocks on npm.
3113
+ */
3114
+ async function ensurePiInstalled(opts = {}) {
3115
+ const acquired = await updatePi("latest", opts);
3116
+ const retry = await checkPiVersion({ force: true });
3117
+ if (retry.installed && retry.installedVersion) return retry.installedVersion;
3118
+ throw new Error(acquired ? "install did not place pi on PATH" : "another Pi install is already running; retry in a moment");
3119
+ }
3120
+ /**
3121
+ * Fire-and-forget freshness refresh for a healthy Pi install. Never
3122
+ * blocks launch and never throws: on the throttled schedule it probes
3123
+ * npm for a newer Pi and, when one exists, queues a DETACHED post-exit
3124
+ * install (same pattern as the proxy self-update) so neither startup
3125
+ * nor the running session nor shutdown ever waits on npm. The
3126
+ * cross-process install lock serializes against concurrent launches;
3127
+ * every failure degrades to a debug log.
3128
+ *
3129
+ * Deliberately never touches a below-floor install: the floor is
3130
+ * enforced foreground by the launcher (fail-closed), and a background
3131
+ * task must not change what the running session validated.
3132
+ */
3133
+ function refreshPiInBackground(opts) {
3134
+ if (!opts.autoUpdate) return;
3135
+ (async () => {
3136
+ try {
3137
+ if (!shouldCheckNow(await readCache())) return;
3138
+ const installedVersion = await getInstalledPiVersion();
3139
+ if (!meetsPiMinVersion(installedVersion)) return;
3140
+ const npmPath = resolveExecutable("npm");
3141
+ const latestVersion = await getLatestPiVersion();
3142
+ await writeCache({
3143
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
3144
+ installedVersion,
3145
+ latestVersion
3146
+ });
3147
+ if (!npmPath) return;
3148
+ if (!latestVersion || !isPiNewer(installedVersion, latestVersion)) return;
3149
+ if (await withInstallLock("pi-install.lock", async () => {
3150
+ queueDetachedGlobalInstall(npmPath, `@earendil-works/pi-coding-agent@${latestVersion}`, piRegistryArgs());
3151
+ })) consola.info(`Pi ${installedVersion} → ${latestVersion} update queued; it takes effect on the next launch.`);
3152
+ } catch (err) {
3153
+ consola.debug("Background Pi refresh failed:", err);
3154
+ }
3155
+ })().catch((err) => {
3156
+ consola.debug("Background Pi refresh failed:", err);
3157
+ });
3158
+ }
3159
+ //#endregion
2608
3160
  //#region src/lib/proxy.ts
2609
3161
  let socketCounter = 0;
2610
3162
  /**
@@ -2958,7 +3510,7 @@ function collectToolFieldKeys(body) {
2958
3510
  //#endregion
2959
3511
  //#region package.json
2960
3512
  var name = "github-router";
2961
- var version = "0.3.356";
3513
+ var version = "0.3.367";
2962
3514
  //#endregion
2963
3515
  //#region src/lib/approval.ts
2964
3516
  const awaitApproval = async () => {
@@ -3826,6 +4378,7 @@ completionRoutes.post("/", async (c) => {
3826
4378
  //#endregion
3827
4379
  //#region src/services/copilot/create-embeddings.ts
3828
4380
  const createEmbeddings = async (payload) => {
4381
+ assertCopilotModelAllowed(payload.model);
3829
4382
  if (!state.copilotToken) throw new Error("Copilot token not found");
3830
4383
  const body = JSON.stringify(payload);
3831
4384
  const response = await fetchWithTransientRetry(() => tryRefreshAndRetry(() => fetch(`${copilotBaseUrl(state)}/embeddings`, {
@@ -5996,11 +6549,23 @@ const LAUNCH_SECRET_HEADER = "X-GH-Router-Launch-Secret";
5996
6549
  */
5997
6550
  function runMessagesIdentityPreflight(c) {
5998
6551
  const header = c.req.header(LAUNCH_SECRET_HEADER);
5999
- if (!header) return { ok: true };
6000
- const launch = findLaunchBySecret(header);
6552
+ if (header) {
6553
+ const launch = findLaunchBySecret(header);
6554
+ if (!launch) return {
6555
+ ok: false,
6556
+ reason: "X-GH-Router-Launch-Secret header did not match any registered launch (the launch may have been restarted, or the header was tampered with)"
6557
+ };
6558
+ return {
6559
+ ok: true,
6560
+ launch
6561
+ };
6562
+ }
6563
+ const bearerSecret = launchSecretFromBearer(c.req.header("authorization"));
6564
+ if (bearerSecret === void 0) return { ok: true };
6565
+ const launch = bearerSecret ? findLaunchBySecret(bearerSecret) : void 0;
6001
6566
  if (!launch) return {
6002
6567
  ok: false,
6003
- reason: "X-GH-Router-Launch-Secret header did not match any registered launch (the launch may have been restarted, or the header was tampered with)"
6568
+ reason: `Authorization bearer carried a ${LAUNCH_BOUND_TOKEN_PREFIX} launch token that did not match any registered launch (the launch may have been restarted, or the token was tampered with)`
6004
6569
  };
6005
6570
  return {
6006
6571
  ok: true,
@@ -6008,6 +6573,24 @@ function runMessagesIdentityPreflight(c) {
6008
6573
  };
6009
6574
  }
6010
6575
  /**
6576
+ * Pull the launch secret out of an `Authorization: Bearer` value.
6577
+ *
6578
+ * Returns `undefined` for anything that does not assert a launch identity:
6579
+ * a missing header, another scheme, or the shared `github-router-synthetic`
6580
+ * token. Returns an empty string for a prefixed but empty token, which the
6581
+ * caller treats as a failed match rather than as unbound traffic — a request
6582
+ * that says "I am this launch" and names nobody is never silently downgraded
6583
+ * to BYO.
6584
+ */
6585
+ function launchSecretFromBearer(authorization) {
6586
+ if (!authorization) return void 0;
6587
+ const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
6588
+ if (!match) return void 0;
6589
+ const token = match[1].trim();
6590
+ if (!token.startsWith("github-router-launch:")) return void 0;
6591
+ return token.slice(LAUNCH_BOUND_TOKEN_PREFIX.length);
6592
+ }
6593
+ /**
6011
6594
  * Anthropic-shaped rejection for a failed identity preflight. 403, never
6012
6595
  * 401 — see the no-401 invariant note on `runMessagesIdentityPreflight`.
6013
6596
  */
@@ -6169,6 +6752,11 @@ function preprocessFastRequest(rawBody, launch, subagentRequest = false) {
6169
6752
  body: rawBody,
6170
6753
  modified: false
6171
6754
  };
6755
+ if (isLocalFamily(launch?.profileId)) return {
6756
+ body: rawBody,
6757
+ originalModel,
6758
+ modified: false
6759
+ };
6172
6760
  if (isRetiredFastModelAlias(originalModel)) return {
6173
6761
  body: rawBody,
6174
6762
  originalModel,
@@ -6224,6 +6812,114 @@ function preprocessFastRequest(rawBody, launch, subagentRequest = false) {
6224
6812
  modified: true
6225
6813
  };
6226
6814
  }
6815
+ const LOCAL_DEFAULT_BASE_URL = `https://localhost:11111/v1`;
6816
+ let cliOverride;
6817
+ let warnedInert = false;
6818
+ function trimTrailingSlashes(value) {
6819
+ return value.replace(/\/+$/, "");
6820
+ }
6821
+ /**
6822
+ * Validate an absolute http(s) base URL and normalize it to the form the
6823
+ * egress concatenates (`<base>/messages`). A bare origin gains the documented
6824
+ * `/v1` prefix so `--localurl http://localhost:11111` and
6825
+ * `--localurl http://localhost:11111/v1` mean the same thing.
6826
+ */
6827
+ function normalizeBaseUrl(raw, source) {
6828
+ const trimmed = raw.trim();
6829
+ if (trimmed.length === 0) throw new Error(`${source} must not be empty`);
6830
+ let parsed;
6831
+ try {
6832
+ parsed = new URL(trimmed);
6833
+ } catch {
6834
+ throw new Error(`${source} must be an absolute http(s) URL (got "${trimmed}")`);
6835
+ }
6836
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`${source} must be an http(s) URL (got "${parsed.protocol}")`);
6837
+ if (parsed.search.length > 0 || parsed.hash.length > 0) throw new Error(`${source} must not carry a query or fragment (got "${trimmed}")`);
6838
+ if (parsed.pathname === "/" || parsed.pathname === "") parsed.pathname = "/v1";
6839
+ return trimTrailingSlashes(parsed.toString());
6840
+ }
6841
+ function parseLocalPort(raw, source) {
6842
+ const trimmed = raw.trim();
6843
+ if (!/^\d+$/.test(trimmed)) throw new Error(`${source} must be an integer port (got "${trimmed}")`);
6844
+ const port = Number(trimmed);
6845
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`${source} must be between 1 and 65535 (got "${trimmed}")`);
6846
+ return port;
6847
+ }
6848
+ function withPort(baseUrl, port) {
6849
+ const parsed = new URL(baseUrl);
6850
+ parsed.port = String(port);
6851
+ return trimTrailingSlashes(parsed.toString());
6852
+ }
6853
+ /**
6854
+ * Resolve the local upstream base URL.
6855
+ *
6856
+ * Precedence, highest first:
6857
+ * 1. `--localurl` (full base URL)
6858
+ * 2. `--localport` (port of the base URL resolved below)
6859
+ * 3. `GH_ROUTER_LOCAL_BASE_URL`
6860
+ * 4. `GH_ROUTER_LOCAL_PORT`
6861
+ * 5. `https://localhost:11111/v1`
6862
+ *
6863
+ * The default scheme is `https` because that is the only endpoint measured.
6864
+ * A plain-HTTP server needs an explicit `--localurl http://...`; inferring the
6865
+ * scheme from the port number would be exactly the guess this profile refuses
6866
+ * to make.
6867
+ */
6868
+ function localBaseUrl(env = process.env) {
6869
+ if (cliOverride?.baseUrl !== void 0) return cliOverride.baseUrl;
6870
+ const envBaseRaw = (env.GH_ROUTER_LOCAL_BASE_URL ?? "").trim();
6871
+ const base = envBaseRaw.length > 0 ? normalizeBaseUrl(envBaseRaw, "GH_ROUTER_LOCAL_BASE_URL") : LOCAL_DEFAULT_BASE_URL;
6872
+ if (cliOverride?.port !== void 0) return withPort(base, cliOverride.port);
6873
+ const envPortRaw = (env.GH_ROUTER_LOCAL_PORT ?? "").trim();
6874
+ if (envPortRaw.length > 0) return withPort(base, parseLocalPort(envPortRaw, "GH_ROUTER_LOCAL_PORT"));
6875
+ return base;
6876
+ }
6877
+ /**
6878
+ * Apply the CLI-level endpoint override. Called once per launch, before
6879
+ * `setupAndServe` starts accepting requests. Passing an empty object clears
6880
+ * any previous override.
6881
+ *
6882
+ * Deliberately does NOT write `process.env`: the child environment is
6883
+ * filtered and rebuilt, so a module-level value is the only surface that
6884
+ * cannot be reinterpreted by something else downstream.
6885
+ */
6886
+ function configureLocalEgress(override) {
6887
+ const baseProvided = override.baseUrl !== void 0;
6888
+ const portProvided = override.port !== void 0;
6889
+ if (!baseProvided && !portProvided) {
6890
+ cliOverride = void 0;
6891
+ warnedInert = false;
6892
+ return;
6893
+ }
6894
+ if (baseProvided && portProvided) throw new Error("--localurl and --localport cannot be combined; pass one endpoint spelling");
6895
+ if (override.profileId !== void 0 && !isLocalFamily(override.profileId)) {
6896
+ if (!warnedInert) {
6897
+ warnedInert = true;
6898
+ consola.warn(`--localurl/--localport only apply to the local launch profiles (profile: ${override.profileId}); ignoring`);
6899
+ }
6900
+ cliOverride = void 0;
6901
+ return;
6902
+ }
6903
+ if (override.baseUrl !== void 0) {
6904
+ cliOverride = { baseUrl: normalizeBaseUrl(override.baseUrl, "--localurl") };
6905
+ return;
6906
+ }
6907
+ cliOverride = { port: parseLocalPort(String(override.port), "--localport") };
6908
+ }
6909
+ /**
6910
+ * The session id sent upstream on the local path.
6911
+ *
6912
+ * `x-claude-code-session-id` is what the local server requires (a request
6913
+ * without it is a 400). It must stay stable per conversation, so the client's
6914
+ * own value always wins and the process-level id is only a fallback for a
6915
+ * caller that sent none. Never synthesize a fresh value per request: the
6916
+ * header exists for prompt-cache routing, and a random value defeats it.
6917
+ */
6918
+ function localSessionId(c) {
6919
+ const incoming = c.req.header("x-claude-code-session-id")?.trim();
6920
+ if (incoming !== void 0 && incoming.length > 0) return incoming;
6921
+ return state.sessionId;
6922
+ }
6227
6923
  //#endregion
6228
6924
  //#region src/lib/prompt-window-salvage.ts
6229
6925
  /**
@@ -6453,6 +7149,22 @@ function extractBetaHeaders(c) {
6453
7149
  return headers;
6454
7150
  }
6455
7151
  /**
7152
+ * Beta headers for a local-profile request: forwarded VERBATIM.
7153
+ *
7154
+ * `filterBetaHeader`'s allowlist is a list of capabilities COPILOT supports.
7155
+ * A local server's capabilities are unknowable by construction (the profile
7156
+ * assumes nothing about the stack behind the endpoint), so filtering here would
7157
+ * strip features the server may well implement. The one value removed is the
7158
+ * proxy's own `advisor-tool-` beta: the router consumes that marker rather than
7159
+ * forwarding it, on every profile.
7160
+ */
7161
+ function rawLocalBetaHeaders(c) {
7162
+ const anthropicBeta = c.req.header("anthropic-beta");
7163
+ if (!anthropicBeta) return {};
7164
+ const kept = anthropicBeta.split(",").map((part) => part.trim()).filter((part) => part.length > 0 && !part.startsWith("advisor-tool-"));
7165
+ return kept.length > 0 ? { "anthropic-beta": kept.join(",") } : {};
7166
+ }
7167
+ /**
6456
7168
  * Extract the text content from the last user message for web search.
6457
7169
  * Handles both string content and content block arrays (multimodal).
6458
7170
  */
@@ -6697,7 +7409,8 @@ async function handleCompletion(c) {
6697
7409
  });
6698
7410
  }
6699
7411
  if (state.manualApprove) await awaitApproval();
6700
- const betaHeaders = extractBetaHeaders(c);
7412
+ const localProfileRequest = effectiveLocalProfile(identity.launch?.profileId) !== void 0;
7413
+ const betaHeaders = localProfileRequest ? rawLocalBetaHeaders(c) : extractBetaHeaders(c);
6701
7414
  const incomingBeta = c.req.header("anthropic-beta");
6702
7415
  const advisorRequested = isAdvisorRequested(incomingBeta);
6703
7416
  const fastProfileRequest = identity.launch?.profileId === "fast";
@@ -6705,8 +7418,10 @@ async function handleCompletion(c) {
6705
7418
  const cheapProfileRequest = identity.launch?.profileId === "cheap" || identity.launch?.profileId === "cheap1m";
6706
7419
  const cheapestProfileRequest = isCheapestFamily(identity.launch?.profileId);
6707
7420
  const balancedProfileRequest = isBalancedFamily(identity.launch?.profileId);
6708
- const cheapestFamilyAdvisorModel = isCheapestFamily(identity.launch?.profileId) ? cheapestContractFor(identity.launch?.profileId).advisorModel : void 0;
6709
- const cheapestFamilyAdvisorClientModel = isCheapestFamily(identity.launch?.profileId) ? cheapestContractFor(identity.launch?.profileId).advisorClientModel : void 0;
7421
+ const localAdvisorRequest = identity.launch?.profileId === "local2";
7422
+ const curatedAdvisorContract = localAdvisorRequest ? local2AdvisorContract() : cheapestProfileRequest ? cheapestContractFor(identity.launch?.profileId) : void 0;
7423
+ const curatedAdvisorModel = curatedAdvisorContract?.advisorModel;
7424
+ const curatedAdvisorClientModel = curatedAdvisorContract?.advisorClientModel;
6710
7425
  const subagentAgentId = (c.req.header("x-claude-code-agent-id") ?? "").trim();
6711
7426
  const subagentRequest = subagentAgentId.length > 0;
6712
7427
  const fastSubagentRequest = fastProfileRequest && subagentRequest;
@@ -6717,16 +7432,18 @@ async function handleCompletion(c) {
6717
7432
  const fastLeadAdvisor = fastProfileRequest && !fastSubagentRequest;
6718
7433
  const maxLeadAdvisor = maxProfileRequest && !maxSubagentRequest;
6719
7434
  const cheapLeadAdvisor = cheapProfileRequest && !cheapSubagentRequest;
6720
- const cheapestLeadAdvisor = cheapestProfileRequest && !cheapestSubagentRequest;
7435
+ const curatedLeadAdvisor = cheapestProfileRequest && !cheapestSubagentRequest || localAdvisorRequest && !subagentRequest;
6721
7436
  const cheapestReviewerAdvisor = cheapestProfileRequest && (subagentAgentId === "reviewer" || isCheapestReviewerModel(rawBody));
6722
- if (cheapestProfileRequest && subagentRequest) consola.debug(`cheapest subagent advisor gate: agentId=${JSON.stringify(subagentAgentId)} reviewerModel=${isCheapestReviewerModel(rawBody)} granted=${cheapestReviewerAdvisor && advisorRequested}`);
6723
- const advisorEnabled = advisorRequested && !fastSubagentRequest && !maxSubagentRequest && !cheapSubagentRequest && (!cheapestSubagentRequest || cheapestReviewerAdvisor) && !balancedSubagentRequest;
7437
+ const localReviewerAdvisor = localAdvisorRequest && (subagentAgentId === "reviewer" || subagentAgentId.startsWith("reviewer-"));
7438
+ if ((cheapestProfileRequest || localAdvisorRequest) && subagentRequest) consola.debug(`curated subagent advisor gate: agentId=${JSON.stringify(subagentAgentId)} reviewerModel=${isCheapestReviewerModel(rawBody)} granted=${(cheapestReviewerAdvisor || localReviewerAdvisor) && advisorRequested}`);
7439
+ const advisorEnabled = advisorRequested && !localProfileRequest && !fastSubagentRequest && !maxSubagentRequest && !cheapSubagentRequest && (!cheapestSubagentRequest || cheapestReviewerAdvisor) && !balancedSubagentRequest;
6724
7440
  const fastAdvisorEnabled = fastLeadAdvisor && advisorRequested && hasNonEmptyTools(rawBody);
6725
7441
  const maxAdvisorEnabled = maxLeadAdvisor && advisorRequested && hasNonEmptyTools(rawBody);
6726
7442
  const cheapAdvisorEnabled = cheapLeadAdvisor && advisorRequested && hasNonEmptyTools(rawBody);
6727
- const cheapestAdvisorEnabled = cheapestLeadAdvisor && advisorRequested && hasNonEmptyTools(rawBody);
6728
- const cheapestReviewerEnabled = cheapestReviewerAdvisor && advisorRequested && hasNonEmptyTools(rawBody);
6729
- const advisorBehaviorEnabled = balancedProfileRequest ? false : fastLeadAdvisor ? fastAdvisorEnabled : cheapLeadAdvisor ? cheapAdvisorEnabled : cheapestLeadAdvisor ? cheapestAdvisorEnabled : maxLeadAdvisor ? maxAdvisorEnabled : cheapestReviewerAdvisor ? cheapestReviewerEnabled : advisorEnabled;
7443
+ const curatedAdvisorEnabled = curatedLeadAdvisor && advisorRequested && hasNonEmptyTools(rawBody);
7444
+ const curatedReviewerAdvisor = cheapestReviewerAdvisor || localReviewerAdvisor;
7445
+ const curatedReviewerEnabled = curatedReviewerAdvisor && advisorRequested && hasNonEmptyTools(rawBody);
7446
+ const advisorBehaviorEnabled = balancedProfileRequest ? false : localProfileRequest ? curatedAdvisorEnabled || curatedReviewerEnabled : fastLeadAdvisor ? fastAdvisorEnabled : cheapLeadAdvisor ? cheapAdvisorEnabled : curatedLeadAdvisor ? curatedAdvisorEnabled : maxLeadAdvisor ? maxAdvisorEnabled : curatedReviewerAdvisor ? curatedReviewerEnabled : advisorEnabled;
6730
7447
  let fastAdvisorChoice;
6731
7448
  let maxAdvisorChoice;
6732
7449
  if (maxAdvisorEnabled) {
@@ -6787,17 +7504,21 @@ async function handleCompletion(c) {
6787
7504
  }, 503);
6788
7505
  }
6789
7506
  }
6790
- if (cheapestAdvisorEnabled) {
6791
- const mismatch = cheapestAdvisorMetadataMismatch(rawBody, cheapestFamilyAdvisorClientModel ?? CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL);
6792
- if (mismatch) return c.json({
6793
- type: "error",
6794
- error: {
6795
- type: "invalid_request_error",
6796
- message: `Cheapest Advisor model mismatch: ${mismatch}. Run \`/advisor ${cheapestFamilyAdvisorClientModel ?? CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL}\` to restore the fixed cheapest profile, or relaunch with \`github-router claude -m ${identity.launch?.profileId ?? "cheapest"}\`.`
6797
- }
6798
- }, 400);
7507
+ if (curatedAdvisorEnabled) {
7508
+ const mismatch = cheapestAdvisorMetadataMismatch(rawBody, curatedAdvisorClientModel ?? CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL);
7509
+ if (mismatch) {
7510
+ const curatedLabel = localAdvisorRequest ? "Local Advisor" : "Cheapest Advisor";
7511
+ const curatedAlias = localAdvisorRequest ? "local2" : "cheapest";
7512
+ return c.json({
7513
+ type: "error",
7514
+ error: {
7515
+ type: "invalid_request_error",
7516
+ message: `${curatedLabel} model mismatch: ${mismatch}. Run \`/advisor ${curatedAdvisorClientModel ?? CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL}\` to restore the fixed ${curatedAlias} profile, or relaunch with \`github-router claude -m ${identity.launch?.profileId ?? curatedAlias}\`.`
7517
+ }
7518
+ }, 400);
7519
+ }
6799
7520
  try {
6800
- fastAdvisorChoice = resolveCheapestAdvisorModel(cheapestFamilyAdvisorModel);
7521
+ fastAdvisorChoice = resolveCheapestAdvisorModel(curatedAdvisorModel);
6801
7522
  } catch (error) {
6802
7523
  return c.json({
6803
7524
  type: "error",
@@ -6808,8 +7529,8 @@ async function handleCompletion(c) {
6808
7529
  }, 503);
6809
7530
  }
6810
7531
  }
6811
- if (cheapestReviewerEnabled && !fastAdvisorChoice) try {
6812
- fastAdvisorChoice = resolveCheapestAdvisorModel(cheapestFamilyAdvisorModel);
7532
+ if (curatedReviewerEnabled && !fastAdvisorChoice) try {
7533
+ fastAdvisorChoice = resolveCheapestAdvisorModel(curatedAdvisorModel);
6813
7534
  } catch (error) {
6814
7535
  return c.json({
6815
7536
  type: "error",
@@ -6834,7 +7555,7 @@ async function handleCompletion(c) {
6834
7555
  }
6835
7556
  let finalBody = await processWebSearch(fastPreprocess.body);
6836
7557
  finalBody = sanitizeAnthropicBody(finalBody);
6837
- if (fastSubagentRequest || maxSubagentRequest || cheapestSubagentRequest && !cheapestReviewerAdvisor) finalBody = stripAdvisorTool(finalBody);
7558
+ if (fastSubagentRequest || maxSubagentRequest || cheapestSubagentRequest && !cheapestReviewerAdvisor || localProfileRequest && !advisorBehaviorEnabled) finalBody = stripAdvisorTool(finalBody);
6838
7559
  const loopGuard = guardAnthropicBody(finalBody);
6839
7560
  if (loopGuard.action === "abort") return c.json({
6840
7561
  type: "error",
@@ -6845,7 +7566,14 @@ async function handleCompletion(c) {
6845
7566
  }, 400, { "x-should-retry": "false" });
6846
7567
  if (loopGuard.body !== void 0) finalBody = loopGuard.body;
6847
7568
  if (advisorBehaviorEnabled) {
6848
- finalBody = injectAdvisorTool(finalBody, cheapestReviewerAdvisor ? CHEAPEST_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS : cheapestLeadAdvisor ? CHEAPEST_ADVISOR_TOOL_INSTRUCTIONS : fastLeadAdvisor ? FAST_ADVISOR_TOOL_INSTRUCTIONS : maxLeadAdvisor ? MAX_PROFILE_ADVISOR_INSTRUCTIONS : void 0);
7569
+ const curatedAdvisorInstructions = localAdvisorRequest ? {
7570
+ lead: LOCAL_ADVISOR_TOOL_INSTRUCTIONS,
7571
+ reviewer: LOCAL_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS
7572
+ } : {
7573
+ lead: CHEAPEST_ADVISOR_TOOL_INSTRUCTIONS,
7574
+ reviewer: CHEAPEST_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS
7575
+ };
7576
+ finalBody = injectAdvisorTool(finalBody, curatedReviewerAdvisor ? curatedAdvisorInstructions.reviewer : curatedLeadAdvisor ? curatedAdvisorInstructions.lead : fastLeadAdvisor ? FAST_ADVISOR_TOOL_INSTRUCTIONS : maxLeadAdvisor ? MAX_PROFILE_ADVISOR_INSTRUCTIONS : void 0);
6849
7577
  consola.info("ADVISOR enabled for this request — injecting __anthropic_advisor tool; will translate tool_use → server_tool_use{advisor} on the SSE stream");
6850
7578
  }
6851
7579
  if (finalBody.includes("\"mcp_servers\"")) try {
@@ -6858,10 +7586,10 @@ async function handleCompletion(c) {
6858
7586
  }
6859
7587
  }, 400);
6860
7588
  } catch {}
6861
- const { body: resolvedBody, originalModel, resolvedModel, selectedModel } = resolveModelInBody$1(finalBody);
7589
+ const { body: resolvedBody, originalModel, resolvedModel, selectedModel } = localProfileRequest ? localModelInBody$1(finalBody) : resolveModelInBody$1(finalBody);
6862
7590
  const modelId = resolvedModel ?? originalModel;
6863
7591
  const { body: promptWindowBody } = await salvageOversizedPrompt(resolvedBody, selectedModel);
6864
- const messagesRoute = classifyMessagesRoute(modelId, selectedModel, originalModel, fastProfileRequest);
7592
+ const messagesRoute = localProfileRequest ? "claude-passthrough" : classifyMessagesRoute(modelId, selectedModel, originalModel, fastProfileRequest);
6865
7593
  if (messagesRoute !== "claude-passthrough") {
6866
7594
  const endpoint = messagesRoute === "chat-shim" ? "chat" : "responses";
6867
7595
  let parsedBase;
@@ -6869,7 +7597,7 @@ async function handleCompletion(c) {
6869
7597
  parsedBase = JSON.parse(promptWindowBody);
6870
7598
  } catch {}
6871
7599
  const wantsStream = parsedBase?.stream === true;
6872
- if ((fastAdvisorEnabled || cheapAdvisorEnabled || cheapestAdvisorEnabled || maxAdvisorEnabled || cheapestReviewerEnabled) && wantsStream) {
7600
+ if ((fastAdvisorEnabled || cheapAdvisorEnabled || curatedAdvisorEnabled || maxAdvisorEnabled || curatedReviewerEnabled) && wantsStream) {
6873
7601
  const initialConversation = Array.isArray(parsedBase.messages) ? parsedBase.messages : [];
6874
7602
  const parsedInitial = parseAnthropicRequest(parsedBase, modelId, selectedModel);
6875
7603
  const translatedAdvisorAborter = new AbortController();
@@ -6892,7 +7620,7 @@ async function handleCompletion(c) {
6892
7620
  effort: maxAdvisorChoice.effort,
6893
7621
  escalated: false,
6894
7622
  fastProfile: false
6895
- } : cheapAdvisorEnabled || cheapestAdvisorEnabled || cheapestReviewerEnabled ? {
7623
+ } : cheapAdvisorEnabled || curatedAdvisorEnabled || curatedReviewerEnabled ? {
6896
7624
  model: fastAdvisorChoice.model,
6897
7625
  effort: resolveAdvisorEffort(rawBody, fastAdvisorChoice.model, true),
6898
7626
  escalated: fastAdvisorChoice.escalated,
@@ -6910,12 +7638,13 @@ async function handleCompletion(c) {
6910
7638
  requestHeaders: {},
6911
7639
  advisorModel: advisorChoice.model,
6912
7640
  advisorEscalated: advisorChoice.escalated,
6913
- advisorFastProfile: advisorChoice.fastProfile && !cheapestReviewerEnabled,
7641
+ advisorFastProfile: advisorChoice.fastProfile && !curatedReviewerEnabled,
6914
7642
  advisorMaxProfile: maxAdvisorEnabled,
6915
- advisorCheapProfile: cheapAdvisorEnabled || cheapestAdvisorEnabled || cheapestReviewerEnabled,
6916
- advisorCheapestProfile: cheapestAdvisorEnabled || cheapestReviewerEnabled,
6917
- advisorReviewerProfile: cheapestReviewerEnabled,
6918
- advisorMaxTurns: cheapestReviewerEnabled ? 5 : void 0,
7643
+ advisorCheapProfile: cheapAdvisorEnabled || curatedAdvisorEnabled || curatedReviewerEnabled,
7644
+ advisorCheapestProfile: curatedAdvisorEnabled || curatedReviewerEnabled,
7645
+ advisorReviewerProfile: curatedReviewerEnabled,
7646
+ advisorLocalProfile: localAdvisorRequest,
7647
+ advisorMaxTurns: curatedReviewerEnabled ? 5 : void 0,
6919
7648
  advisorEffort: advisorChoice.effort,
6920
7649
  externalAborter: translatedAdvisorAborter,
6921
7650
  continueTurn: makeShimContinueTurn(endpoint, {
@@ -6943,7 +7672,7 @@ async function handleCompletion(c) {
6943
7672
  };
6944
7673
  return messagesRoute === "chat-shim" ? handleNonClaudeChat(c, shimOpts) : handleNonClaudeResponses(c, shimOpts);
6945
7674
  }
6946
- if (modelId) logEndpointMismatch(modelId, "/v1/messages");
7675
+ if (modelId && !localProfileRequest) logEndpointMismatch(modelId, "/v1/messages");
6947
7676
  const effectiveBetas = applyDefaultBetas(betaHeaders, resolvedModel ?? originalModel);
6948
7677
  const advisorAborter = advisorBehaviorEnabled ? new AbortController() : void 0;
6949
7678
  const requestHeaders = {
@@ -6960,7 +7689,10 @@ async function handleCompletion(c) {
6960
7689
  let acceptedRepair;
6961
7690
  const repairedMessageIndices = /* @__PURE__ */ new Set();
6962
7691
  for (let attempt = 0; response === void 0; attempt++) try {
6963
- response = await createMessages(nativeBody, requestHeaders, advisorAborter?.signal, true);
7692
+ response = await createMessages(nativeBody, requestHeaders, advisorAborter?.signal, true, localProfileRequest ? {
7693
+ baseUrl: localBaseUrl(),
7694
+ sessionId: localSessionId(c)
7695
+ } : void 0);
6964
7696
  if (acceptedRepair) {
6965
7697
  rememberThinkingHistoryRepair(acceptedRepair.fingerprint);
6966
7698
  consola.warn(`Thinking-history repair succeeded: message=${acceptedRepair.messageIndex} removed_blocks=${acceptedRepair.removedBlocks} attempts=${attempt}`);
@@ -6989,6 +7721,7 @@ async function handleCompletion(c) {
6989
7721
  acceptedRepair = thinkingRepair;
6990
7722
  repairedMessageIndices.add(thinkingRepair.messageIndex);
6991
7723
  }
7724
+ if (localProfileRequest && response.ok) recordZeroCostRequest(originalModel);
6992
7725
  const contentType = response.headers.get("content-type") ?? "";
6993
7726
  const clientAcceptsSSE = (c.req.header("accept") ?? "").includes("text/event-stream");
6994
7727
  let isStreaming = contentType.includes("text/event-stream");
@@ -7038,22 +7771,28 @@ async function handleCompletion(c) {
7038
7771
  requestHeaders,
7039
7772
  advisorModel: advisorChoice.model,
7040
7773
  advisorEscalated: advisorChoice.escalated,
7041
- advisorFastProfile: (fastLeadAdvisor || cheapLeadAdvisor || cheapestLeadAdvisor) && !cheapestReviewerEnabled,
7774
+ advisorFastProfile: (fastLeadAdvisor || cheapLeadAdvisor || curatedLeadAdvisor) && !curatedReviewerEnabled,
7042
7775
  advisorMaxProfile: maxAdvisorEnabled,
7043
- advisorCheapProfile: cheapLeadAdvisor || cheapestLeadAdvisor || cheapestReviewerEnabled,
7044
- advisorCheapestProfile: cheapestAdvisorEnabled || cheapestReviewerEnabled,
7045
- advisorReviewerProfile: cheapestReviewerEnabled,
7046
- advisorMaxTurns: cheapestReviewerEnabled ? 5 : void 0,
7047
- advisorEffort: maxAdvisorChoice ? maxAdvisorChoice.effort : resolveAdvisorEffort(rawBody, advisorChoice.model, fastLeadAdvisor || cheapLeadAdvisor || cheapestLeadAdvisor),
7776
+ advisorCheapProfile: cheapLeadAdvisor || curatedLeadAdvisor || curatedReviewerEnabled,
7777
+ advisorCheapestProfile: curatedAdvisorEnabled || curatedReviewerEnabled,
7778
+ advisorReviewerProfile: curatedReviewerEnabled,
7779
+ advisorLocalProfile: localAdvisorRequest,
7780
+ localEgress: localProfileRequest ? {
7781
+ baseUrl: localBaseUrl(),
7782
+ sessionId: localSessionId(c)
7783
+ } : void 0,
7784
+ advisorMaxTurns: curatedReviewerEnabled ? 5 : void 0,
7785
+ advisorEffort: maxAdvisorChoice ? maxAdvisorChoice.effort : resolveAdvisorEffort(rawBody, advisorChoice.model, fastLeadAdvisor || cheapLeadAdvisor || curatedLeadAdvisor),
7048
7786
  externalAborter: advisorAborter
7049
7787
  }), {
7050
7788
  status: response.status,
7051
7789
  headers: streamHeaders
7052
7790
  });
7053
7791
  }
7792
+ const aicTap = localProfileRequest ? void 0 : createAnthropicAicTap((usage) => recordAic(resolvedModel, usage));
7054
7793
  return new Response(response.body ? relayAnthropicStream(response.body, {
7055
7794
  routePath: c.req.path,
7056
- onBytes: createAnthropicAicTap((usage) => recordAic(resolvedModel, usage)).onBytes
7795
+ ...aicTap ? { onBytes: aicTap.onBytes } : {}
7057
7796
  }) : null, {
7058
7797
  status: response.status,
7059
7798
  headers: streamHeaders
@@ -7063,7 +7802,7 @@ async function handleCompletion(c) {
7063
7802
  if (!cappedResult.ok) return c.json(cappedResult.errorResponse, cappedResult.status);
7064
7803
  const responseBody = cappedResult.value;
7065
7804
  const usage = responseBody.usage;
7066
- const aicNano = extractAndRecordAic(resolvedModel, responseBody);
7805
+ const aicNano = localProfileRequest ? void 0 : extractAndRecordAic(resolvedModel, responseBody);
7067
7806
  logRequest({
7068
7807
  method: "POST",
7069
7808
  path: c.req.path,
@@ -7084,6 +7823,37 @@ async function handleCompletion(c) {
7084
7823
  return c.json(responseBody, response.status);
7085
7824
  }
7086
7825
  /**
7826
+ * Verbatim alternative to `resolveModelInBody` for the local profiles.
7827
+ *
7828
+ * The body is forwarded byte-for-byte: no model rewrite (the tier ids
7829
+ * `opus` / `sonnet` / `haiku` are the local server's own, and `resolveModel`'s
7830
+ * opus-family preference would map `opus` onto a Copilot `claude-opus-*`), no
7831
+ * thinking translation or effort clamp (both consult a Copilot catalog entry
7832
+ * that does not describe this model), and no Anthropic-only field strip (the
7833
+ * local server is the thing those fields were written for).
7834
+ *
7835
+ * `selectedModel` is deliberately `undefined` — the catalog knows nothing
7836
+ * about this model, and `salvageOversizedPrompt` / `logEndpointMismatch`
7837
+ * correctly no-op on it.
7838
+ */
7839
+ function localModelInBody$1(rawBody) {
7840
+ let originalModel;
7841
+ try {
7842
+ const parsed = JSON.parse(rawBody);
7843
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
7844
+ const model = parsed.model;
7845
+ if (typeof model === "string" && model.length > 0) originalModel = model;
7846
+ }
7847
+ } catch {}
7848
+ return {
7849
+ body: rawBody,
7850
+ ...originalModel ? {
7851
+ originalModel,
7852
+ resolvedModel: originalModel
7853
+ } : {}
7854
+ };
7855
+ }
7856
+ /**
7087
7857
  * Parse the JSON body, resolve the model name, sanitize cache_control
7088
7858
  * fields, translate thinking-mode shape for adaptive-thinking models,
7089
7859
  * and re-serialize. Returns the body string, original/resolved model
@@ -7409,19 +8179,23 @@ async function handleCountTokens(c) {
7409
8179
  }
7410
8180
  }, 400);
7411
8181
  } catch {}
7412
- const { body: finalBody, originalModel, resolvedModel } = resolveModelInBody(strippedBody);
8182
+ const localProfileRequest = effectiveLocalProfile(identity.launch?.profileId) !== void 0;
8183
+ const { body: finalBody, originalModel, resolvedModel } = localProfileRequest ? localModelInBody(strippedBody) : resolveModelInBody(strippedBody);
7413
8184
  const extraHeaders = {};
7414
8185
  const anthropicBeta = c.req.header("anthropic-beta");
7415
8186
  if (anthropicBeta) {
7416
- const filtered = filterBetaHeader(anthropicBeta);
8187
+ const filtered = localProfileRequest ? anthropicBeta.split(",").map((part) => part.trim()).filter((part) => part.length > 0 && !part.startsWith("advisor-tool-")).join(",") : filterBetaHeader(anthropicBeta);
7417
8188
  if (filtered) extraHeaders["anthropic-beta"] = filtered;
7418
8189
  }
7419
8190
  const modelId = resolvedModel ?? originalModel;
7420
- const selectedModel = state.models?.data.find((m) => m.id === modelId);
8191
+ const selectedModel = localProfileRequest ? void 0 : state.models?.data.find((m) => m.id === modelId);
7421
8192
  const response = await countTokens(finalBody, {
7422
8193
  ...selectedModel?.requestHeaders,
7423
8194
  ...extraHeaders
7424
- }, void 0, true);
8195
+ }, void 0, true, localProfileRequest ? {
8196
+ baseUrl: localBaseUrl(),
8197
+ sessionId: localSessionId(c)
8198
+ } : void 0);
7425
8199
  const responseBody = await parseJsonOrDiagnose(response, c.req.path);
7426
8200
  logRequest({
7427
8201
  method: "POST",
@@ -7434,6 +8208,28 @@ async function handleCountTokens(c) {
7434
8208
  return c.json(responseBody);
7435
8209
  }
7436
8210
  /**
8211
+ * Verbatim alternative to `resolveModelInBody` for the local profiles: read
8212
+ * the body's own `model` and change nothing else. See the sibling helper in
8213
+ * `handler.ts` for the full rationale.
8214
+ */
8215
+ function localModelInBody(rawBody) {
8216
+ let originalModel;
8217
+ try {
8218
+ const parsed = JSON.parse(rawBody);
8219
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
8220
+ const model = parsed.model;
8221
+ if (typeof model === "string" && model.length > 0) originalModel = model;
8222
+ }
8223
+ } catch {}
8224
+ return {
8225
+ body: rawBody,
8226
+ ...originalModel ? {
8227
+ originalModel,
8228
+ resolvedModel: originalModel
8229
+ } : {}
8230
+ };
8231
+ }
8232
+ /**
7437
8233
  * Parse the JSON body, resolve the model name, sanitize cache_control, and re-serialize.
7438
8234
  */
7439
8235
  function resolveModelInBody(rawBody) {
@@ -7850,6 +8646,7 @@ async function handleResponsesCompact(c) {
7850
8646
  if (!state.copilotToken) throw new Error("Copilot token not found");
7851
8647
  if (state.manualApprove) await awaitApproval();
7852
8648
  const body = await c.req.json();
8649
+ assertCopilotModelAllowed(body.model);
7853
8650
  const compactUrl = `${copilotBaseUrl(state)}/responses/compact`;
7854
8651
  const doFetch = () => fetch(compactUrl, {
7855
8652
  method: "POST",
@@ -8610,8 +9407,9 @@ function getClaudeCodeEnvVars(serverUrl, model, launchProfileId = "standard", pi
8610
9407
  const isFastProfile = launchProfileId === "fast";
8611
9408
  const isMaxProfile = launchProfileId === "max";
8612
9409
  const isCheapProfile = launchProfileId === "cheap" || launchProfileId === "cheap1m" || isCheapestFamily(launchProfileId);
8613
- const routerWinsTiers = isFastProfile || isCheapProfile;
8614
- const pinStrict200K = launchProfileId === "cheap" || isCheapestFamily(launchProfileId) || isBalancedFamily(launchProfileId);
9410
+ const isLocalProfile = isLocalFamily(launchProfileId);
9411
+ const routerWinsTiers = isFastProfile || isCheapProfile || isLocalProfile;
9412
+ const pinStrict200K = launchProfileId === "cheap" || isCheapestFamily(launchProfileId) || isBalancedFamily(launchProfileId) || isLocalProfile;
8615
9413
  if (pinStrict200K) {
8616
9414
  if (process.env.CLAUDE_CODE_DISABLE_1M_CONTEXT === void 0 || process.env.CLAUDE_CODE_DISABLE_1M_CONTEXT === "") vars.CLAUDE_CODE_DISABLE_1M_CONTEXT = "1";
8617
9415
  }
@@ -8619,12 +9417,12 @@ function getClaudeCodeEnvVars(serverUrl, model, launchProfileId = "standard", pi
8619
9417
  if (pinLeadEffort !== void 0) {
8620
9418
  if ((process.env.CLAUDE_CODE_EFFORT_LEVEL ?? "").trim() === "") vars.CLAUDE_CODE_EFFORT_LEVEL = pinLeadEffort;
8621
9419
  }
8622
- const smallFastModel = isMaxProfile ? MAX_LUNA_HIGH_ALIAS_ID : isFastProfile ? LUNA_HAIKU_ALIAS_ID : isCheapProfile ? LUNA_HAIKU_ALIAS_ID : isBudgetClaudeLead(model) && (state.models?.data?.some((m) => m.id === "claude-haiku-4.5") ?? false) ? BUDGET_SMALL_FAST_SLUG : "claude-sonnet-5";
9420
+ const smallFastModel = isMaxProfile ? MAX_LUNA_HIGH_ALIAS_ID : isFastProfile ? LUNA_HAIKU_ALIAS_ID : isCheapProfile ? LUNA_HAIKU_ALIAS_ID : isLocalProfile ? LOCAL_PROFILE_TIER_MODELS.haiku : isBudgetClaudeLead(model) && (state.models?.data?.some((m) => m.id === "claude-haiku-4.5") ?? false) ? BUDGET_SMALL_FAST_SLUG : "claude-sonnet-5";
8623
9421
  if (process.env.ANTHROPIC_SMALL_FAST_MODEL === void 0 || routerWinsTiers) vars.ANTHROPIC_SMALL_FAST_MODEL = (isFastProfile || isMaxProfile) && !isCheapProfile ? oneMSuffixForAlias(smallFastModel) : smallFastModel;
8624
- const seedTierRow = (modelKey, nameKey, bareSlug) => {
8625
- if (process.env[modelKey] !== void 0) return;
9422
+ const seedTierRow = (modelKey, nameKey, bareSlug, force = false) => {
9423
+ if (!force && process.env[modelKey] !== void 0) return;
8626
9424
  vars[modelKey] = pinStrict200K ? bareSlug : withOneMSuffixForLead(bareSlug);
8627
- if (process.env[nameKey] === void 0) vars[nameKey] = bareSlug;
9425
+ if (force || process.env[nameKey] === void 0) vars[nameKey] = bareSlug;
8628
9426
  };
8629
9427
  const seedFastAliasTierRow = (modelKey, nameKey, aliasId, displayName, force = false) => {
8630
9428
  if (!force && process.env[modelKey] !== void 0) return;
@@ -8671,11 +9469,15 @@ function getClaudeCodeEnvVars(serverUrl, model, launchProfileId = "standard", pi
8671
9469
  if (routerWinsTiers || process.env.ANTHROPIC_CUSTOM_MODEL_OPTION_NAME === void 0) vars.ANTHROPIC_CUSTOM_MODEL_OPTION_NAME = "GPT-6 Luna (max)";
8672
9470
  if (routerWinsTiers || process.env.ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES === void 0) vars.ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES = fastAliasCapabilities;
8673
9471
  }
9472
+ } else if (isLocalProfile) {
9473
+ seedTierRow("ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME", LOCAL_PROFILE_TIER_MODELS.opus, routerWinsTiers);
9474
+ seedTierRow("ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL_NAME", LOCAL_PROFILE_TIER_MODELS.sonnet, routerWinsTiers);
9475
+ seedTierRow("ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME", LOCAL_PROFILE_TIER_MODELS.haiku, routerWinsTiers);
8674
9476
  } else {
8675
9477
  seedTierRow("ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL_NAME", "claude-sonnet-5");
8676
9478
  seedTierRow("ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME", smallFastModel);
8677
9479
  }
8678
- if (!isMaxProfile) seedTierRow("ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME", "claude-opus-5.5");
9480
+ if (!isMaxProfile && !isLocalProfile) seedTierRow("ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME", "claude-opus-5.5");
8679
9481
  if (process.env.CLAUDE_CODE_PLAN_V2_AGENT_COUNT === void 0) vars.CLAUDE_CODE_PLAN_V2_AGENT_COUNT = "7";
8680
9482
  for (const key of [
8681
9483
  "CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL",
@@ -8684,6 +9486,10 @@ function getClaudeCodeEnvVars(serverUrl, model, launchProfileId = "standard", pi
8684
9486
  "CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING",
8685
9487
  "CLAUDE_CODE_ENABLE_TASKS"
8686
9488
  ]) if (process.env[key] === void 0) vars[key] = "1";
9489
+ if (launchProfileId === "local") {
9490
+ delete vars.CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL;
9491
+ if (process.env.CLAUDE_CODE_DISABLE_ADVISOR_TOOL === void 0) vars.CLAUDE_CODE_DISABLE_ADVISOR_TOOL = "1";
9492
+ }
8687
9493
  applyAutoCompactWindow(vars, launchProfileId, pickerModels);
8688
9494
  if (toolbeltEnabled()) Object.assign(vars, toolbeltPathOverride(process.env, PATHS.TOOLBELT_BIN_DIR));
8689
9495
  return vars;
@@ -8778,7 +9584,10 @@ function getCodexEnvVars(serverUrl) {
8778
9584
  * shell export can't re-route the session off the proxy.
8779
9585
  */
8780
9586
  function getPiLaunchEnvVars(mirrorDir) {
8781
- const vars = { PI_CODING_AGENT_DIR: mirrorDir };
9587
+ const vars = {
9588
+ PI_CODING_AGENT_DIR: mirrorDir,
9589
+ PI_CODING_AGENT_SESSION_DIR: piSessionsDir()
9590
+ };
8782
9591
  if (process.env.GH_ROUTER_PI_VERBOSE_NPM !== "1") {
8783
9592
  vars.npm_config_loglevel = "error";
8784
9593
  vars.npm_config_audit = "false";
@@ -8786,10 +9595,12 @@ function getPiLaunchEnvVars(mirrorDir) {
8786
9595
  vars.npm_config_update_notifier = "false";
8787
9596
  }
8788
9597
  vars.npm_config_allow_scripts = "";
9598
+ vars.npm_config_registry = resolvePiRegistry();
9599
+ vars.npm_config_min_release_age = "0";
8789
9600
  if (toolbeltEnabled()) Object.assign(vars, toolbeltPathOverride(process.env, PATHS.TOOLBELT_BIN_DIR));
8790
9601
  return vars;
8791
9602
  }
8792
9603
  //#endregion
8793
- export { formatFastPrerequisiteFailure as A, runSelfUpdate as B, CHEAP_REVIEWER_ALIAS_ID as C, formatCheap1mPrerequisiteFailure as D, formatBalancedPrerequisiteFailure as E, validateCheapProfilePrerequisites as F, updateClaude as H, validateCheapestProfilePrerequisites as I, validateFastProfilePrerequisites as L, resolveLaunchProfile as M, validateBalancedProfilePrerequisites as N, formatCheapPrerequisiteFailure as O, validateCheap1mProfilePrerequisites as P, validateMaxProfileLaunch as R, CHEAP_PLAN_ALIAS_ID as S, MAX_BROWSE_LOW_ALIAS_ID as T, checkClaudeVersion as V, CHEAPEST_EXPLORE_ALIAS_ID as _, setupAndServe as a, CHEAP_EXPLORE_ALIAS_ID as b, startKeepAwake as c, listModelsForEndpoint as d, enableFileLogging as f, BROWSE_LOW_ALIAS_ID as g, BALANCED_REVIEWER_ALIAS_ID as h, parseSharedArgs as i, profileDescriptor as j, formatCheapestPrerequisiteFailure as k, stopKeepAwake as l, BALANCED_GENERAL_PURPOSE_ALIAS_ID as m, getCodexEnvVars as n, sharedServerArgs as o, BALANCED_EXPLORE_ALIAS_ID as p, getPiLaunchEnvVars as r, LAUNCH_SECRET_HEADER as s, getClaudeCodeEnvVars as t, injectModelPickerSettingsFile as u, CHEAPEST_GENERAL_PURPOSE_ALIAS_ID as v, LUNA_SCOUT_ALIAS_ID as w, CHEAP_GENERAL_PURPOSE_ALIAS_ID as x, CHEAPEST_REVIEWER_ALIAS_ID as y, queueDetachedGlobalInstall as z };
9604
+ export { runSelfUpdate as $, CHEAPEST_GENERAL_PURPOSE_ALIAS_ID as A, formatCheapPrerequisiteFailure as B, listModelsForEndpoint as C, BALANCED_REVIEWER_ALIAS_ID as D, BALANCED_GENERAL_PURPOSE_ALIAS_ID as E, CHEAP_REVIEWER_ALIAS_ID as F, resolveLaunchProfile as G, formatFastPrerequisiteFailure as H, LUNA_SCOUT_ALIAS_ID as I, validateCheapProfilePrerequisites as J, validateBalancedProfilePrerequisites as K, MAX_BROWSE_LOW_ALIAS_ID as L, CHEAP_EXPLORE_ALIAS_ID as M, CHEAP_GENERAL_PURPOSE_ALIAS_ID as N, BROWSE_LOW_ALIAS_ID as O, CHEAP_PLAN_ALIAS_ID as P, validateMaxProfileLaunch as Q, formatBalancedPrerequisiteFailure as R, injectModelPickerSettingsFile as S, BALANCED_EXPLORE_ALIAS_ID as T, formatLocalPrerequisiteFailure as U, formatCheapestPrerequisiteFailure as V, profileDescriptor as W, validateFastProfilePrerequisites as X, validateCheapestProfilePrerequisites as Y, validateLocalProfilePrerequisites as Z, ensurePiAgentMirror as _, setupAndServe as a, startKeepAwake as b, localBaseUrl as c, ensurePiInstalled as d, checkClaudeVersion as et, getInstalledPiVersion as f, updatePi as g, resolvePiRegistry as h, parseSharedArgs as i, CHEAPEST_REVIEWER_ALIAS_ID as j, CHEAPEST_EXPLORE_ALIAS_ID as k, LAUNCH_SECRET_HEADER as l, refreshPiInBackground as m, getCodexEnvVars as n, sharedServerArgs as o, meetsPiMinVersion as p, validateCheap1mProfilePrerequisites as q, getPiLaunchEnvVars as r, configureLocalEgress as s, getClaudeCodeEnvVars as t, updateClaude as tt, PI_MIN_VERSION as u, removeOwnPiAgentMirror as v, enableFileLogging as w, stopKeepAwake as x, sweepStalePiAgentMirrors as y, formatCheap1mPrerequisiteFailure as z };
8794
9605
 
8795
- //# sourceMappingURL=server-setup-VYf8ptCH.js.map
9606
+ //# sourceMappingURL=server-setup-DVPL9iph.js.map