github-router 0.3.379 → 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 (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-BJ1fjX7V.js} +10 -10
  10. package/dist/{attribution-settings-BWYL2b8N.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-CSuIdaLV.js → claude-BWwkOMi3.js} +26 -25
  19. package/dist/{claude-CSuIdaLV.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-BG0pfud9.js → codex-C6ix3BaY.js} +8 -7
  23. package/dist/{codex-BG0pfud9.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-DmeBxzIo.js → pi-YhoA26wi.js} +383 -88
  99. package/dist/pi-YhoA26wi.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-DrHAX2Bh.js} +15 -14
  117. package/dist/{serve-zbQKfx1E.js.map → serve-DrHAX2Bh.js.map} +1 -1
  118. package/dist/{server-setup-ClZdV33Q.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-mnedD5cH.js → start-DvV3Lbwy.js} +5 -4
  123. package/dist/{start-mnedD5cH.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-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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi-memory-bridge-BxmCIIbk.js","names":["fsp"],"sources":["../src/lib/pi-memory-bridge.ts"],"sourcesContent":["import fs from \"node:fs\"\nimport fsp from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\n/**\n * Pi memory bridge: repo instruction + user-global + auto-memory surfacing.\n *\n * Pi natively loads per-dir first-win\n * `AGENTS.override.md > AGENTS.md > AGENTS.MD > CLAUDE.md > CLAUDE.MD`\n * (agentDir global + fs-root → cwd, concatenated, no trust gate).\n * It does NOT load `.github/copilot-instructions.md`,\n * `.github/instructions/*.instructions.md` (`applyTo`), `.claude/rules/`\n * (`paths:`), `@path` imports, `CLAUDE.local.md`, `./.claude/CLAUDE.md`,\n * `~/.claude/CLAUDE.md`, or Claude auto-memory.\n *\n * Strategy (per approved plan): synthesize the static repo-wide slice into\n * the per-launch mirror's `AGENTS.md` (a Pi-native candidate, so no new\n * loader is needed) and lazy-attach path-scoped rules via the\n * `gh-router-pi` extension's `tool_result` hook (mirrors\n * `pi-code/claude-rules.ts`). Auto-memory is on-demand only (`/memory`\n * command + explicit read), never auto-injected.\n *\n * The synthesized block is a permanent per-turn cost: Pi loads the mirror's\n * `AGENTS.md` into the `project_context` system-prompt section on EVERY turn\n * (`core/resource-loader.js` → `renderProjectContext`). It is therefore\n * written as instruction text, not as a report: one heading per source group,\n * one `path — body` line per file, no titles, no provenance comments. Measured\n * on a realistic repo: 86% of the pre-compaction block was scaffolding.\n *\n * The bridge does NOT try to replace what Pi loads natively. Pi still reads\n * the repo's own `AGENTS.md`/`CLAUDE.md` (and `AGENTS.override.md`) itself, so\n * a repo that ships both a native context file and a bridged Copilot/Claude\n * file sees the shared guidance twice; that is expected, because suppressing a\n * repo's own file to save bytes would silently drop guidance the user can see.\n *\n * All filesystem access is best-effort: missing/unreadable files are\n * skipped, never fatal. Pure helpers are exported for unit tests.\n */\n\nexport const PI_BRIDGE_STATIC_BUDGET_BYTES = 24_000 as const\n/**\n * Floor reserved for every group that still has content to write, so one huge\n * first section cannot starve the rest down to a bare truncation marker. A\n * group that cannot fit its floor is written as a named omission instead of a\n * silent gap; see `buildMirrorBridgeSection`.\n */\nexport const PI_BRIDGE_SECTION_FLOOR_BYTES = 1_500 as const\n/**\n * Room held back for the \"omitted for budget\" row, so a body can never consume\n * the space reserved to report that something did not fit.\n */\nconst PI_BRIDGE_OMISSION_ROW_BYTES = 160\nexport const PI_BRIDGE_IMPORT_MAX_DEPTH = 4 as const\nexport const PI_BRIDGE_IMPORT_MAX_FILES = 10 as const\nexport const PI_BRIDGE_MEMORY_INDEX_MAX_LINES = 200 as const\nexport const PI_BRIDGE_MEMORY_INDEX_MAX_BYTES = 25_000 as const\nexport const PI_BRIDGE_FENCE_BEGIN = \"<!-- gh-router memory-bridge begin -->\"\nexport const PI_BRIDGE_FENCE_END = \"<!-- gh-router memory-bridge end -->\"\n\nexport interface PiBridgeScopedRule {\n /** Display path (absolute or repo-relative) for attribution. */\n file: string\n /** Rule body with frontmatter stripped. */\n body: string\n /** Glob list from `paths:` / `applyTo:` / `globs:`. Empty = unscoped. */\n globs: Array<string>\n /** Where the rule came from (for `/context` surfacing). */\n source: string\n}\n\nexport interface PiBridgeCollected {\n /** Repo-wide copilot instructions that were found (after import expansion). */\n copilotInstructions: Array<{ file: string; content: string }>\n /** Unscoped Claude rules (inlined statically). */\n unscopedRules: Array<{ file: string; content: string }>\n /** Path-scoped rules (lazy-attached, not inlined). */\n scopedRules: Array<PiBridgeScopedRule>\n /** User-global files found (capped, inlined). */\n userGlobal: Array<{ file: string; content: string }>\n /** Resolved `@` imports (appended once, deduped). */\n imports: Array<{ file: string; content: string }>\n /** Skipped files with reasons (for `/context`). */\n skipped: Array<{ file: string; reason: string }>\n /** Entries dropped because another entry named the same file (realpath/inode). */\n deduped?: number\n}\n\nexport interface PiBridgeStats {\n staticFiles: number\n scopedRules: number\n imports: number\n skipped: number\n /**\n * True when any body (or the whole block) was cut by the byte budget. Computed\n * here and surfaced by `/memory`, `/context`, `.gh-router-bridge.json` and a\n * launch warning — a silent cut is the failure mode this field exists for.\n */\n truncated: boolean\n /** Bytes of the emitted fenced section, so `/memory` can show the real cost. */\n bytes: number\n}\n\nfunction byteLength(s: string): number {\n return Buffer.byteLength(s, \"utf8\")\n}\n\n/**\n * Truncate to a UTF-8 byte budget without splitting a code point, marker\n * included in the budget.\n *\n * Exported because the foreign-artifact bridge caps with the same measure Pi's\n * own limits are stated in, and `label` keeps the truncation marker honest\n * about which bridge did the cutting.\n */\nexport function capBytes(\n s: string,\n max: number,\n label = \"gh-router memory bridge\",\n): { text: string; truncated: boolean } {\n if (byteLength(s) <= max) return { text: s, truncated: false }\n // The marker is part of the budget, not extra: a caller that asserts \"≤ 8\n // KiB\" means the returned string, so the head is cut short enough for the\n // marker to fit inside `max`.\n const marker = `\\n…[truncated by ${label}]`\n const budget = Math.max(0, max - byteLength(marker))\n let low = 0\n let high = s.length\n while (low < high) {\n const mid = Math.floor((low + high) / 2)\n if (byteLength(s.slice(0, mid)) <= budget) low = mid + 1\n else high = mid\n }\n return { text: `${s.slice(0, Math.max(0, low - 1))}${marker}`, truncated: true }\n}\n\n/** Strip YAML frontmatter (`--- ... ---`) and return body + raw frontmatter. */\nexport function splitFrontmatter(raw: string): { frontmatter: string; body: string } {\n const normalized = raw.replace(/\\r\\n/g, \"\\n\")\n if (!normalized.startsWith(\"---\")) return { frontmatter: \"\", body: normalized }\n const end = normalized.indexOf(\"\\n---\", 3)\n if (end === -1) return { frontmatter: \"\", body: normalized }\n return {\n frontmatter: normalized.slice(3, end).trim(),\n body: normalized.slice(end + 4).replace(/^\\n/, \"\"),\n }\n}\n\n/**\n * Minimal frontmatter glob extraction for `paths:` / `applyTo:` / `globs:`.\n * Supports `key: \"glob\"`, `key: a, b`, and YAML lists. Case-insensitive keys.\n * Returns [] when no scoping key is present (unscoped rule).\n */\nexport function extractScopeGlobs(frontmatter: string): Array<string> {\n const out: Array<string> = []\n const lines = frontmatter.split(\"\\n\")\n let i = 0\n while (i < lines.length) {\n const line = lines[i] ?? \"\"\n const m = /^\\s*(paths|applyTo|globs)\\s*:\\s*(.*)$/i.exec(line)\n if (!m) {\n i++\n continue\n }\n const rest = (m[2] ?? \"\").trim()\n if (rest.startsWith(\"[\") && rest.endsWith(\"]\")) {\n for (const part of rest.slice(1, -1).split(\",\")) {\n const v = part.trim().replace(/^[\"']|[\"']$/g, \"\")\n if (v) out.push(v)\n }\n i++\n continue\n }\n if (rest && !rest.startsWith(\"|\") && !rest.startsWith(\">\")) {\n const v = rest.replace(/^[\"']|[\"']$/g, \"\").split(\"#\")[0]?.trim() ?? \"\"\n if (v) {\n for (const part of v.split(\",\")) {\n const p = part.trim()\n if (p) out.push(p)\n }\n }\n i++\n continue\n }\n // Block list on following indented lines (`- \"glob\"`).\n i++\n while (i < lines.length) {\n const item = lines[i] ?? \"\"\n const im = /^\\s+-\\s+(.+)$/.exec(item)\n if (!im) break\n const v = (im[1] ?? \"\").trim().replace(/^[\"']|[\"']$/g, \"\")\n if (v) out.push(v)\n i++\n }\n }\n return out\n}\n\n/** Convert a single glob to RegExp. `*` stays in-segment, `**` crosses. */\nfunction globToRegExp(glob: string): RegExp {\n const g = glob.trim().replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\")\n let re = \"\"\n let k = 0\n while (k < g.length) {\n const c = g[k]\n if (c === \"*\") {\n if (g[k + 1] === \"*\") {\n // `**/` → optional any-prefix; trailing `/**` → any suffix.\n if (g[k + 2] === \"/\") {\n re += \"(?:.*/)?\"\n k += 3\n } else {\n re += \".*\"\n k += 2\n }\n } else {\n re += \"[^/]*\"\n k += 1\n }\n continue\n }\n if (c === \"?\") {\n re += \"[^/]\"\n k += 1\n continue\n }\n if (\"+()|^$.{}[]\\\\\".includes(c ?? \"\")) re += `\\\\${c}`\n else re += c\n k += 1\n }\n // Slashless patterns (`*.ts`) match basename at any depth (gitignore-style).\n if (!g.includes(\"/\")) re = `(?:.*/)?${re}`\n return new RegExp(`^${re}$`)\n}\n\n/**\n * Does a touched file match any of the rule globs?\n * `touchedAbs` may be absolute or repo-relative; `ruleRoot` scopes\n * project-relative globs. Falls back to basename matching.\n */\nexport function ruleMatchesFile(\n globs: ReadonlyArray<string>,\n touchedAbs: string,\n ruleRoot: string,\n): boolean {\n if (globs.length === 0) return false\n const candidates = new Set<string>()\n const norm = touchedAbs.replace(/\\\\/g, \"/\")\n candidates.add(norm)\n const rel = path.relative(ruleRoot, touchedAbs).replace(/\\\\/g, \"/\")\n if (rel && !rel.startsWith(\"..\")) candidates.add(rel)\n candidates.add(path.basename(touchedAbs))\n for (const glob of globs) {\n let re: RegExp\n try {\n re = globToRegExp(glob)\n } catch {\n continue\n }\n for (const c of candidates) {\n if (re.test(c)) return true\n }\n }\n return false\n}\n\n/** Extract `@path` references (whole-line or trailing) ending in a text extension. */\nexport function extractAtImports(content: string): Array<string> {\n const refs: Array<string> = []\n const seen = new Set<string>()\n const pattern = /@([~.]?[\\w./\\\\-]+\\.(?:md|txt|yaml|yml|json|toml))(?:\\s|$)/g\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim()\n if (!trimmed.includes(\"@\")) continue\n // Skip fenced-code `@` mentions (commented-out imports must not expand).\n pattern.lastIndex = 0\n let m: RegExpExecArray | null\n while ((m = pattern.exec(trimmed)) !== null) {\n const ref = m[1] ?? \"\"\n if (ref && !seen.has(ref)) {\n seen.add(ref)\n refs.push(ref)\n }\n }\n }\n return refs\n}\n\n/**\n * Resolve `@` imports against an in-memory file map (pure, testable).\n * Depth-capped, cycle-safe, budget-capped. Returns appended bodies only\n * (base files are never re-appended by the caller).\n */\nexport function resolveImportsPure(\n baseFiles: ReadonlyArray<{ file: string; content: string }>,\n readFile: (absPath: string) => string | undefined,\n homeDir: string,\n maxDepth = PI_BRIDGE_IMPORT_MAX_DEPTH,\n maxFiles = PI_BRIDGE_IMPORT_MAX_FILES,\n): Array<{ file: string; content: string }> {\n const out: Array<{ file: string; content: string }> = []\n const visited = new Set<string>()\n for (const base of baseFiles) {\n try {\n visited.add(path.resolve(base.file))\n } catch {\n visited.add(base.file)\n }\n }\n const visit = (importerAbs: string, content: string, depth: number): void => {\n if (depth > maxDepth || out.length >= maxFiles) return\n const baseDir = path.dirname(importerAbs)\n for (const ref of extractAtImports(content)) {\n if (out.length >= maxFiles) return\n let expanded = ref\n if (expanded.startsWith(\"~\")) expanded = path.join(homeDir, expanded.slice(1))\n const abs = path.isAbsolute(expanded) ? path.normalize(expanded) : path.resolve(baseDir, expanded)\n if (visited.has(abs)) continue\n visited.add(abs)\n const body = readFile(abs)\n if (body === undefined) continue\n out.push({ file: abs, content: splitFrontmatter(body).body })\n visit(abs, body, depth + 1)\n }\n }\n for (const base of baseFiles) {\n let abs = base.file\n try {\n abs = path.resolve(base.file)\n } catch {\n // keep as-is\n }\n visit(abs, base.content, 1)\n }\n return out\n}\n\n/** Cap Claude auto-memory index the way Claude Code measures it. */\nexport function capMemoryIndex(raw: string): string {\n const lines = raw.split(\"\\n\").slice(0, PI_BRIDGE_MEMORY_INDEX_MAX_LINES)\n let text = lines.join(\"\\n\")\n if (byteLength(text) > PI_BRIDGE_MEMORY_INDEX_MAX_BYTES) {\n text = capBytes(text, PI_BRIDGE_MEMORY_INDEX_MAX_BYTES).text\n }\n return text\n}\n\n/** Redact likely secrets before persisting synthesized bridge content. */\nexport function redactSecrets(text: string): string {\n return text\n .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, \"[REDACTED private key]\")\n .replace(/(sk-(live|test)-[A-Za-z0-9_-]{8,})/g, \"[REDACTED]\")\n .replace(/(gh[pousr]_[A-Za-z0-9_]{8,})/g, \"[REDACTED]\")\n .replace(/(xox[baprs]-[A-Za-z0-9-]{8,})/g, \"[REDACTED]\")\n .replace(/eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}/g, \"[REDACTED jwt]\")\n}\n\nasync function readIfExists(file: string): Promise<string | undefined> {\n try {\n return await fsp.readFile(file, \"utf8\")\n } catch {\n return undefined\n }\n}\n\n/**\n * Collect bridge inputs from disk (best-effort). Repo root is the cwd's\n * git top-level when resolvable, else cwd. Only reads files; never writes.\n */\nexport async function collectBridgeInputs(\n cwd = process.cwd(),\n homeDir = os.homedir(),\n): Promise<PiBridgeCollected> {\n const collected: PiBridgeCollected = {\n copilotInstructions: [],\n unscopedRules: [],\n scopedRules: [],\n userGlobal: [],\n imports: [],\n skipped: [],\n }\n // Repo root: walk up for `.git` (cheap, no subprocess).\n let repoRoot = cwd\n try {\n let dir = path.resolve(cwd)\n for (let depth = 0; depth < 12; depth++) {\n try {\n await fsp.stat(path.join(dir, \".git\"))\n repoRoot = dir\n break\n } catch {\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n }\n } catch {\n repoRoot = cwd\n }\n\n // 1. Repo-wide Copilot instructions (+ `@` expansion later).\n const copilotFile = path.join(repoRoot, \".github\", \"copilot-instructions.md\")\n const copilotBody = await readIfExists(copilotFile)\n const baseForImports: Array<{ file: string; content: string }> = []\n if (copilotBody !== undefined) {\n collected.copilotInstructions.push({ file: copilotFile, content: splitFrontmatter(copilotBody).body })\n baseForImports.push({ file: copilotFile, content: copilotBody })\n }\n\n // 2. Path-specific Copilot instructions (applyTo).\n try {\n const dir = path.join(repoRoot, \".github\", \"instructions\")\n const entries = await fsp.readdir(dir)\n for (const name of entries.sort()) {\n if (!name.endsWith(\".instructions.md\")) continue\n const file = path.join(dir, name)\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const { frontmatter, body } = splitFrontmatter(raw)\n const globs = extractScopeGlobs(frontmatter)\n if (globs.length === 0 || globs.includes(\"**\") || globs.includes(\"**/*\")) {\n collected.unscopedRules.push({ file, content: body })\n } else {\n collected.scopedRules.push({ file, body, globs, source: \"copilot-instructions\" })\n }\n }\n } catch {\n // no instructions dir — not an error\n }\n\n // 3. Claude rules (nearest `.claude/rules` at-or-above cwd).\n try {\n let dir: string | null = null\n let walk = path.resolve(cwd)\n for (let depth = 0; depth < 12; depth++) {\n try {\n await fsp.stat(path.join(walk, \".claude\", \"rules\"))\n dir = path.join(walk, \".claude\", \"rules\")\n break\n } catch {\n const parent = path.dirname(walk)\n if (parent === walk) break\n walk = parent\n }\n }\n if (dir) {\n const entries = await fsp.readdir(dir)\n for (const name of entries.sort()) {\n if (!name.endsWith(\".md\")) continue\n const file = path.join(dir, name)\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const { frontmatter, body } = splitFrontmatter(raw)\n if (!body.trim()) {\n collected.skipped.push({ file, reason: \"empty after frontmatter strip\" })\n continue\n }\n const globs = extractScopeGlobs(frontmatter)\n if (globs.length === 0) collected.unscopedRules.push({ file, content: body })\n else collected.scopedRules.push({ file, body, globs, source: \"claude-rules\" })\n }\n }\n } catch {\n // unreadable rules dir — skip\n }\n\n // 4. Alternate project memory `./.claude/CLAUDE.md`. Recorded here only;\n // step 7 dedupes it against anything the same file reached through an `@`\n // import, and Pi still loads the repo's OWN AGENTS.md/CLAUDE.md natively\n // (`loadProjectContextFiles`), which this bridge deliberately does not try\n // to replace: suppressing a repo's own context file to save bytes would\n // silently drop guidance the user can see.\n const dotClaude = path.join(repoRoot, \".claude\", \"CLAUDE.md\")\n const dotBody = await readIfExists(dotClaude)\n if (dotBody !== undefined && dotBody.trim()) {\n collected.unscopedRules.push({ file: dotClaude, content: splitFrontmatter(dotBody).body })\n baseForImports.push({ file: dotClaude, content: dotBody })\n }\n\n // 5. User-global files (inlined, capped downstream).\n for (const file of [\n path.join(homeDir, \".claude\", \"CLAUDE.md\"),\n path.join(homeDir, \".copilot\", \"copilot-instructions.md\"),\n ]) {\n const raw = await readIfExists(file)\n if (raw !== undefined && raw.trim()) {\n collected.userGlobal.push({ file, content: splitFrontmatter(raw).body })\n baseForImports.push({ file, content: raw })\n }\n }\n\n // 6. `@` imports across everything collected so far.\n const fileMap = new Map<string, string>()\n for (const group of [collected.copilotInstructions, collected.unscopedRules, collected.userGlobal]) {\n for (const entry of group) {\n try {\n fileMap.set(path.resolve(entry.file), entry.content)\n } catch {\n fileMap.set(entry.file, entry.content)\n }\n }\n }\n // Async BFS over `@` imports (map first, disk fallback). Seeds `seen`\n // with base files so a self-import never re-appends the base body.\n const seen = new Set<string>()\n for (const b of baseForImports) {\n try {\n seen.add(path.resolve(b.file))\n } catch {\n seen.add(b.file)\n }\n }\n const queue: Array<{ importer: string; content: string; depth: number }> = baseForImports.map((b) => ({\n importer: b.file,\n content: b.content,\n depth: 1,\n }))\n while (queue.length > 0 && collected.imports.length < PI_BRIDGE_IMPORT_MAX_FILES) {\n const head = queue.shift()\n if (!head || head.depth > PI_BRIDGE_IMPORT_MAX_DEPTH) continue\n let importerAbs = head.importer\n try {\n importerAbs = path.resolve(head.importer)\n } catch {\n // keep\n }\n const baseDir = path.dirname(importerAbs)\n for (const ref of extractAtImports(head.content)) {\n if (collected.imports.length + seen.size >= PI_BRIDGE_IMPORT_MAX_FILES) break\n let expanded = ref\n if (expanded.startsWith(\"~\")) expanded = path.join(homeDir, expanded.slice(1))\n const abs = path.isAbsolute(expanded) ? path.normalize(expanded) : path.resolve(baseDir, expanded)\n if (seen.has(abs)) continue\n seen.add(abs)\n const hit = fileMap.get(abs) ?? (await readIfExists(abs))\n if (hit === undefined) {\n collected.skipped.push({ file: abs, reason: `import of ${head.importer} not found` })\n continue\n }\n const body = splitFrontmatter(hit).body\n collected.imports.push({ file: abs, content: body })\n queue.push({ importer: abs, content: hit, depth: head.depth + 1 })\n }\n }\n\n return dedupeCollected(collected)\n}\n\n/**\n * Canonical identity for a collected file: `realpath` when it resolves (so a\n * symlinked rule is not emitted twice under two names), `INO` identity as a\n * fallback for hard links (two names for one inode are one rule), the resolved\n * path otherwise.\n */\nfunction fileIdentity(file: string): string {\n const resolved = (() => {\n try {\n return path.resolve(file)\n } catch {\n return file\n }\n })()\n try {\n const real = fs.realpathSync.native(resolved)\n const { dev, ino } = fs.statSync(real)\n return ino ? `${dev}:${ino}` : real\n } catch {\n return resolved\n }\n}\n\n/**\n * Drop entries that name the same file (symlink, hard link, or an `@` import\n * that re-reaches a base file). First occurrence wins: groups are ordered by\n * authority (repo-wide, then project rules, then user-global, then imports), so\n * the earlier copy is the one with the better provenance.\n */\nfunction dedupeCollected(collected: PiBridgeCollected): PiBridgeCollected {\n const seen = new Set<string>()\n const keep = <T extends { file: string }>(entry: T): boolean => {\n const id = fileIdentity(entry.file)\n if (seen.has(id)) return false\n seen.add(id)\n return true\n }\n const imports = collected.imports.filter(keep)\n const unscopedRules = collected.unscopedRules.filter(keep)\n const userGlobal = collected.userGlobal.filter(keep)\n const copilotInstructions = collected.copilotInstructions.filter(keep)\n const scopedRules = collected.scopedRules.filter(keep)\n const skipped = collected.skipped.filter(keep)\n const dropped =\n (collected.imports.length - imports.length)\n + (collected.unscopedRules.length - unscopedRules.length)\n + (collected.userGlobal.length - userGlobal.length)\n + (collected.copilotInstructions.length - copilotInstructions.length)\n + (collected.scopedRules.length - scopedRules.length)\n return {\n copilotInstructions,\n unscopedRules,\n scopedRules,\n userGlobal,\n imports,\n skipped,\n ...(dropped > 0 ? { deduped: dropped } : {}),\n }\n}\n\n/**\n * Display form of a source path: repo-relative when it lives under the repo,\n * `~`-relative when under the home directory, absolute otherwise. Keeps the\n * block free of absolute paths, which cost bytes the model never needs.\n */\nfunction displaySource(file: string, repoRoot?: string, homeDir?: string): string {\n const clean = file.replaceAll(\"\\0\", \"\")\n const rel = (root: string): string | undefined => {\n const base = root.replace(/[\\\\/]+$/, \"\")\n if (!base) return undefined\n if (clean === base) return undefined\n if (!clean.startsWith(`${base}/`) && !clean.startsWith(`${base}\\\\`)) return undefined\n return clean.slice(base.length + 1)\n }\n const inRepo = repoRoot ? rel(repoRoot) : undefined\n if (inRepo) return inRepo\n const inHome = homeDir ? rel(homeDir) : undefined\n if (inHome) return `~/${inHome}`\n return clean\n}\n\ninterface BridgeGroup {\n title: string\n entries: ReadonlyArray<{ file: string; content: string }>\n}\n\n/**\n * Build the static mirror `AGENTS.md` bridge section.\n *\n * Every emitted byte is a per-turn prompt cost, so the block carries\n * instruction text and nothing else: one heading per group, one line per file\n * in the form `` `path` — body ``, bodies copied verbatim (a `file:line` list\n * is real AGENTS.md content and must not be flattened), and no title or\n * provenance comments. Returns `section: \"\"` when nothing was collected, so\n * the caller writes no block at all — and `mergeBridgeIntoAgentsMd` then strips\n * any block a previous launch wrote, rather than leaving stale guidance in the\n * prompt forever.\n *\n * Budget: `PI_BRIDGE_STATIC_BUDGET_BYTES` still bounds the block, but every\n * group with content keeps `PI_BRIDGE_SECTION_FLOOR_BYTES` (capped at an even\n * share of what is left), so the last group cannot be reduced to a bare\n * truncation marker by a large first one. A group that still cannot fit is\n * written as a named omission, which the model can act on, unlike a silence.\n * Redaction runs per body BEFORE the cap, so a cut can never leave the first\n * half of a secret in the prompt.\n *\n * The ceiling is an invariant, not a target: the fence is part of the ledger\n * (it used to be appended after the fact, which let the accounting overshoot)\n * and the omission row is a single capped row for the whole group, because a\n * group of 40 small files could otherwise spend the whole budget on markers\n * alone. That row leads with the omitted COUNT, so it stays informative even\n * when its own list of names is cut.\n */\nexport function buildMirrorBridgeSection(\n collected: PiBridgeCollected,\n opts: { repoRoot?: string; homeDir?: string } = {},\n): { section: string; stats: PiBridgeStats } {\n const homeDir = opts.homeDir ?? os.homedir()\n const groups: Array<BridgeGroup> = [\n { title: \"Copilot repo instructions\", entries: collected.copilotInstructions },\n { title: \"Unscoped project rules\", entries: collected.unscopedRules },\n { title: \"User-global instructions\", entries: collected.userGlobal },\n { title: \"Imported (`@path`)\", entries: collected.imports },\n ].filter((g) => g.entries.length > 0)\n const scoped = collected.scopedRules\n\n let truncated = false\n const parts: Array<string> = []\n // The fence and its blank line are emitted bytes, so they are charged to the\n // ledger up front; leaving them out is what let an adversarial group stack\n // past the ceiling on top of an already-full budget.\n let used = byteLength(PI_BRIDGE_FENCE_BEGIN) + byteLength(PI_BRIDGE_FENCE_END) + 4\n const live = (): Array<BridgeGroup> =>\n groups.filter((g) => g.entries.some((e) => e.content.replaceAll(\"\\0\", \"\").trim().length > 0))\n\n for (const [index, group] of groups.entries()) {\n // The lazy path-scoped list is a consumer of this same budget, so it counts\n // as one more group when the floors are handed out. Without that, an\n // oversized static slice left it zero room and every scoped rule silently\n // became unreachable for the whole session.\n const remainingGroups = Math.max(1, live().length - index + (scoped.length > 0 ? 1 : 0))\n // Reserve a floor for every group that still has to be written, never more\n // than an even share of what is left.\n const share = Math.floor(Math.max(0, PI_BRIDGE_STATIC_BUDGET_BYTES - used - 512) / remainingGroups)\n const floor = Math.min(PI_BRIDGE_SECTION_FLOOR_BYTES, Math.max(200, share))\n const budget = Math.max(0, PI_BRIDGE_STATIC_BUDGET_BYTES - used - 512 - floor * (remainingGroups - 1))\n const heading = `## ${group.title}`\n const rendered: Array<string> = []\n const omitted: Array<string> = []\n let groupTruncated = false\n const roomLeft = (): number =>\n budget - byteLength(heading) - 2 - rendered.reduce((n, s) => n + byteLength(s) + 2, 0)\n for (const entry of group.entries) {\n // Redact FIRST: a cap applied to unredacted text can leave a secret\n // prefix in the prompt.\n const body = redactSecrets(entry.content.replaceAll(\"\\0\", \"\")).trim()\n if (!body) continue\n const source = displaySource(entry.file, opts.repoRoot, homeDir)\n const line = `\\`${source}\\` — ${body}`\n const room = roomLeft()\n // Hold back room for the omission row, so a body cannot eat the space\n // that is supposed to say \"some rules did not fit\".\n if (room <= PI_BRIDGE_OMISSION_ROW_BYTES) {\n omitted.push(source)\n continue\n }\n const capped = capBytes(line, room - PI_BRIDGE_OMISSION_ROW_BYTES)\n if (capped.truncated) groupTruncated = true\n rendered.push(capped.text)\n }\n if (omitted.length > 0) {\n // One capped row for the whole group. The COUNT comes first so the row\n // stays informative even when the name list itself has to be cut (a group\n // of 40 small files would otherwise spend the budget on markers alone).\n groupTruncated = true\n const names = omitted.map((source) => `\\`${source}\\``).join(\", \")\n const row = `- Omitted for budget (${omitted.length}): ${names}`\n const room = roomLeft()\n if (room > 0) rendered.push(capBytes(row, room).text)\n }\n if (rendered.length === 0) continue\n if (groupTruncated) truncated = true\n parts.push(heading, \"\", ...rendered, \"\")\n used = byteLength(PI_BRIDGE_FENCE_BEGIN) + byteLength(PI_BRIDGE_FENCE_END) + 4 + byteLength(parts.join(\"\\n\"))\n if (used >= PI_BRIDGE_STATIC_BUDGET_BYTES - 512) break\n }\n\n if (scoped.length > 0) {\n // One line per rule. The glob is what the model needs; the body is\n // attached lazily on the first matching read. The scoped list shares the\n // same budget as the sections above it, and it gets a floor too: an\n // oversized static slice must not turn the lazy list into an invisible one,\n // because those rules are then unreachable for the whole session.\n const header = \"## Path-scoped rules (attached on first matching read/edit/write)\"\n // Never more than what is actually left: the floors above already reserved\n // this section's share, and adding a floor on top of a spent budget is how\n // the ceiling used to be overshot.\n const room = Math.max(0, PI_BRIDGE_STATIC_BUDGET_BYTES - used - 512)\n const rows: Array<string> = []\n const omitted: Array<string> = []\n let scopedTruncated = false\n for (const rule of scoped) {\n const source = displaySource(rule.file, opts.repoRoot, homeDir)\n const row = `- \\`${source}\\` — \\`${rule.globs.join(\", \").replaceAll(\"\\0\", \"\")}\\``\n const left = room - byteLength(header) - 2 - rows.reduce((n, s) => n + byteLength(s) + 2, 0)\n if (left <= PI_BRIDGE_OMISSION_ROW_BYTES) {\n omitted.push(source)\n continue\n }\n rows.push(capBytes(row, left - PI_BRIDGE_OMISSION_ROW_BYTES).text)\n }\n if (omitted.length > 0) {\n scopedTruncated = true\n const names = omitted.map((source) => `\\`${source}\\``).join(\", \")\n const left = room - byteLength(header) - 2 - rows.reduce((n, s) => n + byteLength(s) + 2, 0)\n if (left > 0) rows.push(capBytes(`- Omitted for budget (${omitted.length}): ${names}`, left).text)\n }\n if (rows.length > 0) {\n if (scopedTruncated) truncated = true\n parts.push(header, \"\", ...rows, \"\")\n }\n }\n\n if (parts.length === 0) {\n return {\n section: \"\",\n stats: {\n staticFiles: 0,\n scopedRules: scoped.length,\n imports: collected.imports.length,\n skipped: collected.skipped.length,\n truncated,\n bytes: 0,\n },\n }\n }\n\n const section = `${PI_BRIDGE_FENCE_BEGIN}\\n\\n${parts.join(\"\\n\").trimEnd()}\\n\\n${PI_BRIDGE_FENCE_END}\\n`\n return {\n section,\n stats: {\n staticFiles:\n collected.copilotInstructions.length + collected.unscopedRules.length + collected.userGlobal.length,\n scopedRules: scoped.length,\n imports: collected.imports.length,\n skipped: collected.skipped.length,\n truncated,\n bytes: byteLength(section),\n },\n }\n}\n\n/**\n * Merge a bridge section into mirror `AGENTS.md`: append when absent,\n * replace the fenced block when present.\n *\n * Byte-stable: merging the same section repeatedly must not grow the file. The\n * obvious implementation (`before + section + after`) is NOT, because `section`\n * ends with a newline and `after` starts with one, so every relaunch appended a\n * blank line that nothing ever removed. The result is normalized here instead:\n * `section` contributes exactly one trailing newline and `after` contributes\n * none of its leading ones.\n *\n * An empty `section` means the bridge found nothing to say: return the existing\n * user content untouched, but STRIP any fence this launcher wrote previously.\n * A stale block advertises guidance that no longer exists and still costs prompt\n * bytes every turn, so leaving it in place is worse than writing nothing.\n */\nexport function mergeBridgeIntoAgentsMd(existing: string | undefined, section: string): string {\n const body = (existing ?? \"\").replace(/\\r\\n/g, \"\\n\")\n const begin = body.indexOf(PI_BRIDGE_FENCE_BEGIN)\n const end = body.indexOf(PI_BRIDGE_FENCE_END)\n const fenced = begin !== -1 && end !== -1 && end > begin\n if (!section.trim()) {\n if (!fenced) return existing ?? \"\"\n // Drop the previous block, keep whatever the user put around it.\n const before = body.slice(0, begin).replace(/\\n*$/, \"\")\n const after = body.slice(end + PI_BRIDGE_FENCE_END.length).replace(/^\\n+/, \"\").trimEnd()\n if (!before) return after ? `${after}\\n` : \"\"\n return after ? `${before}\\n\\n${after}\\n` : `${before}\\n`\n }\n const block = `${section.trimEnd()}\\n`\n if (!body.trim()) return block\n if (fenced) {\n const before = body.slice(0, begin).replace(/\\n*$/, \"\")\n const after = body.slice(end + PI_BRIDGE_FENCE_END.length).replace(/^\\n+/, \"\").trimEnd()\n const head = before ? `${before}\\n\\n` : \"\"\n const tail = after ? `\\n${after}\\n` : \"\"\n return `${head}${block}${tail}`\n }\n const before = body.replace(/\\n*$/, \"\")\n return `${before}\\n\\n${block}`\n}\n\n/** Resolve the Claude auto-memory index path for a repo (on-demand read). */\nexport function claudeAutoMemoryIndex(homeDir: string, repoRoot: string): string {\n const slug = repoRoot.replace(/^\\//, \"\").replace(/\\//g, \"-\")\n return path.join(homeDir, \".claude\", \"projects\", slug || \"-\", \"memory\", \"MEMORY.md\")\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,gCAAgC;;;;;;;AAO7C,MAAa,gCAAgC;;;;;AAK7C,MAAM,+BAA+B;AAKrC,MAAa,wBAAwB;AACrC,MAAa,sBAAsB;AA6CnC,SAAS,WAAW,GAAmB;CACrC,OAAO,OAAO,WAAW,GAAG,MAAM;AACpC;;;;;;;;;AAUA,SAAgB,SACd,GACA,KACA,QAAQ,2BAC8B;CACtC,IAAI,WAAW,CAAC,KAAK,KAAK,OAAO;EAAE,MAAM;EAAG,WAAW;CAAM;CAI7D,MAAM,SAAS,oBAAoB,MAAM;CACzC,MAAM,SAAS,KAAK,IAAI,GAAG,MAAM,WAAW,MAAM,CAAC;CACnD,IAAI,MAAM;CACV,IAAI,OAAO,EAAE;CACb,OAAO,MAAM,MAAM;EACjB,MAAM,MAAM,KAAK,OAAO,MAAM,QAAQ,CAAC;EACvC,IAAI,WAAW,EAAE,MAAM,GAAG,GAAG,CAAC,KAAK,QAAQ,MAAM,MAAM;OAClD,OAAO;CACd;CACA,OAAO;EAAE,MAAM,GAAG,EAAE,MAAM,GAAG,KAAK,IAAI,GAAG,MAAM,CAAC,CAAC,IAAI;EAAU,WAAW;CAAK;AACjF;;AAGA,SAAgB,iBAAiB,KAAoD;CACnF,MAAM,aAAa,IAAI,QAAQ,SAAS,IAAI;C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,KAAK,QAAQ,qBAAqB;CAChD,MAAM,MAAM,KAAK,QAAQ,mBAAmB;CAC5C,MAAM,SAAS,UAAU,MAAM,QAAQ,MAAM,MAAM;CACnD,IAAI,CAAC,QAAQ,KAAK,GAAG;EACnB,IAAI,CAAC,QAAQ,OAAO,YAAY;EAEhC,MAAM,SAAS,KAAK,MAAM,GAAG,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE;EACtD,MAAM,QAAQ,KAAK,MAAM,MAAM,EAA0B,CAAC,CAAC,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ;EACvF,IAAI,CAAC,QAAQ,OAAO,QAAQ,GAAG,MAAM,MAAM;EAC3C,OAAO,QAAQ,GAAG,OAAO,MAAM,MAAM,MAAM,GAAG,OAAO;CACvD;CACA,MAAM,QAAQ,GAAG,QAAQ,QAAQ,EAAE;CACnC,IAAI,CAAC,KAAK,KAAK,GAAG,OAAO;CACzB,IAAI,QAAQ;EACV,MAAM,SAAS,KAAK,MAAM,GAAG,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE;EACtD,MAAM,QAAQ,KAAK,MAAM,MAAM,EAA0B,CAAC,CAAC,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ;EAGvF,OAAO,GAFM,SAAS,GAAG,OAAO,QAAQ,KAEvB,QADJ,QAAQ,KAAK,MAAM,MAAM;CAExC;CAEA,OAAO,GADQ,KAAK,QAAQ,QAAQ,EACrB,EAAE,MAAM;AACzB"}
