github-router 0.3.356 → 0.3.367

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/dist/ado-tools-rysFZDws.js +1 -0
  2. package/dist/{aic-ledger-BuFrsGur.js → aic-ledger-_mvGW2Ev.js} +42 -7
  3. package/dist/aic-ledger-_mvGW2Ev.js.map +1 -0
  4. package/dist/{aic-statusline-settings-DBS9sEGC.js → aic-statusline-settings-B5EMMSFC.js} +2 -2
  5. package/dist/{aic-statusline-settings-DBS9sEGC.js.map → aic-statusline-settings-B5EMMSFC.js.map} +1 -1
  6. package/dist/{attribution-settings-CnmV9MSv.js → attribution-settings-wVzQvIdL.js} +188 -64
  7. package/dist/attribution-settings-wVzQvIdL.js.map +1 -0
  8. package/dist/{auth-DFawaLJU.js → auth-B3UvYB2r.js} +3 -3
  9. package/dist/{auth-DFawaLJU.js.map → auth-B3UvYB2r.js.map} +1 -1
  10. package/dist/browser-ext/manifest.json +1 -1
  11. package/dist/{check-usage-BkVEl-Su.js → check-usage-45vyaLfl.js} +4 -4
  12. package/dist/{check-usage-BkVEl-Su.js.map → check-usage-45vyaLfl.js.map} +1 -1
  13. package/dist/{claude-DvR3Y7fu.js → claude-B3pIageM.js} +89 -41
  14. package/dist/claude-B3pIageM.js.map +1 -0
  15. package/dist/{claude-md-injection-Cpzolxin.js → claude-md-injection-BV4tPUWo.js} +126 -35
  16. package/dist/claude-md-injection-BV4tPUWo.js.map +1 -0
  17. package/dist/{codex-DQpSPjpQ.js → codex-B_AMB6JM.js} +7 -7
  18. package/dist/{codex-DQpSPjpQ.js.map → codex-B_AMB6JM.js.map} +1 -1
  19. package/dist/{copilot-discount-Bsmv_3OX.js → copilot-discount-BuDbQOHq.js} +2 -2
  20. package/dist/{copilot-discount-Bsmv_3OX.js.map → copilot-discount-BuDbQOHq.js.map} +1 -1
  21. package/dist/{debug-DkNTuErv.js → debug-DL2JsRqY.js} +2 -2
  22. package/dist/{debug-DkNTuErv.js.map → debug-DL2JsRqY.js.map} +1 -1
  23. package/dist/engine-D3oNrF6Z.js +1 -0
  24. package/dist/{gate-discovery-B2x_8hNL.js → gate-discovery-CXE-7VcM.js} +5 -5
  25. package/dist/{gate-discovery-B2x_8hNL.js.map → gate-discovery-CXE-7VcM.js.map} +1 -1
  26. package/dist/{get-copilot-usage-P9chc-X2.js → get-copilot-usage-BbGmK03C.js} +2 -2
  27. package/dist/{get-copilot-usage-P9chc-X2.js.map → get-copilot-usage-BbGmK03C.js.map} +1 -1
  28. package/dist/hooks.mjs +200 -117
  29. package/dist/hooks.sha256 +1 -1
  30. package/dist/{index-cmd-BkfYr9FH.js → index-cmd-CjRcmYk3.js} +4 -4
  31. package/dist/{index-cmd-BkfYr9FH.js.map → index-cmd-CjRcmYk3.js.map} +1 -1
  32. package/dist/{internal-aic-status-C6L4-ncP.js → internal-aic-status-BAVomi5A.js} +4 -4
  33. package/dist/{internal-aic-status-C6L4-ncP.js.map → internal-aic-status-BAVomi5A.js.map} +1 -1
  34. package/dist/{internal-artifact-open-DgJ3PCtt.js → internal-artifact-open-NAGn9Mgt.js} +2 -2
  35. package/dist/{internal-artifact-open-DgJ3PCtt.js.map → internal-artifact-open-NAGn9Mgt.js.map} +1 -1
  36. package/dist/{internal-fast-dispatch-guard-CicGz6oM.js → internal-fast-dispatch-guard-DP25L_Bx.js} +1 -1
  37. package/dist/{internal-fast-dispatch-guard-CgBtUsQI.js → internal-fast-dispatch-guard-DbrgO9Ab.js} +2 -2
  38. package/dist/{internal-fast-dispatch-guard-CgBtUsQI.js.map → internal-fast-dispatch-guard-DbrgO9Ab.js.map} +1 -1
  39. package/dist/{internal-first-mate-guard-DTXPT7JW.js → internal-first-mate-guard-C8GwLbaX.js} +1 -1
  40. package/dist/{internal-first-mate-guard-BfWYN6Jb.js → internal-first-mate-guard-GufCUMl3.js} +3 -3
  41. package/dist/{internal-first-mate-guard-BfWYN6Jb.js.map → internal-first-mate-guard-GufCUMl3.js.map} +1 -1
  42. package/dist/{internal-max-dispatch-guard-mNl9CCir.js → internal-max-dispatch-guard-BB0vwiPx.js} +1 -1
  43. package/dist/{internal-max-dispatch-guard-CY8l9SDw.js → internal-max-dispatch-guard-BodVFHRC.js} +2 -2
  44. package/dist/{internal-max-dispatch-guard-CY8l9SDw.js.map → internal-max-dispatch-guard-BodVFHRC.js.map} +1 -1
  45. package/dist/{internal-plan-review-2OHTs8Nk.js → internal-plan-review-ChFx8wTX.js} +3 -3
  46. package/dist/{internal-plan-review-2OHTs8Nk.js.map → internal-plan-review-ChFx8wTX.js.map} +1 -1
  47. package/dist/{internal-prompt-submit-CkfUcu34.js → internal-prompt-submit-BaccW_CC.js} +4 -4
  48. package/dist/{internal-prompt-submit-CkfUcu34.js.map → internal-prompt-submit-BaccW_CC.js.map} +1 -1
  49. package/dist/{internal-prompt-submit-DZ_-2A6a.js → internal-prompt-submit-DPUBQZtG.js} +2 -2
  50. package/dist/{internal-rebrief-EhBHAHsz.js → internal-rebrief-NjSlx5QY.js} +4 -4
  51. package/dist/{internal-rebrief-EhBHAHsz.js.map → internal-rebrief-NjSlx5QY.js.map} +1 -1
  52. package/dist/{internal-session-bind-Bv50ju2n.js → internal-session-bind-dsUOcKxU.js} +2 -2
  53. package/dist/{internal-session-bind-Bv50ju2n.js.map → internal-session-bind-dsUOcKxU.js.map} +1 -1
  54. package/dist/{internal-stop-hook-Dm-m8RoA.js → internal-stop-hook-B2TTl6Zp.js} +5 -5
  55. package/dist/{internal-stop-hook-Dm-m8RoA.js.map → internal-stop-hook-B2TTl6Zp.js.map} +1 -1
  56. package/dist/{internal-stop-review-K6f8xsCh.js → internal-stop-review-D_KEV_04.js} +2 -2
  57. package/dist/{internal-stop-review-K6f8xsCh.js.map → internal-stop-review-D_KEV_04.js.map} +1 -1
  58. package/dist/{internal-worker-guard-GVhTjVlR.js → internal-worker-guard-DB6shBIn.js} +2 -2
  59. package/dist/{internal-worker-guard-GVhTjVlR.js.map → internal-worker-guard-DB6shBIn.js.map} +1 -1
  60. package/dist/{internal-workspace-header-d2hFf9Jy.js → internal-workspace-header-DBg5Y7oN.js} +2 -2
  61. package/dist/{internal-workspace-header-d2hFf9Jy.js.map → internal-workspace-header-DBg5Y7oN.js.map} +1 -1
  62. package/dist/{lifecycle-C6cxM_Nk.js → lifecycle-9nX09dBl.js} +2 -2
  63. package/dist/{lifecycle-C6cxM_Nk.js.map → lifecycle-9nX09dBl.js.map} +1 -1
  64. package/dist/lifecycle-C_CT13c9.js +1 -0
  65. package/dist/lifecycle-DibiH857.js +1 -0
  66. package/dist/{lifecycle-pl9QpvqD.js → lifecycle-Gge2Dadd.js} +2 -2
  67. package/dist/{lifecycle-pl9QpvqD.js.map → lifecycle-Gge2Dadd.js.map} +1 -1
  68. package/dist/main.js +23 -23
  69. package/dist/{mcp-workspace-header-Su8uUxJg.js → mcp-workspace-header-Xw9B1W6T.js} +2 -2
  70. package/dist/{mcp-workspace-header-Su8uUxJg.js.map → mcp-workspace-header-Xw9B1W6T.js.map} +1 -1
  71. package/dist/{models-D8v8OTbN.js → models-BR6i348u.js} +3 -3
  72. package/dist/{models-D8v8OTbN.js.map → models-BR6i348u.js.map} +1 -1
  73. package/dist/{orchestration-Bov4rZEi.js → orchestration-D3-2ulhX.js} +2 -2
  74. package/dist/{orchestration-Bov4rZEi.js.map → orchestration-D3-2ulhX.js.map} +1 -1
  75. package/dist/{paths-BSI_EtDT.js → paths-C5477RGC.js} +48 -4
  76. package/dist/paths-C5477RGC.js.map +1 -0
  77. package/dist/paths-CEswtFj5.js +1 -0
  78. package/dist/{peer-mcp-personas-CVxXq1Q-.js → peer-mcp-personas-BOgR46nM.js} +641 -270
  79. package/dist/peer-mcp-personas-BOgR46nM.js.map +1 -0
  80. package/dist/{pi-D-BgxVhx.js → pi-DcWp83mx.js} +377 -602
  81. package/dist/pi-DcWp83mx.js.map +1 -0
  82. package/dist/{plan-review-hook-CHK1wL3-.js → plan-review-hook-C9K-em4D.js} +3 -3
  83. package/dist/{plan-review-hook-CHK1wL3-.js.map → plan-review-hook-C9K-em4D.js.map} +1 -1
  84. package/dist/{provision-DYmZgZDr.js → provision-DkWR9B6I.js} +5 -5
  85. package/dist/{provision-DYmZgZDr.js.map → provision-DkWR9B6I.js.map} +1 -1
  86. package/dist/{self-invocation-Dk_UHD_v.js → self-invocation-BtcGj-lY.js} +2 -2
  87. package/dist/{self-invocation-Dk_UHD_v.js.map → self-invocation-BtcGj-lY.js.map} +1 -1
  88. package/dist/{serve-DfxxKLFl.js → serve-BGwEVDdc.js} +14 -14
  89. package/dist/{serve-DfxxKLFl.js.map → serve-BGwEVDdc.js.map} +1 -1
  90. package/dist/{server-setup-VYf8ptCH.js → server-setup-DVPL9iph.js} +911 -100
  91. package/dist/server-setup-DVPL9iph.js.map +1 -0
  92. package/dist/{service-backend-DHyd9vjW.js → service-backend-B6D_DY1Z.js} +3 -3
  93. package/dist/{service-backend-DHyd9vjW.js.map → service-backend-B6D_DY1Z.js.map} +1 -1
  94. package/dist/{start-BsY1d26G.js → start-BUWx3nSr.js} +4 -4
  95. package/dist/{start-BsY1d26G.js.map → start-BUWx3nSr.js.map} +1 -1
  96. package/dist/{static-context-pack-dKrzbfIN.js → static-context-pack-ChHuxBpk.js} +232 -61
  97. package/dist/static-context-pack-ChHuxBpk.js.map +1 -0
  98. package/dist/{stop-gate-hook-CC7VWkZM.js → stop-gate-hook-DnLC09Lg.js} +3 -3
  99. package/dist/{stop-gate-hook-CC7VWkZM.js.map → stop-gate-hook-DnLC09Lg.js.map} +1 -1
  100. package/dist/{stop-gate-policy-CoR8xKNQ.js → stop-gate-policy-Dx9c98_d.js} +2 -2
  101. package/dist/{stop-gate-policy-CoR8xKNQ.js.map → stop-gate-policy-Dx9c98_d.js.map} +1 -1
  102. package/dist/{token-CA2s70qj.js → token-OTb61rOC.js} +2 -2
  103. package/dist/{token-CA2s70qj.js.map → token-OTb61rOC.js.map} +1 -1
  104. package/dist/{worker-dispatch-B_rriT7z.js → worker-dispatch-B1w2qfjX.js} +2 -2
  105. package/dist/{worker-dispatch-B_rriT7z.js.map → worker-dispatch-B1w2qfjX.js.map} +1 -1
  106. package/docs/azure-mcp.md +29 -31
  107. package/package.json +1 -1
  108. package/dist/ado-tools-DokE2DbX.js +0 -1
  109. package/dist/aic-ledger-BuFrsGur.js.map +0 -1
  110. package/dist/attribution-settings-CnmV9MSv.js.map +0 -1
  111. package/dist/claude-DvR3Y7fu.js.map +0 -1
  112. package/dist/claude-md-injection-Cpzolxin.js.map +0 -1
  113. package/dist/engine-DgmsdkCe.js +0 -1
  114. package/dist/lifecycle-BU_d2QMs.js +0 -1
  115. package/dist/lifecycle-ByFyew_w.js +0 -1
  116. package/dist/paths-BSI_EtDT.js.map +0 -1
  117. package/dist/paths-BYxX9DfA.js +0 -1
  118. package/dist/peer-mcp-personas-CVxXq1Q-.js.map +0 -1
  119. package/dist/pi-D-BgxVhx.js.map +0 -1
  120. package/dist/server-setup-VYf8ptCH.js.map +0 -1
  121. package/dist/static-context-pack-dKrzbfIN.js.map +0 -1
