github-router 0.3.378 → 0.3.380

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 (164) hide show
  1. package/README.md +62 -0
  2. package/dist/ado-tools-CsfbnY8x.js +1 -0
  3. package/dist/{aic-ledger-CeSXqTEE.js → aic-ledger-6GKI28nY.js} +3 -3
  4. package/dist/{aic-ledger-CeSXqTEE.js.map → aic-ledger-6GKI28nY.js.map} +1 -1
  5. package/dist/{aic-statusline-settings-BKveu679.js → aic-statusline-settings-wLL1l_Z6.js} +2 -2
  6. package/dist/{aic-statusline-settings-BKveu679.js.map → aic-statusline-settings-wLL1l_Z6.js.map} +1 -1
  7. package/dist/atomic-file-Dif1kLKM.js +198 -0
  8. package/dist/atomic-file-Dif1kLKM.js.map +1 -0
  9. package/dist/{attribution-settings-BR5Umj2L.js → attribution-settings-BJ1fjX7V.js} +10 -10
  10. package/dist/{attribution-settings-BR5Umj2L.js.map → attribution-settings-BJ1fjX7V.js.map} +1 -1
  11. package/dist/{auth-BZHpTtfF.js → auth-5TKcQbbH.js} +3 -3
  12. package/dist/{auth-BZHpTtfF.js.map → auth-5TKcQbbH.js.map} +1 -1
  13. package/dist/bin.js +1479 -0
  14. package/dist/bin.js.map +1 -0
  15. package/dist/browser-ext/manifest.json +1 -1
  16. package/dist/{check-usage-BlIWDuV2.js → check-usage-DM39fdel.js} +4 -4
  17. package/dist/{check-usage-BlIWDuV2.js.map → check-usage-DM39fdel.js.map} +1 -1
  18. package/dist/{claude--4O3wHRq.js → claude-BWwkOMi3.js} +26 -25
  19. package/dist/{claude--4O3wHRq.js.map → claude-BWwkOMi3.js.map} +1 -1
  20. package/dist/{claude-md-injection-Biq_Xhve.js → claude-md-injection-DNMDcw1W.js} +15 -24
  21. package/dist/claude-md-injection-DNMDcw1W.js.map +1 -0
  22. package/dist/{codex-DHRMLpSo.js → codex-C6ix3BaY.js} +8 -7
  23. package/dist/{codex-DHRMLpSo.js.map → codex-C6ix3BaY.js.map} +1 -1
  24. package/dist/{copilot-discount-UXC6NQbN.js → copilot-discount-DM98PuAF.js} +2 -2
  25. package/dist/{copilot-discount-UXC6NQbN.js.map → copilot-discount-DM98PuAF.js.map} +1 -1
  26. package/dist/{debug-1HUHCWFl.js → debug-Df0Kuzi3.js} +2 -2
  27. package/dist/{debug-1HUHCWFl.js.map → debug-Df0Kuzi3.js.map} +1 -1
  28. package/dist/diagnostics-cXjCT_JQ.js +12 -0
  29. package/dist/diagnostics-cXjCT_JQ.js.map +1 -0
  30. package/dist/engine-B6la_uIW.js +1 -0
  31. package/dist/{gate-discovery-DjH9YXoN.js → gate-discovery-2ILpM2fi.js} +5 -5
  32. package/dist/{gate-discovery-DjH9YXoN.js.map → gate-discovery-2ILpM2fi.js.map} +1 -1
  33. package/dist/{get-copilot-usage-CKg42gSH.js → get-copilot-usage-BZ6t2hFZ.js} +2 -2
  34. package/dist/{get-copilot-usage-CKg42gSH.js.map → get-copilot-usage-BZ6t2hFZ.js.map} +1 -1
  35. package/dist/hooks.mjs +13 -0
  36. package/dist/hooks.sha256 +1 -1
  37. package/dist/{index-cmd-sKwchRJz.js → index-cmd-DsK6VFs8.js} +4 -4
  38. package/dist/{index-cmd-sKwchRJz.js.map → index-cmd-DsK6VFs8.js.map} +1 -1
  39. package/dist/{internal-aic-status-B_hEeM37.js → internal-aic-status-CUZ7-trf.js} +3 -3
  40. package/dist/{internal-aic-status-B_hEeM37.js.map → internal-aic-status-CUZ7-trf.js.map} +1 -1
  41. package/dist/{internal-artifact-open-DbHjipxU.js → internal-artifact-open-DRBg1PpV.js} +2 -2
  42. package/dist/{internal-artifact-open-DbHjipxU.js.map → internal-artifact-open-DRBg1PpV.js.map} +1 -1
  43. package/dist/{internal-fast-dispatch-guard-DMzqs-r8.js → internal-fast-dispatch-guard-D6-Ees_6.js} +1 -1
  44. package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js → internal-fast-dispatch-guard-ZeS9u0A3.js} +2 -2
  45. package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js.map → internal-fast-dispatch-guard-ZeS9u0A3.js.map} +1 -1
  46. package/dist/{internal-first-mate-guard-BxPDUsV3.js → internal-first-mate-guard-BijeVpi9.js} +1 -1
  47. package/dist/{internal-first-mate-guard-4Yro9xNM.js → internal-first-mate-guard-DsEEsLKJ.js} +3 -3
  48. package/dist/{internal-first-mate-guard-4Yro9xNM.js.map → internal-first-mate-guard-DsEEsLKJ.js.map} +1 -1
  49. package/dist/{internal-max-dispatch-guard-0teaxIc1.js → internal-max-dispatch-guard-4RLca1i5.js} +2 -2
  50. package/dist/{internal-max-dispatch-guard-0teaxIc1.js.map → internal-max-dispatch-guard-4RLca1i5.js.map} +1 -1
  51. package/dist/{internal-max-dispatch-guard-5LSaHN_y.js → internal-max-dispatch-guard-DeEfWqfP.js} +1 -1
  52. package/dist/{internal-plan-review-BfHLeszV.js → internal-plan-review-bzqGNdtw.js} +3 -3
  53. package/dist/{internal-plan-review-BfHLeszV.js.map → internal-plan-review-bzqGNdtw.js.map} +1 -1
  54. package/dist/{internal-prompt-submit-BixNLmM3.js → internal-prompt-submit-BZ2-CExM.js} +4 -4
  55. package/dist/{internal-prompt-submit-BixNLmM3.js.map → internal-prompt-submit-BZ2-CExM.js.map} +1 -1
  56. package/dist/{internal-prompt-submit-Ou8xtRXj.js → internal-prompt-submit-ZBhH-SQ1.js} +2 -2
  57. package/dist/{internal-rebrief-BBGM0PMv.js → internal-rebrief-BIWbN7Sr.js} +4 -4
  58. package/dist/{internal-rebrief-BBGM0PMv.js.map → internal-rebrief-BIWbN7Sr.js.map} +1 -1
  59. package/dist/{internal-session-bind-pN1V11Mn.js → internal-session-bind-BL6hFRLO.js} +2 -2
  60. package/dist/{internal-session-bind-pN1V11Mn.js.map → internal-session-bind-BL6hFRLO.js.map} +1 -1
  61. package/dist/{internal-stop-hook-DO9Iiaes.js → internal-stop-hook-cDF1MuJZ.js} +5 -5
  62. package/dist/{internal-stop-hook-DO9Iiaes.js.map → internal-stop-hook-cDF1MuJZ.js.map} +1 -1
  63. package/dist/{internal-stop-review-BWp-4XWW.js → internal-stop-review-y8zjpK_3.js} +2 -2
  64. package/dist/{internal-stop-review-BWp-4XWW.js.map → internal-stop-review-y8zjpK_3.js.map} +1 -1
  65. package/dist/{internal-worker-guard-C9OZPgzu.js → internal-worker-guard-DdyYBZR0.js} +2 -2
  66. package/dist/{internal-worker-guard-C9OZPgzu.js.map → internal-worker-guard-DdyYBZR0.js.map} +1 -1
  67. package/dist/{internal-workspace-header-B4TXFBLU.js → internal-workspace-header-BMKbO8yX.js} +2 -2
  68. package/dist/{internal-workspace-header-B4TXFBLU.js.map → internal-workspace-header-BMKbO8yX.js.map} +1 -1
  69. package/dist/lib/tree-sitter-pool/worker.js +268 -21
  70. package/dist/lifecycle-BOjgq9_l.js +1 -0
  71. package/dist/{lifecycle-vjHAFCaY.js → lifecycle-BlC_kzNt.js} +2 -2
  72. package/dist/{lifecycle-vjHAFCaY.js.map → lifecycle-BlC_kzNt.js.map} +1 -1
  73. package/dist/{lifecycle-Dh9y8OF1.js → lifecycle-COZhARmE.js} +2 -2
  74. package/dist/{lifecycle-Dh9y8OF1.js.map → lifecycle-COZhARmE.js.map} +1 -1
  75. package/dist/lifecycle-NQvr4flt.js +1 -0
  76. package/dist/main.js +39 -24
  77. package/dist/main.js.map +1 -1
  78. package/dist/{mcp-workspace-header-C5-dOWNa.js → mcp-workspace-header-Bpa4BId8.js} +2 -2
  79. package/dist/{mcp-workspace-header-C5-dOWNa.js.map → mcp-workspace-header-Bpa4BId8.js.map} +1 -1
  80. package/dist/{models-B6nH1sS6.js → models-BDV-YLf2.js} +3 -3
  81. package/dist/{models-B6nH1sS6.js.map → models-BDV-YLf2.js.map} +1 -1
  82. package/dist/npm-env-H60tX76c.js +130 -0
  83. package/dist/npm-env-H60tX76c.js.map +1 -0
  84. package/dist/optional-DGAeyguL.js +586 -0
  85. package/dist/optional-DGAeyguL.js.map +1 -0
  86. package/dist/{orchestration-B93jxrWI.js → orchestration-Bto5Nc1Y.js} +2 -2
  87. package/dist/{orchestration-B93jxrWI.js.map → orchestration-Bto5Nc1Y.js.map} +1 -1
  88. package/dist/origin-BXtpcKP9.js +382 -0
  89. package/dist/origin-BXtpcKP9.js.map +1 -0
  90. package/dist/origin-DbFUCiGp.js +1 -0
  91. package/dist/paths-CquOjytP.js +1 -0
  92. package/dist/paths-DK_b2ihK.js +176 -0
  93. package/dist/paths-DK_b2ihK.js.map +1 -0
  94. package/dist/{paths-CVEO8jEH.js → paths-DeFmYJhO.js} +16 -3
  95. package/dist/paths-DeFmYJhO.js.map +1 -0
  96. package/dist/{peer-mcp-personas-OWsSm6To.js → peer-mcp-personas-Dny0r5Am.js} +14 -14
  97. package/dist/{peer-mcp-personas-OWsSm6To.js.map → peer-mcp-personas-Dny0r5Am.js.map} +1 -1
  98. package/dist/{pi-B0EFY6l7.js → pi-YhoA26wi.js} +718 -119
  99. package/dist/pi-YhoA26wi.js.map +1 -0
  100. package/dist/pi-foreign-artifacts-CNt6wQ1P.js +660 -0
  101. package/dist/pi-foreign-artifacts-CNt6wQ1P.js.map +1 -0
  102. package/dist/pi-memory-bridge-BxmCIIbk.js +618 -0
  103. package/dist/pi-memory-bridge-BxmCIIbk.js.map +1 -0
  104. package/dist/pi-memory-bridge-D5A0h_Kf.js +1 -0
  105. package/dist/pi-version-check-BeBB0Ny9.js +551 -0
  106. package/dist/pi-version-check-BeBB0Ny9.js.map +1 -0
  107. package/dist/pi-version-check-D5RvdLsG.js +1 -0
  108. package/dist/{plan-review-hook-MhjK92wq.js → plan-review-hook-D_yyjOgO.js} +3 -3
  109. package/dist/{plan-review-hook-MhjK92wq.js.map → plan-review-hook-D_yyjOgO.js.map} +1 -1
  110. package/dist/{provision-DPL8aGe2.js → provision-BWtuDq_v.js} +30 -36
  111. package/dist/provision-BWtuDq_v.js.map +1 -0
  112. package/dist/rerank-cross-encoder-BhjImuwG.js +192 -0
  113. package/dist/rerank-cross-encoder-BhjImuwG.js.map +1 -0
  114. package/dist/{self-invocation-DMUnXVGT.js → self-invocation-Dnq4iVD6.js} +4 -31
  115. package/dist/{self-invocation-DMUnXVGT.js.map → self-invocation-Dnq4iVD6.js.map} +1 -1
  116. package/dist/{serve-C13q-9w0.js → serve-DrHAX2Bh.js} +15 -14
  117. package/dist/{serve-C13q-9w0.js.map → serve-DrHAX2Bh.js.map} +1 -1
  118. package/dist/{server-setup-CptI7SUT.js → server-setup-DLwejgVA.js} +12 -638
  119. package/dist/server-setup-DLwejgVA.js.map +1 -0
  120. package/dist/{service-backend-Cdgz6WPx.js → service-backend-BdhWVRSz.js} +17 -62
  121. package/dist/service-backend-BdhWVRSz.js.map +1 -0
  122. package/dist/{start-DioCGjM8.js → start-DvV3Lbwy.js} +5 -4
  123. package/dist/{start-DioCGjM8.js.map → start-DvV3Lbwy.js.map} +1 -1
  124. package/dist/{static-context-pack-CtnBwHSd.js → static-context-pack-BKFelEbM.js} +3 -3
  125. package/dist/{static-context-pack-CtnBwHSd.js.map → static-context-pack-BKFelEbM.js.map} +1 -1
  126. package/dist/{stop-gate-hook-CBVLD8iB.js → stop-gate-hook-DBOj0TqL.js} +3 -3
  127. package/dist/{stop-gate-hook-CBVLD8iB.js.map → stop-gate-hook-DBOj0TqL.js.map} +1 -1
  128. package/dist/{stop-gate-policy-BehNiNix.js → stop-gate-policy-Bp2wGh_W.js} +2 -2
  129. package/dist/{stop-gate-policy-BehNiNix.js.map → stop-gate-policy-Bp2wGh_W.js.map} +1 -1
  130. package/dist/{token-CPzYxU4Y.js → token-CKPOBdO0.js} +23 -88
  131. package/dist/{token-CPzYxU4Y.js.map → token-CKPOBdO0.js.map} +1 -1
  132. package/dist/{token-DHEkiO4g.js → token-Ygd7D32L.js} +3 -3
  133. package/dist/{token-DHEkiO4g.js.map → token-Ygd7D32L.js.map} +1 -1
  134. package/dist/update-CB21YRKz.js +1 -0
  135. package/dist/update-T1L7yFon.js +1548 -0
  136. package/dist/update-T1L7yFon.js.map +1 -0
  137. package/dist/update-fEgWTrIx.js +214 -0
  138. package/dist/update-fEgWTrIx.js.map +1 -0
  139. package/dist/update-lock-BeS_WmC8.js +1 -0
  140. package/dist/update-lock-BmXx6QaR.js +171 -0
  141. package/dist/update-lock-BmXx6QaR.js.map +1 -0
  142. package/dist/volatile-root-DQNNvQ7Z.js +50 -0
  143. package/dist/volatile-root-DQNNvQ7Z.js.map +1 -0
  144. package/dist/{worker-dispatch-C7RtNOXv.js → worker-dispatch-DBWKTMda.js} +2 -2
  145. package/dist/{worker-dispatch-C7RtNOXv.js.map → worker-dispatch-DBWKTMda.js.map} +1 -1
  146. package/dist/{workiq-CQauEAMc.js → workiq-D5b7xlbr.js} +2 -2
  147. package/dist/{workiq-CQauEAMc.js.map → workiq-D5b7xlbr.js.map} +1 -1
  148. package/dist/{workiq-tools-DL6rC4bP.js → workiq-tools-DdiQ2DOW.js} +1 -1
  149. package/package.json +16 -4
  150. package/dist/ado-tools-CRkyU51J.js +0 -1
  151. package/dist/claude-md-injection-Biq_Xhve.js.map +0 -1
  152. package/dist/engine-V46un8Xl.js +0 -1
  153. package/dist/lifecycle-BENRuuX6.js +0 -1
  154. package/dist/lifecycle-Dli9vGI2.js +0 -1
  155. package/dist/paths-Be9_ujQ3.js +0 -1
  156. package/dist/paths-CVEO8jEH.js.map +0 -1
  157. package/dist/pi-B0EFY6l7.js.map +0 -1
  158. package/dist/pi-memory-bridge-Dvj1T3e3.js +0 -403
  159. package/dist/pi-memory-bridge-Dvj1T3e3.js.map +0 -1
  160. package/dist/provision-DPL8aGe2.js.map +0 -1
  161. package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
  162. package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
  163. package/dist/server-setup-CptI7SUT.js.map +0 -1
  164. package/dist/service-backend-Cdgz6WPx.js.map +0 -1