@@ -0,0 +1 @@
1
+ export { i as PI_BRIDGE_STATIC_BUDGET_BYTES, a as buildMirrorBridgeSection, s as collectBridgeInputs, u as mergeBridgeIntoAgentsMd } from "./pi-memory-bridge-BxmCIIbk.js";
@@ -0,0 +1,551 @@
1
+ import { a as parseBoolEnv, c as runCommandCapture, s as resolveExecutable, u as runCommandVoid } from "./exec-BC0MAnoA.js";
2
+ import { t as withInstallLock } from "./update-lock-BmXx6QaR.js";
3
+ import { t as getPackageVersion } from "./version-CTqwKr26.js";
4
+ import consola from "consola";
5
+ import path from "node:path";
6
+ import fs from "node:fs/promises";
7
+ import os from "node:os";
8
+ import { spawn } from "node:child_process";
9
+ // src/lib/claude-version-check.ts
10
+ const NPM_PACKAGE$1 = "@anthropic-ai/claude-code";
11
+ const THROTTLE_HOURS$2 = 1;
12
+ const NPM_VIEW_TIMEOUT_MS$2 = 5e3;
13
+ const CLAUDE_VERSION_TIMEOUT_MS = 3e3;
14
+ const NPM_INSTALL_TIMEOUT_MS = 12e4;
15
+ /** Path to the throttle cache. Created on demand. */
16
+ function cacheFilePath$2() {
17
+ return path.join(os.homedir(), ".local", "share", "github-router", "last-update-check");
18
+ }
19
+ /**
20
+ * Read the throttle cache. Returns null on missing/corrupt file —
21
+ * triggers a fresh check.
22
+ */
23
+ async function readCache$2() {
24
+ try {
25
+ const raw = await fs.readFile(cacheFilePath$2(), "utf8");
26
+ const parsed = JSON.parse(raw);
27
+ if (typeof parsed.checkedAt !== "string" || parsed.installedVersion !== null && typeof parsed.installedVersion !== "string" || parsed.latestVersion !== null && typeof parsed.latestVersion !== "string") return null;
28
+ return parsed;
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+ async function writeCache$2(cache) {
34
+ try {
35
+ await fs.mkdir(path.dirname(cacheFilePath$2()), { recursive: true });
36
+ await fs.writeFile(cacheFilePath$2(), JSON.stringify(cache), { mode: 384 });
37
+ } catch (err) {
38
+ consola.debug("Failed to write claude version-check cache:", err);
39
+ }
40
+ }
41
+ /** Check if it's been more than THROTTLE_HOURS since the last check. */
42
+ function shouldCheckNow$2(cache) {
43
+ if (!cache) return true;
44
+ const lastCheck = new Date(cache.checkedAt).getTime();
45
+ if (Number.isNaN(lastCheck)) return true;
46
+ return (Date.now() - lastCheck) / 1e3 / 3600 >= THROTTLE_HOURS$2;
47
+ }
48
+ /**
49
+ * Read the installed `claude` version. Returns null if claude is not
50
+ * on PATH or the version probe fails (e.g. older versions that don't
51
+ * support `--version` cleanly).
52
+ *
53
+ * Windows-safe: `claude` is a `.cmd` shim that `execFile` cannot launch
54
+ * directly. We resolve it to an absolute path (excluding the cwd, so a
55
+ * planted `claude.cmd` in an untrusted repo can't run) and invoke it
56
+ * through the shared exec helper.
57
+ */
58
+ async function getInstalledVersion() {
59
+ const claudePath = resolveExecutable("claude");
60
+ if (!claudePath) return null;
61
+ try {
62
+ const { stdout, code } = await runCommandCapture([claudePath, "--version"], { timeoutMs: CLAUDE_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
+ * Fetch the latest version of @anthropic-ai/claude-code from the npm
72
+ * registry. Returns null on network failure / npm unavailable.
73
+ *
74
+ * Windows-safe: `npm` is `npm.cmd`; resolved to an absolute path
75
+ * (excluding cwd) before invocation.
76
+ */
77
+ async function getLatestVersion$1() {
78
+ const npmPath = resolveExecutable("npm");
79
+ if (!npmPath) return null;
80
+ try {
81
+ const { stdout, code } = await runCommandCapture([
82
+ npmPath,
83
+ "view",
84
+ NPM_PACKAGE$1,
85
+ "version",
86
+ "--silent"
87
+ ], { timeoutMs: NPM_VIEW_TIMEOUT_MS$2 });
88
+ if (code !== 0) return null;
89
+ const v = stdout.trim();
90
+ return /^\d+\.\d+\.\d+/.test(v) ? v : null;
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+ /**
96
+ * Compare two semver-shaped strings (only the leading X.Y.Z, no
97
+ * pre-release / metadata handling — sufficient for npm-published
98
+ * stable releases). Returns true if `latest` is strictly higher than
99
+ * `installed`.
100
+ */
101
+ function isNewer(installed, latest) {
102
+ if (!installed || !latest) return false;
103
+ const a = installed.split(".").map((n) => parseInt(n, 10));
104
+ const b = latest.split(".").map((n) => parseInt(n, 10));
105
+ for (let i = 0; i < 3; i++) {
106
+ const av = a[i] ?? 0;
107
+ const bv = b[i] ?? 0;
108
+ if (av < bv) return true;
109
+ if (av > bv) return false;
110
+ }
111
+ return false;
112
+ }
113
+ /**
114
+ * Run a version check (subject to throttle). Side-effect: updates the
115
+ * throttle cache. Returns the comparison result.
116
+ */
117
+ async function checkClaudeVersion(opts = {}) {
118
+ if (opts.noCheck) return {
119
+ installed: false,
120
+ installedVersion: null,
121
+ latestVersion: null,
122
+ needsUpdate: false,
123
+ skipped: true,
124
+ skipReason: "disabled"
125
+ };
126
+ const cache = await readCache$2();
127
+ if (!opts.force && !shouldCheckNow$2(cache)) return {
128
+ installed: cache?.installedVersion !== null,
129
+ installedVersion: cache?.installedVersion ?? null,
130
+ latestVersion: cache?.latestVersion ?? null,
131
+ needsUpdate: isNewer(cache?.installedVersion ?? null, cache?.latestVersion ?? null),
132
+ skipped: true,
133
+ skipReason: "throttled"
134
+ };
135
+ const installedVersion = await getInstalledVersion();
136
+ if (installedVersion === null) return {
137
+ installed: false,
138
+ installedVersion: null,
139
+ latestVersion: null,
140
+ needsUpdate: false,
141
+ skipped: true,
142
+ skipReason: "no-claude"
143
+ };
144
+ const latestVersion = await getLatestVersion$1();
145
+ await writeCache$2({
146
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
147
+ installedVersion,
148
+ latestVersion
149
+ });
150
+ if (latestVersion === null) return {
151
+ installed: true,
152
+ installedVersion,
153
+ latestVersion: null,
154
+ needsUpdate: false,
155
+ skipped: true,
156
+ skipReason: "no-npm"
157
+ };
158
+ return {
159
+ installed: true,
160
+ installedVersion,
161
+ latestVersion,
162
+ needsUpdate: isNewer(installedVersion, latestVersion),
163
+ skipped: false
164
+ };
165
+ }
166
+ /**
167
+ * Heuristic: did `claude update` fail because the subcommand does not
168
+ * exist (a build predating `claude update`), as opposed to a transient
169
+ * update error? We only npm-fall-back on this specific signal — falling
170
+ * back on any failure would install a conflicting npm copy on
171
+ * native-installer machines.
172
+ *
173
+ * Matches the usage/Commander-style "unknown command" messages CLIs emit
174
+ * for an unrecognized subcommand. Deliberately narrow.
175
+ */
176
+ function looksLikeUnknownUpdateCommand(output) {
177
+ return /unknown command|unknown subcommand|unrecognized (sub)?command|invalid command|command not found|is not a (known|valid) command/i.test(output);
178
+ }
179
+ async function updateClaude(latestVersion, deps = {}) {
180
+ const _resolve = deps.resolveExecutable ?? resolveExecutable;
181
+ const _capture = deps.runCommandCapture ?? runCommandCapture;
182
+ const _void = deps.runCommandVoid ?? runCommandVoid;
183
+ const _lock = deps.withInstallLock ?? withInstallLock;
184
+ const claudePath = _resolve("claude");
185
+ if (!claudePath) throw new Error("claude not found on PATH");
186
+ if (!await _lock("claude-update.lock", async () => {
187
+ consola.info(`Updating Claude Code to ${latestVersion} via \`claude update\`...`);
188
+ const { code, stdout, stderr } = await _capture([claudePath, "update"], { timeoutMs: NPM_INSTALL_TIMEOUT_MS });
189
+ const combined = `${stdout}${stderr}`;
190
+ const trimmed = combined.trim();
191
+ if (trimmed) process.stdout.write(trimmed.endsWith("\n") ? trimmed : `${trimmed}\n`);
192
+ if (code === 0) {
193
+ consola.success(`Claude Code updated to ${latestVersion}`);
194
+ return;
195
+ }
196
+ if (!looksLikeUnknownUpdateCommand(combined)) throw new Error(`\`claude update\` exited with code ${code}`);
197
+ const npmPath = _resolve("npm");
198
+ if (!npmPath) throw new Error(`this Claude Code build predates \`claude update\` and npm is not on PATH; update manually: npm install -g ${NPM_PACKAGE$1}@latest`);
199
+ consola.warn(`This Claude Code build predates \`claude update\`; falling back to \`npm install -g ${NPM_PACKAGE$1}@latest\`.`);
200
+ const { code: npmCode, stderr: npmStderr } = await _void([
201
+ npmPath,
202
+ "install",
203
+ "-g",
204
+ `${NPM_PACKAGE$1}@latest`,
205
+ "--silent"
206
+ ], { timeoutMs: NPM_INSTALL_TIMEOUT_MS });
207
+ if (npmCode !== 0) throw new Error(`npm install failed: ${npmStderr.trim() || `exit ${npmCode}`}`);
208
+ consola.success(`${NPM_PACKAGE$1} updated to ${latestVersion}`);
209
+ })) consola.debug("Claude Code update already in progress in another process; skipping.");
210
+ }
211
+ // src/lib/self-update.ts
212
+ /**
213
+ * Self-update for the `github-router` proxy.
214
+ *
215
+ * The proxy is a *running* process, so updating its own global install
216
+ * in place (`npm install -g github-router@latest`) deletes/overwrites
217
+ * files the OS holds open — on Windows that fails deterministically
218
+ * (EPERM/EBUSY) and can corrupt the install. So we never install in
219
+ * place: when a newer version exists we spawn a **detached updater that
220
+ * waits for this process to exit**, then installs. The update takes
221
+ * effect on the next launch — no re-exec, no restart prompt.
222
+ *
223
+ * Best-effort throughout: every failure is swallowed to debug/warn and
224
+ * never blocks startup. The startup probe is bounded and the install is
225
+ * off the critical path (detached), so even a blackholed network can't
226
+ * delay the proxy from serving.
227
+ */
228
+ const NPM_PACKAGE = "github-router";
229
+ const THROTTLE_HOURS$1 = 1;
230
+ const NPM_VIEW_TIMEOUT_MS$1 = 5e3;
231
+ function cacheFilePath$1() {
232
+ return path.join(os.homedir(), ".local", "share", "github-router", "last-self-update-check");
233
+ }
234
+ async function readCache$1() {
235
+ try {
236
+ const parsed = JSON.parse(await fs.readFile(cacheFilePath$1(), "utf8"));
237
+ if (typeof parsed.checkedAt !== "string") return null;
238
+ return parsed;
239
+ } catch {
240
+ return null;
241
+ }
242
+ }
243
+ async function writeCache$1(cache) {
244
+ try {
245
+ await fs.mkdir(path.dirname(cacheFilePath$1()), { recursive: true });
246
+ await fs.writeFile(cacheFilePath$1(), JSON.stringify(cache), { mode: 384 });
247
+ } catch (err) {
248
+ consola.debug("Failed to write self-update cache:", err);
249
+ }
250
+ }
251
+ function shouldCheckNow$1(cache) {
252
+ if (!cache) return true;
253
+ const last = new Date(cache.checkedAt).getTime();
254
+ if (Number.isNaN(last)) return true;
255
+ return (Date.now() - last) / 1e3 / 3600 >= THROTTLE_HOURS$1;
256
+ }
257
+ async function getLatestVersion(npmPath) {
258
+ try {
259
+ const { stdout, code } = await runCommandCapture([
260
+ npmPath,
261
+ "view",
262
+ NPM_PACKAGE,
263
+ "version",
264
+ "--silent"
265
+ ], { timeoutMs: NPM_VIEW_TIMEOUT_MS$1 });
266
+ if (code !== 0) return null;
267
+ const v = stdout.trim();
268
+ return /^\d+\.\d+\.\d+/.test(v) ? v : null;
269
+ } catch {
270
+ return null;
271
+ }
272
+ }
273
+ /**
274
+ * Spawn a detached process that waits for THIS proxy (pid) to exit,
275
+ * then runs `npm install -g <spec>`. Fully detached and unref'd so it
276
+ * outlives the proxy; output discarded.
277
+ *
278
+ * The waiter is a tiny inline Node script (Node is guaranteed present —
279
+ * the proxy runs on it) that polls `process.kill(pid, 0)` until the
280
+ * parent is gone, then execs npm. This avoids the Windows file-lock by
281
+ * never touching the global install while the proxy holds it open.
282
+ *
283
+ * Shared by the proxy self-update (`github-router@latest`) and the Pi
284
+ * background refresh (`@earendil-works/pi-coding-agent@<version>`):
285
+ * both must update a global install without delaying startup, holding
286
+ * shutdown, or racing each other (callers hold `withInstallLock`
287
+ * before queueing).
288
+ */
289
+ function queueDetachedGlobalInstall(npmPath, spec, extraArgs = []) {
290
+ const parentPid = process.pid;
291
+ const installArgs = [
292
+ "install",
293
+ "-g",
294
+ spec,
295
+ ...extraArgs
296
+ ];
297
+ const waiter = `
298
+ const pid = ${parentPid};
299
+ const { spawn } = require("node:child_process");
300
+ function alive() { try { process.kill(pid, 0); return true } catch { return false } }
301
+ const timer = setInterval(() => {
302
+ if (alive()) return;
303
+ clearInterval(timer);
304
+ const args = [...${JSON.stringify(installArgs)}, "--silent"];
305
+ const isWin = process.platform === "win32";
306
+ const child = spawn(${JSON.stringify(npmPath)}, args, {
307
+ stdio: "ignore", windowsHide: true, shell: isWin, detached: !isWin,
308
+ });
309
+ child.on("error", () => process.exit(0));
310
+ child.on("exit", () => process.exit(0));
311
+ // Safety: never hang forever.
312
+ setTimeout(() => process.exit(0), 180000).unref();
313
+ }, 500);
314
+ // Safety cap on the wait itself (e.g. extremely long sessions still
315
+ // eventually give up rather than leak the waiter).
316
+ setTimeout(() => { clearInterval(timer); process.exit(0); }, 24 * 3600 * 1000).unref();
317
+ `.trim();
318
+ spawn(process.execPath, ["-e", waiter], {
319
+ detached: true,
320
+ stdio: "ignore",
321
+ windowsHide: true
322
+ }).unref();
323
+ }
324
+ function spawnDetachedUpdater(npmPath) {
325
+ queueDetachedGlobalInstall(npmPath, `${NPM_PACKAGE}@latest`);
326
+ }
327
+ /**
328
+ * Probe npm for a newer `github-router` and, if found, queue a detached
329
+ * post-exit update. Returns quickly; never throws. Call AFTER the
330
+ * server is listening so the bounded probe can't delay binding.
331
+ */
332
+ async function runSelfUpdate(opts) {
333
+ if (!opts.selfUpdate) return;
334
+ if (parseBoolEnv(process.env.GH_ROUTER_NO_SELF_UPDATE) === true) return;
335
+ try {
336
+ const { classifyOrigin } = await import("./origin-DbFUCiGp.js");
337
+ const origin = await classifyOrigin();
338
+ if (origin.origin === "npx" || origin.origin === "bunx") {
339
+ const { scheduleBackgroundSelfInstall } = await import("./update-CB21YRKz.js");
340
+ const detail = await scheduleBackgroundSelfInstall({ quiet: true });
341
+ consola.debug(`self-update: managed path: ${detail}`);
342
+ return;
343
+ }
344
+ if (origin.origin !== "npm-global") {
345
+ consola.debug(`self-update: skipped for origin ${origin.origin} (${origin.detail})`);
346
+ return;
347
+ }
348
+ const cache = await readCache$1();
349
+ if (!opts.force && !shouldCheckNow$1(cache)) return;
350
+ const installed = getPackageVersion();
351
+ if (installed === "unknown") return;
352
+ const npmPath = resolveExecutable("npm");
353
+ if (!npmPath) return;
354
+ const latest = await getLatestVersion(npmPath);
355
+ await writeCache$1({
356
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
357
+ installedVersion: installed,
358
+ latestVersion: latest
359
+ });
360
+ if (!latest || !isNewer(installed, latest)) return;
361
+ if (await withInstallLock("self-update.lock", async () => {
362
+ spawnDetachedUpdater(npmPath);
363
+ })) consola.info(`github-router ${installed} → ${latest} update queued; it takes effect on the next launch.`);
364
+ } catch (err) {
365
+ consola.debug("Self-update check failed:", err);
366
+ }
367
+ }
368
+ // src/lib/pi-version-check.ts
369
+ const PI_NPM_PACKAGE = "@earendil-works/pi-coding-agent";
370
+ /**
371
+ * Minimum Pi version the `pi` launcher supports.
372
+ *
373
+ * The floor is pinned to the first release whose `before_agent_start` event
374
+ * carries the `messageType` discriminator (present at 1.3.0, absent at 1.1.0).
375
+ * The generated extension's prompt hook stands down for non-user events using
376
+ * that field, and without it the hook would fire on subagent and system turns
377
+ * the user never typed, which is a wrong brief rather than a missing one.
378
+ * Below-floor Pi hard-exits at the launcher (`src/pi.ts`), but only where the
379
+ * gate actually runs: the install probe, the background refresh, and this floor
380
+ * check all sit inside `--update-check` (default on), so `--no-update-check`
381
+ * (documented for offline/CI) skips the floor as well. That path is still
382
+ * fail-closed rather than silently wrong: the generated extension's own shape
383
+ * probe sees the missing `messageType`, warns once with the fix, and injects
384
+ * nothing.
385
+ */
386
+ const PI_MIN_VERSION = "1.3.0";
387
+ /**
388
+ * Registry used for the PI PACKAGE ONLY.
389
+ *
390
+ * Pi must come from a registry that actually carries it. A corporate npm mirror
391
+ * can lag npmjs far enough that its `latest` sits below `PI_MIN_VERSION`, and
392
+ * the launcher then fail-closes on an upgrade command the user cannot satisfy
393
+ * (their `npm install -g` resolves through the same lagging mirror). Pointing
394
+ * the Pi probe and install at npmjs by default keeps the floor reachable;
395
+ * `GH_ROUTER_NPM_REGISTRY` overrides it for a mirror that does carry the
396
+ * package. Everything else this repo installs still resolves through the user's
397
+ * configured registry.
398
+ */
399
+ const PI_DEFAULT_REGISTRY = "https://registry.npmjs.org/";
400
+ /**
401
+ * Resolve the registry for Pi package operations. Accepts `GH_ROUTER_NPM_REGISTRY`
402
+ * when it is an http(s) URL and falls back to `PI_DEFAULT_REGISTRY` with a
403
+ * warning otherwise, so a typo degrades to the working default rather than
404
+ * bricking the launcher.
405
+ */
406
+ function resolvePiRegistry() {
407
+ const raw = process.env.GH_ROUTER_NPM_REGISTRY?.trim();
408
+ if (!raw) return PI_DEFAULT_REGISTRY;
409
+ if (!/^https?:\/\//i.test(raw)) {
410
+ consola.warn(`Ignoring GH_ROUTER_NPM_REGISTRY=${JSON.stringify(raw)}: expected an http(s) URL. Using ${PI_DEFAULT_REGISTRY}.`);
411
+ return PI_DEFAULT_REGISTRY;
412
+ }
413
+ return raw.endsWith("/") ? raw : `${raw}/`;
414
+ }
415
+ /** `npm` args that pin an operation to the resolved Pi registry. */
416
+ function piRegistryArgs(registry = resolvePiRegistry()) {
417
+ return [`--registry=${registry}`];
418
+ }
419
+ const THROTTLE_HOURS = 1;
420
+ const NPM_VIEW_TIMEOUT_MS = 5e3;
421
+ const PI_VERSION_TIMEOUT_MS = 3e3;
422
+ /** Path to the throttle cache. Created on demand. Separate file from the Claude check. */
423
+ function cacheFilePath() {
424
+ return path.join(os.homedir(), ".local", "share", "github-router", "last-pi-update-check");
425
+ }
426
+ async function readCache() {
427
+ try {
428
+ const raw = await fs.readFile(cacheFilePath(), "utf8");
429
+ const parsed = JSON.parse(raw);
430
+ if (typeof parsed.checkedAt !== "string" || parsed.installedVersion !== null && typeof parsed.installedVersion !== "string" || parsed.latestVersion !== null && typeof parsed.latestVersion !== "string") return null;
431
+ return parsed;
432
+ } catch {
433
+ return null;
434
+ }
435
+ }
436
+ async function writeCache(cache) {
437
+ try {
438
+ await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true });
439
+ await fs.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 384 });
440
+ } catch (err) {
441
+ consola.debug("Failed to write pi version-check cache:", err);
442
+ }
443
+ }
444
+ function shouldCheckNow(cache) {
445
+ if (!cache) return true;
446
+ const lastCheck = new Date(cache.checkedAt).getTime();
447
+ if (Number.isNaN(lastCheck)) return true;
448
+ return (Date.now() - lastCheck) / 1e3 / 3600 >= THROTTLE_HOURS;
449
+ }
450
+ /**
451
+ * Read the installed `pi` version. Returns null if pi is not on PATH
452
+ * or the version probe fails.
453
+ *
454
+ * Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path
455
+ * (excluding the cwd) before invocation via the shared exec helper.
456
+ */
457
+ async function getInstalledPiVersion() {
458
+ const piPath = resolveExecutable("pi");
459
+ if (!piPath) return null;
460
+ try {
461
+ const { stdout, code } = await runCommandCapture([piPath, "--version"], { timeoutMs: PI_VERSION_TIMEOUT_MS });
462
+ if (code !== 0) return null;
463
+ const match = stdout.match(/(\d+\.\d+\.\d+)/);
464
+ return match ? match[1] : null;
465
+ } catch {
466
+ return null;
467
+ }
468
+ }
469
+ /** Fetch the latest Pi version from npm. Null on network/npm failure. */
470
+ async function getLatestPiVersion() {
471
+ const npmPath = resolveExecutable("npm");
472
+ if (!npmPath) return null;
473
+ try {
474
+ const { stdout, code } = await runCommandCapture([
475
+ npmPath,
476
+ "view",
477
+ PI_NPM_PACKAGE,
478
+ "version",
479
+ "--silent",
480
+ ...piRegistryArgs()
481
+ ], { timeoutMs: NPM_VIEW_TIMEOUT_MS });
482
+ if (code !== 0) return null;
483
+ const v = stdout.trim();
484
+ return /^\d+\.\d+\.\d+/.test(v) ? v : null;
485
+ } catch {
486
+ return null;
487
+ }
488
+ }
489
+ /**
490
+ * Compare two semver-shaped strings (leading X.Y.Z only). True when
491
+ * `latest` is strictly higher than `installed`.
492
+ */
493
+ function isPiNewer(installed, latest) {
494
+ if (!installed || !latest) return false;
495
+ const a = installed.split(".").map((n) => parseInt(n, 10));
496
+ const b = latest.split(".").map((n) => parseInt(n, 10));
497
+ for (let i = 0; i < 3; i++) {
498
+ const av = a[i] ?? 0;
499
+ const bv = b[i] ?? 0;
500
+ if (av < bv) return true;
501
+ if (av > bv) return false;
502
+ }
503
+ return false;
504
+ }
505
+ /** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */
506
+ function meetsPiMinVersion(version) {
507
+ if (!version) return false;
508
+ return !isPiNewer(version, PI_MIN_VERSION);
509
+ }
510
+ /**
511
+ * Fire-and-forget freshness refresh for a healthy Pi install. Never
512
+ * blocks launch and never throws: on the throttled schedule it probes
513
+ * npm for a newer Pi and, when one exists, queues a DETACHED post-exit
514
+ * install (same pattern as the proxy self-update) so neither startup
515
+ * nor the running session nor shutdown ever waits on npm. The
516
+ * cross-process install lock serializes against concurrent launches;
517
+ * every failure degrades to a debug log.
518
+ *
519
+ * Deliberately never touches a below-floor install: the floor is
520
+ * enforced foreground by the launcher (fail-closed), and a background
521
+ * task must not change what the running session validated.
522
+ */
523
+ function refreshPiInBackground(opts) {
524
+ if (!opts.autoUpdate) return;
525
+ (async () => {
526
+ try {
527
+ if (!shouldCheckNow(await readCache())) return;
528
+ const installedVersion = await getInstalledPiVersion();
529
+ if (!meetsPiMinVersion(installedVersion)) return;
530
+ const npmPath = resolveExecutable("npm");
531
+ const latestVersion = await getLatestPiVersion();
532
+ await writeCache({
533
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
534
+ installedVersion,
535
+ latestVersion
536
+ });
537
+ if (!npmPath) return;
538
+ if (!latestVersion || !isPiNewer(installedVersion, latestVersion)) return;
539
+ if (await withInstallLock("pi-install.lock", async () => {
540
+ queueDetachedGlobalInstall(npmPath, `@earendil-works/pi-coding-agent@${latestVersion}`, piRegistryArgs());
541
+ })) consola.info(`Pi ${installedVersion} → ${latestVersion} update queued; it takes effect on the next launch.`);
542
+ } catch (err) {
543
+ consola.debug("Background Pi refresh failed:", err);
544
+ }
545
+ })().catch((err) => {
546
+ consola.debug("Background Pi refresh failed:", err);
547
+ });
548
+ }
549
+ export { isPiNewer as a, refreshPiInBackground as c, checkClaudeVersion as d, updateClaude as f, getInstalledPiVersion as i, resolvePiRegistry as l, PI_MIN_VERSION as n, meetsPiMinVersion as o, PI_NPM_PACKAGE as r, piRegistryArgs as s, PI_DEFAULT_REGISTRY as t, runSelfUpdate as u };
550
+
551
+ //# sourceMappingURL=pi-version-check-BeBB0Ny9.js.map