github-router 0.3.379 → 0.3.381

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 (165) 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-BWYL2b8N.js → attribution-settings-BEwSkdhK.js} +10 -10
  10. package/dist/{attribution-settings-BWYL2b8N.js.map → attribution-settings-BEwSkdhK.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-CSuIdaLV.js → claude-CkrhHkPQ.js} +26 -25
  19. package/dist/{claude-CSuIdaLV.js.map → claude-CkrhHkPQ.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-BG0pfud9.js → codex-50GzveCD.js} +8 -7
  23. package/dist/{codex-BG0pfud9.js.map → codex-50GzveCD.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-DmeBxzIo.js → pi-DVud9eQn.js} +386 -243
  99. package/dist/pi-DVud9eQn.js.map +1 -0
  100. package/dist/{pi-foreign-artifacts-DZ4tioyO.js → pi-foreign-artifacts-CNt6wQ1P.js} +2 -2
  101. package/dist/{pi-foreign-artifacts-DZ4tioyO.js.map → pi-foreign-artifacts-CNt6wQ1P.js.map} +1 -1
  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-zbQKfx1E.js → serve-B8Igr9Q0.js} +15 -14
  117. package/dist/{serve-zbQKfx1E.js.map → serve-B8Igr9Q0.js.map} +1 -1
  118. package/dist/{server-setup-ClZdV33Q.js → server-setup-byIhjgOb.js} +708 -640
  119. package/dist/server-setup-byIhjgOb.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-mnedD5cH.js → start-7CiQIl0r.js} +5 -4
  123. package/dist/{start-mnedD5cH.js.map → start-7CiQIl0r.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-DmeBxzIo.js.map +0 -1
  158. package/dist/pi-memory-bridge-Bp9AnYw9.js +0 -1
  159. package/dist/pi-memory-bridge-CICIdDVP.js +0 -413
  160. package/dist/pi-memory-bridge-CICIdDVP.js.map +0 -1
  161. package/dist/provision-DPL8aGe2.js.map +0 -1
  162. package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
  163. package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
  164. package/dist/server-setup-ClZdV33Q.js.map +0 -1
  165. package/dist/service-backend-Cdgz6WPx.js.map +0 -1
@@ -1,23 +1,217 @@
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-ClZdV33Q.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 { H as validateCheapestProfilePrerequisites, I as formatLocalPrerequisiteFailure, L as profileDescriptor, P as formatCheapestPrerequisiteFailure, R as resolveLaunchProfile, W as validateLocalProfilePrerequisites, _ as enableFileLogging, a as setupAndServe, c as ensurePiAgentMirror, d as seedPiPackageCache, f as sweepStalePiPackageCaches, i as parseSharedArgs, j as formatBalancedPrerequisiteFailure, l as removeOwnPiAgentMirror, m as stopKeepAwake, o as sharedServerArgs, p as startKeepAwake, r as getPiLaunchEnvVars, s as LAUNCH_SECRET_HEADER, u as sweepStalePiAgentMirrors, z as validateBalancedProfilePrerequisites } from "./server-setup-byIhjgOb.js";
10
+ import { t as FRESH_CONSULT_CONTRACT } from "./claude-md-injection-DNMDcw1W.js";
11
+ 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";
12
+ 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";
13
+ import { i as launchChild, t as provisionToolbelt } from "./provision-BWtuDq_v.js";
14
+ import { t as PATHS } from "./paths-DeFmYJhO.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";
17
21
  import path from "node:path";
18
- import { createHash, randomBytes } from "node:crypto";
22
+ import { 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.
@@ -290,156 +484,6 @@ function buildPiStatusPayload(source, opts) {
290
484
  worktree: null
291
485
  };
292
486
  }
293
- // src/lib/pi-package-cache.ts
294
- /**
295
- * Persistent npm-package cache for Pi launches.
296
- *
297
- * Pi installs the mirror's `packages[]` into `<agentDir>/npm` on every
298
- * boot, and the agent dir is a fresh per-launch mirror
299
- * (`pi-agent-<pid>-<rand>`) — so every launch pays a full registry
300
- * install (~5s + `added N packages` noise that bypasses
301
- * `npm_config_loglevel=error`). Pi skips the install when the package
302
- * dir already exists and the installed version satisfies the configured
303
- * range — and unpinned `npm:name` specs match ANY installed version —
304
- * so pre-seeding `<mirror>/npm` from a durable cache makes repeat
305
- * launches install nothing: faster AND silent.
306
- *
307
- * Keyed by the exact package set (sorted spec fingerprints), so flag
308
- * combinations (`--helpers`/`--ui`/`--search`/`--browse`) each get
309
- * their own entry and can never cross-contaminate. Entries older than
310
- * the max age are treated as a miss so unpinned packages periodically
311
- * refresh to upstream latest; the fresh install is then saved back over
312
- * the entry. Opt out entirely with `GH_ROUTER_PI_NO_PACKAGE_CACHE=1`.
313
- *
314
- * Max age defaults to 24h, not the original 7d. Pi resolves an unpinned
315
- * `npm:name` spec to whatever is already installed, so the max age IS the
316
- * worst-case staleness of every extension the user runs — a week of it meant a
317
- * fix published upstream on Monday was still missing the following Sunday.
318
- * A day bounds the lag without making the cache pointless: the npm install it
319
- * avoids takes ~5s, so one refresh per day is paid back by every other launch
320
- * that day. Override with `GH_ROUTER_PI_PACKAGE_CACHE_HOURS`.
321
- */
322
- const PI_PACKAGE_CACHE_MAX_AGE_MS = 864e5;
323
- /**
324
- * Effective max age. Read per call rather than at module load so a test (or a
325
- * long-lived process re-reading config) can change the env and observe it, and
326
- * so a malformed value degrades to the default instead of `NaN` day math —
327
- * `Date.now() - mtime > NaN` is always false, which would make every entry
328
- * eternally fresh.
329
- */
330
- function piPackageCacheMaxAgeMs() {
331
- const raw = (process.env["GH_ROUTER_PI_PACKAGE_CACHE_HOURS"] ?? "").trim();
332
- if (!raw) return PI_PACKAGE_CACHE_MAX_AGE_MS;
333
- const hours = Number(raw);
334
- if (!Number.isFinite(hours) || hours <= 0) return PI_PACKAGE_CACHE_MAX_AGE_MS;
335
- return hours * 3600 * 1e3;
336
- }
337
- function cacheDisabled() {
338
- return process.env.GH_ROUTER_PI_NO_PACKAGE_CACHE === "1";
339
- }
340
- /** Stable fingerprint of one `packages[]` entry (order-independent). */
341
- function piPackageSpecFingerprint(entry) {
342
- if (typeof entry === "string") return entry;
343
- const join = (v) => [...v ?? []].sort().join(",");
344
- return [
345
- entry.source,
346
- `ext:${join(entry.extensions)}`,
347
- `skills:${join(entry.skills)}`,
348
- `prompts:${join(entry.prompts)}`,
349
- `themes:${join(entry.themes)}`
350
- ].join("::");
351
- }
352
- /** Order-independent cache key for a launch's full `packages[]` slice. */
353
- function piPackageCacheKey(packages) {
354
- const specs = packages.map(piPackageSpecFingerprint).sort();
355
- return createHash("sha256").update(specs.join("\n")).digest("hex").slice(0, 16);
356
- }
357
- function piPackageCacheDir(key) {
358
- return path.join(PATHS.APP_DIR, "pi-packages", key);
359
- }
360
- function npmDirOf(root) {
361
- return path.join(root, "npm");
362
- }
363
- async function mtimeMsOf(dir) {
364
- try {
365
- return (await fs$1.stat(dir)).mtimeMs;
366
- } catch {
367
- return null;
368
- }
369
- }
370
- /**
371
- * Copy the cached `<key>/npm` tree into a fresh mirror before Pi boots.
372
- * Returns true on a hit (mirror pre-seeded; Pi should install nothing).
373
- * Stale entries (older than the max age) are a miss so the launch
374
- * refreshes to upstream latest. Never throws.
375
- */
376
- async function seedPiPackageCache(mirrorDir, packages) {
377
- if (cacheDisabled()) return false;
378
- const key = piPackageCacheKey(packages);
379
- const cachedNpm = npmDirOf(piPackageCacheDir(key));
380
- const mtime = await mtimeMsOf(cachedNpm);
381
- if (mtime === null) return false;
382
- const maxAge = piPackageCacheMaxAgeMs();
383
- if (Date.now() - mtime > maxAge) {
384
- const ageHours = Math.floor((Date.now() - mtime) / 36e5);
385
- consola.debug(`Pi package cache ${key} is stale (${ageHours}h old, max ${Math.round(maxAge / 36e5)}h); refreshing from registry.`);
386
- return false;
387
- }
388
- try {
389
- await fs$1.cp(cachedNpm, npmDirOf(mirrorDir), { recursive: true });
390
- return true;
391
- } catch (err) {
392
- consola.debug("Pi package cache seed skipped:", err);
393
- return false;
394
- }
395
- }
396
- /**
397
- * Persist a mirror's installed `<mirror>/npm` tree back to the cache
398
- * (call on shutdown, BEFORE the mirror is removed). Overwrites the
399
- * entry, refreshing its mtime. Never throws.
400
- */
401
- async function savePiPackageCache(mirrorDir, packages) {
402
- if (cacheDisabled()) return;
403
- const mirrorNpm = npmDirOf(mirrorDir);
404
- if (await mtimeMsOf(path.join(mirrorNpm, "node_modules")) === null) return;
405
- const dest = npmDirOf(piPackageCacheDir(piPackageCacheKey(packages)));
406
- try {
407
- await fs$1.mkdir(path.dirname(dest), { recursive: true });
408
- await fs$1.rm(dest, {
409
- recursive: true,
410
- force: true
411
- });
412
- await fs$1.cp(mirrorNpm, dest, { recursive: true });
413
- } catch (err) {
414
- consola.debug("Pi package cache save skipped:", err);
415
- }
416
- }
417
- /**
418
- * Sweep cache entries whose `npm/` tree is older than the max age.
419
- * Best-effort, never throws. Runs opportunistically at boot.
420
- */
421
- async function sweepStalePiPackageCaches() {
422
- if (cacheDisabled()) return;
423
- const root = path.join(PATHS.APP_DIR, "pi-packages");
424
- let entries;
425
- try {
426
- entries = await fs$1.readdir(root);
427
- } catch {
428
- return;
429
- }
430
- await Promise.all(entries.map(async (entry) => {
431
- const npmDir = npmDirOf(path.join(root, entry));
432
- try {
433
- const mtime = await mtimeMsOf(npmDir);
434
- if (mtime === null || Date.now() - mtime > piPackageCacheMaxAgeMs()) await fs$1.rm(path.join(root, entry), {
435
- recursive: true,
436
- force: true
437
- });
438
- } catch (err) {
439
- consola.debug(`Pi package cache sweep: skipping ${entry}:`, err);
440
- }
441
- }));
442
- }
443
487
  // src/lib/pi-models-settings.ts
444
488
  /**
445
489
  * Pi thinking levels that can appear in `thinkingLevelMap`. `off` is
@@ -1503,6 +1547,23 @@ function buildPiLaunchCard(opts) {
1503
1547
  return lines.join("\n");
1504
1548
  }
1505
1549
  /**
1550
+ * Registered with Pi inside the digest, only when the memory bridge actually
1551
+ * wrote a block into the mirror's `AGENTS.md`.
1552
+ *
1553
+ * Why a line at all: the block is a permanent per-turn prompt cost, and the
1554
+ * measured failure mode of agent-authored project instructions is restatement —
1555
+ * a study of LLM-generated AGENTS.md files found ~23% higher cost with no
1556
+ * success gain, because the model paraphrases the file back at the user. One
1557
+ * sentence stating the contract (follow it, cite it, do not repeat it) is
1558
+ * cheaper than any restructuring and is the whole behavioural delta we want
1559
+ * from "having read AGENTS.md".
1560
+ *
1561
+ * Emitted only when `bridge` is true: naming AGENTS.md on a launch whose bridge
1562
+ * is off (or whose `-nc` disabled context files) would point the model at
1563
+ * guidance this launch does not have.
1564
+ */
1565
+ 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.";
1566
+ /**
1506
1567
  * Short operating digest appended to APPEND_SYSTEM.md (prompt-cache-stable).
1507
1568
  * Mode identity — always injected. Peer consult sentences drop out under
1508
1569
  * `peers: false` so the digest never names tools that don't exist.
@@ -1515,7 +1576,8 @@ function buildPiAppendSystem(profileId, opts = {}) {
1515
1576
  "",
1516
1577
  `- Lead owns planning directly; there is no Plan subagent.`,
1517
1578
  PI_TOOL_PREFERENCE_LINE,
1518
- ...opts.codeSearch === true ? [PI_SEARCH_ORDER_LINE] : []
1579
+ ...opts.codeSearch === true ? [PI_SEARCH_ORDER_LINE] : [],
1580
+ ...opts.bridge === true ? [PI_CONTEXT_CONTRACT_LINE] : []
1519
1581
  ];
1520
1582
  if (peers) {
1521
1583
  const oracle = piOracleEnabled(profileId);
@@ -2790,8 +2852,8 @@ function buildPiMemoryBridgeSection(bridge) {
2790
2852
  ` description: "Show bridged memory inventory and auto-memory locations (on-demand; nothing auto-injected)",`,
2791
2853
  ` handler: async (_args, ctx) => {`,
2792
2854
  ` try {`,
2793
- ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,
2794
- ` 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)"];`,
2855
+ ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0, truncated: false, bytes: 0 };`,
2856
+ ` 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)"];`,
2795
2857
  ` try {`,
2796
2858
  ` const files = (BRIDGE.scopedRules || []).map((r) => r.file);`,
2797
2859
  ` if (files.length > 0) lines.push(" Scoped files:", ...files.slice(0, 20).map((f) => " - " + f));`,
@@ -2807,8 +2869,8 @@ function buildPiMemoryBridgeSection(bridge) {
2807
2869
  ` description: "Show what the gh-router memory bridge loaded",`,
2808
2870
  ` handler: async (_args, ctx) => {`,
2809
2871
  ` try {`,
2810
- ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,
2811
- ` 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");`,
2872
+ ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0, truncated: false, bytes: 0 };`,
2873
+ ` 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");`,
2812
2874
  ` } catch {}`,
2813
2875
  ` },`,
2814
2876
  ` });`,
@@ -2843,7 +2905,7 @@ function buildPiExtensionSource(opts) {
2843
2905
  `}`,
2844
2906
  ``
2845
2907
  ] : [], `export default function (pi) {`);
2846
- if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
2908
+ if (opts.bridge) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
2847
2909
  if (opts.foreign && opts.foreign.agents.length + opts.foreign.index.length > 0) lines.push(...buildPiForeignAgentsSection(opts.foreign));
2848
2910
  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 ? [
2849
2911
  ` // Cheapest-profile execution brief, injected ABOVE the model's turn.`,
@@ -3051,6 +3113,69 @@ function buildPiPrompts(opts) {
3051
3113
  });
3052
3114
  return prompts;
3053
3115
  }
3116
+ // src/lib/pi-mirror-guards.ts
3117
+ async function isFile(file) {
3118
+ try {
3119
+ return (await fs$1.stat(file)).isFile();
3120
+ } catch {
3121
+ return false;
3122
+ }
3123
+ }
3124
+ /** Collect the precedence hazards for this launch. Never throws. */
3125
+ async function inspectMirrorPrecedence(mirrorDir, projectCwd) {
3126
+ const projectAppend = path.join(projectCwd, ".pi", "APPEND_SYSTEM.md");
3127
+ const userClaudeMd = path.join(mirrorDir, "CLAUDE.md");
3128
+ return {
3129
+ agentsOverride: await isFile(path.join(mirrorDir, "AGENTS.override.md")),
3130
+ systemMd: await isFile(path.join(mirrorDir, "SYSTEM.md")),
3131
+ projectAppendSystem: await isFile(projectAppend) ? projectAppend : null,
3132
+ userClaudeMd: await isFile(userClaudeMd) ? userClaudeMd : null
3133
+ };
3134
+ }
3135
+ /**
3136
+ * The launch warnings a bridge block provokes, as data rather than as calls.
3137
+ *
3138
+ * Both messages describe the SAME Pi rule in opposite directions: one context
3139
+ * file per directory, first candidate wins. They are only true when a block was
3140
+ * actually written (`bridgeActive`), because otherwise `AGENTS.md` either does
3141
+ * not exist (so `CLAUDE.md` still loads) or was never touched by us. Returning
3142
+ * strings keeps the gating unit-testable; the launcher only logs them.
3143
+ */
3144
+ function bridgeShadowWarnings(precedence, opts) {
3145
+ if (!opts.bridgeActive) return [];
3146
+ const warnings = [];
3147
+ if (precedence.agentsOverride) {
3148
+ const file = path.join(opts.mirrorDir, "AGENTS.override.md");
3149
+ 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.`);
3150
+ }
3151
+ 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.`);
3152
+ return warnings;
3153
+ }
3154
+ /**
3155
+ * Split the router's skills into "write" and "already the user's".
3156
+ *
3157
+ * The mirror is seeded from `~/.pi/agent` before this runs, so a user-level
3158
+ * `skills/gh-oracle/SKILL.md` is already on disk. Overwriting it would silently
3159
+ * destroy the user's copy, so the user's file wins and the caller reports the
3160
+ * collision instead.
3161
+ */
3162
+ async function planSkillWrites(mirrorDir, skills) {
3163
+ const write = [];
3164
+ const shadowed = [];
3165
+ for (const skill of skills) {
3166
+ const file = path.join(mirrorDir, "skills", skill.dir, "SKILL.md");
3167
+ if (await isFile(file)) shadowed.push({
3168
+ dir: skill.dir,
3169
+ file,
3170
+ skill
3171
+ });
3172
+ else write.push(skill);
3173
+ }
3174
+ return {
3175
+ write,
3176
+ shadowed
3177
+ };
3178
+ }
3054
3179
  // src/lib/pi-mcp-config.ts
3055
3180
  /**
3056
3181
  * Pi's MCP surface for the router's scoped groups.
@@ -3358,6 +3483,10 @@ const piArgs = {
3358
3483
  type: "string",
3359
3484
  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."
3360
3485
  },
3486
+ "pi-path": {
3487
+ type: "string",
3488
+ 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."
3489
+ },
3361
3490
  "update-check": {
3362
3491
  type: "boolean",
3363
3492
  default: true,
@@ -3486,26 +3615,21 @@ const pi = defineCommand({
3486
3615
  }
3487
3616
  let server;
3488
3617
  let serverUrl;
3618
+ const piPath = typeof args["pi-path"] === "string" ? args["pi-path"].trim() : "";
3489
3619
  const updateCheck = args["update-check"] !== false;
3490
3620
  const autoUpdate = args["auto-update"] !== false;
3491
- let installedVersion = null;
3492
- const pendingInstall = {
3621
+ const managePi = updateCheck && piPath === "";
3622
+ let piCommand = null;
3623
+ const pendingResolve = {
3493
3624
  promise: null,
3494
3625
  abort: null
3495
3626
  };
3496
- if (updateCheck) {
3497
- try {
3498
- installedVersion = await getInstalledPiVersion();
3499
- } catch (err) {
3500
- consola.debug("Pi presence probe failed:", err);
3501
- }
3502
- if (installedVersion === null) {
3503
- const controller = new AbortController();
3504
- pendingInstall.abort = () => controller.abort();
3505
- pendingInstall.promise = ensurePiInstalled({ signal: controller.signal });
3506
- pendingInstall.promise.catch(() => {});
3507
- }
3508
- }
3627
+ if (managePi) {
3628
+ const controller = new AbortController();
3629
+ pendingResolve.abort = () => controller.abort();
3630
+ pendingResolve.promise = resolvePiCommand({ signal: controller.signal });
3631
+ pendingResolve.promise.catch(() => {});
3632
+ } else if (piPath !== "") piCommand = await resolvePiCommand({ piPath });
3509
3633
  try {
3510
3634
  const quietBoot = existsSync(PATHS.GITHUB_TOKEN_PATH) && !parsed.verbose && !parsed.showToken;
3511
3635
  const priorLevel = consola.level;
@@ -3523,34 +3647,34 @@ const pi = defineCommand({
3523
3647
  server = setupResult.server;
3524
3648
  serverUrl = setupResult.serverUrl;
3525
3649
  } catch (error) {
3526
- pendingInstall.abort?.();
3650
+ pendingResolve.abort?.();
3527
3651
  consola.error("Failed to start server:", error instanceof Error ? error.message : error);
3528
3652
  process$1.exit(1);
3529
3653
  }
3530
3654
  runSelfUpdate({ selfUpdate: args["self-update"] !== false });
3531
- if (pendingInstall.promise) try {
3532
- installedVersion = await pendingInstall.promise;
3655
+ if (pendingResolve.promise) try {
3656
+ piCommand = await pendingResolve.promise;
3533
3657
  } catch (err) {
3534
- 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.`);
3535
- process$1.exit(1);
3658
+ consola.debug("Pi resolution failed:", err);
3536
3659
  } finally {
3537
- pendingInstall.promise = null;
3538
- pendingInstall.abort = null;
3660
+ pendingResolve.promise = null;
3661
+ pendingResolve.abort = null;
3539
3662
  }
3540
- if (updateCheck && installedVersion !== null) {
3541
- if (!meetsPiMinVersion(installedVersion)) {
3542
- if (autoUpdate) try {
3543
- await updatePi("latest");
3544
- installedVersion = await getInstalledPiVersion();
3545
- } catch (err) {
3546
- 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()}\`.`);
3547
- process$1.exit(1);
3548
- }
3549
- if (!meetsPiMinVersion(installedVersion)) {
3550
- 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()}\`.`);
3551
- process$1.exit(1);
3552
- }
3553
- } else refreshPiInBackground({ autoUpdate });
3663
+ if (managePi) {
3664
+ if (!piCommand || piCommand.command === "") {
3665
+ const detail = piCommand?.note ?? "no runnable `pi` was found";
3666
+ 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.`);
3667
+ process$1.exit(1);
3668
+ }
3669
+ if (!meetsPiMinVersion(piCommand.version)) {
3670
+ 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.`);
3671
+ process$1.exit(1);
3672
+ }
3673
+ if (piCommand.note) consola.info(piCommand.note);
3674
+ if (autoUpdate) {
3675
+ if (piCommand.source === "path") refreshPiInBackground({ autoUpdate });
3676
+ else scheduleBackgroundPiInstall().then((detail) => consola.debug(`managed Pi refresh: ${detail}`), (err) => consola.debug("managed Pi refresh failed:", err));
3677
+ }
3554
3678
  }
3555
3679
  const peersEnabled = args["peers"] !== false;
3556
3680
  const sweEnabled = args["swe"] === true;
@@ -3589,7 +3713,9 @@ const pi = defineCommand({
3589
3713
  process$1.exit(1);
3590
3714
  }
3591
3715
  enableFileLogging();
3592
- let packagesForCache = [];
3716
+ const precedence = await inspectMirrorPrecedence(mirror, process$1.cwd());
3717
+ 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.`);
3718
+ 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.`);
3593
3719
  let foreignAvailable;
3594
3720
  let foreignStats;
3595
3721
  const launchSecret = randomBytes(32).toString("hex");
@@ -3652,24 +3778,26 @@ const pi = defineCommand({
3652
3778
  userKeybindings = {};
3653
3779
  }
3654
3780
  await writeJsonFile(keybindingsPath, { ...mergePiKeybindingsSettings(userKeybindings, buildPiKeybindingsJson()) });
3655
- packagesForCache = [...builtSettings.packages];
3656
- if (await seedPiPackageCache(mirror, packagesForCache)) consola.debug("Pi package cache hit: mirror pre-seeded, skipping registry install.");
3781
+ const seed = await seedPiPackageCache(mirror, builtSettings.packages);
3782
+ consola.debug(`Pi package cache: ${seed.reason}.`);
3657
3783
  const bridgeDisabled = args["memory-bridge"] === false || process$1.env.GH_ROUTER_PI_BRIDGE === "0" || process$1.env.GH_ROUTER_DISABLE_PI_BRIDGE === "1";
3658
3784
  let bridgeStats;
3659
3785
  let bridgeScoped = [];
3786
+ let bridgeSection = "";
3787
+ let bridgeCollected;
3788
+ let bridgeActive = false;
3660
3789
  if (!bridgeDisabled) {
3661
3790
  const passthrough = collectPiPassthroughArgs(rawArgs, piArgs);
3662
3791
  if (!(passthrough.includes("--no-context-files") || passthrough.includes("-nc"))) try {
3663
- const { collectBridgeInputs } = await import("./pi-memory-bridge-Bp9AnYw9.js");
3792
+ const { PI_BRIDGE_STATIC_BUDGET_BYTES, buildMirrorBridgeSection, collectBridgeInputs } = await import("./pi-memory-bridge-D5A0h_Kf.js");
3664
3793
  const collected = await collectBridgeInputs(process$1.cwd());
3665
- bridgeStats = {
3666
- staticFiles: collected.copilotInstructions.length + collected.unscopedRules.length + collected.userGlobal.length,
3667
- scopedRules: collected.scopedRules.length,
3668
- imports: collected.imports.length,
3669
- skipped: collected.skipped.length
3670
- };
3794
+ const rendered = buildMirrorBridgeSection(collected, { repoRoot: process$1.cwd() });
3795
+ bridgeCollected = collected;
3796
+ bridgeSection = rendered.section;
3797
+ bridgeStats = rendered.stats;
3671
3798
  bridgeScoped = collected.scopedRules;
3672
- globalThis.__ghRouterBridgeCollected = collected;
3799
+ bridgeActive = rendered.stats.bytes > 0;
3800
+ 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.`);
3673
3801
  } catch (err) {
3674
3802
  consola.debug("Pi memory bridge collection skipped:", err);
3675
3803
  }
@@ -3687,15 +3815,22 @@ const pi = defineCommand({
3687
3815
  peers: peersEnabled
3688
3816
  });
3689
3817
  for (const [rel, content] of Object.entries(routerAgentFiles)) await writeTextFile(path.join(mirror, rel), content);
3690
- for (const skill of routerSkills) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
3818
+ const skillPlan = await planSkillWrites(mirror, routerSkills);
3819
+ for (const skill of skillPlan.write) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
3820
+ const shadowedSkills = skillPlan.shadowed.map(({ dir, file }) => ({
3821
+ dir,
3822
+ file
3823
+ }));
3824
+ 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.`);
3691
3825
  for (const prompt of routerPrompts) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
3692
3826
  await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, {
3693
3827
  peers: peersEnabled,
3694
- codeSearch: surfaces.codeSearch
3828
+ codeSearch: surfaces.codeSearch,
3829
+ bridge: bridgeActive
3695
3830
  }));
3696
3831
  let foreign;
3697
3832
  if (foreignEnabled) try {
3698
- const { buildForeignAgentIndex, buildReservedNames, piForeignHomeDir, piForeignRepoRoot, planForeignArtifacts, writeForeignArtifacts } = await import("./pi-foreign-artifacts-DZ4tioyO.js");
3833
+ const { buildForeignAgentIndex, buildReservedNames, piForeignHomeDir, piForeignRepoRoot, planForeignArtifacts, writeForeignArtifacts } = await import("./pi-foreign-artifacts-CNt6wQ1P.js");
3699
3834
  const repoRoot = await piForeignRepoRoot(process$1.cwd());
3700
3835
  const homeDir = piForeignHomeDir();
3701
3836
  const reservedNames = await buildReservedNames({
@@ -3748,7 +3883,7 @@ const pi = defineCommand({
3748
3883
  consola.debug("Pi foreign bridge skipped:", err);
3749
3884
  }
3750
3885
  else try {
3751
- const { countForeignAgentFiles, piForeignHomeDir, piForeignRepoRoot } = await import("./pi-foreign-artifacts-DZ4tioyO.js");
3886
+ const { countForeignAgentFiles, piForeignHomeDir, piForeignRepoRoot } = await import("./pi-foreign-artifacts-CNt6wQ1P.js");
3752
3887
  foreignAvailable = await countForeignAgentFiles({
3753
3888
  repoRoot: await piForeignRepoRoot(process$1.cwd()),
3754
3889
  homeDir: piForeignHomeDir()
@@ -3775,30 +3910,38 @@ const pi = defineCommand({
3775
3910
  if (written.skippedReason) consola.warn(`Pi MCP: left ${written.path} alone (${written.skippedReason}); the scoped groups are not exposed to Pi this launch.`);
3776
3911
  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.`);
3777
3912
  }
3778
- try {
3779
- const collected = globalThis.__ghRouterBridgeCollected;
3780
- if (collected) {
3781
- const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-Bp9AnYw9.js");
3782
- const { section } = buildMirrorBridgeSection(collected, { repoRoot: process$1.cwd() });
3783
- const agentsPath = path.join(mirror, "AGENTS.md");
3784
- let existing;
3785
- try {
3786
- existing = await fs$1.readFile(agentsPath, "utf8");
3787
- } catch {
3788
- existing = void 0;
3789
- }
3790
- await writeTextFile(agentsPath, mergeBridgeIntoAgentsMd(existing, section));
3791
- await writeJsonFile(path.join(mirror, ".gh-router-bridge.json"), {
3792
- stats: bridgeStats ?? null,
3793
- scopedRuleFiles: bridgeScoped.map((r) => r.file)
3794
- });
3913
+ if (bridgeCollected) try {
3914
+ const { mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-D5A0h_Kf.js");
3915
+ const agentsPath = path.join(mirror, "AGENTS.md");
3916
+ let existing;
3917
+ try {
3918
+ existing = await fs$1.readFile(agentsPath, "utf8");
3919
+ } catch {
3920
+ existing = void 0;
3795
3921
  }
3922
+ const userText = mergeBridgeIntoAgentsMd(existing, "").trim();
3923
+ const merged = mergeBridgeIntoAgentsMd(existing, bridgeSection);
3924
+ if (merged !== (existing ?? "")) await writeTextFile(agentsPath, merged);
3925
+ const shadowWarnings = bridgeShadowWarnings(precedence, {
3926
+ bridgeActive,
3927
+ mirrorDir: mirror,
3928
+ userOwnsAgentsMd: userText.length > 0
3929
+ });
3930
+ for (const warning of shadowWarnings) consola.warn(warning);
3931
+ await writeJsonFile(path.join(mirror, ".gh-router-bridge.json"), {
3932
+ stats: bridgeStats ?? null,
3933
+ deduped: bridgeCollected.deduped ?? 0,
3934
+ shadowedSkills,
3935
+ scopedRuleFiles: bridgeScoped.map((r) => r.file),
3936
+ precedence: {
3937
+ agentsOverride: precedence.agentsOverride ? path.join(mirror, "AGENTS.override.md") : null,
3938
+ userClaudeMd: precedence.userClaudeMd,
3939
+ systemMd: precedence.systemMd ? path.join(mirror, "SYSTEM.md") : null,
3940
+ projectAppendSystem: precedence.projectAppendSystem
3941
+ }
3942
+ });
3796
3943
  } catch (err) {
3797
3944
  consola.debug("Pi memory bridge synthesis skipped:", err);
3798
- } finally {
3799
- try {
3800
- delete globalThis.__ghRouterBridgeCollected;
3801
- } catch {}
3802
3945
  }
3803
3946
  } catch (err) {
3804
3947
  consola.error(`Failed to write Pi launch files: ${err instanceof Error ? err.message : String(err)}.`);
@@ -3868,9 +4011,10 @@ const pi = defineCommand({
3868
4011
  })}\n`);
3869
4012
  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");
3870
4013
  const { disposeBluebirdClients } = await import("./bluebird-client-BvoMTmEv.js");
3871
- const { disposeAdoClients } = await import("./ado-tools-CRkyU51J.js");
4014
+ const { disposeAdoClients } = await import("./ado-tools-CsfbnY8x.js");
3872
4015
  launchChild({
3873
4016
  kind: "pi",
4017
+ execArgs: piCommand && piCommand.command !== "" ? [piCommand.command, ...piCommand.args] : void 0,
3874
4018
  envVars: {
3875
4019
  ...getPiLaunchEnvVars(mirror),
3876
4020
  GH_ROUTER_HOOK_MCP_URL: serverUrl,
@@ -3889,7 +4033,6 @@ const pi = defineCommand({
3889
4033
  await stopKeepAwake();
3890
4034
  await disposeBluebirdClients();
3891
4035
  await disposeAdoClients();
3892
- await savePiPackageCache(mirror, packagesForCache);
3893
4036
  await removeOwnPiAgentMirror();
3894
4037
  await removeAicLedgerFile();
3895
4038
  },
@@ -3905,4 +4048,4 @@ const pi = defineCommand({
3905
4048
  });
3906
4049
  export { pi };
3907
4050
 
3908
- //# sourceMappingURL=pi-DmeBxzIo.js.map
4051
+ //# sourceMappingURL=pi-DVud9eQn.js.map