@@ -1,16 +1,20 @@
1
- import { H as profileDescriptor, I as formatBalancedPrerequisiteFailure, S as enableFileLogging, U as resolveLaunchProfile, V as formatLocalPrerequisiteFailure, W as validateBalancedProfilePrerequisites, Y as validateLocalProfilePrerequisites, Z as runSelfUpdate, _ as sweepStalePiAgentMirrors, a as setupAndServe, c as PI_MIN_VERSION, d as meetsPiMinVersion, f as refreshPiInBackground, g as removeOwnPiAgentMirror, h as ensurePiAgentMirror, i as parseSharedArgs, l as ensurePiInstalled, m as updatePi, o as sharedServerArgs, p as resolvePiRegistry, q as validateCheapestProfilePrerequisites, r as getPiLaunchEnvVars, s as LAUNCH_SECRET_HEADER, u as getInstalledPiVersion, v as startKeepAwake, y as stopKeepAwake, z as formatCheapestPrerequisiteFailure } from "./server-setup-CptI7SUT.js";
2
- import { i as buildAicStatusHookCommand, n as AIC_STATUSLINE_DISABLE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-BKveu679.js";
3
- import { d as removeAicLedgerFile, f as sweepStaleAicLedgerFiles, n as aicSnapshot, o as formatAicExitSummary, t as aicLedgerPath } from "./aic-ledger-CeSXqTEE.js";
4
- import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-UXC6NQbN.js";
5
- import { r as resolveSelfInvocation } from "./self-invocation-DMUnXVGT.js";
6
- import { t as PATHS } from "./paths-CVEO8jEH.js";
7
- import { t as FRESH_CONSULT_CONTRACT } from "./claude-md-injection-Biq_Xhve.js";
8
- import { Bn as colbertDegradedWarning, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, Dt as artifactToolsEnabled, Gn as LOCAL_CONSULT_REDACTION_NOTE, Mn as provisionBrowserAssets, Nt as browserToolsEnabled, Qt as kustoToolsEnabled, Sn as unregisterLaunch, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, Wn as LOCAL_CONSULT_REDACTION_LINE, bn as registerLaunch, fn as configureLocalEgress, jt as browseAgentEnabled, pn as localBaseUrl, sn as workiqToolsEnabled } from "./peer-mcp-personas-OWsSm6To.js";
9
- import { C as localContractFor, O as LOCAL_PROFILE_TIER_MODELS, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, h as consultIsLocalTransport, p as cheapestContractFor, v as isCheapestFamily, y as isCheaplocalProfile } from "./static-context-pack-CtnBwHSd.js";
10
- import { i as launchChild, t as provisionToolbelt } from "./provision-DPL8aGe2.js";
1
+ import { c as refreshPiInBackground, l as resolvePiRegistry, n as PI_MIN_VERSION, o as meetsPiMinVersion, u as runSelfUpdate } from "./pi-version-check-BeBB0Ny9.js";
2
+ import { c as runCommandCapture, s as resolveExecutable } from "./exec-BC0MAnoA.js";
3
+ import { d as readPointer, l as isOurShim, o as scheduleBackgroundPiInstall, u as ensureManagedInstall } from "./update-T1L7yFon.js";
4
+ import { b as versionDir } from "./paths-DK_b2ihK.js";
5
+ import { i as buildAicStatusHookCommand, n as AIC_STATUSLINE_DISABLE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-wLL1l_Z6.js";
6
+ import { d as removeAicLedgerFile, f as sweepStaleAicLedgerFiles, n as aicSnapshot, o as formatAicExitSummary, t as aicLedgerPath } from "./aic-ledger-6GKI28nY.js";
7
+ import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-DM98PuAF.js";
8
+ import { r as resolveSelfInvocation } from "./self-invocation-Dnq4iVD6.js";
9
+ import { B as validateCheapestProfilePrerequisites, F as profileDescriptor, H as validateLocalProfilePrerequisites, I as resolveLaunchProfile, L as validateBalancedProfilePrerequisites, M as formatCheapestPrerequisiteFailure, P as formatLocalPrerequisiteFailure, a as setupAndServe, c as ensurePiAgentMirror, d as startKeepAwake, f as stopKeepAwake, h as enableFileLogging, i as parseSharedArgs, k as formatBalancedPrerequisiteFailure, l as removeOwnPiAgentMirror, o as sharedServerArgs, r as getPiLaunchEnvVars, s as LAUNCH_SECRET_HEADER, u as sweepStalePiAgentMirrors } from "./server-setup-DLwejgVA.js";
10
+ import { t as PATHS } from "./paths-DeFmYJhO.js";
11
+ import { t as FRESH_CONSULT_CONTRACT } from "./claude-md-injection-DNMDcw1W.js";
12
+ import { Bn as colbertDegradedWarning, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, Dt as artifactToolsEnabled, Gn as LOCAL_CONSULT_REDACTION_NOTE, Mn as provisionBrowserAssets, Nt as browserToolsEnabled, Qt as kustoToolsEnabled, Sn as unregisterLaunch, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, Wn as LOCAL_CONSULT_REDACTION_LINE, bn as registerLaunch, fn as configureLocalEgress, jt as browseAgentEnabled, pn as localBaseUrl, sn as workiqToolsEnabled } from "./peer-mcp-personas-Dny0r5Am.js";
13
+ import { C as localContractFor, O as LOCAL_PROFILE_TIER_MODELS, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, h as consultIsLocalTransport, p as cheapestContractFor, v as isCheapestFamily, y as isCheaplocalProfile } from "./static-context-pack-BKFelEbM.js";
14
+ import { i as launchChild, t as provisionToolbelt } from "./provision-BWtuDq_v.js";
11
15
  import { t as state } from "./state-CCGDJ43X.js";
12
16
  import { t as getPackageVersion } from "./version-CTqwKr26.js";
13
- import { P as warmTreeSitterPool } from "./service-backend-Cdgz6WPx.js";
17
+ import { P as warmTreeSitterPool } from "./service-backend-BdhWVRSz.js";
14
18
  import { defineCommand } from "citty";
15
19
  import consola from "consola";
16
20
  import { existsSync } from "node:fs";
@@ -18,6 +22,196 @@ import path from "node:path";
18
22
  import { createHash, randomBytes } from "node:crypto";
19
23
  import fs$1 from "node:fs/promises";
20
24
  import process$1 from "node:process";
25
+ // src/lib/managed-install/pi-command.ts
26
+ /**
27
+ * "Which Pi do we launch, and how do we spell it?"
28
+ *
29
+ * Pi is not a dependency of this package: the launcher spawns whatever `pi` the
30
+ * user has. That is fine until you look at what happens today when the answer
31
+ * changes underneath a session — `npm install -g` while the launcher is running
32
+ * mutates a tree the spawned Pi has open, and on Windows that is `EPERM`. The
33
+ * managed install gives Pi a versioned, rename-published home instead, so a Pi
34
+ * refresh becomes the same safe operation as a router refresh.
35
+ *
36
+ * Precedence (plan §6), in order:
37
+ *
38
+ * 1. `--pi-path <abs>` — explicit user override, never floor-checked. Someone
39
+ * pointing at a local build is testing, not asking for our opinion.
40
+ * 2. `pi` on PATH, provided it is **not our own shim** and meets
41
+ * `PI_MIN_VERSION`. The shim check is not cosmetic: our `pi` shim execs the
42
+ * managed launcher, so adopting it as "the user's Pi" would make the
43
+ * launcher's own spawn resolve to itself.
44
+ * 3. The managed pointer, when it meets the floor.
45
+ * 4. Install into the managed dir and use that.
46
+ *
47
+ * Rule 2's floor is what lets the managed install take over from a user install
48
+ * that is too old, which previously could only be fixed by rewriting the user's
49
+ * global npm tree (`npm install -g` from `updatePi`). Falling through is
50
+ * reported, never silent: a user whose `pi` was silently ignored would file a
51
+ * bug about "the wrong version".
52
+ */
53
+ /** Timeout for `pi --version`. Generous: a cold V8 start on Windows is slow. */
54
+ const VERSION_TIMEOUT_MS = 5e3;
55
+ /** Run `<exe> --version` and pull the semver out. Null on any failure. */
56
+ async function probePiVersion(command, args = []) {
57
+ try {
58
+ const { stdout, code } = await runCommandCapture([
59
+ command,
60
+ ...args,
61
+ "--version"
62
+ ], { timeoutMs: VERSION_TIMEOUT_MS });
63
+ if (code !== 0) return null;
64
+ const match = stdout.match(/(\d+\.\d+\.\d+)/);
65
+ return match ? match[1] : null;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+ /**
71
+ * The package's own `bin` target for `pi`, relative to the package root.
72
+ *
73
+ * Read from the installed `package.json` rather than hardcoded because Pi has
74
+ * already moved it once (`dist/cli.js` → `dist/bundle/cli.js`), and a hardcoded
75
+ * path turns a Pi refactor into "the launcher cannot start Pi at all".
76
+ */
77
+ async function piBinEntry(packageRoot) {
78
+ try {
79
+ const raw = await fs$1.readFile(path.join(packageRoot, "package.json"), "utf8");
80
+ const parsed = JSON.parse(raw);
81
+ if (typeof parsed.bin === "string") return parsed.bin;
82
+ if (parsed.bin && typeof parsed.bin === "object") {
83
+ const value = parsed.bin["pi"];
84
+ if (typeof value === "string") return value;
85
+ }
86
+ } catch {}
87
+ return null;
88
+ }
89
+ /**
90
+ * The managed Pi's argv prefix, if a complete and in-floor payload is live.
91
+ *
92
+ * `process.execPath` is not necessarily Node — under `bunx` it is Bun, and Pi's
93
+ * bundle is built for Node. So prefer a real `node` on PATH and only fall back
94
+ * to the running interpreter, which at least guarantees *an* interpreter exists.
95
+ */
96
+ async function managedPiCommand() {
97
+ const pointer = await readPointer("pi", { verifyEntry: false });
98
+ if (!pointer) return null;
99
+ if (!meetsPiMinVersion(pointer.version)) return null;
100
+ const root = versionDir("pi", pointer.version);
101
+ const packageDir = path.join(root, "node_modules", "@earendil-works", "pi-coding-agent");
102
+ const relative = await piBinEntry(packageDir);
103
+ if (!relative) return null;
104
+ const entry = path.join(packageDir, relative);
105
+ try {
106
+ if (!(await fs$1.stat(entry)).isFile()) return null;
107
+ } catch {
108
+ return null;
109
+ }
110
+ return {
111
+ command: resolveExecutable("node") ?? process.execPath,
112
+ args: [entry],
113
+ source: "managed",
114
+ version: pointer.version
115
+ };
116
+ }
117
+ /** Is this resolved `pi` a PATH user install rather than our own shim? */
118
+ async function isUserPi(candidate) {
119
+ try {
120
+ return !await isOurShim(candidate);
121
+ } catch {
122
+ return false;
123
+ }
124
+ }
125
+ /**
126
+ * Resolve the Pi invocation to spawn.
127
+ *
128
+ * Never throws: every failure degrades to a later rule, and the final answer is
129
+ * always a runnable-or-explainable command. The caller decides whether "nothing
130
+ * resolved" is fatal.
131
+ */
132
+ async function resolvePiCommand(opts = {}) {
133
+ const explicit = opts.piPath?.trim();
134
+ if (explicit) return {
135
+ command: explicit,
136
+ args: [],
137
+ source: "flag",
138
+ version: await probePiVersion(explicit)
139
+ };
140
+ const onPath = resolveExecutable("pi");
141
+ let belowFloor = null;
142
+ if (onPath && await isUserPi(onPath)) {
143
+ const version = await probePiVersion(onPath);
144
+ if (version && meetsPiMinVersion(version)) return {
145
+ command: onPath,
146
+ args: [],
147
+ source: "path",
148
+ version
149
+ };
150
+ if (version) belowFloor = version;
151
+ }
152
+ const managed = await managedPiCommand();
153
+ if (managed) return belowFloor ? {
154
+ ...managed,
155
+ note: `Using the managed Pi ${managed.version}: the \`pi\` on PATH is v${belowFloor}, below the supported floor v${PI_MIN_VERSION}. Upgrade that one (or drop it from PATH, or pass --pi-path) to choose it again.`
156
+ } : managed;
157
+ if (opts.noInstall || opts.allowInstall === false) return null;
158
+ const kind = "pi";
159
+ const latest = await latestPiVersion();
160
+ if (!latest) return {
161
+ command: "",
162
+ args: [],
163
+ source: "installed",
164
+ version: null,
165
+ note: "Pi is not installed and its latest version could not be resolved (offline, or npm is not on PATH)."
166
+ };
167
+ const outcome = await ensureManagedInstall({
168
+ kind,
169
+ version: latest,
170
+ registry: resolvePiRegistry(),
171
+ signal: opts.signal
172
+ });
173
+ const installed = await managedPiCommand();
174
+ if (installed) return belowFloor ? {
175
+ ...installed,
176
+ note: `Using the managed Pi ${installed.version}: the \`pi\` on PATH is v${belowFloor}, below the supported floor v${PI_MIN_VERSION}. Upgrade that one (or drop it from PATH, or pass --pi-path) to choose it again.`
177
+ } : {
178
+ ...installed,
179
+ source: "installed"
180
+ };
181
+ return {
182
+ command: "",
183
+ args: [],
184
+ source: "installed",
185
+ version: null,
186
+ note: outcome.kind === "installed" || outcome.kind === "adopted" ? `Pi ${outcome.version ?? ""} was installed but no runnable entry was found.` : outcome.detail ?? "Pi is not installed and could not be installed automatically."
187
+ };
188
+ }
189
+ /**
190
+ * `npm view … version` for Pi, pinned to the Pi registry.
191
+ *
192
+ * Returns null rather than the string `"latest"` on failure: the installer
193
+ * demands an exact version, so passing a tag through would fail one layer later
194
+ * with "invalid version latest" — a confusing error for "you are offline".
195
+ */
196
+ async function latestPiVersion() {
197
+ const npmPath = resolveExecutable("npm");
198
+ if (!npmPath) return null;
199
+ try {
200
+ const { stdout, code } = await runCommandCapture([
201
+ npmPath,
202
+ "view",
203
+ "@earendil-works/pi-coding-agent",
204
+ "version",
205
+ "--silent",
206
+ `--registry=${resolvePiRegistry()}`
207
+ ], { timeoutMs: 8e3 });
208
+ if (code !== 0) return null;
209
+ const value = stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
210
+ return /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(value) ? value : null;
211
+ } catch {
212
+ return null;
213
+ }
214
+ }
21
215
  // src/lib/pi-tier-windows.ts
22
216
  /**
23
217
  * Copilot Default-tier (cheap) input-token thresholds per model.
@@ -468,6 +662,31 @@ function piThinkingLevelMapFor(efforts) {
468
662
  for (const level of PI_THINKING_LEVELS) map[level] = set.has(level) ? level : null;
469
663
  return map;
470
664
  }
665
+ /**
666
+ * Pi's own window for the LOCAL family (`-m local`, `-m local2`).
667
+ *
668
+ * 272K, not 200K, and deliberately NOT `LOCAL_PROFILE_LEAD_CONTEXT_TOKENS`:
669
+ * that constant is the *Claude Code client's* window, pinned at 200K by the
670
+ * seeded `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`, and nothing in this module can
671
+ * move it. Two clients, two windows, both true.
672
+ *
673
+ * The choice is policy, not measurement. Measured on the live endpoint this
674
+ * session: 105K–720K input is accepted verbatim, 730K+ is
675
+ * `400 prompt is too long`, so the real ceiling is ~720K and 272K sits at a
676
+ * 2.6× margin. 272K is also the Copilot Default-tier boundary the roster
677
+ * already uses (`PI_TIER_THRESHOLDS`), so every Pi profile in this repo now
678
+ * budgets against the same number instead of two conventions.
679
+ *
680
+ * Raising the window alone would make compaction WORSE, not better. Pi's
681
+ * clamp is `room = window − input − max(4096, 15% of input)`, and the
682
+ * summarization call's input is `trigger − keepRecentTokens`, not the trigger.
683
+ * Measured through Pi's own `clampMaxTokensToContext`, a 272K window only
684
+ * hands that call the full 65 536 once the trigger is at or under ~198.6K
685
+ * (reserve >= ~73.4K); at a 217 600 trigger it gets 43 736, and at 232 000 it
686
+ * gets 31 744 — today's truncating ceiling. The three constants move together
687
+ * or not at all.
688
+ */
689
+ const PI_LOCAL_CONTEXT_TOKENS = 272e3;
471
690
  /** Provider key used in models.json and agent `provider/model` references. */
472
691
  const PI_PROVIDER_NAME = "gh-router";
473
692
  const PI_MIN_VERSION_NOTE = `Requires Pi >= ${PI_MIN_VERSION} and Node >= 22.19.`;
@@ -798,7 +1017,7 @@ function buildPiModelsJson(opts) {
798
1017
  name: id,
799
1018
  reasoning: true,
800
1019
  input: entry?.vision === false ? ["text"] : ["text", "image"],
801
- contextWindow: piContextWindowFor(id, entry?.maxContextTokens),
1020
+ contextWindow: local && isLocalTier ? PI_LOCAL_CONTEXT_TOKENS : piContextWindowFor(id, entry?.maxContextTokens),
802
1021
  maxTokens,
803
1022
  ...entry?.cost ? { cost: entry.cost } : {},
804
1023
  ...isLocalTier && localHeaders ? { headers: localHeaders } : {},
@@ -811,7 +1030,7 @@ function buildPiModelsJson(opts) {
811
1030
  } } };
812
1031
  }
813
1032
  /**
814
- * Local-family compaction reserve: 80% of the 200K window.
1033
+ * Local-family compaction reserve: a flat 81 600 tokens for the 272K window.
815
1034
  *
816
1035
  * The Copilot derivation below optimises for a price cliff; the local
817
1036
  * endpoint has none, so the binding constraint there is the summarization
@@ -823,13 +1042,38 @@ function buildPiModelsJson(opts) {
823
1042
  * `getSummarizationFailure` refuses the truncated summary
824
1043
  * (`generation hit the token cap and the summary is incomplete`).
825
1044
  *
826
- * Triggering at 160K instead of Pi's 183K default leaves the clamp enough
827
- * room that the 32768 budget below is reachable: at a 160K estimate
828
- * `clampMaxTokensToContext` yields 32768, so the provider sends
829
- * `budget = min(32768, 32768 − 1024)`. Raised reserves alone are not enough
830
- * (the budget, not the trigger, is the ceiling) — both halves ship together.
1045
+ * The reserve is **flat**, not a ratio, so it is the half of this pairing
1046
+ * that has to be recomputed whenever the window moves. 272 000 − 81 600 =
1047
+ * 190 400 is the trigger (70% of the window, vs the 160K/80% it replaces —
1048
+ * the absolute amount of conversation before compaction goes UP).
1049
+ *
1050
+ * The number is derived, not chosen. Pi clamps the summarization request to
1051
+ * `room = window − input − max(4096, 15% · input)` and the summarizer sees
1052
+ * `trigger − keepRecentTokens` (20 000). For the 65 536 budget below to
1053
+ * survive that clamp, that input must stay at or under 178 642
1054
+ * (`(272000 − 65536 − 1024) / 1.15` rounds down one token short). Read back
1055
+ * as a reserve:
1056
+ *
1057
+ * | reserve | trigger | summarizer input | `budget_tokens` |
1058
+ * |---------|---------|------------------|-----------------|
1059
+ * | 40 000 | 232 000 | 212 000 | 31 744 |
1060
+ * | 54 400 | 217 600 | 197 600 | 43 736 |
1061
+ * | 73 357 | 198 643 | 178 643 | 65 535 |
1062
+ * | 81 600 | 190 400 | 170 400 | 65 536 |
1063
+ *
1064
+ * 73 357 is the exact boundary and has zero slack: one token past it and the
1065
+ * budget starts eroding, and a history that overshoots the trigger by 5%
1066
+ * would get 55 264. 81 600 keeps ~8K of headroom, so that same 5% overshoot
1067
+ * still receives 65 218. Ship the number with the slack, not the boundary.
1068
+ *
1069
+ * Both halves ship together: the budget is what the endpoint serves as
1070
+ * `budget_tokens`, and the reserve is what keeps the clamp from eating it.
1071
+ * The two rows above 40 000 are the ones that matter — a raised window with
1072
+ * the OLD reserve leaves the summarizer at 31 744, and even the plan's
1073
+ * original 54 400 caps it at 43 736, i.e. still short of the budget it asks
1074
+ * for, from a launch that claims to have doubled its headroom.
831
1075
  */
832
- const PI_LOCAL_COMPACTION_RESERVE_TOKENS = 4e4;
1076
+ const PI_LOCAL_COMPACTION_RESERVE_TOKENS = 81600;
833
1077
  /**
834
1078
  * Thinking budgets for LOCAL launches only.
835
1079
  *
@@ -838,13 +1082,23 @@ const PI_LOCAL_COMPACTION_RESERVE_TOKENS = 4e4;
838
1082
  * carry no `thinkingLevelMap`, so `clampReasoning` walks `max`/`xhigh` down
839
1083
  * to `high`). 16384 is the ceiling that truncates real summaries — 5 of the
840
1084
  * 19 compactions in the reference session reported output above it, up to
841
- * 21643. 32768 roughly doubles the summarization headroom and costs nothing
842
- * on local inference.
1085
+ * 21643. 65536 quadruples the summarization headroom and costs nothing on
1086
+ * local inference.
1087
+ *
1088
+ * The doubling from 32768 is not a reflex: the endpoint serves the request as
1089
+ * `budget_tokens`, and at the 190 400-token trigger the summarizer sees
1090
+ * 170 400 (`trigger − keepRecentTokens`), where the clamp still affords the
1091
+ * full 65 536 (measured: +5% historical overshoot → 65 218). A 32 768 budget
1092
+ * would be the tight half of what the window now allows, and at the old
1093
+ * 40 000 reserve the second clamp pinned the request back to 31 744 — the
1094
+ * truncating ceiling this constant exists to remove. Both numbers are
1095
+ * measured against Pi's own `clampMaxTokensToContext` in
1096
+ * `tests/pi-models-settings.test.ts` rather than asserted here.
843
1097
  *
844
1098
  * Deliberately NOT emitted for Copilot profiles: there the thinking budget
845
1099
  * is billed reasoning tokens on every turn, not a free local decode.
846
1100
  */
847
- const PI_LOCAL_THINKING_BUDGETS = Object.freeze({ high: 32768 });
1101
+ const PI_LOCAL_THINKING_BUDGETS = Object.freeze({ high: 65536 });
848
1102
  /**
849
1103
  * Derive Pi compaction budgets from live catalog `max_prompt_tokens`
850
1104
  * ceilings AND each model's cheap-tier window — the Pi-native analogue
@@ -862,8 +1116,8 @@ const PI_LOCAL_THINKING_BUDGETS = Object.freeze({ high: 32768 });
862
1116
  * `PI_LOCAL_COMPACTION_RESERVE_TOKENS`): the local catalog carries no
863
1117
  * `max_prompt_tokens`, so the price-cliff derivation has nothing to read,
864
1118
  * and the constraint that matters is the endpoint's thinking-budget
865
- * ceiling. Every local row is the same 200K window, so one flat reserve
866
- * covers the whole roster.
1119
+ * ceiling. Every local row is the same 272K window (see
1120
+ * `PI_LOCAL_CONTEXT_TOKENS`), so one flat reserve covers the whole roster.
867
1121
  */
868
1122
  function derivePiCompactionSettings(catalog, modelIds, profileId) {
869
1123
  const FALLBACK = {
@@ -1426,13 +1680,40 @@ function buildPiLaunchCard(opts) {
1426
1680
  opts.copilotVersion ? `copilot chat ${opts.copilotVersion}` : void 0,
1427
1681
  opts.vsCodeVersion ? `vscode ${opts.vsCodeVersion}` : void 0
1428
1682
  ].filter((part) => typeof part === "string" && part.length > 0);
1429
- return [
1683
+ const lines = [
1430
1684
  `github-router v${opts.version} · pi (${opts.profileId})`,
1431
1685
  ` ${identity.join(" · ")}`,
1432
1686
  ` lead ${opts.lead} · ${opts.modelCount} models · ${surface.join(" ")} · ${opts.serverUrl}`
1433
- ].join("\n");
1687
+ ];
1688
+ const foreign = opts.foreign;
1689
+ if (foreign) {
1690
+ const parts = [`${foreign.agents} foreign agents (lazy)`];
1691
+ if (foreign.prompts > 0) parts.push(`${foreign.prompts} prompts`);
1692
+ if (foreign.skills > 0) parts.push(`${foreign.skills} skills`);
1693
+ lines.push(` foreign: ${parts.join(" · ")}`);
1694
+ if (foreign.renamed.length > 0) lines.push(` renamed ${foreign.renamed.map((r) => `${r.from} → ${r.to}`).join(", ")}`);
1695
+ if (foreign.skipped.length > 0) lines.push(` skipped ${foreign.skipped.map((s) => s.name).join(", ")} (name taken by gh-router)`);
1696
+ } else if (opts.foreignAvailable !== void 0 && opts.foreignAvailable > 0) lines.push(` foreign: ${opts.foreignAvailable} agent definition(s) found, not bridged · add --foreign`);
1697
+ return lines.join("\n");
1434
1698
  }
1435
1699
  /**
1700
+ * Registered with Pi inside the digest, only when the memory bridge actually
1701
+ * wrote a block into the mirror's `AGENTS.md`.
1702
+ *
1703
+ * Why a line at all: the block is a permanent per-turn prompt cost, and the
1704
+ * measured failure mode of agent-authored project instructions is restatement —
1705
+ * a study of LLM-generated AGENTS.md files found ~23% higher cost with no
1706
+ * success gain, because the model paraphrases the file back at the user. One
1707
+ * sentence stating the contract (follow it, cite it, do not repeat it) is
1708
+ * cheaper than any restructuring and is the whole behavioural delta we want
1709
+ * from "having read AGENTS.md".
1710
+ *
1711
+ * Emitted only when `bridge` is true: naming AGENTS.md on a launch whose bridge
1712
+ * is off (or whose `-nc` disabled context files) would point the model at
1713
+ * guidance this launch does not have.
1714
+ */
1715
+ const PI_CONTEXT_CONTRACT_LINE = "- Your project instructions below come from `AGENTS.md` in this agent dir. Follow them and cite the rule when it changes a decision; do not restate them back to the user.";
1716
+ /**
1436
1717
  * Short operating digest appended to APPEND_SYSTEM.md (prompt-cache-stable).
1437
1718
  * Mode identity — always injected. Peer consult sentences drop out under
1438
1719
  * `peers: false` so the digest never names tools that don't exist.
@@ -1445,7 +1726,8 @@ function buildPiAppendSystem(profileId, opts = {}) {
1445
1726
  "",
1446
1727
  `- Lead owns planning directly; there is no Plan subagent.`,
1447
1728
  PI_TOOL_PREFERENCE_LINE,
1448
- ...opts.codeSearch === true ? [PI_SEARCH_ORDER_LINE] : []
1729
+ ...opts.codeSearch === true ? [PI_SEARCH_ORDER_LINE] : [],
1730
+ ...opts.bridge === true ? [PI_CONTEXT_CONTRACT_LINE] : []
1449
1731
  ];
1450
1732
  if (peers) {
1451
1733
  const oracle = piOracleEnabled(profileId);
@@ -2478,6 +2760,159 @@ function buildPiStatuslineFooterSection() {
2478
2760
  ];
2479
2761
  }
2480
2762
  /**
2763
+ * Pinned pi-subagents event contract. The router cannot import the package, so
2764
+ * the event NAME and the request shape are literals here, exactly as the
2765
+ * upstream module defines them (`runtime-agent-events.js`:
2766
+ * `RUNTIME_AGENT_REGISTER_EVENT`, version 1). A version bump upstream leaves
2767
+ * this registration unanswered and the extension reports it — never a crash.
2768
+ */
2769
+ const PI_SUBAGENTS_REGISTER_EVENT = "pi-subagents:runtime-agent-register:v1";
2770
+ const PI_SUBAGENTS_REGISTER_VERSION = 1;
2771
+ /**
2772
+ * Foreign Claude/Copilot agents: one registry entry each, announced in a
2773
+ * compact prompt section, loaded on demand.
2774
+ *
2775
+ * Three seams, and the reasons each is the shape it is:
2776
+ *
2777
+ * 1. **Registration goes through the documented event**, not through pi's
2778
+ * `registerAgent` (there is none) and not through agent FILES. A file in
2779
+ * `<mirror>/agents/` would be a configured agent — a second identity that
2780
+ * `mergeRuntimeAgents` validates on EVERY discovery, so one collision breaks
2781
+ * every `subagent` call in the process. A runtime registration fails only
2782
+ * its own call, and can be removed at runtime.
2783
+ * 2. **The index is a prompt SECTION**, not a chat message. A custom message
2784
+ * is re-emitted on every run and reaches the model as a user turn; sections
2785
+ * are diff-patched by Pi (`diffSystemPromptSections`), so the index is sent
2786
+ * once and stays cache-stable.
2787
+ * 3. **The `tool_result` net is the backstop for what reservation cannot see**
2788
+ * (a user adding a colliding agent mid-session). It disposes exactly the
2789
+ * offender named in the registry's own error and lets the model retry;
2790
+ * every other error is passed through untouched.
2791
+ *
2792
+ * Fail-open everywhere: a Pi build without these events, a pi-subagents that
2793
+ * is not installed, or a rejected registration all degrade to "the foreign
2794
+ * agents are not available", never to a broken session.
2795
+ */
2796
+ function buildPiForeignAgentsSection(foreign) {
2797
+ return [
2798
+ ` // ---- foreign agents: Claude/Copilot, lazy, collision-reserved ----`,
2799
+ ` // No files: each spec is a RUNTIME agent in pi-subagents, so it participates`,
2800
+ ` // in discovery without becoming a configured identity every subagent call`,
2801
+ ` // re-validates. The index below is the only always-on context.`,
2802
+ ` {`,
2803
+ ` let FOREIGN = [];`,
2804
+ ` try { FOREIGN = ${JSON.stringify(foreign.agents.map((a) => ({
2805
+ name: a.name,
2806
+ description: a.description,
2807
+ body: a.body
2808
+ })))}; } catch { FOREIGN = []; }`,
2809
+ ` const FOREIGN_INDEX = ${JSON.stringify(foreign.index)};`,
2810
+ ` const FOREIGN_EVENT = ${JSON.stringify(PI_SUBAGENTS_REGISTER_EVENT)};`,
2811
+ ` const FOREIGN_VERSION = ${PI_SUBAGENTS_REGISTER_VERSION};`,
2812
+ ` const registrations = new Map();`,
2813
+ ` const failures = [];`,
2814
+ ` // Name of the offending runtime agent, from the registry's own throw text.`,
2815
+ ` // Deliberately parsed rather than inferred: the net must never dispose a`,
2816
+ ` // registration that is not the one the registry just named.`,
2817
+ ` const COLLISION_RE = /^Runtime agent '([^']+)' collides with configured agent/;`,
2818
+ ` function registerAll(ctx) {`,
2819
+ ` for (const spec of FOREIGN) {`,
2820
+ ` try {`,
2821
+ ` // Re-registering the same name throws ('collides with runtime agent'),`,
2822
+ ` // so a prior handle for this name is disposed first. Load-bearing on`,
2823
+ ` // /reload: the extension instance is recreated but the pi-subagents`,
2824
+ ` // registry it talks to is not necessarily torn down first.`,
2825
+ ` const prior = registrations.get(spec.name);`,
2826
+ ` if (prior) { try { prior.dispose(); } catch {} registrations.delete(spec.name); }`,
2827
+ ` const request: any = { version: FOREIGN_VERSION, name: spec.name, definition: {`,
2828
+ ` description: spec.description,`,
2829
+ ` systemPrompt: spec.body,`,
2830
+ ` systemPromptMode: "replace",`,
2831
+ ` inheritProjectContext: true,`,
2832
+ ` } };`,
2833
+ ` try { pi.events.emit(FOREIGN_EVENT, request); } catch {}`,
2834
+ ` const result = request.result;`,
2835
+ ` if (result && result.ok === true && result.registration && typeof result.registration.dispose === "function") {`,
2836
+ ` registrations.set(spec.name, result.registration);`,
2837
+ ` continue;`,
2838
+ ` }`,
2839
+ ` const reason = result && result.ok === false && result.error`,
2840
+ ` ? String(result.error.message || result.error)`,
2841
+ ` : "pi-subagents did not answer";`,
2842
+ ` failures.push(spec.name + ": " + reason);`,
2843
+ ` } catch (error) {`,
2844
+ ` failures.push(spec.name + ": " + String(error && error.message ? error.message : error));`,
2845
+ ` }`,
2846
+ ` }`,
2847
+ ` if (failures.length > 0 && ctx && ctx.ui && typeof ctx.ui.notify === "function") {`,
2848
+ ` try { ctx.ui.notify("gh-router: " + failures.length + " foreign agent(s) not bridged (" + failures.slice(0, 3).join("; ") + ")", "warning"); } catch {}`,
2849
+ ` }`,
2850
+ ` }`,
2851
+ ` pi.on("session_start", async (event, ctx) => {`,
2852
+ ` // Children must not pay for the roster: every subagent process loads`,
2853
+ ` // this extension too (background runners mark themselves, foreground`,
2854
+ ` // children load no ambient extensions). Registration there would also`,
2855
+ ` // fight the parent's names in a second registry.`,
2856
+ ` if (process.env.PI_SUBAGENT_CHILD === "1") return;`,
2857
+ ` registerAll(ctx);`,
2858
+ ` });`,
2859
+ ` pi.on("session_shutdown", async () => {`,
2860
+ ` // Load-bearing, not hygiene: a stale registration outliving this`,
2861
+ ` // instance makes the next session's registration of the same name`,
2862
+ ` // throw 'collides with runtime agent'.`,
2863
+ ` for (const registration of registrations.values()) {`,
2864
+ ` try { registration.dispose(); } catch {}`,
2865
+ ` }`,
2866
+ ` registrations.clear();`,
2867
+ ` });`,
2868
+ ` // Self-healing net: a colliding foreign agent fails EVERY subagent call in`,
2869
+ ` // the process, so leaving it registered until the user quits is not an`,
2870
+ ` // option. Only a registration this extension created is ever disposed,`,
2871
+ ` // keyed by the name the registry itself reported.`,
2872
+ ` pi.on("tool_result", async (event) => {`,
2873
+ ` try {`,
2874
+ ` if (!event || event.toolName !== "subagent" || event.isError !== true) return undefined;`,
2875
+ ` const text = Array.isArray(event.content)`,
2876
+ ` ? event.content.map((c) => (c && typeof c.text === "string" ? c.text : "")).join("\\n")`,
2877
+ ` : "";`,
2878
+ ` const match = COLLISION_RE.exec(text);`,
2879
+ ` if (!match) return undefined;`,
2880
+ ` const offender = match[1];`,
2881
+ ` // Reset lastIndex for the shared regex: a stale index would make the`,
2882
+ ` // next match start mid-string and silently miss.`,
2883
+ ` COLLISION_RE.lastIndex = 0;`,
2884
+ ` const registration = registrations.get(offender);`,
2885
+ ` if (!registration) return undefined;`,
2886
+ ` try { registration.dispose(); } catch {}`,
2887
+ ` registrations.delete(offender);`,
2888
+ ` return {`,
2889
+ ` content: [{ type: "text", text: "Foreign agent '" + offender + "' collided with an agent configured in this session and was unregistered. Retry the call, or use a roster agent." }],`,
2890
+ ` isError: false,`,
2891
+ ` };`,
2892
+ ` } catch {`,
2893
+ ` return undefined;`,
2894
+ ` }`,
2895
+ ` });`,
2896
+ ` // The compact index, as a system-prompt section. Skipped in children`,
2897
+ ` // (they never see the roster) and when nothing was bridged.`,
2898
+ ` if (FOREIGN_INDEX) {`,
2899
+ ` pi.on("before_agent_start", async (event) => {`,
2900
+ ` try {`,
2901
+ ` if (process.env.PI_SUBAGENT_CHILD === "1") return undefined;`,
2902
+ ` const options = event && event.systemPromptOptions;`,
2903
+ ` if (!options || typeof options !== "object") return undefined;`,
2904
+ ` if (!options.sections || typeof options.sections !== "object") options.sections = {};`,
2905
+ ` options.sections.foreign_agents = FOREIGN_INDEX;`,
2906
+ ` return undefined;`,
2907
+ ` } catch {`,
2908
+ ` return undefined;`,
2909
+ ` }`,
2910
+ ` });`,
2911
+ ` }`,
2912
+ ` }`
2913
+ ];
2914
+ }
2915
+ /**
2481
2916
  * Memory-bridge section for the generated extension: path-scoped rules
2482
2917
  * lazy-attach on `read/edit/write` tool results (once per rule per
2483
2918
  * session, mirroring `pi-code/claude-rules.ts`), plus `/memory` (bridge
@@ -2567,8 +3002,8 @@ function buildPiMemoryBridgeSection(bridge) {
2567
3002
  ` description: "Show bridged memory inventory and auto-memory locations (on-demand; nothing auto-injected)",`,
2568
3003
  ` handler: async (_args, ctx) => {`,
2569
3004
  ` try {`,
2570
- ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,
2571
- ` const lines = ["Memory bridge (gh-router)", " Static files: " + s.staticFiles, " Scoped rules (lazy): " + s.scopedRules, " Imports: " + s.imports, " Skipped: " + s.skipped, " Auto-memory: ~/.claude/projects/<slug>/memory/MEMORY.md (on-demand read only)", " Pi memory: ~/.pi/agent/memory/ (your own pi-memory install, snapshotted)"];`,
3005
+ ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0, truncated: false, bytes: 0 };`,
3006
+ ` const lines = ["Memory bridge (gh-router)", " Static files: " + s.staticFiles, " Scoped rules (lazy): " + s.scopedRules, " Imports: " + s.imports, " Skipped: " + s.skipped, " Mirror AGENTS.md block: " + (s.bytes || 0) + " bytes" + (s.truncated ? " (TRUNCATED to the budget)" : ""), " Auto-memory: ~/.claude/projects/<slug>/memory/MEMORY.md (on-demand read only)", " Pi memory: ~/.pi/agent/memory/ (your own pi-memory install, snapshotted)"];`,
2572
3007
  ` try {`,
2573
3008
  ` const files = (BRIDGE.scopedRules || []).map((r) => r.file);`,
2574
3009
  ` if (files.length > 0) lines.push(" Scoped files:", ...files.slice(0, 20).map((f) => " - " + f));`,
@@ -2584,8 +3019,8 @@ function buildPiMemoryBridgeSection(bridge) {
2584
3019
  ` description: "Show what the gh-router memory bridge loaded",`,
2585
3020
  ` handler: async (_args, ctx) => {`,
2586
3021
  ` try {`,
2587
- ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,
2588
- ` ctx.ui.notify("Bridge context: " + s.staticFiles + " static, " + s.scopedRules + " scoped (attached " + attached.size + "), " + s.imports + " imports, " + s.skipped + " skipped. Native AGENTS.md/CLAUDE.md still load via Pi.", "info");`,
3022
+ ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0, truncated: false, bytes: 0 };`,
3023
+ ` ctx.ui.notify("Bridge context: " + s.staticFiles + " static, " + s.scopedRules + " scoped (attached " + attached.size + "), " + s.imports + " imports, " + s.skipped + " skipped, " + (s.bytes || 0) + " bytes in the mirror AGENTS.md" + (s.truncated ? " (TRUNCATED)" : "") + ". Native AGENTS.md/CLAUDE.md still load via Pi.", "info");`,
2589
3024
  ` } catch {}`,
2590
3025
  ` },`,
2591
3026
  ` });`,
@@ -2620,7 +3055,8 @@ function buildPiExtensionSource(opts) {
2620
3055
  `}`,
2621
3056
  ``
2622
3057
  ] : [], `export default function (pi) {`);
2623
- if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
3058
+ if (opts.bridge) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
3059
+ if (opts.foreign && opts.foreign.agents.length + opts.foreign.index.length > 0) lines.push(...buildPiForeignAgentsSection(opts.foreign));
2624
3060
  lines.push(...buildPiStatuslineFooterSection(), ...buildPiPlanModeSection(), ` // Route compaction summaries to the mode's cheap capable model;`, ` // ALWAYS fall back to Pi native (return undefined) on any failure.`, ` pi.on("session_before_compact", async (event) => {`, ` try {`, ` const preparation = event.preparation;`, ` if (!preparation || !Array.isArray(preparation.messagesToSummarize)) return undefined;`, ` return undefined; // v1: observe only; native pipeline stays authoritative.`, ` } catch {`, ` return undefined;`, ` }`, ` });`, ...promptBrief ? [
2625
3061
  ` // Cheapest-profile execution brief, injected ABOVE the model's turn.`,
2626
3062
  ` // Produced server-side; this only relays the prompt and re-emits the`,
@@ -2827,6 +3263,69 @@ function buildPiPrompts(opts) {
2827
3263
  });
2828
3264
  return prompts;
2829
3265
  }
3266
+ // src/lib/pi-mirror-guards.ts
3267
+ async function isFile(file) {
3268
+ try {
3269
+ return (await fs$1.stat(file)).isFile();
3270
+ } catch {
3271
+ return false;
3272
+ }
3273
+ }
3274
+ /** Collect the precedence hazards for this launch. Never throws. */
3275
+ async function inspectMirrorPrecedence(mirrorDir, projectCwd) {
3276
+ const projectAppend = path.join(projectCwd, ".pi", "APPEND_SYSTEM.md");
3277
+ const userClaudeMd = path.join(mirrorDir, "CLAUDE.md");
3278
+ return {
3279
+ agentsOverride: await isFile(path.join(mirrorDir, "AGENTS.override.md")),
3280
+ systemMd: await isFile(path.join(mirrorDir, "SYSTEM.md")),
3281
+ projectAppendSystem: await isFile(projectAppend) ? projectAppend : null,
3282
+ userClaudeMd: await isFile(userClaudeMd) ? userClaudeMd : null
3283
+ };
3284
+ }
3285
+ /**
3286
+ * The launch warnings a bridge block provokes, as data rather than as calls.
3287
+ *
3288
+ * Both messages describe the SAME Pi rule in opposite directions: one context
3289
+ * file per directory, first candidate wins. They are only true when a block was
3290
+ * actually written (`bridgeActive`), because otherwise `AGENTS.md` either does
3291
+ * not exist (so `CLAUDE.md` still loads) or was never touched by us. Returning
3292
+ * strings keeps the gating unit-testable; the launcher only logs them.
3293
+ */
3294
+ function bridgeShadowWarnings(precedence, opts) {
3295
+ if (!opts.bridgeActive) return [];
3296
+ const warnings = [];
3297
+ if (precedence.agentsOverride) {
3298
+ const file = path.join(opts.mirrorDir, "AGENTS.override.md");
3299
+ warnings.push(`Pi memory bridge: ${file} shadows the mirror AGENTS.md, so the bridged Copilot/Claude rules are NOT loaded this launch. Remove that file (or pass --no-memory-bridge to silence this) and Pi will read the bridged block.`);
3300
+ }
3301
+ if (precedence.userClaudeMd && !opts.userOwnsAgentsMd) warnings.push(`Pi memory bridge: your ${precedence.userClaudeMd} is NOT loaded any more. Pi reads exactly one context file per agent dir and the bridged block lives in AGENTS.md, which outranks it. Copy your text into AGENTS.md — this launcher keeps it above the bridged block — or pass --no-memory-bridge to read CLAUDE.md again.`);
3302
+ return warnings;
3303
+ }
3304
+ /**
3305
+ * Split the router's skills into "write" and "already the user's".
3306
+ *
3307
+ * The mirror is seeded from `~/.pi/agent` before this runs, so a user-level
3308
+ * `skills/gh-oracle/SKILL.md` is already on disk. Overwriting it would silently
3309
+ * destroy the user's copy, so the user's file wins and the caller reports the
3310
+ * collision instead.
3311
+ */
3312
+ async function planSkillWrites(mirrorDir, skills) {
3313
+ const write = [];
3314
+ const shadowed = [];
3315
+ for (const skill of skills) {
3316
+ const file = path.join(mirrorDir, "skills", skill.dir, "SKILL.md");
3317
+ if (await isFile(file)) shadowed.push({
3318
+ dir: skill.dir,
3319
+ file,
3320
+ skill
3321
+ });
3322
+ else write.push(skill);
3323
+ }
3324
+ return {
3325
+ write,
3326
+ shadowed
3327
+ };
3328
+ }
2830
3329
  // src/lib/pi-mcp-config.ts
2831
3330
  /**
2832
3331
  * Pi's MCP surface for the router's scoped groups.
@@ -3134,6 +3633,10 @@ const piArgs = {
3134
3633
  type: "string",
3135
3634
  description: "Full base URL, including the /v1 prefix, of the local inference endpoint for `-m local` / `-m local2` (e.g. http://localhost:11111/v1). Sets scheme/host/path, which --localport cannot. Mutually exclusive with --localport. Inert on every other profile."
3136
3635
  },
3636
+ "pi-path": {
3637
+ type: "string",
3638
+ description: "Run THIS Pi instead of the one on PATH or the managed copy (absolute path to a pi binary or script). Explicit: skips the version floor, the managed install, and the background refresh."
3639
+ },
3137
3640
  "update-check": {
3138
3641
  type: "boolean",
3139
3642
  default: true,
@@ -3168,6 +3671,11 @@ const piArgs = {
3168
3671
  type: "boolean",
3169
3672
  default: true,
3170
3673
  description: "Bridge Copilot (.github/copilot-instructions.md, .github/instructions/*.instructions.md) and Claude (.claude/rules/, .claude/CLAUDE.md, ~/.claude/CLAUDE.md) memory into Pi. Static repo-wide slice synthesizes into the mirror AGENTS.md; path-scoped rules lazy-attach. Set to false (--no-memory-bridge) for Pi-native discovery only."
3674
+ },
3675
+ foreign: {
3676
+ type: "boolean",
3677
+ default: false,
3678
+ description: "Bridge the project's and your Claude Code and Copilot artifacts: .claude/skills + .github/skills + .copilot/skills as Pi skills, .claude/commands + .github/prompts as prompt shortcuts, and .claude/agents + .github/agents as Pi subagents announced in one compact index and loaded on demand. Authored names are kept; a name already taken by the router, a pi-subagents builtin or your own agent/skill/command is renamed (skills, prompts) or reported (agents) rather than overwritten. Foreign `model:` is ignored — every bridged agent runs on the lead model. Off by default."
3171
3679
  }
3172
3680
  };
3173
3681
  /**
@@ -3257,26 +3765,21 @@ const pi = defineCommand({
3257
3765
  }
3258
3766
  let server;
3259
3767
  let serverUrl;
3768
+ const piPath = typeof args["pi-path"] === "string" ? args["pi-path"].trim() : "";
3260
3769
  const updateCheck = args["update-check"] !== false;
3261
3770
  const autoUpdate = args["auto-update"] !== false;
3262
- let installedVersion = null;
3263
- const pendingInstall = {
3771
+ const managePi = updateCheck && piPath === "";
3772
+ let piCommand = null;
3773
+ const pendingResolve = {
3264
3774
  promise: null,
3265
3775
  abort: null
3266
3776
  };
3267
- if (updateCheck) {
3268
- try {
3269
- installedVersion = await getInstalledPiVersion();
3270
- } catch (err) {
3271
- consola.debug("Pi presence probe failed:", err);
3272
- }
3273
- if (installedVersion === null) {
3274
- const controller = new AbortController();
3275
- pendingInstall.abort = () => controller.abort();
3276
- pendingInstall.promise = ensurePiInstalled({ signal: controller.signal });
3277
- pendingInstall.promise.catch(() => {});
3278
- }
3279
- }
3777
+ if (managePi) {
3778
+ const controller = new AbortController();
3779
+ pendingResolve.abort = () => controller.abort();
3780
+ pendingResolve.promise = resolvePiCommand({ signal: controller.signal });
3781
+ pendingResolve.promise.catch(() => {});
3782
+ } else if (piPath !== "") piCommand = await resolvePiCommand({ piPath });
3280
3783
  try {
3281
3784
  const quietBoot = existsSync(PATHS.GITHUB_TOKEN_PATH) && !parsed.verbose && !parsed.showToken;
3282
3785
  const priorLevel = consola.level;
@@ -3294,37 +3797,38 @@ const pi = defineCommand({
3294
3797
  server = setupResult.server;
3295
3798
  serverUrl = setupResult.serverUrl;
3296
3799
  } catch (error) {
3297
- pendingInstall.abort?.();
3800
+ pendingResolve.abort?.();
3298
3801
  consola.error("Failed to start server:", error instanceof Error ? error.message : error);
3299
3802
  process$1.exit(1);
3300
3803
  }
3301
3804
  runSelfUpdate({ selfUpdate: args["self-update"] !== false });
3302
- if (pendingInstall.promise) try {
3303
- installedVersion = await pendingInstall.promise;
3805
+ if (pendingResolve.promise) try {
3806
+ piCommand = await pendingResolve.promise;
3304
3807
  } catch (err) {
3305
- consola.error(`Pi is not installed and automatic install failed (${err instanceof Error ? err.message : String(err)}). Install it with \`npm install -g @earendil-works/pi-coding-agent --registry=${resolvePiRegistry()}\`, then retry.`);
3306
- process$1.exit(1);
3808
+ consola.debug("Pi resolution failed:", err);
3307
3809
  } finally {
3308
- pendingInstall.promise = null;
3309
- pendingInstall.abort = null;
3810
+ pendingResolve.promise = null;
3811
+ pendingResolve.abort = null;
3310
3812
  }
3311
- if (updateCheck && installedVersion !== null) {
3312
- if (!meetsPiMinVersion(installedVersion)) {
3313
- if (autoUpdate) try {
3314
- await updatePi("latest");
3315
- installedVersion = await getInstalledPiVersion();
3316
- } catch (err) {
3317
- consola.error(`Installed Pi v${installedVersion} is below the supported floor and auto-upgrade failed (${err instanceof Error ? err.message : String(err)}). Upgrade manually: \`npm install -g @earendil-works/pi-coding-agent@latest --registry=${resolvePiRegistry()}\`.`);
3318
- process$1.exit(1);
3319
- }
3320
- if (!meetsPiMinVersion(installedVersion)) {
3321
- consola.error(`Installed Pi v${installedVersion} is below the supported floor (v${PI_MIN_VERSION}). Upgrade: \`npm install -g @earendil-works/pi-coding-agent@latest --registry=${resolvePiRegistry()}\`.`);
3322
- process$1.exit(1);
3323
- }
3324
- } else refreshPiInBackground({ autoUpdate });
3813
+ if (managePi) {
3814
+ if (!piCommand || piCommand.command === "") {
3815
+ const detail = piCommand?.note ?? "no runnable `pi` was found";
3816
+ consola.error(`Cannot launch Pi: ${detail}\nInstall it with \`npm install -g @earendil-works/pi-coding-agent@latest --registry=${resolvePiRegistry()}\`, or run \`github-router update --pi\` to install the managed copy.`);
3817
+ process$1.exit(1);
3818
+ }
3819
+ if (!meetsPiMinVersion(piCommand.version)) {
3820
+ consola.error(`Pi v${piCommand.version ?? "unknown"} (${piCommand.command}) is below the supported floor v${PI_MIN_VERSION}. Install a newer one with \`github-router update --pi\`, or pass --pi-path.`);
3821
+ process$1.exit(1);
3822
+ }
3823
+ if (piCommand.note) consola.info(piCommand.note);
3824
+ if (autoUpdate) {
3825
+ if (piCommand.source === "path") refreshPiInBackground({ autoUpdate });
3826
+ else scheduleBackgroundPiInstall().then((detail) => consola.debug(`managed Pi refresh: ${detail}`), (err) => consola.debug("managed Pi refresh failed:", err));
3827
+ }
3325
3828
  }
3326
3829
  const peersEnabled = args["peers"] !== false;
3327
3830
  const sweEnabled = args["swe"] === true;
3831
+ const foreignEnabled = args["foreign"] === true;
3328
3832
  const helpersEnabled = args["helpers"] !== false;
3329
3833
  const uiEnabled = args["ui"] !== false;
3330
3834
  const searchEnabled = parsed.searchEnabled || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
@@ -3359,7 +3863,12 @@ const pi = defineCommand({
3359
3863
  process$1.exit(1);
3360
3864
  }
3361
3865
  enableFileLogging();
3866
+ const precedence = await inspectMirrorPrecedence(mirror, process$1.cwd());
3867
+ if (precedence.systemMd) consola.warn(`Pi: ${path.join(mirror, "SYSTEM.md")} REPLACES Pi's default system prompt. gh-router's mode guidance is still appended to it, but any harness rules your SYSTEM.md leaves out are not restored. Remove it (or merge it into APPEND_SYSTEM.md) for the stock prompt.`);
3868
+ if (precedence.projectAppendSystem) consola.warn(`Pi: ${precedence.projectAppendSystem} exists. If this project is trusted, Pi loads it INSTEAD of the gh-router mode digest (the mirror's APPEND_SYSTEM.md). Keep one or the other.`);
3362
3869
  let packagesForCache = [];
3870
+ let foreignAvailable;
3871
+ let foreignStats;
3363
3872
  const launchSecret = randomBytes(32).toString("hex");
3364
3873
  try {
3365
3874
  const catalog = state.models?.data.map((m) => {
@@ -3425,29 +3934,121 @@ const pi = defineCommand({
3425
3934
  const bridgeDisabled = args["memory-bridge"] === false || process$1.env.GH_ROUTER_PI_BRIDGE === "0" || process$1.env.GH_ROUTER_DISABLE_PI_BRIDGE === "1";
3426
3935
  let bridgeStats;
3427
3936
  let bridgeScoped = [];
3937
+ let bridgeSection = "";
3938
+ let bridgeCollected;
3939
+ let bridgeActive = false;
3428
3940
  if (!bridgeDisabled) {
3429
3941
  const passthrough = collectPiPassthroughArgs(rawArgs, piArgs);
3430
3942
  if (!(passthrough.includes("--no-context-files") || passthrough.includes("-nc"))) try {
3431
- const { collectBridgeInputs } = await import("./pi-memory-bridge-Dvj1T3e3.js");
3943
+ const { PI_BRIDGE_STATIC_BUDGET_BYTES, buildMirrorBridgeSection, collectBridgeInputs } = await import("./pi-memory-bridge-D5A0h_Kf.js");
3432
3944
  const collected = await collectBridgeInputs(process$1.cwd());
3433
- bridgeStats = {
3434
- staticFiles: collected.copilotInstructions.length + collected.unscopedRules.length + collected.userGlobal.length,
3435
- scopedRules: collected.scopedRules.length,
3436
- imports: collected.imports.length,
3437
- skipped: collected.skipped.length
3438
- };
3945
+ const rendered = buildMirrorBridgeSection(collected, { repoRoot: process$1.cwd() });
3946
+ bridgeCollected = collected;
3947
+ bridgeSection = rendered.section;
3948
+ bridgeStats = rendered.stats;
3439
3949
  bridgeScoped = collected.scopedRules;
3440
- globalThis.__ghRouterBridgeCollected = collected;
3950
+ bridgeActive = rendered.stats.bytes > 0;
3951
+ if (rendered.stats.truncated) consola.warn(`Pi memory bridge: the bridged AGENTS.md block hit its ${Math.round(PI_BRIDGE_STATIC_BUDGET_BYTES / 1e3)} KB budget and was cut to ${rendered.stats.bytes} bytes, so some rules are incomplete or omitted this launch. Raise the budget in src/lib/pi-memory-bridge.ts, or move detail into .claude/rules/ so it attaches on demand instead.`);
3441
3952
  } catch (err) {
3442
3953
  consola.debug("Pi memory bridge collection skipped:", err);
3443
3954
  }
3444
3955
  }
3956
+ const routerAgentFiles = peersEnabled ? buildPiAgentFiles(profileId) : {};
3957
+ const routerSkills = buildPiSkills({
3958
+ profileId,
3959
+ peers: peersEnabled,
3960
+ swe: sweEnabled,
3961
+ search: searchEnabled
3962
+ });
3963
+ const routerPrompts = buildPiPrompts({
3964
+ profileId,
3965
+ swe: sweEnabled,
3966
+ peers: peersEnabled
3967
+ });
3968
+ for (const [rel, content] of Object.entries(routerAgentFiles)) await writeTextFile(path.join(mirror, rel), content);
3969
+ const skillPlan = await planSkillWrites(mirror, routerSkills);
3970
+ for (const skill of skillPlan.write) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
3971
+ const shadowedSkills = skillPlan.shadowed.map(({ dir, file }) => ({
3972
+ dir,
3973
+ file
3974
+ }));
3975
+ if (shadowedSkills.length > 0) consola.warn(`Pi skills: kept your ${shadowedSkills.map((s) => `\`${s.dir}\``).join(", ")} instead of the router's copy (${shadowedSkills[0]?.file}). Remove the user skill to get the router's version back.`);
3976
+ for (const prompt of routerPrompts) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
3977
+ await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, {
3978
+ peers: peersEnabled,
3979
+ codeSearch: surfaces.codeSearch,
3980
+ bridge: bridgeActive
3981
+ }));
3982
+ let foreign;
3983
+ if (foreignEnabled) try {
3984
+ const { buildForeignAgentIndex, buildReservedNames, piForeignHomeDir, piForeignRepoRoot, planForeignArtifacts, writeForeignArtifacts } = await import("./pi-foreign-artifacts-CNt6wQ1P.js");
3985
+ const repoRoot = await piForeignRepoRoot(process$1.cwd());
3986
+ const homeDir = piForeignHomeDir();
3987
+ const reservedNames = await buildReservedNames({
3988
+ mirrorDir: mirror,
3989
+ repoRoot,
3990
+ homeDir,
3991
+ emittedAgents: Object.keys(routerAgentFiles).map((rel) => path.basename(rel, ".md")),
3992
+ emittedSkills: routerSkills.map((skill) => skill.dir),
3993
+ emittedPrompts: routerPrompts.map((prompt) => prompt.name)
3994
+ });
3995
+ const plan = await planForeignArtifacts({
3996
+ repoRoot,
3997
+ homeDir,
3998
+ mirrorDir: mirror,
3999
+ reservedNames
4000
+ });
4001
+ const written = await writeForeignArtifacts(mirror, plan);
4002
+ if (written.overwritten > 0) consola.warn(`Pi foreign bridge: ${written.overwritten} existing file(s) were replaced. That is a bug in the name reservation, not expected behavior.`);
4003
+ foreign = {
4004
+ agents: plan.agents.map(({ name, description, body }) => ({
4005
+ name,
4006
+ description,
4007
+ body
4008
+ })),
4009
+ index: buildForeignAgentIndex(plan.agents)
4010
+ };
4011
+ foreignStats = {
4012
+ agents: plan.agents.length,
4013
+ renamed: [
4014
+ ...plan.agents.filter((agent) => agent.renamedFrom).map((agent) => ({
4015
+ from: String(agent.renamedFrom),
4016
+ to: agent.name
4017
+ })),
4018
+ ...plan.skills.filter((skill) => skill.renamedFrom).map((skill) => ({
4019
+ from: String(skill.renamedFrom),
4020
+ to: skill.name
4021
+ })),
4022
+ ...plan.prompts.filter((prompt) => prompt.renamedFrom).map((prompt) => ({
4023
+ from: String(prompt.renamedFrom),
4024
+ to: prompt.name
4025
+ }))
4026
+ ],
4027
+ skipped: plan.skipped.map(({ name, reason }) => ({
4028
+ name,
4029
+ reason
4030
+ })),
4031
+ written
4032
+ };
4033
+ } catch (err) {
4034
+ consola.debug("Pi foreign bridge skipped:", err);
4035
+ }
4036
+ else try {
4037
+ const { countForeignAgentFiles, piForeignHomeDir, piForeignRepoRoot } = await import("./pi-foreign-artifacts-CNt6wQ1P.js");
4038
+ foreignAvailable = await countForeignAgentFiles({
4039
+ repoRoot: await piForeignRepoRoot(process$1.cwd()),
4040
+ homeDir: piForeignHomeDir()
4041
+ });
4042
+ } catch (err) {
4043
+ consola.debug("Pi foreign artifact probe skipped:", err);
4044
+ }
3445
4045
  await writeTextFile(path.join(mirror, "extensions", "gh-router-pi", "index.ts"), buildPiExtensionSource({
3446
4046
  profileId,
3447
4047
  bridge: bridgeStats ? {
3448
4048
  stats: bridgeStats,
3449
4049
  scopedRules: bridgeScoped
3450
- } : void 0
4050
+ } : void 0,
4051
+ foreign
3451
4052
  }));
3452
4053
  if (surfaces.groups.length > 0) {
3453
4054
  const written = await writePiMcpJson({
@@ -3460,49 +4061,38 @@ const pi = defineCommand({
3460
4061
  if (written.skippedReason) consola.warn(`Pi MCP: left ${written.path} alone (${written.skippedReason}); the scoped groups are not exposed to Pi this launch.`);
3461
4062
  else for (const { key, file } of written.shadowed) consola.warn(`Pi MCP: ${file} declares "${key}" and outranks the mirror copy, so the router's version is not the one Pi will run. Rename that entry to keep both.`);
3462
4063
  }
3463
- if (peersEnabled) {
3464
- const agentFiles = buildPiAgentFiles(profileId);
3465
- for (const [rel, content] of Object.entries(agentFiles)) await writeTextFile(path.join(mirror, rel), content);
3466
- }
3467
- for (const skill of buildPiSkills({
3468
- profileId,
3469
- peers: peersEnabled,
3470
- swe: sweEnabled,
3471
- search: searchEnabled
3472
- })) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
3473
- for (const prompt of buildPiPrompts({
3474
- profileId,
3475
- swe: sweEnabled,
3476
- peers: peersEnabled
3477
- })) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
3478
- await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, {
3479
- peers: peersEnabled,
3480
- codeSearch: surfaces.codeSearch
3481
- }));
3482
- try {
3483
- const collected = globalThis.__ghRouterBridgeCollected;
3484
- if (collected) {
3485
- const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-Dvj1T3e3.js");
3486
- const { section } = buildMirrorBridgeSection(collected, { repoRoot: process$1.cwd() });
3487
- const agentsPath = path.join(mirror, "AGENTS.md");
3488
- let existing;
3489
- try {
3490
- existing = await fs$1.readFile(agentsPath, "utf8");
3491
- } catch {
3492
- existing = void 0;
3493
- }
3494
- await writeTextFile(agentsPath, mergeBridgeIntoAgentsMd(existing, section));
3495
- await writeJsonFile(path.join(mirror, ".gh-router-bridge.json"), {
3496
- stats: bridgeStats ?? null,
3497
- scopedRuleFiles: bridgeScoped.map((r) => r.file)
3498
- });
4064
+ if (bridgeCollected) try {
4065
+ const { mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-D5A0h_Kf.js");
4066
+ const agentsPath = path.join(mirror, "AGENTS.md");
4067
+ let existing;
4068
+ try {
4069
+ existing = await fs$1.readFile(agentsPath, "utf8");
4070
+ } catch {
4071
+ existing = void 0;
3499
4072
  }
4073
+ const userText = mergeBridgeIntoAgentsMd(existing, "").trim();
4074
+ const merged = mergeBridgeIntoAgentsMd(existing, bridgeSection);
4075
+ if (merged !== (existing ?? "")) await writeTextFile(agentsPath, merged);
4076
+ const shadowWarnings = bridgeShadowWarnings(precedence, {
4077
+ bridgeActive,
4078
+ mirrorDir: mirror,
4079
+ userOwnsAgentsMd: userText.length > 0
4080
+ });
4081
+ for (const warning of shadowWarnings) consola.warn(warning);
4082
+ await writeJsonFile(path.join(mirror, ".gh-router-bridge.json"), {
4083
+ stats: bridgeStats ?? null,
4084
+ deduped: bridgeCollected.deduped ?? 0,
4085
+ shadowedSkills,
4086
+ scopedRuleFiles: bridgeScoped.map((r) => r.file),
4087
+ precedence: {
4088
+ agentsOverride: precedence.agentsOverride ? path.join(mirror, "AGENTS.override.md") : null,
4089
+ userClaudeMd: precedence.userClaudeMd,
4090
+ systemMd: precedence.systemMd ? path.join(mirror, "SYSTEM.md") : null,
4091
+ projectAppendSystem: precedence.projectAppendSystem
4092
+ }
4093
+ });
3500
4094
  } catch (err) {
3501
4095
  consola.debug("Pi memory bridge synthesis skipped:", err);
3502
- } finally {
3503
- try {
3504
- delete globalThis.__ghRouterBridgeCollected;
3505
- } catch {}
3506
4096
  }
3507
4097
  } catch (err) {
3508
4098
  consola.error(`Failed to write Pi launch files: ${err instanceof Error ? err.message : String(err)}.`);
@@ -3560,13 +4150,22 @@ const pi = defineCommand({
3560
4150
  search: searchEnabled,
3561
4151
  browse: browseEnabled,
3562
4152
  mcpGroups: surfaces.groups.map((g) => g.group),
4153
+ foreign: foreignStats ? {
4154
+ agents: foreignStats.agents,
4155
+ skills: foreignStats.written.skills,
4156
+ prompts: foreignStats.written.prompts,
4157
+ renamed: foreignStats.renamed,
4158
+ skipped: foreignStats.skipped
4159
+ } : void 0,
4160
+ foreignAvailable,
3563
4161
  serverUrl
3564
4162
  })}\n`);
3565
4163
  if (sweEnabled && !peersEnabled) process$1.stderr.write("Note: --swe without --peers emits no delegate/review skills or prompts (no agents behind them in a peerless launch).\n");
3566
4164
  const { disposeBluebirdClients } = await import("./bluebird-client-BvoMTmEv.js");
3567
- const { disposeAdoClients } = await import("./ado-tools-CRkyU51J.js");
4165
+ const { disposeAdoClients } = await import("./ado-tools-CsfbnY8x.js");
3568
4166
  launchChild({
3569
4167
  kind: "pi",
4168
+ execArgs: piCommand && piCommand.command !== "" ? [piCommand.command, ...piCommand.args] : void 0,
3570
4169
  envVars: {
3571
4170
  ...getPiLaunchEnvVars(mirror),
3572
4171
  GH_ROUTER_HOOK_MCP_URL: serverUrl,
@@ -3601,4 +4200,4 @@ const pi = defineCommand({
3601
4200
  });
3602
4201
  export { pi };
3603
4202
 
3604
- //# sourceMappingURL=pi-B0EFY6l7.js.map
4203
+ //# sourceMappingURL=pi-YhoA26wi.js.map