@@ -1,305 +1,23 @@
1
- import { L as withInstallLock, P as warmTreeSitterPool } from "./service-backend-DHyd9vjW.js";
1
+ import { P as warmTreeSitterPool } from "./service-backend-B6D_DY1Z.js";
2
2
  import { t as getPackageVersion } from "./version-C8x2hQrZ.js";
3
- import { t as PATHS } from "./paths-BSI_EtDT.js";
3
+ import { t as PATHS } from "./paths-C5477RGC.js";
4
4
  import { t as state } from "./state-CiwCLVDZ.js";
5
- import { c as runCommandCapture, s as resolveExecutable, u as runCommandVoid } from "./exec-Bf8g_bIR.js";
6
- import { B as runSelfUpdate, E as formatBalancedPrerequisiteFailure, I as validateCheapestProfilePrerequisites, M as resolveLaunchProfile, N as validateBalancedProfilePrerequisites, a as setupAndServe, c as startKeepAwake, f as enableFileLogging, i as parseSharedArgs, j as profileDescriptor, k as formatCheapestPrerequisiteFailure, l as stopKeepAwake, o as sharedServerArgs, r as getPiLaunchEnvVars, z as queueDetachedGlobalInstall } from "./server-setup-VYf8ptCH.js";
7
- import { Bt as kustoToolsEnabled, D as toolbeltEnabled, Ot as cloudAgentToolsEnabled, bn as provisionAndIndexColbert, nn as registerLaunch, pn as provisionBrowserAssets, pt as adoToolsEnabled, rn as unregisterLaunch, xt as browserToolsEnabled, yn as colbertDegradedWarning } from "./peer-mcp-personas-CVxXq1Q-.js";
8
- import { _ as isBalancedFamily, m as cheapestContractFor, p as balancedContractFor, v as isCheapestFamily } from "./static-context-pack-dKrzbfIN.js";
9
- import { r as resolveSelfInvocation } from "./self-invocation-Dk_UHD_v.js";
10
- import { i as launchChild, t as provisionToolbelt } from "./provision-DYmZgZDr.js";
11
- import { d as sweepStaleAicLedgerFiles, n as aicSnapshot, o as formatAicExitSummary, t as aicLedgerPath, u as removeAicLedgerFile } from "./aic-ledger-BuFrsGur.js";
12
- import { t as CHEAPEST_CONSULT_CONTRACT } from "./claude-md-injection-Cpzolxin.js";
13
- import { i as buildAicStatusHookCommand, n as AIC_STATUSLINE_DISABLE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-DBS9sEGC.js";
14
- import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-Bsmv_3OX.js";
5
+ import { $ as runSelfUpdate, G as resolveLaunchProfile, K as validateBalancedProfilePrerequisites, R as formatBalancedPrerequisiteFailure, U as formatLocalPrerequisiteFailure, V as formatCheapestPrerequisiteFailure, W as profileDescriptor, Y as validateCheapestProfilePrerequisites, Z as validateLocalProfilePrerequisites, _ as ensurePiAgentMirror, a as setupAndServe, b as startKeepAwake, c as localBaseUrl, d as ensurePiInstalled, f as getInstalledPiVersion, g as updatePi, h as resolvePiRegistry, i as parseSharedArgs, l as LAUNCH_SECRET_HEADER, m as refreshPiInBackground, o as sharedServerArgs, p as meetsPiMinVersion, r as getPiLaunchEnvVars, s as configureLocalEgress, u as PI_MIN_VERSION, v as removeOwnPiAgentMirror, w as enableFileLogging, x as stopKeepAwake, y as sweepStalePiAgentMirrors } from "./server-setup-DVPL9iph.js";
6
+ import { At as cloudAgentToolsEnabled, Ct as browserToolsEnabled, D as toolbeltEnabled, En as provisionAndIndexColbert, Ht as kustoToolsEnabled, Tn as colbertDegradedWarning, _t as artifactToolsEnabled, ht as adoToolsEnabled, on as registerLaunch, sn as unregisterLaunch, xt as browseAgentEnabled, yn as provisionBrowserAssets } from "./peer-mcp-personas-BOgR46nM.js";
7
+ import { E as LOCAL_PROFILE_TIER_MODELS, _ as isCheapestFamily, b as local2AdvisorContract, f as balancedContractFor, g as isBalancedFamily, p as cheapestContractFor, v as isLocalFamily, x as localContractFor } from "./static-context-pack-ChHuxBpk.js";
8
+ import { r as resolveSelfInvocation } from "./self-invocation-BtcGj-lY.js";
9
+ import { i as launchChild, t as provisionToolbelt } from "./provision-DkWR9B6I.js";
10
+ import { d as removeAicLedgerFile, f as sweepStaleAicLedgerFiles, n as aicSnapshot, o as formatAicExitSummary, t as aicLedgerPath } from "./aic-ledger-_mvGW2Ev.js";
11
+ import { t as FRESH_CONSULT_CONTRACT } from "./claude-md-injection-BV4tPUWo.js";
12
+ import { i as buildAicStatusHookCommand, n as AIC_STATUSLINE_DISABLE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-B5EMMSFC.js";
13
+ import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-BuDbQOHq.js";
15
14
  import { defineCommand } from "citty";
16
15
  import consola from "consola";
17
16
  import { existsSync } from "node:fs";
18
17
  import path from "node:path";
19
18
  import { createHash, randomBytes } from "node:crypto";
20
19
  import fs$1 from "node:fs/promises";
21
- import os from "node:os";
22
20
  import process$1 from "node:process";
23
- //#region src/lib/pi-version-check.ts
24
- const PI_NPM_PACKAGE = "@earendil-works/pi-coding-agent";
25
- /**
26
- * Minimum Pi version the `pi` launcher supports.
27
- *
28
- * The floor is pinned to the first release whose `before_agent_start` event
29
- * carries the `messageType` discriminator (present at 1.3.0, absent at 1.1.0).
30
- * The generated extension's prompt hook stands down for non-user events using
31
- * that field, and without it the hook would fire on subagent and system turns
32
- * the user never typed, which is a wrong brief rather than a missing one.
33
- * Below-floor Pi hard-exits at the launcher (`src/pi.ts`), but only where the
34
- * gate actually runs: the install probe, the background refresh, and this floor
35
- * check all sit inside `--update-check` (default on), so `--no-update-check`
36
- * (documented for offline/CI) skips the floor as well. That path is still
37
- * fail-closed rather than silently wrong: the generated extension's own shape
38
- * probe sees the missing `messageType`, warns once with the fix, and injects
39
- * nothing.
40
- */
41
- const PI_MIN_VERSION = "1.3.0";
42
- /**
43
- * Registry used for the PI PACKAGE ONLY.
44
- *
45
- * Pi must come from a registry that actually carries it. A corporate npm mirror
46
- * can lag npmjs far enough that its `latest` sits below `PI_MIN_VERSION`, and
47
- * the launcher then fail-closes on an upgrade command the user cannot satisfy
48
- * (their `npm install -g` resolves through the same lagging mirror). Pointing
49
- * the Pi probe and install at npmjs by default keeps the floor reachable;
50
- * `GH_ROUTER_NPM_REGISTRY` overrides it for a mirror that does carry the
51
- * package. Everything else this repo installs still resolves through the user's
52
- * configured registry.
53
- */
54
- const PI_DEFAULT_REGISTRY = "https://registry.npmjs.org/";
55
- /**
56
- * Resolve the registry for Pi package operations. Accepts `GH_ROUTER_NPM_REGISTRY`
57
- * when it is an http(s) URL and falls back to `PI_DEFAULT_REGISTRY` with a
58
- * warning otherwise, so a typo degrades to the working default rather than
59
- * bricking the launcher.
60
- */
61
- function resolvePiRegistry() {
62
- const raw = process.env.GH_ROUTER_NPM_REGISTRY?.trim();
63
- if (!raw) return PI_DEFAULT_REGISTRY;
64
- if (!/^https?:\/\//i.test(raw)) {
65
- consola.warn(`Ignoring GH_ROUTER_NPM_REGISTRY=${JSON.stringify(raw)}: expected an http(s) URL. Using ${PI_DEFAULT_REGISTRY}.`);
66
- return PI_DEFAULT_REGISTRY;
67
- }
68
- return raw.endsWith("/") ? raw : `${raw}/`;
69
- }
70
- /** `npm` args that pin an operation to the resolved Pi registry. */
71
- function piRegistryArgs(registry = resolvePiRegistry()) {
72
- return [`--registry=${registry}`];
73
- }
74
- const THROTTLE_HOURS = 1;
75
- const NPM_VIEW_TIMEOUT_MS = 5e3;
76
- const PI_VERSION_TIMEOUT_MS = 3e3;
77
- const NPM_INSTALL_TIMEOUT_MS = 3e5;
78
- /** Path to the throttle cache. Created on demand. Separate file from the Claude check. */
79
- function cacheFilePath() {
80
- return path.join(os.homedir(), ".local", "share", "github-router", "last-pi-update-check");
81
- }
82
- async function readCache() {
83
- try {
84
- const raw = await fs$1.readFile(cacheFilePath(), "utf8");
85
- const parsed = JSON.parse(raw);
86
- if (typeof parsed.checkedAt !== "string" || parsed.installedVersion !== null && typeof parsed.installedVersion !== "string" || parsed.latestVersion !== null && typeof parsed.latestVersion !== "string") return null;
87
- return parsed;
88
- } catch {
89
- return null;
90
- }
91
- }
92
- async function writeCache(cache) {
93
- try {
94
- await fs$1.mkdir(path.dirname(cacheFilePath()), { recursive: true });
95
- await fs$1.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 384 });
96
- } catch (err) {
97
- consola.debug("Failed to write pi version-check cache:", err);
98
- }
99
- }
100
- function shouldCheckNow(cache) {
101
- if (!cache) return true;
102
- const lastCheck = new Date(cache.checkedAt).getTime();
103
- if (Number.isNaN(lastCheck)) return true;
104
- return (Date.now() - lastCheck) / 1e3 / 3600 >= THROTTLE_HOURS;
105
- }
106
- /**
107
- * Read the installed `pi` version. Returns null if pi is not on PATH
108
- * or the version probe fails.
109
- *
110
- * Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path
111
- * (excluding the cwd) before invocation via the shared exec helper.
112
- */
113
- async function getInstalledPiVersion() {
114
- const piPath = resolveExecutable("pi");
115
- if (!piPath) return null;
116
- try {
117
- const { stdout, code } = await runCommandCapture([piPath, "--version"], { timeoutMs: PI_VERSION_TIMEOUT_MS });
118
- if (code !== 0) return null;
119
- const match = stdout.match(/(\d+\.\d+\.\d+)/);
120
- return match ? match[1] : null;
121
- } catch {
122
- return null;
123
- }
124
- }
125
- /** Fetch the latest Pi version from npm. Null on network/npm failure. */
126
- async function getLatestPiVersion() {
127
- const npmPath = resolveExecutable("npm");
128
- if (!npmPath) return null;
129
- try {
130
- const { stdout, code } = await runCommandCapture([
131
- npmPath,
132
- "view",
133
- PI_NPM_PACKAGE,
134
- "version",
135
- "--silent",
136
- ...piRegistryArgs()
137
- ], { timeoutMs: NPM_VIEW_TIMEOUT_MS });
138
- if (code !== 0) return null;
139
- const v = stdout.trim();
140
- return /^\d+\.\d+\.\d+/.test(v) ? v : null;
141
- } catch {
142
- return null;
143
- }
144
- }
145
- /**
146
- * Compare two semver-shaped strings (leading X.Y.Z only). True when
147
- * `latest` is strictly higher than `installed`.
148
- */
149
- function isPiNewer(installed, latest) {
150
- if (!installed || !latest) return false;
151
- const a = installed.split(".").map((n) => parseInt(n, 10));
152
- const b = latest.split(".").map((n) => parseInt(n, 10));
153
- for (let i = 0; i < 3; i++) {
154
- const av = a[i] ?? 0;
155
- const bv = b[i] ?? 0;
156
- if (av < bv) return true;
157
- if (av > bv) return false;
158
- }
159
- return false;
160
- }
161
- /** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */
162
- function meetsPiMinVersion(version) {
163
- if (!version) return false;
164
- return !isPiNewer(version, PI_MIN_VERSION);
165
- }
166
- /** Run a version check (subject to throttle). Side-effect: updates the cache. */
167
- async function checkPiVersion(opts = {}) {
168
- if (opts.noCheck) return {
169
- installed: false,
170
- installedVersion: null,
171
- latestVersion: null,
172
- needsUpdate: false,
173
- needsMinUpgrade: false,
174
- skipped: true,
175
- skipReason: "disabled"
176
- };
177
- const cache = await readCache();
178
- if (!opts.force && !shouldCheckNow(cache)) {
179
- const installedVersion = cache?.installedVersion ?? null;
180
- const latestVersion = cache?.latestVersion ?? null;
181
- return {
182
- installed: installedVersion !== null,
183
- installedVersion,
184
- latestVersion,
185
- needsUpdate: isPiNewer(installedVersion, latestVersion),
186
- needsMinUpgrade: !meetsPiMinVersion(installedVersion),
187
- skipped: true,
188
- skipReason: "throttled"
189
- };
190
- }
191
- const installedVersion = await getInstalledPiVersion();
192
- if (installedVersion === null) return {
193
- installed: false,
194
- installedVersion: null,
195
- latestVersion: null,
196
- needsUpdate: false,
197
- needsMinUpgrade: true,
198
- skipped: true,
199
- skipReason: "no-pi"
200
- };
201
- const latestVersion = await getLatestPiVersion();
202
- await writeCache({
203
- checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
204
- installedVersion,
205
- latestVersion
206
- });
207
- if (latestVersion === null) return {
208
- installed: true,
209
- installedVersion,
210
- latestVersion: null,
211
- needsUpdate: false,
212
- needsMinUpgrade: !meetsPiMinVersion(installedVersion),
213
- skipped: true,
214
- skipReason: "no-npm"
215
- };
216
- return {
217
- installed: true,
218
- installedVersion,
219
- latestVersion,
220
- needsUpdate: isPiNewer(installedVersion, latestVersion),
221
- needsMinUpgrade: !meetsPiMinVersion(installedVersion),
222
- skipped: false
223
- };
224
- }
225
- /**
226
- * Install (or upgrade) Pi from npm under the cross-process install lock.
227
- * Returns `true` when this call performed the install, `false` when
228
- * another process holds the lock (caller skips — its install will land
229
- * for a later launch). Best-effort: throws on failure; callers fall
230
- * back to the installed version with a visible warning rather than
231
- * stranding the launch.
232
- */
233
- function updatePi(version, opts = {}) {
234
- const npmPath = resolveExecutable("npm");
235
- if (!npmPath) throw new Error("npm not found on PATH; cannot install Pi automatically");
236
- return withInstallLock("pi-install.lock", async () => {
237
- const registry = resolvePiRegistry();
238
- consola.info(`Installing ${PI_NPM_PACKAGE}@${version} from ${registry}...`);
239
- await runCommandVoid([
240
- npmPath,
241
- "install",
242
- "-g",
243
- `${PI_NPM_PACKAGE}@${version}`,
244
- ...piRegistryArgs(registry)
245
- ], {
246
- timeoutMs: NPM_INSTALL_TIMEOUT_MS,
247
- signal: opts.signal
248
- });
249
- });
250
- }
251
- /**
252
- * Blocking fresh install for when Pi is absent entirely. Installs
253
- * `@latest`, then force re-checks; throws when Pi still is not on PATH
254
- * (caller exits with the install command). Only used when there is no
255
- * usable Pi at all — the healthy path never blocks on npm.
256
- */
257
- async function ensurePiInstalled(opts = {}) {
258
- const acquired = await updatePi("latest", opts);
259
- const retry = await checkPiVersion({ force: true });
260
- if (retry.installed && retry.installedVersion) return retry.installedVersion;
261
- throw new Error(acquired ? "install did not place pi on PATH" : "another Pi install is already running; retry in a moment");
262
- }
263
- /**
264
- * Fire-and-forget freshness refresh for a healthy Pi install. Never
265
- * blocks launch and never throws: on the throttled schedule it probes
266
- * npm for a newer Pi and, when one exists, queues a DETACHED post-exit
267
- * install (same pattern as the proxy self-update) so neither startup
268
- * nor the running session nor shutdown ever waits on npm. The
269
- * cross-process install lock serializes against concurrent launches;
270
- * every failure degrades to a debug log.
271
- *
272
- * Deliberately never touches a below-floor install: the floor is
273
- * enforced foreground by the launcher (fail-closed), and a background
274
- * task must not change what the running session validated.
275
- */
276
- function refreshPiInBackground(opts) {
277
- if (!opts.autoUpdate) return;
278
- (async () => {
279
- try {
280
- if (!shouldCheckNow(await readCache())) return;
281
- const installedVersion = await getInstalledPiVersion();
282
- if (!meetsPiMinVersion(installedVersion)) return;
283
- const npmPath = resolveExecutable("npm");
284
- const latestVersion = await getLatestPiVersion();
285
- await writeCache({
286
- checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
287
- installedVersion,
288
- latestVersion
289
- });
290
- if (!npmPath) return;
291
- if (!latestVersion || !isPiNewer(installedVersion, latestVersion)) return;
292
- if (await withInstallLock("pi-install.lock", async () => {
293
- queueDetachedGlobalInstall(npmPath, `@earendil-works/pi-coding-agent@${latestVersion}`, piRegistryArgs());
294
- })) consola.info(`Pi ${installedVersion} → ${latestVersion} update queued; it takes effect on the next launch.`);
295
- } catch (err) {
296
- consola.debug("Background Pi refresh failed:", err);
297
- }
298
- })().catch((err) => {
299
- consola.debug("Background Pi refresh failed:", err);
300
- });
301
- }
302
- //#endregion
303
21
  //#region src/lib/pi-tier-windows.ts
304
22
  /**
305
23
  * Copilot Default-tier (cheap) input-token thresholds per model.
@@ -570,113 +288,6 @@ function buildPiStatusPayload(source, opts) {
570
288
  worktree: null
571
289
  };
572
290
  }
573
- //#endregion
574
- //#region src/lib/pi-paths.ts
575
- function appDir() {
576
- return path.join(os.homedir(), ".local", "share", "github-router");
577
- }
578
- /** Where the user's real Pi agent dir lives (`PI_CODING_AGENT_DIR` wins). */
579
- function userPiAgentDir() {
580
- const override = (process.env.PI_CODING_AGENT_DIR ?? "").trim();
581
- if (override.length > 0) return override;
582
- return path.join(os.homedir(), ".pi", "agent");
583
- }
584
- /**
585
- * Per-launch suffix for the Pi mirror. Lazily generated once per process
586
- * so every path getter in this module agrees on the directory.
587
- */
588
- let launchSuffix;
589
- function perLaunchSuffix() {
590
- launchSuffix ??= `pi-agent-${process.pid}-${randomBytes(4).toString("hex")}`;
591
- return launchSuffix;
592
- }
593
- /** Router-owned, per-launch Pi agent dir for the spawned `pi` child. */
594
- function piMirrorDir() {
595
- return path.join(appDir(), "pi-mirrors", perLaunchSuffix());
596
- }
597
- /**
598
- * Provision the per-launch Pi mirror: snapshot-copy the user's real Pi
599
- * agent dir (settings, models, skills, prompts, extensions the user owns)
600
- * so the spawned `pi` starts from the user's own setup, then let the
601
- * launcher overlay the mode's generated files on top.
602
- *
603
- * Copy failures of individual user files are debug-logged and skipped —
604
- * a corrupt user file must not strand the launch. Throws only when the
605
- * mirror directory itself cannot be created.
606
- */
607
- async function ensurePiAgentMirror() {
608
- const mirror = piMirrorDir();
609
- await fs$1.mkdir(mirror, { recursive: true });
610
- const source = userPiAgentDir();
611
- let entries;
612
- try {
613
- entries = await fs$1.readdir(source);
614
- } catch {
615
- return mirror;
616
- }
617
- const keepUserExtensions = process.env.GH_ROUTER_PI_KEEP_USER_EXTENSIONS === "1";
618
- const SKIP = /* @__PURE__ */ new Set([
619
- "auth.json",
620
- "sessions",
621
- "models-store.json",
622
- ...keepUserExtensions ? [] : ["extensions"]
623
- ]);
624
- await Promise.all(entries.filter((e) => !SKIP.has(e)).map(async (entry) => {
625
- try {
626
- await fs$1.cp(path.join(source, entry), path.join(mirror, entry), { recursive: true });
627
- } catch (err) {
628
- consola.debug(`Pi mirror: skipping ${entry}:`, err);
629
- }
630
- }));
631
- return mirror;
632
- }
633
- /** Remove THIS launch's Pi mirror on shutdown. Best-effort, never throws. */
634
- async function removeOwnPiAgentMirror() {
635
- try {
636
- await fs$1.rm(piMirrorDir(), {
637
- recursive: true,
638
- force: true
639
- });
640
- } catch (err) {
641
- consola.debug("Pi mirror cleanup failed:", err);
642
- }
643
- }
644
- /**
645
- * Sweep stale Pi mirrors left behind by crashed launches (dirs whose PID
646
- * no longer exists, or older than 24h). Best-effort, never throws.
647
- */
648
- async function sweepStalePiAgentMirrors() {
649
- const root = path.join(appDir(), "pi-mirrors");
650
- let entries;
651
- try {
652
- entries = await fs$1.readdir(root);
653
- } catch {
654
- return;
655
- }
656
- await Promise.all(entries.map(async (entry) => {
657
- const dir = path.join(root, entry);
658
- try {
659
- const stat = await fs$1.stat(dir);
660
- const ageMs = Date.now() - stat.mtimeMs;
661
- const pidMatch = /^pi-agent-(\d+)-[0-9a-f]+$/.exec(entry);
662
- let dead = ageMs > 864e5;
663
- if (pidMatch && !dead) {
664
- const pid = Number.parseInt(pidMatch[1], 10);
665
- try {
666
- process.kill(pid, 0);
667
- } catch {
668
- dead = true;
669
- }
670
- }
671
- if (dead) await fs$1.rm(dir, {
672
- recursive: true,
673
- force: true
674
- });
675
- } catch (err) {
676
- consola.debug(`Pi mirror sweep: skipping ${entry}:`, err);
677
- }
678
- }));
679
- }
680
291
  function cacheDisabled() {
681
292
  return process.env.GH_ROUTER_PI_NO_PACKAGE_CACHE === "1";
682
293
  }
@@ -813,34 +424,90 @@ function piThinkingLevelMapFor(efforts) {
813
424
  /** Provider key used in models.json and agent `provider/model` references. */
814
425
  const PI_PROVIDER_NAME = "gh-router";
815
426
  const PI_MIN_VERSION_NOTE = `Requires Pi >= ${PI_MIN_VERSION} and Node >= 22.19.`;
427
+ function piCopilotContractFor(profileId) {
428
+ return isCheapestFamily(profileId) ? cheapestContractFor(profileId) : balancedContractFor(profileId);
429
+ }
816
430
  /**
817
- * The family contract for a Pi profile. `cheapest2` and `balanced2` are
818
- * derived from their bases, so every resolver below reads one object and a
819
- * `-2` launch cannot pick up a base literal by omission.
431
+ * The family contract for a Pi profile, across all three families. Local is a
432
+ * third family, not a cheapest sibling: its egress and model ids differ even
433
+ * though it inherits the cheapest roster and prose. Only the fields common to
434
+ * every family are reachable here.
820
435
  */
821
436
  function piContractFor(profileId) {
822
- return isCheapestFamily(profileId) ? cheapestContractFor(profileId) : balancedContractFor(profileId);
437
+ return isLocalFamily(profileId) ? localContractFor(profileId) : piCopilotContractFor(profileId);
823
438
  }
824
439
  function piLeadModel(profileId) {
825
440
  return piContractFor(profileId).models.lead;
826
441
  }
442
+ /**
443
+ * Pi's default thinking level for the lead.
444
+ *
445
+ * Local profiles answer `high` because that is the reachable ceiling, not a
446
+ * guess about the server: Pi exposes `xhigh`/`max` only when a row's
447
+ * `thinkingLevelMap` explicitly defines them, and the local rows deliberately
448
+ * carry no map (we do not assume the endpoint's effort ladder), so
449
+ * `clampThinkingLevel` walks any higher request down to `high`.
450
+ */
827
451
  function piLeadThinking(profileId) {
828
- return piContractFor(profileId).leadEffort;
452
+ return isLocalFamily(profileId) ? "high" : piCopilotContractFor(profileId).leadEffort;
829
453
  }
454
+ /**
455
+ * The `peers` persona allow-list this profile registers with the launch
456
+ * registry, or `undefined` when every persona is reachable.
457
+ *
458
+ * Pi's discovery prose (a group's `mcp.json` description) and its skills are
459
+ * the model's only signal for what a group holds, so they have to be derived
460
+ * from the same list the MCP handler enforces. A group described with personas
461
+ * the launch filters out sends the model hunting for tools that answer
462
+ * -32601. `local` is the one Pi profile with an empty list: it keeps the group
463
+ * for the artifact review tools and nothing else.
464
+ */
465
+ function piPersonaAllowlist(profileId) {
466
+ return profileDescriptor(profileId).personaAllowlist;
467
+ }
468
+ /** Whether the Copilot-served `oracle` MCP tool is callable on this profile. */
469
+ function piOracleToolReachable(profileId) {
470
+ const allowlist = piPersonaAllowlist(profileId);
471
+ return allowlist === void 0 || allowlist.has("oracle");
472
+ }
473
+ /**
474
+ * Which model answers the `oracle` subagent.
475
+ *
476
+ * Every Copilot profile's oracle is a Copilot-served consultant pinned by its
477
+ * family contract. `local` has no Copilot oracle at all, yet the subagent
478
+ * still has to be emitted: omitting the file would un-shadow Pi's builtin
479
+ * `oracle`, which also owns the `advisor` alias and is pinned to a model of
480
+ * its own choosing. Pinning our file to the local lead tier keeps the role,
481
+ * its nesting grant and the shadowing intact while running it on the one
482
+ * endpoint the profile is allowed to use.
483
+ */
830
484
  function piOracleModel(profileId) {
831
- return piContractFor(profileId).oracleModel;
485
+ return profileId === "local" ? piLeadModel(profileId) : piContractFor(profileId).oracleModel;
832
486
  }
833
487
  function piOracleThinking(profileId) {
834
- return piContractFor(profileId).oracleEffort;
488
+ return profileId === "local" ? piLeadThinking(profileId) : piContractFor(profileId).oracleEffort;
835
489
  }
836
- /** Cheapest-only advisor. Balanced is advisor-free by design: undefined. */
490
+ /**
491
+ * Advisor row. Cheapest-family launches carry one; `balanced` is advisor-free
492
+ * by design and `local` mirrors that (no Advisor). `local2` is the one local
493
+ * profile with an Advisor, and it is Copilot-served (`gpt-6.1-sol`) — the
494
+ * Advisor always runs on a real Copilot model, never on the local endpoint.
495
+ */
837
496
  function piAdvisorModel(profileId) {
838
- if (!isCheapestFamily(profileId)) return void 0;
839
- const contract = cheapestContractFor(profileId);
840
- return {
841
- model: contract.advisorModel,
842
- thinking: contract.advisorEffort
843
- };
497
+ if (isCheapestFamily(profileId)) {
498
+ const contract = cheapestContractFor(profileId);
499
+ return {
500
+ model: contract.advisorModel,
501
+ thinking: contract.advisorEffort
502
+ };
503
+ }
504
+ if (profileId === "local2") {
505
+ const contract = local2AdvisorContract();
506
+ return {
507
+ model: contract.advisorModel,
508
+ thinking: contract.advisorEffort
509
+ };
510
+ }
844
511
  }
845
512
  function piNativeRoles(profileId) {
846
513
  const { nativeModels, nativeEfforts: efforts } = piContractFor(profileId);
@@ -958,7 +625,7 @@ function piUsdCostFor(prices) {
958
625
  /**
959
626
  * Build the `models.json` provider entry pointing Pi at the running
960
627
  * proxy as an ordinary OpenAI-compatible endpoint (the documented
961
- * Ollama/vLLM pattern — no provider-override extension needed).
628
+ * provider-override pattern — no extension needed).
962
629
  *
963
630
  * The provider speaks `openai-responses`: every roster model is
964
631
  * Responses-only on Copilot, and Pi POSTs `{baseUrl}/responses` for
@@ -981,21 +648,52 @@ function piUsdCostFor(prices) {
981
648
  * paying a send-then-drop round trip, and `thinkingLevelMap` from the
982
649
  * catalog `reasoning_effort` allowlist so Pi never offers an effort
983
650
  * tier Copilot would 400.
651
+ *
652
+ * LOCAL PROFILES speak `anthropic-messages` instead: the provider default
653
+ * becomes Anthropic's wire format, the tier rows (`opus`/`sonnet`/`haiku`)
654
+ * are the endpoint's own ids and stay on it, and every Copilot-served row
655
+ * (the local2 advisor, which is the only Copilot row a local profile has) is
656
+ * pinned to `openai-responses`. That split is load-bearing: a Copilot row
657
+ * left on the provider default would send a real Copilot model id to the
658
+ * LOCAL server,
659
+ * while the tier rows must never be diverted to `/v1/responses` (that route
660
+ * always leaves for Copilot). Catalog endpoint discovery cannot make this
661
+ * call — a local id has no catalog entry, and a Copilot id's endpoints
662
+ * describe Copilot, not whatever is behind the local port. The tier rows
663
+ * also carry the launch's stable session id as a per-model header, since
664
+ * the endpoint requires one for routing and prompt caching, plus the launch
665
+ * secret that makes the proxy route them locally at all (see
666
+ * `launchSecret` below).
667
+ *
668
+ * The two wire formats also disagree about where the version prefix lives,
669
+ * so the local provider's base URL is the proxy ORIGIN and each
670
+ * Copilot-served row overrides it with the `/v1` root.
984
671
  */
985
672
  function buildPiModelsJson(opts) {
986
- const baseUrl = `${opts.serverUrl.replace(/\/+$/, "")}/v1`;
987
- const providerApi = opts.api ?? "openai-responses";
673
+ const origin = opts.serverUrl.replace(/\/+$/, "");
674
+ const local = isLocalFamily(opts.profileId);
675
+ const responsesBaseUrl = `${origin}/v1`;
676
+ const providerBaseUrl = local ? origin : responsesBaseUrl;
677
+ const providerApi = opts.api ?? (local ? "anthropic-messages" : "openai-responses");
678
+ const localTierIds = new Set(Object.values(LOCAL_PROFILE_TIER_MODELS));
679
+ const sessionId = opts.sessionId?.trim();
680
+ const launchSecret = opts.launchSecret?.trim();
681
+ const localHeaders = local && (sessionId || launchSecret) ? {
682
+ ...sessionId ? { "x-claude-code-session-id": sessionId } : {},
683
+ ...launchSecret ? { [LAUNCH_SECRET_HEADER]: launchSecret } : {}
684
+ } : void 0;
988
685
  return { providers: { [PI_PROVIDER_NAME]: {
989
- baseUrl,
686
+ baseUrl: providerBaseUrl,
990
687
  api: providerApi,
991
688
  apiKey: "dummy",
992
689
  authHeader: true,
993
690
  models: piProfileModelIds(opts.profileId, { peers: opts.peers }).map((id) => {
691
+ const isLocalTier = local && localTierIds.has(id);
994
692
  const entry = opts.catalog?.find((m) => m.id === id);
995
693
  const out = entry?.maxOutputTokens;
996
694
  const maxTokens = typeof out === "number" && Number.isFinite(out) && out >= 16 ? Math.floor(out) : PI_MAX_TOKENS_FALLBACK;
997
695
  const endpointApi = piApiForEndpoints(entry?.endpoints);
998
- const override = opts.apiOverrides?.[id] ?? endpointApi;
696
+ const override = local ? isLocalTier ? void 0 : "openai-responses" : opts.apiOverrides?.[id] ?? endpointApi;
999
697
  const thinkingLevelMap = piThinkingLevelMapFor(entry?.efforts);
1000
698
  const inputLimits = piImageResizeFor(entry?.vision, entry?.maxImageBytes);
1001
699
  return {
@@ -1006,9 +704,11 @@ function buildPiModelsJson(opts) {
1006
704
  contextWindow: piContextWindowFor(id, entry?.maxContextTokens),
1007
705
  maxTokens,
1008
706
  ...entry?.cost ? { cost: entry.cost } : {},
707
+ ...isLocalTier && localHeaders ? { headers: localHeaders } : {},
1009
708
  ...thinkingLevelMap ? { thinkingLevelMap } : {},
1010
709
  ...inputLimits ? { inputLimits } : {},
1011
- ...override && override !== providerApi ? { api: override } : {}
710
+ ...override && override !== providerApi ? { api: override } : {},
711
+ ...local && !isLocalTier ? { baseUrl: responsesBaseUrl } : {}
1012
712
  };
1013
713
  })
1014
714
  } } };
@@ -1066,6 +766,12 @@ function derivePiCompactionSettings(catalog, modelIds) {
1066
766
  */
1067
767
  const PI_COSMETIC_SETTING_KEYS = [
1068
768
  "hideThinkingBlock",
769
+ "tuiMode",
770
+ "quietStartup",
771
+ "fullscreenExitOutput",
772
+ "fullscreenScrollbar",
773
+ "fullscreenCopyOnSelect",
774
+ "fullscreenWheelScrollLines",
1069
775
  "theme",
1070
776
  "themeAdaptive",
1071
777
  "groupToolCalls",
@@ -1108,8 +814,6 @@ function applyCosmeticUserOverrides(userSettings, builtSettings) {
1108
814
  * no statusline/footer package (built into `local:gh-router-pi`), no
1109
815
  * compaction replacers, no provider/model overriders.
1110
816
  *
1111
- * - `pi-mcp-adapter`: MCP servers as one proxy tool instead of hundreds
1112
- * of definitions (context/cost win).
1113
817
  * - `pi-web-access`: search/fetch/PDF-extract fallback. Only wired when
1114
818
  * the launch has neither `--search` nor `--browse`, otherwise it
1115
819
  * double-pays our ColBERT/browser surfaces.
@@ -1124,11 +828,6 @@ function applyCosmeticUserOverrides(userSettings, builtSettings) {
1124
828
  * shipping it only buys noise. `@file` mentions + the `context`
1125
829
  * dashboard + `read`/`ls`/`find` cover the need.
1126
830
  */
1127
- const PI_HELPERS_MCP_ADAPTER = {
1128
- source: "npm:pi-mcp-adapter",
1129
- skills: [],
1130
- prompts: []
1131
- };
1132
831
  const PI_HELPERS_WEB_ACCESS = {
1133
832
  source: "npm:pi-web-access",
1134
833
  skills: [],
@@ -1204,9 +903,13 @@ const PI_DEFAULT_TOOLS = Object.freeze([
1204
903
  * (skills/prompts filtered out — the mode's own skills/prompts cover
1205
904
  * the roster, so the third-party sets never reach Ctrl+O).
1206
905
  * The helpful bundle rides `helpers` (default on, peers-gated):
1207
- * `pi-mcp-adapter` + allowlisted `pi-agent-extensions` always, plus
1208
- * `pi-web-access` only when neither search nor browse is on (otherwise
1209
- * it double-pays our ColBERT/browser surfaces). The `--ui` bundle
906
+ * allowlisted `pi-agent-extensions` always, plus `pi-web-access` only
907
+ * when neither search nor browse is on (otherwise it double-pays our
908
+ * ColBERT/browser surfaces). `pi-mcp-adapter` is deliberately NOT in the
909
+ * bundle any more: an installed extension that registers `/mcp` replaces
910
+ * Pi's built-in MCP, and the router's scoped groups are published through
911
+ * native MCP (`<mirror>/mcp.json`) precisely so the model gets
912
+ * `tool_search` and the `mcp_servers` roster. The `--ui` bundle
1210
913
  * (`pi-code`, `pi-claude-code-ui`) is opt-in.
1211
914
  * The statusline footer is built into `local:gh-router-pi` (no
1212
915
  * third-party statusline package: the community bridge reads only the
@@ -1245,6 +948,12 @@ function buildPiSettingsJson(opts) {
1245
948
  },
1246
949
  transport: "auto",
1247
950
  hideThinkingBlock: true,
951
+ tuiMode: "regular",
952
+ quietStartup: true,
953
+ fullscreenExitOutput: "transcript",
954
+ fullscreenScrollbar: "auto",
955
+ fullscreenCopyOnSelect: true,
956
+ fullscreenWheelScrollLines: "auto",
1248
957
  ...ui ? {
1249
958
  themeAdaptive: false,
1250
959
  groupToolCalls: true,
@@ -1271,7 +980,7 @@ function buildPiSettingsJson(opts) {
1271
980
  skills: [],
1272
981
  prompts: []
1273
982
  }] : [],
1274
- ...helpers ? [PI_HELPERS_MCP_ADAPTER, PI_HELPERS_AGENT_EXTENSIONS] : [],
983
+ ...helpers ? [PI_HELPERS_AGENT_EXTENSIONS] : [],
1275
984
  ...webAccess ? [PI_HELPERS_WEB_ACCESS] : [],
1276
985
  ...ui ? [...PI_UI_PACKAGES, PI_CC_THEME_PACKAGE] : [],
1277
986
  "local:gh-router-pi"
@@ -1450,7 +1159,7 @@ function buildPiLaunchCard(opts) {
1450
1159
  if (opts.swe) surface.push("swe");
1451
1160
  if (opts.search) surface.push("search");
1452
1161
  if (opts.browse) surface.push("browse");
1453
- for (const group of opts.azureGroups ?? []) surface.push(group);
1162
+ for (const group of opts.mcpGroups ?? []) if (!surface.includes(group)) surface.push(group);
1454
1163
  const identity = [
1455
1164
  opts.accountType,
1456
1165
  opts.login,
@@ -1478,7 +1187,7 @@ function buildPiAppendSystem(profileId, opts = {}) {
1478
1187
  ];
1479
1188
  if (peers) lines.push(`- Delegate FREELY to Explore for discovery and General-Purpose for scoped work.`, `- Call subagent directly (agent + task); save workflows for genuinely parallel fanout.`, isBalancedFamily(profileId) ? `- Send work to reviewer ONLY when the change alters behavior.` : `- Send finished work to reviewer for assessment.`, `- Ask oracle for a second opinion when the decision itself feels risky.`, advisor ? `- Review the final plan with advisor (advisory) before presenting it.` : `- There is no advisor in this mode: oracle is the only consultant.`, `- Verify, don't vote: consultant verdicts never substitute for running the tests.`, `- After any subagent work completes, always write the final answer yourself.`);
1480
1189
  else lines.push(`- Peerless launch: no subagents or consultants in this session; plan, implement, and verify directly.`);
1481
- if (advisor) lines.push("", CHEAPEST_CONSULT_CONTRACT.trimEnd());
1190
+ if (advisor) lines.push("", FRESH_CONSULT_CONTRACT.trimEnd());
1482
1191
  lines.push("", `(${PI_MIN_VERSION_NOTE})`, "");
1483
1192
  return lines.join("\n");
1484
1193
  }
@@ -1488,13 +1197,19 @@ function buildPiAppendSystem(profileId, opts = {}) {
1488
1197
  * The gh-router Pi extension source, generated per launch into the
1489
1198
  * isolated mirror (`extensions/gh-router-pi/index.ts`).
1490
1199
  *
1491
- * Design (Pi-cooperative): executable seams only — oracle/advisor
1492
- * consult, semantic search, and browser dispatch all POST JSON-RPC
1493
- * `tools/call` to the running proxy's `/mcp/<group>` with the
1494
- * per-launch nonce (the same `GH_ROUTER_HOOK_MCP_URL/NONCE` channel the
1495
- * Claude hooks use), then return the text. No custom provider, no
1496
- * compaction replacement: `session_before_compact` only routes the
1497
- * summary model and always falls back to Pi native on failure.
1200
+ * Design (Pi-cooperative): executable seams only. Model-facing tools are
1201
+ * NOT registered here — every scoped MCP group is published as a native Pi
1202
+ * server in the mirror's `mcp.json` (`src/lib/pi-mcp-config.ts`), which
1203
+ * brings `tool_search`, the `mcp_servers` roster and per-server `exposure`
1204
+ * that a hand-wrapped `registerTool` cannot. What stays is the work no MCP
1205
+ * server can do: the statusline footer, the memory bridge, and (cheapest
1206
+ * family only) the prompt-submit relay, which POSTs JSON-RPC `tools/call`
1207
+ * to the running proxy with the per-launch nonce (the same
1208
+ * `GH_ROUTER_HOOK_MCP_URL/NONCE` channel the Claude hooks use).
1209
+ *
1210
+ * No custom provider, no compaction replacement: `session_before_compact`
1211
+ * only routes the summary model and always falls back to Pi native on
1212
+ * failure.
1498
1213
  *
1499
1214
  * Statusline footer (always on): this extension owns Pi's footer and
1500
1215
  * renders the SAME `internal-aic-status` runner Claude Code uses, fed a
@@ -1843,83 +1558,32 @@ function buildPiMemoryBridgeSection(bridge) {
1843
1558
  ];
1844
1559
  }
1845
1560
  function buildPiExtensionSource(opts) {
1846
- const peers = opts.peers !== false;
1847
- const advisor = peers ? piAdvisorModel(opts.profileId) : void 0;
1848
1561
  const promptBrief = isCheapestFamily(opts.profileId);
1849
1562
  const lines = [];
1850
- lines.push(`// gh-router-pi extension (${opts.profileId} mode). Generated per launch; do not edit.`, `// Executable seams only. Workflow guidance lives in skills/, not here.`, `import { Type } from "typebox";`, `import { spawn } from "node:child_process";`, ``, ...peers ? [
1851
- `const OracleParams = Type.Object({`,
1852
- ` decision: Type.String({ description: "The risky decision to get a second opinion on" }),`,
1853
- ` options: Type.Optional(Type.String({ description: "Options considered" })),`,
1854
- ` context: Type.String({ description: "Missing-context gaps and background the cold-start oracle needs" }),`,
1855
- `});`
1856
- ] : [], ...advisor ? [
1857
- `const AdvisorParams = Type.Object({`,
1858
- ` plan: Type.String({ description: "The final plan to review (advisory)" }),`,
1859
- ` context: Type.Optional(Type.String({ description: "Background context" })),`,
1860
- `});`
1861
- ] : [], ...opts.searchEnabled ? [
1862
- `const CodeSearchParams = Type.Object({`,
1863
- ` query: Type.String({ description: "What to find" }),`,
1864
- ` mode: Type.Optional(Type.String({ description: "semantic (default), lexical, exact, regex, or ast" })),`,
1865
- ` limit: Type.Optional(Type.Number({ description: "Max results" })),`,
1866
- ` workspace: Type.Optional(Type.String({ description: "Absolute path to the project root to search. Defaults to the launch workspace." })),`,
1867
- ` file_glob: Type.Optional(Type.String({ description: "Optional ripgrep glob filter (e.g. src/**/*.ts)" })),`,
1868
- `});`
1869
- ] : [], ...opts.browseEnabled ? [
1870
- `const OpenTabParams = Type.Object({`,
1871
- ` url: Type.String({ description: "URL to load" }),`,
1872
- ` reuseActive: Type.Optional(Type.Boolean({ description: "Navigate the active tab instead of opening a new one" })),`,
1873
- `});`,
1874
- `const NavigateParams = Type.Object({`,
1875
- ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1876
- ` action: Type.String({ description: "goto, back, forward, or reload" }),`,
1877
- ` url: Type.Optional(Type.String({ description: "URL for action=goto" })),`,
1878
- ` hard: Type.Optional(Type.Boolean({ description: "Reload only: bypass cache" })),`,
1879
- `});`,
1880
- `const ScreenshotParams = Type.Object({`,
1881
- ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1882
- ` format: Type.Optional(Type.String({ description: "png or jpeg" })),`,
1883
- ` quality: Type.Optional(Type.Number({ description: "JPEG quality 1-100" })),`,
1884
- `});`,
1885
- `const ActParams = Type.Object({`,
1886
- ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1887
- ` intent: Type.Optional(Type.String({ description: "Natural-language action (INTENT mode)" })),`,
1888
- ` ref: Type.Optional(Type.String({ description: "Element ref for REF mode" })),`,
1889
- ` action: Type.Optional(Type.String({ description: "REF mode action" })),`,
1890
- ` value: Type.Optional(Type.String({ description: "Value for fill/type/select" })),`,
1891
- `});`,
1892
- `const ObserveParams = Type.Object({`,
1893
- ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1894
- ` intent: Type.Optional(Type.String({ description: "Focus for the summary" })),`,
1895
- `});`,
1896
- `const ExtractParams = Type.Object({`,
1897
- ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1898
- ` schema: Type.Any({ description: "JSON schema for the desired output shape" }),`,
1899
- ` instruction: Type.String({ description: "What to extract" }),`,
1900
- `});`
1901
- ] : [], `function stripNul(s) { return String(s ?? "").replace(/\\0/g, ""); }`, `async function toolText(promise) {`, ` const text = await promise;`, ` return { content: [{ type: "text", text: stripNul(text) }], details: undefined };`, `}`, `function toolErrorText(text) {`, ` return { content: [{ type: "text", text }], details: undefined };`, `}`, `const MCP_URL = (process.env.GH_ROUTER_HOOK_MCP_URL ?? "").replace(/\\/+$/, "");`, `const MCP_NONCE = process.env.GH_ROUTER_HOOK_NONCE ?? "";`, `const PI_WORKSPACE = (process.env.GH_ROUTER_WORKSPACE ?? "").trim();`, ...promptBrief ? [`const BRIEF_TIMEOUT_MS = 45000;`] : [], `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`, `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`, `void LEAD_MODEL; void LEAD_THINKING;`, ``, `async function callMcp(group, tool, args, signal) {`, ` const headers = { "content-type": "application/json", accept: "application/json", authorization: "Bearer " + MCP_NONCE };`, ` if (PI_WORKSPACE && (group === "search" || group === "workers" || group === "orchestrate")) { headers["X-GH-Workspace"] = PI_WORKSPACE; }`, ` const res = await fetch(MCP_URL + "/mcp/" + group, {`, ` method: "POST",`, ` headers,`, ` body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } }),`, ` signal,`, ` });`, ` if (!res.ok) throw new Error("mcp " + group + "/" + tool + " -> HTTP " + res.status);`, ` const body = await res.json();`, ` if (body.error) return "Error: " + body.error.message;`, ` const content = body.result && body.result.content;`, ` if (!Array.isArray(content)) return "";`, ` return content.map((c) => c.text || "").join("\\n");`, `}`, ``, `export default function (pi) {`, ...peers ? [
1902
- ` pi.registerTool({`,
1903
- ` name: "oracle",`,
1904
- ` label: "Oracle",`,
1905
- ` description: "Second opinion before acting on a risky decision. Advisory only: challenges assumptions, never edits. Pass decision, options, and context.",`,
1906
- ` parameters: OracleParams,`,
1907
- ` async execute(_toolCallId, params, signal) {`,
1908
- ` const query = stripNul(params.decision || "").trim();`,
1909
- ` const opts = stripNul(params.options || "").trim();`,
1910
- ` const ctx = stripNul(params.context || "").trim();`,
1911
- ` const context = (opts ? "Options considered:\\n" + opts + "\\n\\n" : "") + ctx;`,
1912
- ` if (!query || !context.trim()) return toolErrorText("oracle: decision and context are required (non-empty strings)");`,
1913
- ` return await toolText(callMcp("peers", "oracle", { query, context }, signal));`,
1914
- ` },`,
1915
- ` });`
1916
- ] : []);
1917
- if (advisor) lines.push(` pi.registerTool({`, ` name: "advisor",`, ` label: "Advisor",`, ` description: "Advisory plan review for the lead: review the final plan before presenting it. Never executes.",`, ` parameters: AdvisorParams,`, ` async execute(_toolCallId, params, signal) {`, ` const plan = stripNul(params.plan || "").trim();`, ` const ctx = stripNul(params.context || "").trim();`, ` const context = (plan ? "Plan under review:\\n" + plan : "") + (ctx ? "\\n\\nBackground:\\n" + ctx : "");`, ` if (!plan || !context.trim()) return toolErrorText("advisor: plan and context are required (non-empty strings)");`, ` return await toolText(callMcp("peers", "oracle", { query: "Review this plan (advisory)", context }, signal));`, ` },`, ` });`);
1918
- if (opts.searchEnabled) {
1919
- const codeSearchDescription = opts.searchBackend === "bluebird" ? "Search the indexed Azure DevOps code for this repository (Bluebird). Modes semantic and lexical answer from the remote index and have NO local fallback: a failure returns source \\\"error\\\" and zero results, which means the search did not run, not that nothing matched. Use mode exact/regex/ast for the local engine." : "Semantic-first code search over the workspace index (falls back to lexical with a label). Use for finding code by meaning.";
1920
- lines.push(` pi.registerTool({`, ` name: "code_search",`, ` label: "Code search",`, ` description: "${codeSearchDescription}",`, ` parameters: CodeSearchParams,`, ` async execute(_toolCallId, params, signal) {`, ` const query = stripNul(params.query || "").trim();`, ` if (!query) return toolErrorText("code_search: query is required (non-empty string)");`, ` const workspace = (typeof params.workspace === "string" && params.workspace.trim()) ? params.workspace.trim() : PI_WORKSPACE;`, ` if (!workspace) return toolErrorText("code_search: a workspace is required. Pass the absolute project path as workspace.");`, ` const args = { query, mode: params.mode || "semantic", limit: params.limit || 15, workspace };`, ` if (typeof params.file_glob === "string" && params.file_glob) args.file_glob = params.file_glob;`, ` return await toolText(callMcp("search", "code", args, signal));`, ` },`, ` });`);
1921
- }
1922
- if (opts.browseEnabled) lines.push(` pi.registerTool({`, ` name: "open_tab",`, ` label: "Browser open tab",`, ` description: "Open a URL in a new browser tab (MCP browser/open_tab). Returns install_required with setup steps when the extension is not loaded.",`, ` parameters: OpenTabParams,`, ` async execute(_toolCallId, params, signal) {`, ` const url = stripNul(params.url || "").trim();`, ` if (!url) return toolErrorText("open_tab: url is required");`, ` const args = { url };`, ` if (typeof params.reuseActive === "boolean") args.reuseActive = params.reuseActive;`, ` return await toolText(callMcp("browser", "open_tab", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "navigate",`, ` label: "Browser navigate",`, ` description: "Navigate an existing tab (MCP browser/navigate). Requires tabId + action; url only for action=goto.",`, ` parameters: NavigateParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("navigate: tabId is required (number from open_tab)");`, ` if (!params.action) return toolErrorText("navigate: action is required (goto, back, forward, reload)");`, ` const args = { tabId: params.tabId, action: params.action };`, ` if (typeof params.url === "string" && params.url) args.url = params.url;`, ` if (typeof params.hard === "boolean") args.hard = params.hard;`, ` return await toolText(callMcp("browser", "navigate", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "screenshot",`, ` label: "Browser screenshot",`, ` description: "Screenshot a tab (MCP browser/screenshot). Requires tabId.",`, ` parameters: ScreenshotParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("screenshot: tabId is required (number from open_tab)");`, ` const args = { tabId: params.tabId };`, ` if (typeof params.format === "string" && params.format) args.format = params.format;`, ` if (typeof params.quality === "number") args.quality = params.quality;`, ` return await toolText(callMcp("browser", "screenshot", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "act",`, ` label: "Browser act",`, ` description: "Interact with a tab (MCP browser/act). Requires tabId plus intent or ref.",`, ` parameters: ActParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("act: tabId is required (number from open_tab)");`, ` if (!params.intent && !params.ref) return toolErrorText("act: intent or ref is required");`, ` const args = { tabId: params.tabId };`, ` if (typeof params.intent === "string" && params.intent) args.intent = params.intent;`, ` if (typeof params.ref === "string" && params.ref) args.ref = params.ref;`, ` if (typeof params.action === "string" && params.action) args.action = params.action;`, ` if (typeof params.value === "string") args.value = params.value;`, ` return await toolText(callMcp("browser", "act", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "observe",`, ` label: "Browser observe",`, ` description: "Summarize a tab (MCP browser/observe). Requires tabId.",`, ` parameters: ObserveParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("observe: tabId is required (number from open_tab)");`, ` const args = { tabId: params.tabId };`, ` if (typeof params.intent === "string" && params.intent) args.intent = params.intent;`, ` return await toolText(callMcp("browser", "observe", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "extract",`, ` label: "Browser extract",`, ` description: "Extract structured data from a tab (MCP browser/extract). Requires tabId, schema, instruction.",`, ` parameters: ExtractParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("extract: tabId is required (number from open_tab)");`, ` if (!params.instruction) return toolErrorText("extract: instruction is required");`, ` if (params.schema === undefined) return toolErrorText("extract: schema is required");`, ` return await toolText(callMcp("browser", "extract", { tabId: params.tabId, schema: params.schema, instruction: params.instruction }, signal));`, ` },`, ` });`);
1563
+ lines.push(`// gh-router-pi extension (${opts.profileId} mode). Generated per launch; do not edit.`, `// Executable seams only. Workflow guidance lives in skills/, not here.`, `import { spawn } from "node:child_process";`, ``, `function stripNul(s) { return String(s ?? "").replace(/\\0/g, ""); }`, ...promptBrief ? [
1564
+ `const MCP_URL = (process.env.GH_ROUTER_HOOK_MCP_URL ?? "").replace(/\\/+$/, "");`,
1565
+ `const MCP_NONCE = process.env.GH_ROUTER_HOOK_NONCE ?? "";`,
1566
+ `const PI_WORKSPACE = (process.env.GH_ROUTER_WORKSPACE ?? "").trim();`,
1567
+ `const BRIEF_TIMEOUT_MS = 45000;`
1568
+ ] : [], `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`, `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`, `void LEAD_MODEL; void LEAD_THINKING;`, ``, ...promptBrief ? [
1569
+ `async function callMcp(group, tool, args, signal) {`,
1570
+ ` const headers = { "content-type": "application/json", accept: "application/json", authorization: "Bearer " + MCP_NONCE };`,
1571
+ ` if (PI_WORKSPACE) { headers["X-GH-Workspace"] = PI_WORKSPACE; }`,
1572
+ ` const res = await fetch(MCP_URL + "/mcp/" + group, {`,
1573
+ ` method: "POST",`,
1574
+ ` headers,`,
1575
+ ` body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } }),`,
1576
+ ` signal,`,
1577
+ ` });`,
1578
+ ` if (!res.ok) throw new Error("mcp " + group + "/" + tool + " -> HTTP " + res.status);`,
1579
+ ` const body = await res.json();`,
1580
+ ` if (body.error) return "Error: " + body.error.message;`,
1581
+ ` const content = body.result && body.result.content;`,
1582
+ ` if (!Array.isArray(content)) return "";`,
1583
+ ` return content.map((c) => c.text || "").join("\\n");`,
1584
+ `}`,
1585
+ ``
1586
+ ] : [], `export default function (pi) {`);
1923
1587
  if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
1924
1588
  lines.push(...buildPiStatuslineFooterSection(), ` // 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 ? [
1925
1589
  ` // Cheapest-profile execution brief, injected ABOVE the model's turn.`,
@@ -1986,24 +1650,36 @@ function buildPiExtensionSource(opts) {
1986
1650
  function buildPiSkills(opts) {
1987
1651
  const peers = opts.peers !== false;
1988
1652
  const skills = [];
1989
- if (peers) skills.push({
1990
- dir: "gh-oracle",
1991
- content: [
1992
- "---",
1993
- "name: gh-oracle",
1994
- "description: Consult the oracle for a second opinion on risky decisions. Use when the decision itself feels risky.",
1995
- "---",
1996
- "",
1997
- "# Oracle consult",
1998
- "",
1999
- "Call the `oracle` tool with the decision, the options considered, and the",
2000
- "missing-context gaps. The oracle is cold-start: it sees only what you pass.",
2001
- "Its verdict is advisory — verify with tests and code, never substitute votes",
2002
- "for verification. (The `oracle` tool is the one-shot consult; the `oracle`",
2003
- "subagent is the same role for interactive follow-ups — same name, different",
2004
- "invocation. Prefer the tool for a single verdict.)"
2005
- ].join("\n")
2006
- });
1653
+ if (peers) {
1654
+ const oracleBody = piOracleToolReachable(opts.profileId) ? [
1655
+ "Call `mcp__gh-router-peers__oracle` (load it with `tool_search` if it is",
1656
+ "not in the tool list yet) with the decision, the options considered, and",
1657
+ "the missing-context gaps. The oracle is cold-start: it sees only what you",
1658
+ "pass. Its verdict is advisory — verify with tests and code, never",
1659
+ "substitute votes for verification. (The MCP tool is the one-shot consult;",
1660
+ "the `oracle` subagent is the same role for interactive follow-ups — same",
1661
+ "name, different invocation. Prefer the tool for a single verdict.)"
1662
+ ] : [
1663
+ "Delegate to the `oracle` subagent through the `subagent` tool with the",
1664
+ "decision, the options considered, and the missing-context gaps. The",
1665
+ "oracle is cold-start: it sees only what you pass, plus whatever it reads",
1666
+ "itself. Its verdict is advisory — verify with tests and code, never",
1667
+ "substitute votes for verification."
1668
+ ];
1669
+ skills.push({
1670
+ dir: "gh-oracle",
1671
+ content: [
1672
+ "---",
1673
+ "name: gh-oracle",
1674
+ "description: Consult the oracle for a second opinion on risky decisions. Use when the decision itself feels risky.",
1675
+ "---",
1676
+ "",
1677
+ "# Oracle consult",
1678
+ "",
1679
+ ...oracleBody
1680
+ ].join("\n")
1681
+ });
1682
+ }
2007
1683
  if (opts.search === true) skills.push({
2008
1684
  dir: "gh-search-first",
2009
1685
  content: [
@@ -2014,14 +1690,15 @@ function buildPiSkills(opts) {
2014
1690
  "",
2015
1691
  "# Search first",
2016
1692
  "",
2017
- "Use `code_search` (semantic by default) before broad reads. The response",
2018
- "labels its `source`: `semantic`, `lexical`, or `lexical-fallback` — a",
2019
- "fallback is never silent, so retry narrower on fallback rather than",
2020
- "assuming full coverage."
1693
+ "Use `mcp__gh-router-search__code` (semantic by default; load it with",
1694
+ "`tool_search` if it is not in the tool list yet) before broad reads. The",
1695
+ "response labels its `source`: `semantic`, `lexical`, or",
1696
+ "`lexical-fallback` — a fallback is never silent, so retry narrower on",
1697
+ "fallback rather than assuming full coverage."
2021
1698
  ].join("\n")
2022
1699
  });
2023
1700
  if (opts.swe === true && peers) {
2024
- const consults = isBalancedFamily(opts.profileId) ? "`oracle` for consults" : "`oracle`/`advisor` for consults";
1701
+ const consults = piAdvisorModel(opts.profileId) ? "`oracle`/`advisor` for consults" : "`oracle` for consults";
2025
1702
  skills.push({
2026
1703
  dir: "gh-delegate",
2027
1704
  content: [
@@ -2059,7 +1736,7 @@ function buildPiSkills(opts) {
2059
1736
  "# Advisor review",
2060
1737
  "",
2061
1738
  "The lead plans directly (there is no Plan subagent). Review the final plan",
2062
- "with the `advisor` tool before presenting it. Advisory only: it never",
1739
+ "with the `advisor` subagent before presenting it. Advisory only: it never",
2063
1740
  "executes and never overrides verification."
2064
1741
  ].join("\n")
2065
1742
  });
@@ -2105,7 +1782,7 @@ function buildPiPrompts(opts) {
2105
1782
  "description: Advisory review of the current plan before presenting",
2106
1783
  "argument-hint: \"[plan]\"",
2107
1784
  "---",
2108
- "Review the final plan with the advisor tool (advisory) before presenting it: ${1:-the current plan}."
1785
+ "Review the final plan with the advisor subagent (advisory) before presenting it: ${1:-the current plan}."
2109
1786
  ].join("\n")
2110
1787
  });
2111
1788
  return prompts;
@@ -2115,22 +1792,28 @@ function buildPiPrompts(opts) {
2115
1792
  /**
2116
1793
  * Pi's MCP surface for the router's scoped groups.
2117
1794
  *
2118
- * `<Pi agent dir>/mcp.json` is Pi's own MCP configuration (the file `pi mcp add`
2119
- * writes), and `pi-mcp-adapter` reads it as a compatibility input on Pi 0.99+.
2120
- * Pi's agent dir in a router launch IS the per-launch mirror
2121
- * (`PI_CODING_AGENT_DIR`, `getPiLaunchEnvVars`), so this file is per-launch and
2122
- * swept with the mirror. Nothing here touches the user's real `~/.pi/agent`.
1795
+ * `<Pi agent dir>/mcp.json` is Pi's OWN MCP configuration: built-in MCP reads
1796
+ * it at session start (`builtin:mcp`, Pi 0.99+), and the router's agent dir in
1797
+ * a Pi launch IS the per-launch mirror (`PI_CODING_AGENT_DIR`,
1798
+ * `getPiLaunchEnvVars`), so this file is per-launch and swept with the mirror.
1799
+ * Nothing here touches the user's real `~/.pi/agent`.
1800
+ *
1801
+ * Built-in MCP is why `pi-mcp-adapter` is gone from the helper bundle. Per Pi's
1802
+ * own `docs/mcp.md`, an installed extension that registers `/mcp` REPLACES
1803
+ * built-in MCP for the session, and Pi then never reads this file at all. The
1804
+ * adapter was a prerequisite for MCP before native support landed and is a
1805
+ * blocker for it now, so the two cannot coexist.
2123
1806
  *
2124
- * Precedence is the reason every key carries the `gh-router-` prefix. In the
2125
- * adapter's load order the mirror file is #4, while `.mcp.json` (#7),
2126
- * `.pi/mcp.json` (#8) and `.pi/mcp-adapter.json` (#9) all win over it and
2127
- * replace a same-named server as a whole. Keying a group as `ado` would
1807
+ * Precedence is the reason every key carries the `gh-router-` prefix. Native Pi
1808
+ * reads user-level servers from this file and project servers from
1809
+ * `.pi/mcp.json` (once the project is trusted), and a project entry replaces a
1810
+ * same-named user-level entry as a whole. Keying a group as `ado` would
2128
1811
  * therefore hand the model the workspace's own `ado` server under a name we
2129
1812
  * meant for ours; `gh-router-ado` cannot be shadowed by accident.
2130
1813
  *
2131
1814
  * The bearer is written as an interpolation placeholder rather than a literal:
2132
- * the adapter expands `${VAR}` in `headers` from the child environment at
2133
- * connection time, and `GH_ROUTER_HOOK_NONCE` is already in the Pi launch env
1815
+ * Pi expands `${VAR}` in `headers` from the child environment at connection
1816
+ * time, and `GH_ROUTER_HOOK_NONCE` is already in the Pi launch env
2134
1817
  * (`src/pi.ts`). A literal token would put a live secret on disk for the life
2135
1818
  * of the mirror.
2136
1819
  *
@@ -2139,8 +1822,34 @@ function buildPiPrompts(opts) {
2139
1822
  */
2140
1823
  /** Key prefix reserved for router-owned entries. Never emit a bare group name. */
2141
1824
  const PI_MCP_SERVER_PREFIX = "gh-router-";
2142
- /** Placeholder the adapter expands from the Pi child env at connect time. */
1825
+ /** Placeholder Pi expands from the Pi child env at connect time. */
2143
1826
  const PI_MCP_NONCE_PLACEHOLDER = "Bearer ${GH_ROUTER_HOOK_NONCE}";
1827
+ /**
1828
+ * Workspace header placeholder.
1829
+ *
1830
+ * Native MCP sends no workspace of its own, and the worker tools refuse a call
1831
+ * that names neither an explicit `workspace` argument nor this header. The
1832
+ * generated extension set it by hand on its own `search`/`workers`/
1833
+ * `orchestrate` calls; with those calls gone, the header has to ride the server
1834
+ * entry or every worker call fails for want of a workspace. Sent on every
1835
+ * group: the proxy ignores it where it is unused.
1836
+ */
1837
+ const PI_MCP_WORKSPACE_PLACEHOLDER = "${GH_ROUTER_WORKSPACE}";
1838
+ /**
1839
+ * Deferred, not direct.
1840
+ *
1841
+ * `deferred` keeps the tools out of the declared tool set until `tool_search`
1842
+ * loads a match, which Pi activates automatically for a deferred server. Two
1843
+ * reasons this is the right default rather than `direct`:
1844
+ *
1845
+ * - every group is listed in the `mcp_servers` system-prompt section with its
1846
+ * `description`, so discovery is intact without paying the declaration cost
1847
+ * of ~60 tools on every request;
1848
+ * - Pi waits up to 10 s at the first prompt for servers with `direct` tools
1849
+ * to connect. `deferred` servers are not in that wait, so a slow or absent
1850
+ * proxy cannot stall the session.
1851
+ */
1852
+ const PI_MCP_EXPOSURE = "deferred";
2144
1853
  /** Router-owned server key for a scoped group, e.g. `ado` -> `gh-router-ado`. */
2145
1854
  function piMcpServerKey(group) {
2146
1855
  return `${PI_MCP_SERVER_PREFIX}${group}`;
@@ -2163,16 +1872,49 @@ function readMcpServerKeys(raw) {
2163
1872
  }
2164
1873
  }
2165
1874
  /**
2166
- * The adapter forwards `description` verbatim, so this is the model's only
2167
- * pre-search signal for what a server is. Kept to what every tool in the group
2168
- * actually does; read-only is a property of the group's default surface, not a
2169
- * promise about every call.
1875
+ * Under `deferred` exposure this line is the model's ONLY pre-search signal for
1876
+ * what a server is, so each one says what the group does and when to reach for
1877
+ * it rather than naming the server back at the model.
1878
+ *
1879
+ * Only the seven groups a Pi profile can reach are listed. `orchestrate`,
1880
+ * `decide`, `fleet` and `first-mate` sit outside every Pi profile's
1881
+ * `allowedGroups` (`src/lib/launch-profile.ts`), so `resolvePiSurfaces` can
1882
+ * never emit them and a description for them would be dead text.
2170
1883
  */
2171
1884
  const GROUP_DESCRIPTIONS = {
1885
+ peers: "Cross-lab adversarial reviewers (codex_critic, codex_reviewer, gemini_critic, gemini_reviewer, opus_critic) plus oracle, a stateless expert consultant. Reach for a critic when a plan or a diff needs a second lab's judgement; reach for oracle when repository evidence alone cannot settle a self-contained technical trade-off.",
1886
+ search: "Code and web search for this workspace. code is semantic-first with a labelled lexical fallback and reports which engine answered; web runs a Copilot-backed web search. Reach for code before broad file reads when you are locating code by meaning rather than by exact text.",
1887
+ workers: "Autonomous worker subagents that run their own agent loop on a scoped task: explore reads and searches, review also runs commands to verify, implement edits files in an isolated git worktree and returns the diff. Reach for a worker when the task is big enough that its context should not land in yours.",
1888
+ browser: "Drive a real Chrome or Edge tab: open, navigate, read the page, screenshot, click, type, evaluate JavaScript. Reach for it when the answer lives in a web UI rather than in the repository.",
2172
1889
  ado: "Azure DevOps for the open repository: repositories, work items, pipelines and wikis.",
2173
1890
  kusto: "Azure Data Explorer: query and management commands against the cluster named on each call, or the launch default.",
2174
1891
  cloudagent: "Microsoft Cloud Agent jobs: hand a prompt plus an Azure DevOps repository to a cloud coding agent, then poll it for hours and collect the answer. create_job, create_pr_job and cancel_job spend compute; confirm with the user before creating a job the user did not ask for."
2175
1892
  };
1893
+ /** The `peers` half of `GROUP_DESCRIPTIONS.peers`, split out so the oracle's
1894
+ * availability can be stated rather than assumed. */
1895
+ const PEERS_ORACLE_SENTENCE = "oracle, a stateless expert consultant. Reach for oracle when repository evidence alone cannot settle a self-contained technical trade-off.";
1896
+ /** What the artifact tools do, in the same one-line voice. */
1897
+ const PEERS_ARTIFACT_SENTENCE = "The artifact_* tools open a workspace file in the human review panel and drain the reviewer's comments and actions; reach for them when a human has to look at the result before work continues.";
1898
+ /**
1899
+ * The `peers` description for a profile's persona allow-list.
1900
+ *
1901
+ * `deferred` exposure makes this line the model's only pre-search signal, so
1902
+ * it may name only personas the MCP handler will actually answer: every
1903
+ * pinned profile registers a list (`undefined` means unrestricted), and
1904
+ * naming a critic a filtered launch answers with -32601 wastes the model's
1905
+ * turn. The critics are named only on an unrestricted surface; the oracle
1906
+ * and the artifact tools are named when their own gates admit them.
1907
+ *
1908
+ * Returns `""` when the group would hold nothing, so the caller can leave the
1909
+ * server unpublished rather than advertise an empty one.
1910
+ */
1911
+ function peersGroupDescription(personas, artifactAvailable) {
1912
+ if (personas === void 0) return GROUP_DESCRIPTIONS.peers;
1913
+ const parts = [];
1914
+ if (personas.has("oracle")) parts.push(PEERS_ORACLE_SENTENCE);
1915
+ if (artifactAvailable) parts.push(PEERS_ARTIFACT_SENTENCE);
1916
+ return parts.join(" ");
1917
+ }
2176
1918
  /**
2177
1919
  * The one place that decides which Pi surfaces this launch emits.
2178
1920
  *
@@ -2182,31 +1924,40 @@ const GROUP_DESCRIPTIONS = {
2182
1924
  * same flag), and the skill prose it would enable is ColBERT-specific. What
2183
1925
  * Bluebird does serve is `code` — `runUnifiedCodeSearch` routes `semantic` and
2184
1926
  * `lexical` through it whenever `state.bluebirdEnabled` is set — so an Azure
2185
- * checkout with Bluebird auto-enabled and no `--search` still deserves the seam.
1927
+ * checkout with Bluebird auto-enabled and no `--search` still deserves the
1928
+ * group.
2186
1929
  *
2187
- * The Azure groups ride the adapter, which only exists when `helpers` and
2188
- * `peers` both hold (`buildPiSettingsJson` adds it as `helpers && peers`).
2189
- * Writing the config without the adapter would leave it inert at best: the file
2190
- * is also Pi's own built-in MCP config, so an ungated write would expose the
2191
- * groups through a backend this path has never validated.
1930
+ * Group selection reproduces the pinned-profile branch of the Claude launcher
1931
+ * (`src/claude.ts`) instead of inventing a second policy, so a Pi session and a
1932
+ * `github-router claude -m cheapest2` session see the same servers:
1933
+ * `peers` (unless `--no-peers`), `search`, `workers` only when the browse agent
1934
+ * is available, `browser` under `--browse`, and the three Azure groups under
1935
+ * their own predicates. Everything is then filtered through
1936
+ * `profileDescriptor(profileId).allowedGroups`, which is
1937
+ * `{peers, search, browser, ado, kusto, cloudagent}` for `local`/`local2` and
1938
+ * adds `workers` for the other four Pi profiles — so `orchestrate`, `decide`,
1939
+ * `fleet` and `first-mate` stay off everywhere.
2192
1940
  */
2193
1941
  function resolvePiSurfaces(opts) {
2194
1942
  const codeSearchBackend = opts.bluebirdEnabled ? "bluebird" : "colbert";
1943
+ const descriptor = profileDescriptor(opts.profileId);
1944
+ const allowed = descriptor.allowedGroups;
2195
1945
  const groups = [];
2196
- if (opts.helpersEnabled && opts.peersEnabled) {
2197
- if (opts.adoEnabled) groups.push({
2198
- group: "ado",
2199
- description: GROUP_DESCRIPTIONS["ado"]
2200
- });
2201
- if (opts.kustoEnabled) groups.push({
2202
- group: "kusto",
2203
- description: GROUP_DESCRIPTIONS["kusto"]
1946
+ const push = (group, description = GROUP_DESCRIPTIONS[group]) => {
1947
+ if (allowed && !allowed.has(group)) return;
1948
+ if (!description) return;
1949
+ groups.push({
1950
+ group,
1951
+ description
2204
1952
  });
2205
- if (opts.cloudAgentEnabled) groups.push({
2206
- group: "cloudagent",
2207
- description: GROUP_DESCRIPTIONS["cloudagent"]
2208
- });
2209
- }
1953
+ };
1954
+ if (opts.peersEnabled) push("peers", peersGroupDescription(descriptor.personaAllowlist, opts.artifactToolsAvailable));
1955
+ push("search");
1956
+ if (opts.browseAgentAvailable) push("workers");
1957
+ if (opts.directBrowserAvailable) push("browser");
1958
+ if (opts.adoEnabled) push("ado");
1959
+ if (opts.kustoEnabled) push("kusto");
1960
+ if (opts.cloudAgentEnabled) push("cloudagent");
2210
1961
  return {
2211
1962
  search: opts.searchEnabled,
2212
1963
  codeSearch: opts.searchEnabled || opts.bluebirdEnabled,
@@ -2222,12 +1973,12 @@ async function readIfPresent(file) {
2222
1973
  return null;
2223
1974
  }
2224
1975
  }
2225
- /** Project-scoped files the adapter reads, in its own precedence order. */
2226
- const PROJECT_MCP_FILES = [
2227
- path.join(".mcp.json"),
2228
- path.join(".pi", "mcp.json"),
2229
- path.join(".pi", "mcp-adapter.json")
2230
- ];
1976
+ /**
1977
+ * The project-scoped file native Pi reads. `.mcp.json` and
1978
+ * `.pi/mcp-adapter.json` were adapter-only inputs and are gone with it: warning
1979
+ * about a file Pi never reads would be a false positive.
1980
+ */
1981
+ const PROJECT_MCP_FILES = [path.join(".pi", "mcp.json")];
2231
1982
  /**
2232
1983
  * Write one remote entry per group into `<mirrorDir>/mcp.json`.
2233
1984
  *
@@ -2269,7 +2020,11 @@ async function writePiMcpJson(opts) {
2269
2020
  nextServers[key] = {
2270
2021
  type: "http",
2271
2022
  url: `${opts.serverUrl}/mcp/${group.group}`,
2272
- headers: { Authorization: PI_MCP_NONCE_PLACEHOLDER },
2023
+ headers: {
2024
+ Authorization: PI_MCP_NONCE_PLACEHOLDER,
2025
+ "X-GH-Workspace": PI_MCP_WORKSPACE_PLACEHOLDER
2026
+ },
2027
+ exposure: PI_MCP_EXPOSURE,
2273
2028
  description: group.description
2274
2029
  };
2275
2030
  }
@@ -2315,7 +2070,15 @@ const piArgs = {
2315
2070
  model: {
2316
2071
  alias: "m",
2317
2072
  type: "string",
2318
- description: "Pi launch profile: cheapest/cheapest2 (Luna-led, cheapest tier) or balanced/balanced2 (Sol-led, most-complex-tasks tier). The `-2` aliases move the Sol tier from 5.6 to 6.1; cheapest2 also raises the Advisor to high, and balanced2's Oracle is Grok 4.7. Only these four aliases are supported for `github-router pi`."
2073
+ description: "Pi launch profile: cheapest/cheapest2 (Luna-led, cheapest tier), balanced/balanced2 (Sol-led, most-complex-tasks tier), or local/local2 (the main loop and every subagent run against a local inference endpoint instead of Copilot; local allows no Copilot model at all, local2 allows only the Advisor and the Oracle, both on Sol). The `-2` aliases move the Sol tier from 5.6 to 6.1; cheapest2 also raises the Advisor to high, and balanced2's Oracle is Grok 4.7. Only these six aliases are supported for `github-router pi`."
2074
+ },
2075
+ localport: {
2076
+ type: "string",
2077
+ description: "Port of the LOCAL MODEL SERVER that `-m local` / `-m local2` forward the main loop to (not the proxy's own --port). Default 11111, giving https://localhost:11111/v1. Inert on every other profile."
2078
+ },
2079
+ localurl: {
2080
+ type: "string",
2081
+ 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."
2319
2082
  },
2320
2083
  "update-check": {
2321
2084
  type: "boolean",
@@ -2335,12 +2098,12 @@ const piArgs = {
2335
2098
  peers: {
2336
2099
  type: "boolean",
2337
2100
  default: true,
2338
- description: "Wire the peer/subagent floor: native agent files, the oracle tool (plus cheapest-family advisor), the gh-oracle skill, and the pi-subagents package. Set to false (--no-peers) for a lead-only session; prereqs then validate the lead model only."
2101
+ description: "Wire the peer/subagent floor: native agent files, the gh-oracle skill, the pi-subagents package, and the gh-router-peers MCP group (the personas and artifact review tools the chosen profile allows). Set to false (--no-peers) for a lead-only session; prereqs then validate the lead model only."
2339
2102
  },
2340
2103
  helpers: {
2341
2104
  type: "boolean",
2342
2105
  default: true,
2343
- description: "Wire the helpful bundle: pi-mcp-adapter, allowlisted pi-agent-extensions (sessions, ask_user, todos, handoff, context, analytics — no review/loop/footer, no files picker so Ctrl+Shift+O stays unambiguous for the UI), and pi-web-access when neither --search nor --browse is on. Set to false (--no-helpers) for pi-subagents + gh-router-pi only."
2106
+ description: "Wire the helpful bundle: allowlisted pi-agent-extensions (sessions, ask_user, todos, handoff, context, analytics — no review/loop/footer, no files picker so Ctrl+Shift+O stays unambiguous for the UI), and pi-web-access when neither --search nor --browse is on. MCP is native Pi MCP now, so no adapter package is bundled. Set to false (--no-helpers) for pi-subagents + gh-router-pi only."
2344
2107
  },
2345
2108
  ui: {
2346
2109
  type: "boolean",
@@ -2407,7 +2170,7 @@ async function writeTextFile(file, content) {
2407
2170
  const pi = defineCommand({
2408
2171
  meta: {
2409
2172
  name: "pi",
2410
- description: "Start the proxy server and launch the Pi coding agent (cheapest/balanced families)"
2173
+ description: "Start the proxy server and launch the Pi coding agent (cheapest/balanced families, or a local model server)"
2411
2174
  },
2412
2175
  args: piArgs,
2413
2176
  async run({ args, rawArgs }) {
@@ -2418,11 +2181,22 @@ const pi = defineCommand({
2418
2181
  }
2419
2182
  const parsed = parseSharedArgs(args);
2420
2183
  const launchProfileId = resolveLaunchProfile(args.model);
2421
- if (!isCheapestFamily(launchProfileId) && !isBalancedFamily(launchProfileId)) {
2422
- process$1.stderr.write(`github-router pi supports only -m cheapest, -m cheapest2, -m balanced, and -m balanced2 (got ${JSON.stringify(args.model ?? "")}).\n`);
2184
+ if (!isCheapestFamily(launchProfileId) && !isBalancedFamily(launchProfileId) && !isLocalFamily(launchProfileId)) {
2185
+ process$1.stderr.write(`github-router pi supports only -m cheapest, -m cheapest2, -m balanced, -m balanced2, -m local, and -m local2 (got ${JSON.stringify(args.model ?? "")}).\n`);
2423
2186
  process$1.exit(1);
2424
2187
  }
2425
2188
  const profileId = launchProfileId;
2189
+ try {
2190
+ configureLocalEgress({
2191
+ ...typeof args.localurl === "string" ? { baseUrl: args.localurl } : {},
2192
+ ...typeof args.localport === "string" ? { port: args.localport } : {},
2193
+ profileId
2194
+ });
2195
+ if (isLocalFamily(profileId)) consola.info(`[local] upstream ${localBaseUrl()}`);
2196
+ } catch (error) {
2197
+ process$1.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
2198
+ process$1.exit(1);
2199
+ }
2426
2200
  let server;
2427
2201
  let serverUrl;
2428
2202
  const updateCheck = args["update-check"] !== false;
@@ -2498,17 +2272,20 @@ const pi = defineCommand({
2498
2272
  const searchEnabled = parsed.searchEnabled || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
2499
2273
  const browseEnabled = browserToolsEnabled();
2500
2274
  const surfaces = resolvePiSurfaces({
2275
+ profileId,
2501
2276
  searchEnabled,
2502
2277
  bluebirdEnabled: state.bluebirdEnabled === true,
2503
2278
  adoEnabled: adoToolsEnabled(),
2504
2279
  kustoEnabled: kustoToolsEnabled(),
2505
2280
  cloudAgentEnabled: cloudAgentToolsEnabled(),
2506
- helpersEnabled,
2281
+ browseAgentAvailable: browseAgentEnabled(),
2282
+ directBrowserAvailable: browseEnabled,
2283
+ artifactToolsAvailable: artifactToolsEnabled(),
2507
2284
  peersEnabled
2508
2285
  });
2509
- const prereqCheck = isCheapestFamily(profileId) ? validateCheapestProfilePrerequisites(state.models, { peers: peersEnabled }, profileId) : validateBalancedProfilePrerequisites(state.models, { peers: peersEnabled }, profileId);
2286
+ const prereqCheck = isLocalFamily(profileId) ? validateLocalProfilePrerequisites(state.models, profileId) : isCheapestFamily(profileId) ? validateCheapestProfilePrerequisites(state.models, { peers: peersEnabled }, profileId) : validateBalancedProfilePrerequisites(state.models, { peers: peersEnabled }, profileId);
2510
2287
  if (!prereqCheck.ok) {
2511
- const message = isCheapestFamily(profileId) ? formatCheapestPrerequisiteFailure(prereqCheck.missing, profileId) : formatBalancedPrerequisiteFailure(prereqCheck.missing, profileId);
2288
+ const message = isLocalFamily(profileId) ? formatLocalPrerequisiteFailure(prereqCheck.missing, profileId, "pi") : isCheapestFamily(profileId) ? formatCheapestPrerequisiteFailure(prereqCheck.missing, profileId) : formatBalancedPrerequisiteFailure(prereqCheck.missing, profileId);
2512
2289
  consola.error(message);
2513
2290
  process$1.stderr.write(`${message}\n`);
2514
2291
  process$1.exit(1);
@@ -2524,6 +2301,7 @@ const pi = defineCommand({
2524
2301
  }
2525
2302
  enableFileLogging();
2526
2303
  let packagesForCache = [];
2304
+ const launchSecret = randomBytes(32).toString("hex");
2527
2305
  try {
2528
2306
  const catalog = state.models?.data.map((m) => {
2529
2307
  const cost = piUsdCostFor(m.billing?.token_prices);
@@ -2543,7 +2321,9 @@ const pi = defineCommand({
2543
2321
  serverUrl,
2544
2322
  profileId,
2545
2323
  catalog,
2546
- peers: peersEnabled
2324
+ peers: peersEnabled,
2325
+ sessionId: state.sessionId,
2326
+ launchSecret
2547
2327
  }));
2548
2328
  const settingsPath = path.join(mirror, "settings.json");
2549
2329
  let userSettings = {};
@@ -2595,10 +2375,6 @@ const pi = defineCommand({
2595
2375
  }
2596
2376
  await writeTextFile(path.join(mirror, "extensions", "gh-router-pi", "index.ts"), buildPiExtensionSource({
2597
2377
  profileId,
2598
- searchEnabled: surfaces.codeSearch,
2599
- searchBackend: surfaces.codeSearchBackend,
2600
- browseEnabled,
2601
- peers: peersEnabled,
2602
2378
  bridge: bridgeStats ? {
2603
2379
  stats: bridgeStats,
2604
2380
  scopedRules: bridgeScoped
@@ -2611,7 +2387,7 @@ const pi = defineCommand({
2611
2387
  serverUrl,
2612
2388
  groups: surfaces.groups
2613
2389
  });
2614
- if (written.skippedReason) consola.warn(`Pi MCP: left ${written.path} alone (${written.skippedReason}); the Azure groups are not exposed to Pi this launch.`);
2390
+ if (written.skippedReason) consola.warn(`Pi MCP: left ${written.path} alone (${written.skippedReason}); the scoped groups are not exposed to Pi this launch.`);
2615
2391
  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.`);
2616
2392
  }
2617
2393
  if (peersEnabled) {
@@ -2685,11 +2461,10 @@ const pi = defineCommand({
2685
2461
  if (browserToolsEnabled()) provisionBrowserAssets().catch((err) => consola.debug("Browser extension provisioning failed:", err));
2686
2462
  const descriptor = profileDescriptor(profileId);
2687
2463
  const nonce = randomBytes(32).toString("hex");
2688
- const secret = randomBytes(32).toString("hex");
2689
2464
  const entry = registerLaunch({
2690
2465
  profileId,
2691
2466
  nonce,
2692
- secret,
2467
+ secret: launchSecret,
2693
2468
  allowedGroups: peersEnabled ? descriptor.allowedGroups : new Set([...descriptor.allowedGroups ?? []].filter((g) => g !== "peers")),
2694
2469
  allowedPersonas: peersEnabled ? descriptor.personaAllowlist : /* @__PURE__ */ new Set()
2695
2470
  });
@@ -2711,12 +2486,12 @@ const pi = defineCommand({
2711
2486
  swe: sweEnabled,
2712
2487
  search: searchEnabled,
2713
2488
  browse: browseEnabled,
2714
- azureGroups: surfaces.groups.map((g) => g.group),
2489
+ mcpGroups: surfaces.groups.map((g) => g.group),
2715
2490
  serverUrl
2716
2491
  })}\n`);
2717
2492
  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");
2718
2493
  const { disposeBluebirdClients } = await import("./bluebird-client-DGE3WZqh.js");
2719
- const { disposeAdoClients } = await import("./ado-tools-DokE2DbX.js");
2494
+ const { disposeAdoClients } = await import("./ado-tools-rysFZDws.js");
2720
2495
  launchChild({
2721
2496
  kind: "pi",
2722
2497
  envVars: {
@@ -2754,4 +2529,4 @@ const pi = defineCommand({
2754
2529
  //#endregion
2755
2530
  export { pi };
2756
2531
 
2757
- //# sourceMappingURL=pi-D-BgxVhx.js.map
2532
+ //# sourceMappingURL=pi-DcWp83mx.js.map