github-router 0.3.352 → 0.3.354

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 (72) hide show
  1. package/README.md +1 -38
  2. package/dist/ado-tools-CN4i9OVl.js +1 -0
  3. package/dist/{aic-statusline-settings-LnoxjBPe.js → aic-statusline-settings-EdsV1gzY.js} +6 -4
  4. package/dist/aic-statusline-settings-EdsV1gzY.js.map +1 -0
  5. package/dist/{attribution-settings-ul6VU6iP.js → attribution-settings-8Uv97n9j.js} +51 -39
  6. package/dist/{attribution-settings-ul6VU6iP.js.map → attribution-settings-8Uv97n9j.js.map} +1 -1
  7. package/dist/balanced-profile-contract-DtnTIBjL.js +105 -0
  8. package/dist/balanced-profile-contract-DtnTIBjL.js.map +1 -0
  9. package/dist/browser-ext/manifest.json +1 -1
  10. package/dist/{claude-xO1XW-Nn.js → claude-C_1OM7ce.js} +68 -59
  11. package/dist/claude-C_1OM7ce.js.map +1 -0
  12. package/dist/{claude-md-injection-BoXOsg7h.js → claude-md-injection-CDOoGNEJ.js} +20 -15
  13. package/dist/claude-md-injection-CDOoGNEJ.js.map +1 -0
  14. package/dist/{codex-DzUR40JA.js → codex-5eTmciDG.js} +5 -5
  15. package/dist/{codex-DzUR40JA.js.map → codex-5eTmciDG.js.map} +1 -1
  16. package/dist/{copilot-discount-C3jfysK-.js → copilot-discount-kpOLluHm.js} +3 -1
  17. package/dist/copilot-discount-kpOLluHm.js.map +1 -0
  18. package/dist/engine-CIAopp0h.js +1 -0
  19. package/dist/fast-profile-contract-JOnZBgFB.js +61 -0
  20. package/dist/fast-profile-contract-JOnZBgFB.js.map +1 -0
  21. package/dist/{gate-discovery-Cvdko01z.js → gate-discovery-CqJVzT_D.js} +2 -2
  22. package/dist/{gate-discovery-Cvdko01z.js.map → gate-discovery-CqJVzT_D.js.map} +1 -1
  23. package/dist/hooks.mjs +193 -12
  24. package/dist/hooks.sha256 +1 -1
  25. package/dist/{internal-aic-status-Dmi2bCsR.js → internal-aic-status-wYPsCG4r.js} +2 -2
  26. package/dist/{internal-aic-status-Dmi2bCsR.js.map → internal-aic-status-wYPsCG4r.js.map} +1 -1
  27. package/dist/{internal-fast-dispatch-guard-Cv7zf0ZI.js → internal-fast-dispatch-guard-A8teEib4.js} +1 -1
  28. package/dist/{internal-fast-dispatch-guard-BQm1MI9d.js → internal-fast-dispatch-guard-D_TCtJhQ.js} +3 -2
  29. package/dist/{internal-fast-dispatch-guard-BQm1MI9d.js.map → internal-fast-dispatch-guard-D_TCtJhQ.js.map} +1 -1
  30. package/dist/{internal-max-dispatch-guard-T-M7DRIW.js → internal-max-dispatch-guard-BM_B15EH.js} +1 -1
  31. package/dist/{internal-max-dispatch-guard-DkJixDmG.js → internal-max-dispatch-guard-D7ByWH4v.js} +2 -2
  32. package/dist/{internal-max-dispatch-guard-DkJixDmG.js.map → internal-max-dispatch-guard-D7ByWH4v.js.map} +1 -1
  33. package/dist/{internal-prompt-submit-B9MJxc3K.js → internal-prompt-submit-C77GnEaW.js} +3 -3
  34. package/dist/internal-prompt-submit-C77GnEaW.js.map +1 -0
  35. package/dist/{internal-prompt-submit-6OXEdQCK.js → internal-prompt-submit-CDTwamkW.js} +2 -2
  36. package/dist/{internal-rebrief-zIdunX3R.js → internal-rebrief-DZygfGHp.js} +6 -6
  37. package/dist/internal-rebrief-DZygfGHp.js.map +1 -0
  38. package/dist/{internal-stop-hook-DGcRVh_2.js → internal-stop-hook-Dn_AF0BF.js} +2 -2
  39. package/dist/{internal-stop-hook-DGcRVh_2.js.map → internal-stop-hook-Dn_AF0BF.js.map} +1 -1
  40. package/dist/main.js +11 -11
  41. package/dist/{max-profile-contract-DQDEDCsR.js → max-profile-contract-CMvzKSsg.js} +2 -2
  42. package/dist/max-profile-contract-CMvzKSsg.js.map +1 -0
  43. package/dist/{peer-mcp-personas-DDMKRFFG.js → peer-mcp-personas-DlF1dKCs.js} +142 -165
  44. package/dist/peer-mcp-personas-DlF1dKCs.js.map +1 -0
  45. package/dist/{pi-jVNeQXWf.js → pi-2m2IgZlm.js} +61 -62
  46. package/dist/pi-2m2IgZlm.js.map +1 -0
  47. package/dist/{provision-BtYRtvrj.js → provision-DLGlhu3a.js} +2 -2
  48. package/dist/{provision-BtYRtvrj.js.map → provision-DLGlhu3a.js.map} +1 -1
  49. package/dist/{serve-CmgmxigM.js → serve-8tXHVHOr.js} +7 -7
  50. package/dist/{serve-CmgmxigM.js.map → serve-8tXHVHOr.js.map} +1 -1
  51. package/dist/{server-setup-DinOFWiC.js → server-setup-BBSmse1J.js} +190 -127
  52. package/dist/server-setup-BBSmse1J.js.map +1 -0
  53. package/dist/{start-Dgsaz0HM.js → start-B7jTBpAc.js} +3 -3
  54. package/dist/{start-Dgsaz0HM.js.map → start-B7jTBpAc.js.map} +1 -1
  55. package/dist/{static-context-pack-CyucviRD.js → static-context-pack-BRqt4ajJ.js} +313 -6
  56. package/dist/static-context-pack-BRqt4ajJ.js.map +1 -0
  57. package/package.json +1 -1
  58. package/dist/ado-tools-xbuVU7YN.js +0 -1
  59. package/dist/aic-statusline-settings-LnoxjBPe.js.map +0 -1
  60. package/dist/balanced-profile-contract-XiIj4O1U.js +0 -127
  61. package/dist/balanced-profile-contract-XiIj4O1U.js.map +0 -1
  62. package/dist/claude-md-injection-BoXOsg7h.js.map +0 -1
  63. package/dist/claude-xO1XW-Nn.js.map +0 -1
  64. package/dist/copilot-discount-C3jfysK-.js.map +0 -1
  65. package/dist/engine-DwLIk1Zn.js +0 -1
  66. package/dist/internal-prompt-submit-B9MJxc3K.js.map +0 -1
  67. package/dist/internal-rebrief-zIdunX3R.js.map +0 -1
  68. package/dist/max-profile-contract-DQDEDCsR.js.map +0 -1
  69. package/dist/peer-mcp-personas-DDMKRFFG.js.map +0 -1
  70. package/dist/pi-jVNeQXWf.js.map +0 -1
  71. package/dist/server-setup-DinOFWiC.js.map +0 -1
  72. package/dist/static-context-pack-CyucviRD.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"pi-jVNeQXWf.js","names":["fs","fs","fs","fs","fs","process"],"sources":["../src/lib/pi-version-check.ts","../src/lib/pi-tier-windows.ts","../src/lib/pi-statusline.ts","../src/lib/pi-paths.ts","../src/lib/pi-package-cache.ts","../src/lib/pi-models-settings.ts","../src/lib/pi-extension.ts","../src/lib/pi-mcp-config.ts","../src/pi.ts"],"sourcesContent":["import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport {\n resolveExecutable,\n runCommandCapture,\n runCommandVoid,\n} from \"./exec\"\nimport { queueDetachedGlobalInstall } from \"./self-update\"\nimport { withInstallLock } from \"./update-lock\"\n\nexport const PI_NPM_PACKAGE = \"@earendil-works/pi-coding-agent\"\n/**\n * Minimum Pi version the `pi` launcher supports.\n *\n * The floor is pinned to the first release whose `before_agent_start` event\n * carries the `messageType` discriminator (present at 1.3.0, absent at 1.1.0).\n * The generated extension's prompt hook stands down for non-user events using\n * that field, and without it the hook would fire on subagent and system turns\n * the user never typed, which is a wrong brief rather than a missing one.\n * Below-floor Pi hard-exits at the launcher (`src/pi.ts`), but only where the\n * gate actually runs: the install probe, the background refresh, and this floor\n * check all sit inside `--update-check` (default on), so `--no-update-check`\n * (documented for offline/CI) skips the floor as well. That path is still\n * fail-closed rather than silently wrong: the generated extension's own shape\n * probe sees the missing `messageType`, warns once with the fix, and injects\n * nothing.\n */\nexport const PI_MIN_VERSION = \"1.3.0\"\n\n/**\n * Registry used for the PI PACKAGE ONLY.\n *\n * Pi must come from a registry that actually carries it. A corporate npm mirror\n * can lag npmjs far enough that its `latest` sits below `PI_MIN_VERSION`, and\n * the launcher then fail-closes on an upgrade command the user cannot satisfy\n * (their `npm install -g` resolves through the same lagging mirror). Pointing\n * the Pi probe and install at npmjs by default keeps the floor reachable;\n * `GH_ROUTER_NPM_REGISTRY` overrides it for a mirror that does carry the\n * package. Everything else this repo installs still resolves through the user's\n * configured registry.\n */\nexport const PI_DEFAULT_REGISTRY = \"https://registry.npmjs.org/\"\n\n/**\n * Resolve the registry for Pi package operations. Accepts `GH_ROUTER_NPM_REGISTRY`\n * when it is an http(s) URL and falls back to `PI_DEFAULT_REGISTRY` with a\n * warning otherwise, so a typo degrades to the working default rather than\n * bricking the launcher.\n */\nexport function resolvePiRegistry(): string {\n const raw = process.env.GH_ROUTER_NPM_REGISTRY?.trim()\n if (!raw) return PI_DEFAULT_REGISTRY\n if (!/^https?:\\/\\//i.test(raw)) {\n consola.warn(\n `Ignoring GH_ROUTER_NPM_REGISTRY=${JSON.stringify(raw)}: expected an http(s) URL. Using ${PI_DEFAULT_REGISTRY}.`,\n )\n return PI_DEFAULT_REGISTRY\n }\n return raw.endsWith(\"/\") ? raw : `${raw}/`\n}\n\n/** `npm` args that pin an operation to the resolved Pi registry. */\nexport function piRegistryArgs(registry: string = resolvePiRegistry()): string[] {\n return [`--registry=${registry}`]\n}\n\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\nconst PI_VERSION_TIMEOUT_MS = 3000\nconst NPM_INSTALL_TIMEOUT_MS = 300_000 // 5 min — pi pulls a larger tree than claude\n\ninterface PiVersionCheckCache {\n /** ISO timestamp of last check */\n checkedAt: string\n /** Installed version at last check */\n installedVersion: string | null\n /** Latest version on npm at last check */\n latestVersion: string | null\n}\n\n/** Path to the throttle cache. Created on demand. Separate file from the Claude check. */\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n \"last-pi-update-check\",\n )\n}\n\nasync function readCache(): Promise<PiVersionCheckCache | null> {\n try {\n const raw = await fs.readFile(cacheFilePath(), \"utf8\")\n const parsed = JSON.parse(raw) as PiVersionCheckCache\n if (\n typeof parsed.checkedAt !== \"string\"\n || (parsed.installedVersion !== null\n && typeof parsed.installedVersion !== \"string\")\n || (parsed.latestVersion !== null\n && typeof parsed.latestVersion !== \"string\")\n ) {\n return null\n }\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: PiVersionCheckCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n consola.debug(\"Failed to write pi version-check cache:\", err)\n }\n}\n\nfunction shouldCheckNow(cache: PiVersionCheckCache | null): boolean {\n if (!cache) return true\n const lastCheck = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(lastCheck)) return true\n const hoursSince = (Date.now() - lastCheck) / 1000 / 3600\n return hoursSince >= THROTTLE_HOURS\n}\n\n/**\n * Read the installed `pi` version. Returns null if pi is not on PATH\n * or the version probe fails.\n *\n * Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path\n * (excluding the cwd) before invocation via the shared exec helper.\n */\nexport async function getInstalledPiVersion(): Promise<string | null> {\n const piPath = resolveExecutable(\"pi\")\n if (!piPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [piPath, \"--version\"],\n { timeoutMs: PI_VERSION_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const match = stdout.match(/(\\d+\\.\\d+\\.\\d+)/)\n return match ? match[1] : null\n } catch {\n return null\n }\n}\n\n/** Fetch the latest Pi version from npm. Null on network/npm failure. */\nasync function getLatestPiVersion(): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [\n npmPath,\n \"view\",\n PI_NPM_PACKAGE,\n \"version\",\n \"--silent\",\n ...piRegistryArgs(),\n ],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Compare two semver-shaped strings (leading X.Y.Z only). True when\n * `latest` is strictly higher than `installed`.\n */\nexport function isPiNewer(\n installed: string | null,\n latest: string | null,\n): boolean {\n if (!installed || !latest) return false\n const a = installed.split(\".\").map((n) => parseInt(n, 10))\n const b = latest.split(\".\").map((n) => parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = a[i] ?? 0\n const bv = b[i] ?? 0\n if (av < bv) return true\n if (av > bv) return false\n }\n return false\n}\n\n/** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */\nexport function meetsPiMinVersion(version: string | null): boolean {\n if (!version) return false\n return !isPiNewer(version, PI_MIN_VERSION)\n}\n\nexport interface PiVersionCheckResult {\n /** Whether pi is on PATH at all */\n installed: boolean\n installedVersion: string | null\n latestVersion: string | null\n /** True if a newer version is available */\n needsUpdate: boolean\n /** True if the installed version is below the supported floor */\n needsMinUpgrade: boolean\n /** Whether the check was skipped (throttled or disabled) */\n skipped: boolean\n skipReason?: \"throttled\" | \"disabled\" | \"no-npm\" | \"no-pi\"\n}\n\n/** Run a version check (subject to throttle). Side-effect: updates the cache. */\nexport async function checkPiVersion(opts: {\n noCheck?: boolean\n force?: boolean\n} = {}): Promise<PiVersionCheckResult> {\n if (opts.noCheck) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: false,\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) {\n const installedVersion = cache?.installedVersion ?? null\n const latestVersion = cache?.latestVersion ?? null\n return {\n installed: installedVersion !== null,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"throttled\",\n }\n }\n\n const installedVersion = await getInstalledPiVersion()\n if (installedVersion === null) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: true,\n skipped: true,\n skipReason: \"no-pi\",\n }\n }\n\n const latestVersion = await getLatestPiVersion()\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n\n if (latestVersion === null) {\n return {\n installed: true,\n installedVersion,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"no-npm\",\n }\n }\n\n return {\n installed: true,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: false,\n }\n}\n\n/**\n * Install (or upgrade) Pi from npm under the cross-process install lock.\n * Returns `true` when this call performed the install, `false` when\n * another process holds the lock (caller skips — its install will land\n * for a later launch). Best-effort: throws on failure; callers fall\n * back to the installed version with a visible warning rather than\n * stranding the launch.\n */\nexport function updatePi(version: string, opts: { signal?: AbortSignal } = {}): Promise<boolean> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) {\n throw new Error(\"npm not found on PATH; cannot install Pi automatically\")\n }\n return withInstallLock(\"pi-install.lock\", async () => {\n const registry = resolvePiRegistry()\n consola.info(`Installing ${PI_NPM_PACKAGE}@${version} from ${registry}...`)\n await runCommandVoid(\n [\n npmPath,\n \"install\",\n \"-g\",\n `${PI_NPM_PACKAGE}@${version}`,\n ...piRegistryArgs(registry),\n ],\n { timeoutMs: NPM_INSTALL_TIMEOUT_MS, signal: opts.signal },\n )\n })\n}\n\n/**\n * Blocking fresh install for when Pi is absent entirely. Installs\n * `@latest`, then force re-checks; throws when Pi still is not on PATH\n * (caller exits with the install command). Only used when there is no\n * usable Pi at all — the healthy path never blocks on npm.\n */\nexport async function ensurePiInstalled(opts: { signal?: AbortSignal } = {}): Promise<string> {\n const acquired = await updatePi(\"latest\", opts)\n const retry = await checkPiVersion({ force: true })\n if (retry.installed && retry.installedVersion) return retry.installedVersion\n throw new Error(\n acquired\n ? \"install did not place pi on PATH\"\n : \"another Pi install is already running; retry in a moment\",\n )\n}\n\n/**\n * Fire-and-forget freshness refresh for a healthy Pi install. Never\n * blocks launch and never throws: on the throttled schedule it probes\n * npm for a newer Pi and, when one exists, queues a DETACHED post-exit\n * install (same pattern as the proxy self-update) so neither startup\n * nor the running session nor shutdown ever waits on npm. The\n * cross-process install lock serializes against concurrent launches;\n * every failure degrades to a debug log.\n *\n * Deliberately never touches a below-floor install: the floor is\n * enforced foreground by the launcher (fail-closed), and a background\n * task must not change what the running session validated.\n */\nexport function refreshPiInBackground(opts: { autoUpdate: boolean }): void {\n if (!opts.autoUpdate) return\n void (async () => {\n try {\n const cache = await readCache()\n if (!shouldCheckNow(cache)) return\n const installedVersion = await getInstalledPiVersion()\n if (!meetsPiMinVersion(installedVersion)) return\n const npmPath = resolveExecutable(\"npm\")\n const latestVersion = await getLatestPiVersion()\n // Optimistic throttle write: concurrent/next launches back off\n // even while the detached install is still settling.\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n if (!npmPath) return\n if (!latestVersion || !isPiNewer(installedVersion, latestVersion)) return\n const queued = await withInstallLock(\"pi-install.lock\", async () => {\n queueDetachedGlobalInstall(\n npmPath,\n `${PI_NPM_PACKAGE}@${latestVersion}`,\n piRegistryArgs(),\n )\n })\n if (queued) {\n consola.info(\n `Pi ${installedVersion} → ${latestVersion} update queued; it takes effect on the next launch.`,\n )\n }\n } catch (err) {\n consola.debug(\"Background Pi refresh failed:\", err)\n }\n })().catch((err) => {\n consola.debug(\"Background Pi refresh failed:\", err)\n })\n}\n","import consola from \"consola\"\n\nimport type { Model } from \"~/services/copilot/get-models\"\n\n/**\n * Copilot Default-tier (cheap) input-token thresholds per model.\n *\n * Sourced from https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing\n * (per 1M tokens; tiers key on per-request INPUT tokens):\n * - gpt-6-luna: Default ≤ 272K ($0.10 in) vs Long > 272K ($0.20 in)\n * - gpt-5.6-sol: Default ≤ 272K ($4.00 in) vs Long > 272K ($8.00 in)\n * - gpt-6-sol: Default ≤ 272K ($2.00 in) vs Long > 272K ($4.00 in)\n * - grok-4.6: Default ≤ 200K ($2.00 in) vs Long > 200K ($4.00 in)\n *\n * The live catalog carries no tier data (flat `billing.token_prices` +\n * single `limits.*` only), so this table is hardcoded by exact model id —\n * same precedent as `FALLBACK_TOKEN_PRICES`. Anything not listed here\n * runs at the 200K default window. LAST_VERIFIED 2026-09-24: refresh the\n * values (and the drift expectations below) when the billing doc changes.\n */\nexport const PI_TIER_THRESHOLDS: Readonly<Record<string, number>> = Object.freeze({\n \"gpt-6-luna\": 272_000,\n \"gpt-5.6-sol\": 272_000,\n \"gpt-6-sol\": 272_000,\n \"grok-4.6\": 200_000,\n})\n\n/** Window for models with no pinned tier threshold. */\nexport const PI_TIER_FALLBACK_TOKENS = 200_000 as const\n\n/** Pinned Default-tier threshold for a model id, or the 200K fallback. */\nexport function piTierThresholdFor(modelId: string): number {\n return PI_TIER_THRESHOLDS[modelId] ?? PI_TIER_FALLBACK_TOKENS\n}\n\n/**\n * Effective Pi `contextWindow` for a model: its cheap-tier threshold,\n * defensively capped at the catalog-advertised total window so a stale\n * table can never budget above what Copilot serves.\n */\nexport function piContextWindowFor(\n modelId: string,\n advertisedMaxContextTokens?: number,\n): number {\n const threshold = piTierThresholdFor(modelId)\n if (\n typeof advertisedMaxContextTokens === \"number\"\n && Number.isFinite(advertisedMaxContextTokens)\n && advertisedMaxContextTokens > 0\n ) {\n return Math.min(threshold, Math.floor(advertisedMaxContextTokens))\n }\n return threshold\n}\n\n/**\n * Expected Default-tier input prices in CATALOG normalized units\n * (`price/1e9*1e6/batch`, same as `livePricesFor`), NOT billing-doc USD.\n * Empirically catalog units = USD × 100 (live luna 10/50 vs $0.10/$1.20,\n * sol 200/1000 vs $2/$10, opus-5.5 400/2000 vs $4/$20 — all ×100).\n * grok-4.6's 200 is inferred the same way (doc $2.00 × 100); if live\n * disagrees the warning fires, which is the guard working, not failing.\n */\nconst EXPECTED_DEFAULT_INPUT_PER_1M: Readonly<Record<string, number>> =\n Object.freeze({\n \"gpt-6-luna\": 10,\n \"gpt-5.6-sol\": 400,\n \"gpt-6-sol\": 200,\n \"grok-4.6\": 200,\n })\n\n/**\n * Warn loudly when live catalog input prices disagree with the pinned\n * tier table's implied Default rates — the table (or the billing doc)\n * drifted and needs a refresh. Warn-only; never blocks a launch.\n * Pure over caller-supplied rows so it is unit-testable.\n */\nexport function tierPriceDriftWarnings(\n rows: ReadonlyArray<{ id: string; inputPer1M: number | undefined }>,\n): Array<string> {\n const warnings: Array<string> = []\n for (const row of rows) {\n const expected = EXPECTED_DEFAULT_INPUT_PER_1M[row.id]\n if (expected === undefined) continue\n if (row.inputPer1M === undefined) continue\n if (Math.abs(row.inputPer1M - expected) > 1e-9) {\n warnings.push(\n `Copilot catalog prices for \"${row.id}\" (${row.inputPer1M}/1M input, catalog units) disagree with the pinned Pi tier table (${expected}/1M Default). Refresh PI_TIER_THRESHOLDS in src/lib/pi-tier-windows.ts.`,\n )\n }\n }\n return warnings\n}\n\n/** Emit drift warnings to stderr (launch-time seam). */\nexport function warnOnTierPriceDrift(\n rows: ReadonlyArray<{ id: string; inputPer1M: number | undefined }>,\n): void {\n for (const warning of tierPriceDriftWarnings(rows)) {\n consola.warn(warning)\n }\n}\n\n/**\n * Normalize live catalog input prices to per-1M rows for the drift guard.\n * Same validation as `livePricesFor` (batch must be a positive safe\n * integer, prices finite and non-negative); anything else yields\n * `undefined` (unknown — skipped, never treated as drift).\n */\nexport function liveInputPer1M(\n models: ReadonlyArray<Model> | undefined,\n): Array<{ id: string; inputPer1M: number | undefined }> {\n return (models ?? []).map((m) => {\n const prices = m.billing?.token_prices\n const batch = prices?.batch_size\n const input = prices?.input_price\n const valid =\n typeof batch === \"number\" && Number.isSafeInteger(batch) && batch > 0\n && typeof input === \"number\" && Number.isFinite(input) && input >= 0\n return {\n id: m.id,\n inputPer1M: valid ? input / 1e9 * 1e6 / (batch as number) : undefined,\n }\n })\n}\n\n/** One-call launch seam: normalize the live catalog and warn on drift. */\nexport function warnOnTierPriceDriftForModels(\n models: ReadonlyArray<Model> | undefined,\n): void {\n warnOnTierPriceDrift(liveInputPer1M(models))\n}\n","/**\n * Pi footer statusline: Claude-shaped payload builder + launch constants.\n *\n * `github-router pi` does NOT use the community `npm:pi-statusline` bridge\n * (verified live against v0.0.2: it reads `statusLine` from the user's real\n * `~/.pi/agent/settings.json` / project `.pi/settings.json` and never sees\n * the router-owned mirror behind `PI_CODING_AGENT_DIR`, so a mirror-injected\n * block is dead config; its payload also hardcodes\n * `cost.total_lines_*` to null and derives `used_percentage` from the\n * latest turn only). Instead the mode's own `local:gh-router-pi` extension\n * (see `src/lib/pi-extension.ts`) builds this payload natively from the Pi\n * extension context and spawns the SAME `internal-aic-status` runner Claude\n * uses — one renderer, byte-identical segments.\n *\n * `buildPiStatusPayload` is intentionally dependency-free (no imports, no\n * module-scope references — every helper is nested inside): the generated\n * extension embeds its source via `Function.prototype.toString()`, and a\n * drift test pins that the embedded copy equals this function exactly.\n */\n\nexport const PI_STATUS_COMMAND_ENV = \"GH_ROUTER_AIC_STATUS_COMMAND\"\n\n/** Debounce between Pi refresh events before re-spawning the runner. */\nexport const PI_STATUSLINE_DEBOUNCE_MS = 300\n/** Hard cap for one runner invocation; a hung script must never wedge the footer. */\nexport const PI_STATUSLINE_TIMEOUT_MS = 5000\n/** Width fallback when the footer has never rendered (mirrors default-statusline). */\nexport const PI_STATUSLINE_WIDTH_FALLBACK = 120\n\nexport interface PiStatusModel {\n id?: unknown\n displayName?: unknown\n name?: unknown\n contextWindow?: unknown\n}\n\nexport interface PiStatusContextUsage {\n tokens?: unknown\n contextWindow?: unknown\n percent?: unknown\n}\n\nexport interface PiStatusSource {\n cwd?: unknown\n sessionId?: unknown\n model?: PiStatusModel\n contextUsage?: PiStatusContextUsage | null | undefined\n /** `sessionManager.getBranch()` preferred; `getEntries()` accepted. */\n entries?: ReadonlyArray<unknown>\n}\n\nexport function buildPiStatusPayload(\n source: PiStatusSource,\n opts: { nowMs: number; sessionStartMs?: number },\n): Record<string, unknown> {\n function asRecord(value: unknown): Record<string, unknown> {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>\n }\n return {}\n }\n function finiteNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined\n }\n function nonNegativeInt(value: unknown): number | undefined {\n const n = finiteNumber(value)\n if (n === undefined || n < 0) return undefined\n return Math.floor(n)\n }\n function nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined\n }\n function timestampMs(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value) && value > 0) {\n // Pi message timestamps are epoch-ms; entry timestamps are ISO strings.\n return value < 1e12 ? Math.floor(value * 1000) : Math.floor(value)\n }\n if (typeof value === \"string\" && value.length > 0) {\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n }\n\n const src = asRecord(source)\n const cwd = nonEmptyString(src.cwd) ?? \"\"\n const sessionId = nonEmptyString(src.sessionId) ?? null\n const model = asRecord(src.model)\n const modelId = nonEmptyString(model.id) ?? null\n const displayName =\n nonEmptyString(model.displayName) ?? nonEmptyString(model.name) ?? modelId\n const usage = asRecord(src.contextUsage)\n const usedPct = finiteNumber(usage.percent)\n const windowSize =\n nonNegativeInt(usage.contextWindow) ?? nonNegativeInt(model.contextWindow) ?? null\n\n const rawEntries = Array.isArray(src.entries) ? src.entries : []\n let totalIn = 0\n let totalOut = 0\n let seenUsage = false\n let linesAdded = 0\n let linesRemoved = 0\n let latestInput: number | null = null\n let latestOutput: number | null = null\n let latestCacheWrite: number | null = null\n let latestCacheRead: number | null = null\n let firstTs: number | undefined\n let lastTs: number | undefined\n\n function noteTimestamp(value: unknown): void {\n const ms = timestampMs(value)\n if (ms === undefined) return\n if (firstTs === undefined || ms < firstTs) firstTs = ms\n if (lastTs === undefined || ms > lastTs) lastTs = ms\n }\n function addLines(details: unknown): void {\n const record = asRecord(details)\n if (Object.keys(record).length === 0) return\n const added = finiteNumber(record.linesAdded)\n const removed = finiteNumber(record.linesRemoved)\n if (added !== undefined && added >= 0) linesAdded += Math.floor(added)\n if (removed !== undefined && removed >= 0) linesRemoved += Math.floor(removed)\n // One nesting level (namespaced tool details); deeper shapes are ignored\n // rather than risking double-counts.\n for (const key of [\"details\", \"result\", \"data\"]) {\n const nested = asRecord(record[key])\n if (Object.keys(nested).length === 0) continue\n const nestedAdded = finiteNumber(nested.linesAdded)\n const nestedRemoved = finiteNumber(nested.linesRemoved)\n const consumedParent = added !== undefined || removed !== undefined\n if (!consumedParent) {\n if (nestedAdded !== undefined && nestedAdded >= 0) {\n linesAdded += Math.floor(nestedAdded)\n }\n if (nestedRemoved !== undefined && nestedRemoved >= 0) {\n linesRemoved += Math.floor(nestedRemoved)\n }\n }\n }\n }\n\n for (const entry of rawEntries) {\n const record = asRecord(entry)\n if (record.type !== \"message\") continue\n const message = asRecord(record.message)\n noteTimestamp(record.timestamp)\n noteTimestamp(message.timestamp)\n if (message.role === \"assistant\") {\n if (message.stopReason === \"aborted\" || message.stopReason === \"error\") continue\n const entryUsage = asRecord(message.usage)\n const input = nonNegativeInt(entryUsage.input)\n const output = nonNegativeInt(entryUsage.output)\n if (input !== undefined) {\n totalIn += input\n seenUsage = true\n }\n if (output !== undefined) {\n totalOut += output\n seenUsage = true\n }\n latestInput = input ?? latestInput\n latestOutput = output ?? latestOutput\n const cacheWrite = nonNegativeInt(entryUsage.cacheWrite)\n const cacheRead = nonNegativeInt(entryUsage.cacheRead)\n if (cacheWrite !== undefined) latestCacheWrite = cacheWrite\n if (cacheRead !== undefined) latestCacheRead = cacheRead\n } else if (message.role === \"toolResult\") {\n addLines(message.details)\n }\n }\n\n // Duration: wall-clock from session start when the extension tracked it\n // (matches Claude's total_duration_ms, idle included); transcript-derived\n // span as the restart-proof fallback; null until either is available.\n let durationMs: number | null = null\n const startMs = finiteNumber(opts.sessionStartMs)\n if (startMs !== undefined && startMs > 0) {\n durationMs = Math.max(0, Math.floor(opts.nowMs - startMs))\n } else if (firstTs !== undefined && lastTs !== undefined) {\n durationMs = Math.max(0, lastTs - firstTs)\n }\n\n return {\n cwd,\n session_id: sessionId,\n transcript_path: null,\n model: { id: modelId, display_name: displayName },\n workspace: { current_dir: cwd, project_dir: cwd },\n version: null,\n output_style: { name: \"default\" },\n cost: {\n // List-price USD is deliberately never forwarded (same rule as the\n // Claude path: it contradicts the AIC billing unit). The runner reads\n // duration + line counts from this block.\n total_cost_usd: null,\n total_duration_ms: durationMs,\n total_api_duration_ms: null,\n total_lines_added: linesAdded,\n total_lines_removed: linesRemoved,\n },\n context_window: {\n total_input_tokens: seenUsage ? totalIn : null,\n total_output_tokens: seenUsage ? totalOut : null,\n context_window_size: windowSize,\n // Authoritative Pi percent only — never a latest-turn ratio (the\n // bridge's 3%-vs-42% failure mode). Null renders the `--%` placeholder.\n used_percentage:\n usedPct !== undefined ? Math.max(0, Math.round(usedPct)) : null,\n remaining_percentage:\n usedPct !== undefined ? Math.max(0, 100 - Math.round(usedPct)) : null,\n current_usage:\n latestInput !== null || latestOutput !== null\n ? {\n input_tokens: latestInput,\n output_tokens: latestOutput,\n cache_creation_input_tokens: latestCacheWrite,\n cache_read_input_tokens: latestCacheRead,\n }\n : null,\n },\n exceeds_200k_tokens: false,\n rate_limits: null,\n vim: null,\n agent: null,\n worktree: null,\n }\n}\n","import { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nfunction appDir(): string {\n return path.join(os.homedir(), \".local\", \"share\", \"github-router\")\n}\n\n/** Where the user's real Pi agent dir lives (`PI_CODING_AGENT_DIR` wins). */\nexport function userPiAgentDir(): string {\n const override = (process.env.PI_CODING_AGENT_DIR ?? \"\").trim()\n if (override.length > 0) return override\n return path.join(os.homedir(), \".pi\", \"agent\")\n}\n\n/**\n * Per-launch suffix for the Pi mirror. Lazily generated once per process\n * so every path getter in this module agrees on the directory.\n */\nlet launchSuffix: string | undefined\n\nfunction perLaunchSuffix(): string {\n launchSuffix ??= `pi-agent-${process.pid}-${randomBytes(4).toString(\"hex\")}`\n return launchSuffix\n}\n\n/** Router-owned, per-launch Pi agent dir for the spawned `pi` child. */\nexport function piMirrorDir(): string {\n return path.join(appDir(), \"pi-mirrors\", perLaunchSuffix())\n}\n\n/**\n * Provision the per-launch Pi mirror: snapshot-copy the user's real Pi\n * agent dir (settings, models, skills, prompts, extensions the user owns)\n * so the spawned `pi` starts from the user's own setup, then let the\n * launcher overlay the mode's generated files on top.\n *\n * Copy failures of individual user files are debug-logged and skipped —\n * a corrupt user file must not strand the launch. Throws only when the\n * mirror directory itself cannot be created.\n */\nexport async function ensurePiAgentMirror(): Promise<string> {\n const mirror = piMirrorDir()\n await fs.mkdir(mirror, { recursive: true })\n const source = userPiAgentDir()\n let entries: Array<string>\n try {\n entries = await fs.readdir(source)\n } catch {\n // No user Pi dir yet (fresh machine) — the mirror starts empty and\n // the launcher writes every file Pi needs.\n return mirror\n }\n // Snapshot user-owned resources; never auth.json (credentials stay the\n // user's — Pi resolves its dummy/provider key from our generated\n // models.json, and copying OAuth tokens into a swept dir risks stranding\n // them), never sessions/ (per-project history must not leak across the\n // isolation boundary), never models-store.json. User `extensions/` are\n // excluded by default: third-party workflow orchestrators (background\n // lanes / preflight tools) otherwise ride into the cost-controlled\n // profile and break its fixed roster contract. Opt back in with\n // GH_ROUTER_PI_KEEP_USER_EXTENSIONS=1.\n const keepUserExtensions = process.env.GH_ROUTER_PI_KEEP_USER_EXTENSIONS === \"1\"\n const SKIP = new Set([\n \"auth.json\",\n \"sessions\",\n \"models-store.json\",\n ...(keepUserExtensions ? [] : [\"extensions\"]),\n ])\n await Promise.all(\n entries\n .filter((e) => !SKIP.has(e))\n .map(async (entry) => {\n try {\n await fs.cp(path.join(source, entry), path.join(mirror, entry), {\n recursive: true,\n })\n } catch (err) {\n consola.debug(`Pi mirror: skipping ${entry}:`, err)\n }\n }),\n )\n return mirror\n}\n\n/** Remove THIS launch's Pi mirror on shutdown. Best-effort, never throws. */\nexport async function removeOwnPiAgentMirror(): Promise<void> {\n try {\n await fs.rm(piMirrorDir(), { recursive: true, force: true })\n } catch (err) {\n consola.debug(\"Pi mirror cleanup failed:\", err)\n }\n}\n\n/**\n * Sweep stale Pi mirrors left behind by crashed launches (dirs whose PID\n * no longer exists, or older than 24h). Best-effort, never throws.\n */\nexport async function sweepStalePiAgentMirrors(): Promise<void> {\n const root = path.join(appDir(), \"pi-mirrors\")\n let entries: Array<string>\n try {\n entries = await fs.readdir(root)\n } catch {\n return\n }\n await Promise.all(\n entries.map(async (entry) => {\n const dir = path.join(root, entry)\n try {\n const stat = await fs.stat(dir)\n const ageMs = Date.now() - stat.mtimeMs\n const pidMatch = /^pi-agent-(\\d+)-[0-9a-f]+$/.exec(entry)\n let dead = ageMs > 24 * 3600 * 1000\n if (pidMatch && !dead) {\n const pid = Number.parseInt(pidMatch[1], 10)\n try {\n process.kill(pid, 0)\n } catch {\n dead = true // ESRCH — PID is gone\n }\n }\n if (dead) await fs.rm(dir, { recursive: true, force: true })\n } catch (err) {\n consola.debug(`Pi mirror sweep: skipping ${entry}:`, err)\n }\n }),\n )\n}\n","import { createHash } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { PATHS } from \"./paths\"\nimport type { PiPackageEntry } from \"./pi-models-settings\"\n\n/**\n * Persistent npm-package cache for Pi launches.\n *\n * Pi installs the mirror's `packages[]` into `<agentDir>/npm` on every\n * boot, and the agent dir is a fresh per-launch mirror\n * (`pi-agent-<pid>-<rand>`) — so every launch pays a full registry\n * install (~5s + `added N packages` noise that bypasses\n * `npm_config_loglevel=error`). Pi skips the install when the package\n * dir already exists and the installed version satisfies the configured\n * range — and unpinned `npm:name` specs match ANY installed version —\n * so pre-seeding `<mirror>/npm` from a durable cache makes repeat\n * launches install nothing: faster AND silent.\n *\n * Keyed by the exact package set (sorted spec fingerprints), so flag\n * combinations (`--helpers`/`--ui`/`--search`/`--browse`) each get\n * their own entry and can never cross-contaminate. Entries older than\n * `PI_PACKAGE_CACHE_MAX_AGE_MS` (default 7d) are treated as a miss so\n * unpinned packages periodically refresh to upstream latest; the fresh\n * install is then saved back over the entry. Opt out entirely with\n * `GH_ROUTER_PI_NO_PACKAGE_CACHE=1`.\n */\n\nexport const PI_PACKAGE_CACHE_MAX_AGE_MS = 7 * 24 * 3600 * 1000\n\nfunction cacheDisabled(): boolean {\n return process.env.GH_ROUTER_PI_NO_PACKAGE_CACHE === \"1\"\n}\n\n/** Stable fingerprint of one `packages[]` entry (order-independent). */\nexport function piPackageSpecFingerprint(entry: PiPackageEntry): string {\n if (typeof entry === \"string\") return entry\n const join = (v: ReadonlyArray<string> | undefined): string => [...(v ?? [])].sort().join(\",\")\n return [\n entry.source,\n `ext:${join(entry.extensions)}`,\n `skills:${join(entry.skills)}`,\n `prompts:${join(entry.prompts)}`,\n `themes:${join(entry.themes)}`,\n ].join(\"::\")\n}\n\n/** Order-independent cache key for a launch's full `packages[]` slice. */\nexport function piPackageCacheKey(packages: ReadonlyArray<PiPackageEntry>): string {\n const specs = packages.map(piPackageSpecFingerprint).sort()\n return createHash(\"sha256\").update(specs.join(\"\\n\")).digest(\"hex\").slice(0, 16)\n}\n\nexport function piPackageCacheDir(key: string): string {\n return path.join(PATHS.APP_DIR, \"pi-packages\", key)\n}\n\nfunction npmDirOf(root: string): string {\n return path.join(root, \"npm\")\n}\n\nasync function mtimeMsOf(dir: string): Promise<number | null> {\n try {\n const stat = await fs.stat(dir)\n return stat.mtimeMs\n } catch {\n return null\n }\n}\n\n/**\n * Copy the cached `<key>/npm` tree into a fresh mirror before Pi boots.\n * Returns true on a hit (mirror pre-seeded; Pi should install nothing).\n * Stale entries (older than the max age) are a miss so the launch\n * refreshes to upstream latest. Never throws.\n */\nexport async function seedPiPackageCache(\n mirrorDir: string,\n packages: ReadonlyArray<PiPackageEntry>,\n): Promise<boolean> {\n if (cacheDisabled()) return false\n const key = piPackageCacheKey(packages)\n const cachedNpm = npmDirOf(piPackageCacheDir(key))\n const mtime = await mtimeMsOf(cachedNpm)\n if (mtime === null) return false\n if (Date.now() - mtime > PI_PACKAGE_CACHE_MAX_AGE_MS) {\n consola.debug(`Pi package cache ${key} is stale; refreshing from registry.`)\n return false\n }\n try {\n await fs.cp(cachedNpm, npmDirOf(mirrorDir), { recursive: true })\n return true\n } catch (err) {\n consola.debug(\"Pi package cache seed skipped:\", err)\n return false\n }\n}\n\n/**\n * Persist a mirror's installed `<mirror>/npm` tree back to the cache\n * (call on shutdown, BEFORE the mirror is removed). Overwrites the\n * entry, refreshing its mtime. Never throws.\n */\nexport async function savePiPackageCache(\n mirrorDir: string,\n packages: ReadonlyArray<PiPackageEntry>,\n): Promise<void> {\n if (cacheDisabled()) return\n const mirrorNpm = npmDirOf(mirrorDir)\n const marker = await mtimeMsOf(path.join(mirrorNpm, \"node_modules\"))\n if (marker === null) return\n const dest = npmDirOf(piPackageCacheDir(piPackageCacheKey(packages)))\n try {\n await fs.mkdir(path.dirname(dest), { recursive: true })\n await fs.rm(dest, { recursive: true, force: true })\n await fs.cp(mirrorNpm, dest, { recursive: true })\n } catch (err) {\n consola.debug(\"Pi package cache save skipped:\", err)\n }\n}\n\n/**\n * Sweep cache entries whose `npm/` tree is older than the max age.\n * Best-effort, never throws. Runs opportunistically at boot.\n */\nexport async function sweepStalePiPackageCaches(): Promise<void> {\n if (cacheDisabled()) return\n const root = path.join(PATHS.APP_DIR, \"pi-packages\")\n let entries: Array<string>\n try {\n entries = await fs.readdir(root)\n } catch {\n return\n }\n await Promise.all(\n entries.map(async (entry) => {\n const npmDir = npmDirOf(path.join(root, entry))\n try {\n const mtime = await mtimeMsOf(npmDir)\n if (mtime === null || Date.now() - mtime > PI_PACKAGE_CACHE_MAX_AGE_MS) {\n await fs.rm(path.join(root, entry), { recursive: true, force: true })\n }\n } catch (err) {\n consola.debug(`Pi package cache sweep: skipping ${entry}:`, err)\n }\n }),\n )\n}\n","import {\n BALANCED_PROFILE_MODELS,\n BALANCED_PROFILE_NATIVE_EFFORTS,\n BALANCED_PROFILE_ORACLE_EFFORT,\n BALANCED_PROFILE_ORACLE_MODEL,\n} from \"./balanced-profile-contract\"\nimport {\n CHEAPEST_PROFILE_ADVISOR_EFFORT,\n CHEAPEST_PROFILE_ADVISOR_MODEL,\n CHEAPEST_PROFILE_MODELS,\n CHEAPEST_PROFILE_NATIVE_EFFORTS,\n CHEAPEST_PROFILE_ORACLE_EFFORT,\n CHEAPEST_PROFILE_ORACLE_MODEL,\n} from \"./cheapest-profile-contract\"\nimport { CHEAPEST_CONSULT_CONTRACT } from \"./claude-md-injection\"\nimport { PI_MIN_VERSION } from \"./pi-version-check\"\nimport { piContextWindowFor } from \"./pi-tier-windows\"\n\nexport type PiProfileId = \"cheapest\" | \"balanced\"\n\n/** Minimal catalog view the Pi builders need (adapted from state.models). */\nexport interface PiCatalogModel {\n id: string\n maxContextTokens: number\n maxPromptTokens: number\n maxOutputTokens?: number\n efforts: ReadonlyArray<string>\n /** Canonical endpoint kinds, e.g. \"responses\" | \"chat\" | \"messages\". */\n endpoints: ReadonlyArray<string>\n /**\n * Whether the model accepts image input (`supports.vision`). Absent\n * means unknown — models.json fails OPEN (`[\"text\",\"image\"]`) so Pi's\n * native image paths (@path/--file/paste/read) stay available and the\n * proxy preflight remains the backstop. Only an explicit `false`\n * advertises text-only.\n */\n vision?: boolean\n /** Decoded-byte per-image limit (`limits.vision.max_prompt_image_size`). */\n maxImageBytes?: number\n /**\n * Per-1M USD costs (converted from catalog units by the launcher).\n * All-or-nothing: Pi silently rejects the whole provider when any of\n * the four figures is missing, so the launcher emits `cost` only when\n * input, output, cacheRead AND cacheWrite are all known.\n */\n cost?: {\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n }\n}\n\n/**\n * Pi thinking levels that can appear in `thinkingLevelMap`. `off` is\n * omitted: it means \"no reasoning\" and is never mapped to a provider\n * value.\n */\nexport const PI_THINKING_LEVELS = [\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n] as const\n\n/**\n * Build a Pi `thinkingLevelMap` from a catalog `reasoning_effort`\n * allowlist: supported levels map to themselves, unsupported to `null`\n * (Pi hides them in `/thinking`). Returns `undefined` when the catalog\n * carries no effort signal so Pi falls back to its own defaults rather\n * than a guessed map.\n */\nexport function piThinkingLevelMapFor(\n efforts: ReadonlyArray<string> | undefined,\n): Record<string, string | null> | undefined {\n if (!efforts || efforts.length === 0) return undefined\n const set = new Set(efforts)\n const map: Record<string, string | null> = {}\n for (const level of PI_THINKING_LEVELS) {\n map[level] = set.has(level) ? level : null\n }\n return map\n}\n\n/**\n * Fallback Pi window (tokens) when a model has no pinned cheap-tier\n * threshold. Per-model rows use `piContextWindowFor` (tier threshold);\n * this constant remains the floor no role drops below.\n */\nexport const PI_PROFILE_CONTEXT_TOKENS = 200_000 as const\n/** Provider key used in models.json and agent `provider/model` references. */\nexport const PI_PROVIDER_NAME = \"gh-router\" as const\n\nconst PI_MIN_VERSION_NOTE = `Requires Pi >= ${PI_MIN_VERSION} and Node >= 22.19.`\n\nexport function piLeadModel(profileId: PiProfileId): string {\n return profileId === \"cheapest\"\n ? CHEAPEST_PROFILE_MODELS.lead\n : BALANCED_PROFILE_MODELS.lead\n}\n\nexport function piLeadThinking(profileId: PiProfileId): string {\n // Cheapest lead runs at max effort; balanced at medium (frontier\n // reasoning without the pricey tiers).\n return profileId === \"cheapest\" ? \"max\" : \"medium\"\n}\n\nexport function piOracleModel(profileId: PiProfileId): string {\n return profileId === \"cheapest\"\n ? CHEAPEST_PROFILE_ORACLE_MODEL\n : BALANCED_PROFILE_ORACLE_MODEL\n}\n\nexport function piOracleThinking(profileId: PiProfileId): string {\n return profileId === \"cheapest\"\n ? CHEAPEST_PROFILE_ORACLE_EFFORT\n : BALANCED_PROFILE_ORACLE_EFFORT\n}\n\n/** Cheapest-only advisor. Balanced is advisor-free by design: undefined. */\nexport function piAdvisorModel(\n profileId: PiProfileId,\n): { model: string; thinking: string } | undefined {\n if (profileId !== \"cheapest\") return undefined\n return {\n model: CHEAPEST_PROFILE_ADVISOR_MODEL,\n thinking: CHEAPEST_PROFILE_ADVISOR_EFFORT,\n }\n}\n\nexport interface PiNativeRole {\n name: \"Explore\" | \"General-Purpose\" | \"reviewer\"\n model: string\n thinking: string\n readOnly: boolean\n}\n\nexport function piNativeRoles(profileId: PiProfileId): Array<PiNativeRole> {\n if (profileId === \"cheapest\") {\n return [\n {\n name: \"Explore\",\n model: CHEAPEST_PROFILE_MODELS.explore,\n thinking: CHEAPEST_PROFILE_NATIVE_EFFORTS.Explore,\n readOnly: true,\n },\n {\n name: \"General-Purpose\",\n model: CHEAPEST_PROFILE_MODELS[\"General-Purpose\"],\n thinking: CHEAPEST_PROFILE_NATIVE_EFFORTS[\"General-Purpose\"],\n readOnly: false,\n },\n {\n name: \"reviewer\",\n model: CHEAPEST_PROFILE_MODELS.reviewer,\n thinking: CHEAPEST_PROFILE_NATIVE_EFFORTS.reviewer,\n readOnly: true,\n },\n ]\n }\n return [\n {\n name: \"Explore\",\n model: BALANCED_PROFILE_MODELS.explore,\n thinking: BALANCED_PROFILE_NATIVE_EFFORTS.Explore,\n readOnly: true,\n },\n {\n name: \"General-Purpose\",\n model: BALANCED_PROFILE_MODELS[\"General-Purpose\"],\n thinking: BALANCED_PROFILE_NATIVE_EFFORTS[\"General-Purpose\"],\n readOnly: false,\n },\n {\n name: \"reviewer\",\n model: BALANCED_PROFILE_MODELS.reviewer,\n thinking: BALANCED_PROFILE_NATIVE_EFFORTS.reviewer,\n readOnly: true,\n },\n ]\n}\n\n/**\n * Every model id Pi must see for this profile. Peerless launches\n * (`peers: false`) register the lead only — no peer or native-role model\n * is consumed, so none is exposed to the picker or budgeted.\n */\nexport function piProfileModelIds(\n profileId: PiProfileId,\n opts: { peers?: boolean } = {},\n): Array<string> {\n const ids = new Set<string>([piLeadModel(profileId)])\n if (opts.peers !== false) {\n ids.add(piOracleModel(profileId))\n for (const r of piNativeRoles(profileId)) ids.add(r.model)\n const advisor = piAdvisorModel(profileId)\n if (advisor) ids.add(advisor.model)\n }\n return [...ids]\n}\n\nexport type PiModelApi = \"openai-completions\" | \"openai-responses\"\n\nexport interface PiModelsJson {\n providers: Record<\n string,\n {\n baseUrl: string\n api: PiModelApi\n apiKey: string\n /** Send the dummy bearer; the proxy ignores auth but Pi treats\n * auth-present providers as picker-usable. */\n authHeader: true\n models: Array<{\n id: string\n name: string\n reasoning: true\n input: Array<string>\n contextWindow: number\n /** Pi requires an output limit; the proxy 400s values < 16. */\n maxTokens: number\n cost?: {\n input: number\n output: number\n cacheRead?: number\n cacheWrite?: number\n }\n /**\n * Maps Pi thinking levels to provider values; `null` hides the\n * level in `/thinking`. Derived from the catalog\n * `reasoning_effort` allowlist; omitted when the catalog carries\n * no effort signal.\n */\n thinkingLevelMap?: Record<string, string | null>\n /**\n * Per-model image encode budget so Pi resizes BEFORE sending\n * instead of the proxy dropping after sending. Conservative\n * docs-example values (1568px, 512KiB encoded, q75) clamped\n * further when a model publishes a smaller image-size limit.\n */\n inputLimits?: {\n images?: {\n resize?: {\n maxWidth?: number\n maxHeight?: number\n maxBytes?: number\n jpegQuality?: number\n }\n }\n }\n /** Per-model API override (documented Pi capability) for a\n * future chat-served model on this provider. Omitted when it\n * matches the provider default. */\n api?: PiModelApi\n }>\n }\n >\n}\n\n/**\n * Conservative per-model image resize Pi applies before sending.\n * Docs-example values: 1568px, 512KiB encoded payload, JPEG quality 75.\n * Well under Copilot's 3MiB decoded limit and ample for UI screenshots\n * (measured ~35KB PNG), so sends stay fast and cheap. A model publishing\n * a smaller `max_prompt_image_size` clamps `maxBytes` further via\n * `piImageResizeFor` (encoded budget scaled from the decoded limit).\n */\nexport const PI_IMAGE_RESIZE_MAX_WIDTH: number = 1568\nexport const PI_IMAGE_RESIZE_MAX_HEIGHT: number = 1568\nexport const PI_IMAGE_RESIZE_MAX_BYTES: number = 524288\nexport const PI_IMAGE_RESIZE_JPEG_QUALITY: number = 75\n\n/**\n * Derive the `inputLimits.images.resize` budget for a model row.\n * Returns `undefined` for text-only models (explicit `vision === false`).\n * Otherwise the conservative defaults, with `maxBytes` clamped to the\n * decoded catalog limit scaled to encoded units when that limit is\n * smaller than the default budget.\n */\nexport function piImageResizeFor(\n vision: boolean | undefined,\n maxImageBytes: number | undefined,\n): PiModelsJson[\"providers\"][string][\"models\"][number][\"inputLimits\"] | undefined {\n if (vision === false) return undefined\n let maxBytes = PI_IMAGE_RESIZE_MAX_BYTES\n if (\n typeof maxImageBytes === \"number\"\n && Number.isFinite(maxImageBytes)\n && maxImageBytes > 0\n ) {\n // Encoded payload inflates ~4/3 over decoded bytes; scale the\n // decoded catalog limit into encoded units before clamping.\n const scaled = Math.floor(maxImageBytes * 4 / 3)\n if (scaled < maxBytes) maxBytes = Math.max(scaled, 1)\n }\n return {\n images: {\n resize: {\n maxWidth: PI_IMAGE_RESIZE_MAX_WIDTH,\n maxHeight: PI_IMAGE_RESIZE_MAX_HEIGHT,\n maxBytes,\n jpegQuality: PI_IMAGE_RESIZE_JPEG_QUALITY,\n },\n },\n }\n}\n\n/**\n * Derive a per-model Responses/Completions API from catalog endpoints.\n * Returns `undefined` when the catalog carries no endpoint signal so the\n * caller falls back to the provider default. A Responses-capable model\n * stays on the provider default; a chat-only model overrides to\n * completions.\n */\nexport function piApiForEndpoints(\n endpoints: ReadonlyArray<string> | undefined,\n): PiModelApi | undefined {\n if (!endpoints || endpoints.length === 0) return undefined\n const lower = endpoints.map((e) => e.toLowerCase())\n const hasResponses = lower.some((e) => e.includes(\"responses\"))\n if (hasResponses) return \"openai-responses\"\n if (lower.some((e) => e.includes(\"chat\") || e.includes(\"completion\"))) {\n return \"openai-completions\"\n }\n return undefined\n}\n\n/**\n * Fallback per-request output cap when the catalog carries no\n * max_output_tokens. Matches the documented Luna/Grok 128K ceiling;\n * the live catalog always wins. Never below the proxy's 16-token floor.\n */\nexport const PI_MAX_TOKENS_FALLBACK = 128_000 as const\n\n/** Catalog price units per USD (billing-doc USD x 100 — verified on\n * luna/sol/opus live-vs-doc pairs). Pi cost metadata wants USD/1M;\n * the ratio is spike-verified against the footer math at runtime. */\nexport const PI_CATALOG_UNITS_PER_USD = 100 as const\n\nexport interface PiCatalogTokenPrices {\n batch_size?: number\n input_price?: number\n output_price?: number\n cache_price?: number\n cache_read_price?: number\n cache_write_price?: number\n}\n\n/**\n * Per-1M USD cost for a models.json row, or undefined when unknown.\n *\n * ALL-OR-NOTHING (verified live): Pi silently rejects the entire\n * provider when any of the four figures is missing, surfacing only as\n * `Unknown provider`. A missing figure therefore omits `cost`\n * entirely — guessing zero would under-report real spend, and a\n * partial object breaks the launch.\n */\nexport function piUsdCostFor(\n prices: PiCatalogTokenPrices | undefined,\n): { input: number; output: number; cacheRead: number; cacheWrite: number } | undefined {\n const batch = prices?.batch_size\n const usdPer1M = (v: number | undefined): number | undefined =>\n typeof batch === \"number\" && Number.isSafeInteger(batch) && batch > 0\n && typeof v === \"number\" && Number.isFinite(v) && v >= 0\n ? v / 1e9 * 1e6 / batch / PI_CATALOG_UNITS_PER_USD\n : undefined\n const input = usdPer1M(prices?.input_price)\n const output = usdPer1M(prices?.output_price)\n const cacheRead = usdPer1M(prices?.cache_read_price ?? prices?.cache_price)\n const cacheWrite = usdPer1M(prices?.cache_write_price)\n if (\n input === undefined\n || output === undefined\n || cacheRead === undefined\n || cacheWrite === undefined\n ) {\n return undefined\n }\n return { input, output, cacheRead, cacheWrite }\n}\n\n/**\n * Build the `models.json` provider entry pointing Pi at the running\n * proxy as an ordinary OpenAI-compatible endpoint (the documented\n * Ollama/vLLM pattern — no provider-override extension needed).\n *\n * The provider speaks `openai-responses`: every roster model is\n * Responses-only on Copilot, and Pi POSTs `{baseUrl}/responses` for\n * that API — i.e. our `/v1/responses`, the Codex-proven path. Sending\n * these models to `/v1/chat/completions` is a Copilot 400 (observed).\n * A model whose catalog endpoints lack Responses (future chat-served\n * model) overrides per-model via `piApiForEndpoints`.\n *\n * Every row is BARE (no `[1m]`) with its cheap-tier window from\n * `piContextWindowFor` (272K Luna/Sol, 200K Grok/unknown): Pi budgets\n * `contextWindow` per model, so each role gets its cheapest tier and\n * Long-tier (2x) pricing is structurally unreachable.\n *\n * Vision is fail-open: only an explicit catalog `vision === false`\n * advertises `[\"text\"]`; unknown models advertise `[\"text\",\"image\"]`\n * so Pi's native image paths (@path/--file/paste/read) stay available\n * and the proxy vision preflight (drop-with-note + learned upstream\n * ceilings) remains the backstop. Vision rows also carry\n * `inputLimits.images.resize` so Pi resizes before sending instead of\n * paying a send-then-drop round trip, and `thinkingLevelMap` from the\n * catalog `reasoning_effort` allowlist so Pi never offers an effort\n * tier Copilot would 400.\n */\nexport function buildPiModelsJson(opts: {\n serverUrl: string\n profileId: PiProfileId\n catalog?: ReadonlyArray<PiCatalogModel>\n peers?: boolean\n /** Provider-level API; uniform Responses roster needs no overrides. */\n api?: PiModelApi\n apiOverrides?: Readonly<Record<string, PiModelApi>>\n}): PiModelsJson {\n const baseUrl = `${opts.serverUrl.replace(/\\/+$/, \"\")}/v1`\n const providerApi = opts.api ?? \"openai-responses\"\n return {\n providers: {\n [PI_PROVIDER_NAME]: {\n baseUrl,\n api: providerApi,\n apiKey: \"dummy\",\n authHeader: true as const,\n models: piProfileModelIds(opts.profileId, { peers: opts.peers }).map((id) => {\n const entry = opts.catalog?.find((m) => m.id === id)\n const out = entry?.maxOutputTokens\n const maxTokens =\n typeof out === \"number\" && Number.isFinite(out) && out >= 16\n ? Math.floor(out)\n : PI_MAX_TOKENS_FALLBACK\n const endpointApi = piApiForEndpoints(entry?.endpoints)\n const override = opts.apiOverrides?.[id] ?? endpointApi\n const thinkingLevelMap = piThinkingLevelMapFor(entry?.efforts)\n const inputLimits = piImageResizeFor(entry?.vision, entry?.maxImageBytes)\n return {\n id,\n name: id,\n reasoning: true as const,\n input: entry?.vision === false ? [\"text\"] : [\"text\", \"image\"],\n contextWindow: piContextWindowFor(id, entry?.maxContextTokens),\n maxTokens,\n ...(entry?.cost ? { cost: entry.cost } : {}),\n ...(thinkingLevelMap ? { thinkingLevelMap } : {}),\n ...(inputLimits ? { inputLimits } : {}),\n ...(override && override !== providerApi ? { api: override } : {}),\n }\n }),\n },\n },\n }\n}\n\nexport interface PiCompactionSettings {\n enabled: true\n reserveTokens: number\n keepRecentTokens: number\n modelOverrides: Record<\n string,\n { reserveTokens: number; keepRecentTokens: number }\n >\n}\n\n/**\n * Derive Pi compaction budgets from live catalog `max_prompt_tokens`\n * ceilings AND each model's cheap-tier window — the Pi-native analogue\n * of `deriveAutoCompactWindowTokens`. Pi triggers at\n * `contextWindow − reserveTokens` per active model; the trigger must sit\n * below BOTH the tier price cliff and Copilot's acceptance ceiling:\n * reserve(id) = window(id) − floor(min(prompt, window) × 0.85),\n * clamped to [16384, 100000]. keepRecentTokens stays 20000.\n * The global reserve is the max over models (every model's trigger is\n * safe); overrides carry each model's own value. Unknown catalog (no\n * prompt metadata) → Pi built-in defaults so a missing signal can never\n * disable compaction.\n */\nexport function derivePiCompactionSettings(\n catalog: ReadonlyArray<PiCatalogModel> | undefined,\n modelIds: ReadonlyArray<string>,\n): PiCompactionSettings {\n const FALLBACK = {\n enabled: true as const,\n reserveTokens: 16384,\n keepRecentTokens: 20000,\n modelOverrides: {},\n }\n if (!catalog || catalog.length === 0) return FALLBACK\n const perModel = new Map<string, number>()\n for (const id of modelIds) {\n const entry = catalog.find((m) => m.id === id)\n const window = piContextWindowFor(id, entry?.maxContextTokens)\n const prompt = entry?.maxPromptTokens ?? 0\n const ceiling =\n Number.isFinite(prompt) && prompt > 0 ? Math.min(prompt, window) : window\n perModel.set(\n id,\n Math.min(100_000, Math.max(16384, window - Math.floor(ceiling * 0.85))),\n )\n }\n if (perModel.size === 0) return FALLBACK\n const global = Math.max(...perModel.values())\n const modelOverrides: PiCompactionSettings[\"modelOverrides\"] = {}\n for (const [id, reserve] of perModel) {\n modelOverrides[`${PI_PROVIDER_NAME}/${id}`] = {\n reserveTokens: reserve,\n keepRecentTokens: 20000,\n }\n }\n return {\n enabled: true,\n reserveTokens: global,\n keepRecentTokens: 20000,\n modelOverrides,\n }\n}\n\n/**\n * A Pi `packages[]` entry: either a bare source string (load everything\n * the package declares) or the object form narrowing which resource types\n * load. Object filters can only NARROW the package manifest — they never\n * expose undeclared resources.\n */\nexport type PiPackageEntry =\n | string\n | {\n source: string\n extensions?: Array<string>\n skills?: Array<string>\n prompts?: Array<string>\n themes?: Array<string>\n }\n\nexport interface PiSettingsJson {\n defaultProvider: string\n defaultModel: string\n defaultThinkingLevel: string\n enabledModels: Array<string>\n defaultTools: Array<string>\n compaction: PiCompactionSettings\n /**\n * Per-model startup thinking levels keyed by exact `provider/modelId`.\n * Keeps the picker on tiers the catalog actually supports so Pi never\n * sends an effort Copilot would 400.\n */\n modelThinkingLevels?: Record<string, string>\n /** Inline-image display in capable terminals; part of the native\n * image loop (paste/attach → see → reason). `showTerminalProgress`\n * emits OSC 9;4 tab progress (unsupported terminals ignore it). */\n terminal?: {\n showImages?: boolean\n imageWidthCells?: number\n showTerminalProgress?: boolean\n }\n /**\n * Markdown rendering. Mermaid diagrams stream-render in the TUI\n * (pure display — zero tokens); pinned so a future Pi default change\n * cannot silently drop it. Cosmetic-overridable like the other look keys.\n */\n markdown?: {\n mermaid?: \"off\" | \"final\" | \"streaming\"\n }\n /** Native image pipeline switches. `autoResize` keeps sends under\n * Copilot's image-size limit; `blockImages` is never set (that would\n * reintroduce the text-only block at the settings layer). */\n images?: {\n autoResize?: boolean\n blockImages?: boolean\n }\n /** Preferred transport for multi-transport providers. */\n transport?: \"auto\" | \"sse\" | \"websocket\" | \"websocket-cached\"\n /**\n * Condense the post-update changelog. Display-only noise reduction\n * on update days; zero tokens, fully reversible below.\n */\n collapseChangelog?: boolean\n /**\n * Hide thinking blocks in the transcript. Default-on: reasoning\n * effort still applies, only the display is suppressed. Toggle at\n * runtime via `/settings`; never affects cost or behavior.\n */\n hideThinkingBlock?: boolean\n /**\n * Companion config for the bundled `pi-claude-code-ui` package\n * (which reads flat settings keys): `false` keeps its fixed\n * Claude-style palette regardless of the active Pi theme instead of\n * deriving chrome colors from it. Gated on the `ui` bundle — inert\n * and therefore omitted when the package is not loaded.\n */\n themeAdaptive?: boolean\n /**\n * Claude-Code-style one-line tool rows (same companion package):\n * `summary`/`count` collapse completed calls to a single summary\n * line instead of multi-line previews (expandable via Ctrl+O).\n * Gated on the `ui` bundle like `themeAdaptive`.\n */\n groupToolCalls?: boolean\n readOutputMode?: \"hidden\" | \"summary\" | \"preview\"\n searchOutputMode?: \"hidden\" | \"count\" | \"preview\"\n mcpOutputMode?: \"hidden\" | \"summary\" | \"preview\"\n bashOutputMode?: \"opencode\" | \"summary\" | \"preview\"\n /**\n * Transparent tool-row backgrounds (no heavy chrome — closest to\n * Claude Code's chromeless rows). Same companion-package gating as\n * the other cc-ui keys.\n */\n toolBackground?: \"default\" | \"transparent\" | \"outlines\" | \"border\"\n /**\n * Active Pi theme. Default is the genuine Claude Code dark palette\n * (provided by the bundled theme package below); light-terminal\n * users can pick `claude-code-light` (or any installed theme) and\n * — like every other look key — their own snapshot value wins.\n */\n theme?: string\n /** Branch-summary token budget for session-tree navigation. */\n branchSummary?: {\n reserveTokens?: number\n skipPrompt?: boolean\n }\n retry: {\n enabled: boolean\n maxRetries: number\n /**\n * Provider-level retries stay at 0: provider retries delay Pi from\n * handling quota/usage-limit errors itself, and the proxy already\n * owns transient retry below the agent.\n */\n provider?: {\n maxRetries?: number\n }\n }\n packages: Array<PiPackageEntry>\n /**\n * Subagent overrides. Only `agentOverrides` with `disabled` flags is\n * emitted: the builtin `scout`/`worker`/`researcher`/`evidence-auditor`\n * agents are hidden so habitual invocations resolve deterministically\n * via our own agents' `aliases` instead of running shadow rosters,\n * and the `claude-code`/`codex-exec`/`cursor-agent` families (+ their\n * `-writer` variants) are hidden because they shell out to other CLIs\n * with the operator's own auth — off-proxy, off-ledger, off-cost-control.\n * `delegate` stays enabled (append-mode, inherits the lead model, so it\n * is cost-safe and fills the lightweight-subtask path our roster lacks).\n * `reviewer`/`oracle` need no entry: our same-named files shadow them.\n */\n subagents?: {\n agentOverrides?: Record<string, { disabled?: boolean }>\n }\n}\n\n/**\n * Presentational settings keys that stay user-customizable. When the\n * snapshotted user settings already define one of these, the user's\n * value wins over the built default at launch-merge time (see\n * `applyCosmeticUserOverrides`). Everything else the builder emits —\n * models, tools, thinking levels, compaction, retry, packages — stays\n * built-wins: those are the cost contract, not a preference.\n */\nexport const PI_COSMETIC_SETTING_KEYS = [\n \"hideThinkingBlock\",\n \"theme\",\n \"themeAdaptive\",\n \"groupToolCalls\",\n \"readOutputMode\",\n \"searchOutputMode\",\n \"mcpOutputMode\",\n \"bashOutputMode\",\n \"toolBackground\",\n \"terminal\",\n \"images\",\n \"markdown\",\n \"collapseChangelog\",\n] as const\n\nexport type PiCosmeticSettingKey = (typeof PI_COSMETIC_SETTING_KEYS)[number]\n\n/**\n * Overlay user-defined presentational values onto built settings.\n * Only keys listed in `PI_COSMETIC_SETTING_KEYS` that are actually\n * present (not `undefined`) in `userSettings` override — so a user\n * `~/.pi/agent/settings.json` with e.g. `\"hideThinkingBlock\": false`\n * or `\"readOutputMode\": \"preview\"` keeps their look, while everyone\n * else gets the Claude-Code-like defaults. Returns the picked\n * overrides (empty object when the user customized nothing).\n */\nexport function applyCosmeticUserOverrides(\n userSettings: Record<string, unknown> | undefined,\n builtSettings: PiSettingsJson,\n): Record<string, unknown> {\n const overrides: Record<string, unknown> = {}\n if (!userSettings) return overrides\n const built = builtSettings as unknown as Record<string, unknown>\n for (const key of PI_COSMETIC_SETTING_KEYS) {\n if (!(key in userSettings)) continue\n const value = userSettings[key]\n if (value === undefined) continue\n if (!(key in built)) continue\n overrides[key] = value\n }\n return overrides\n}\n\n/**\n * Helpful third-party bundle, wired extensions-only (skills/prompts/\n * themes filtered out so third-party prose never reaches Ctrl+O — same\n * policy as `pi-subagents`). Router-owned surfaces stay excluded:\n * no statusline/footer package (built into `local:gh-router-pi`), no\n * compaction replacers, no provider/model overriders.\n *\n * - `pi-mcp-adapter`: MCP servers as one proxy tool instead of hundreds\n * of definitions (context/cost win).\n * - `pi-web-access`: search/fetch/PDF-extract fallback. Only wired when\n * the launch has neither `--search` nor `--browse`, otherwise it\n * double-pays our ColBERT/browser surfaces.\n * - `pi-agent-extensions`: allowlisted stable extensions only\n * (sessions, structured questions, todos, handoff, context\n * dashboards, notifications, analytics). `review`/`loop`/`workflow`/\n * `control` overlap our delegate/review pipeline and `powerline-footer`\n * would fight the router-owned AIC footer, so all are excluded.\n * `files` is deliberately excluded too: it registers `ctrl+shift+o`\n * (file browser), colliding with `pi-claude-code-ui`'s `ctrl+shift+o`\n * (extra tool detail) — Pi warns and the files binding dies, so\n * shipping it only buys noise. `@file` mentions + the `context`\n * dashboard + `read`/`ls`/`find` cover the need.\n */\nexport const PI_HELPERS_MCP_ADAPTER: PiPackageEntry = {\n source: \"npm:pi-mcp-adapter\",\n skills: [],\n prompts: [],\n}\n\nexport const PI_HELPERS_WEB_ACCESS: PiPackageEntry = {\n source: \"npm:pi-web-access\",\n skills: [],\n prompts: [],\n}\n\n/** Verified manifest paths (pi-agent-extensions 0.5.x). Bare relative\n * form, NO `./` prefix: Pi matches package-filter patterns with\n * minimatch against root-relative paths, and a `./` prefix matches\n * nothing (observed live: zero extensions loaded, silent).\n * `extensions/files/index.ts` is intentionally absent: it owns\n * `ctrl+shift+o`, which `pi-claude-code-ui` also registers. */\nexport const PI_HELPERS_AGENT_EXTENSIONS: PiPackageEntry = {\n source: \"npm:pi-agent-extensions\",\n extensions: [\n \"extensions/sessions/index.ts\",\n \"extensions/ask-user/index.ts\",\n \"extensions/handoff/index.ts\",\n \"extensions/notify/index.ts\",\n \"extensions/context/index.ts\",\n \"extensions/todos/index.ts\",\n \"extensions/answer/index.ts\",\n \"extensions/cwd-history/index.ts\",\n \"extensions/session-breakdown/index.ts\",\n ],\n skills: [],\n prompts: [],\n themes: [],\n}\n\n/** Claude-look UI bundle: transcript grouping, Shiki diffs, Ctrl+O\n * previews. Default-on (purely presentational — zero model cost);\n * opt out with `--no-ui`. `pi-code` behaviors stay a docs recipe:\n * its `/memory` + `/context` commands would collide with the\n * router-owned pair in `gh-router-pi`, and Pi offers no per-command\n * filtering inside one extension. */\nexport const PI_UI_PACKAGES: ReadonlyArray<PiPackageEntry> = Object.freeze([\n \"npm:pi-claude-code-ui\",\n])\n\n/**\n * Claude Code dark theme (`#D77757` coral and friends) from\n * `better-claude-code-ui`, which ships six CC palettes. Themes-only:\n * extensions/skills/prompts are explicitly emptied so none of the\n * package's status line, footer, or tool rendering loads and fights\n * the router-owned footer or `pi-claude-code-ui`. Theme files are\n * pure JSON data — loading the whole `./theme` dir costs nothing at\n * runtime and leaves all six CC variants pickable via `/settings`,\n * with `claude-code-dark` the default (see `PI_CC_DARK_THEME`).\n */\nexport const PI_CC_THEME_PACKAGE: PiPackageEntry = {\n source: \"npm:better-claude-code-ui\",\n // Bare relative glob, NO `./` prefix (see note above): minimatch\n // matches manifest files by root-relative path, so `./theme` selects\n // nothing and the theme silently fails to load. All six CC variants\n // load as pure JSON data (zero runtime cost); the default is\n // `claude-code-dark`, light-terminal users pick `claude-code-light`.\n themes: [\"theme/*.json\"],\n extensions: [],\n skills: [],\n prompts: [],\n}\n\n/** Default Pi theme: genuine Claude Code dark palette. */\nexport const PI_CC_DARK_THEME = \"claude-code-dark\" as const\n\n/** Built-in tools enabled at startup (Pi-native set incl. Windows). */\nexport const PI_DEFAULT_TOOLS: ReadonlyArray<string> = Object.freeze([\n \"read\",\n \"bash\",\n \"powershell\",\n \"edit\",\n \"write\",\n \"grep\",\n \"find\",\n \"ls\",\n])\n\n/**\n * Build the per-launch `settings.json`. Additive over the snapshotted\n * user settings (the launcher merges lists it owns): narrow model\n * scope, fixed thinking, limited toolset, derived compaction, and the\n * mode's package slice. Never disables retry/transport hardening.\n *\n * `pi-subagents` rides `peersEnabled` and loads extensions ONLY\n * (skills/prompts filtered out — the mode's own skills/prompts cover\n * the roster, so the third-party sets never reach Ctrl+O).\n * The helpful bundle rides `helpers` (default on, peers-gated):\n * `pi-mcp-adapter` + allowlisted `pi-agent-extensions` always, plus\n * `pi-web-access` only when neither search nor browse is on (otherwise\n * it double-pays our ColBERT/browser surfaces). The `--ui` bundle\n * (`pi-code`, `pi-claude-code-ui`) is opt-in.\n * The statusline footer is built into `local:gh-router-pi` (no\n * third-party statusline package: the community bridge reads only the\n * user's real global/project settings and never sees the launch mirror,\n * so it cannot drive a per-launch footer).\n */\nexport function buildPiSettingsJson(opts: {\n profileId: PiProfileId\n searchEnabled: boolean\n browseEnabled: boolean\n catalog?: ReadonlyArray<PiCatalogModel>\n peers?: boolean\n helpers?: boolean\n ui?: boolean\n}): PiSettingsJson {\n const peers = opts.peers !== false\n const helpers = opts.helpers !== false && peers\n const webAccess = helpers && !opts.searchEnabled && !opts.browseEnabled\n const ui = opts.ui !== false\n const modelIds = piProfileModelIds(opts.profileId, { peers })\n const modelThinkingLevels: Record<string, string> = {}\n modelThinkingLevels[`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`] =\n piLeadThinking(opts.profileId)\n for (const role of piNativeRoles(opts.profileId)) {\n modelThinkingLevels[`${PI_PROVIDER_NAME}/${role.model}`] = role.thinking\n }\n modelThinkingLevels[`${PI_PROVIDER_NAME}/${piOracleModel(opts.profileId)}`] =\n piOracleThinking(opts.profileId)\n const advisor = piAdvisorModel(opts.profileId)\n if (advisor) {\n modelThinkingLevels[`${PI_PROVIDER_NAME}/${advisor.model}`] =\n advisor.thinking\n }\n return {\n defaultProvider: PI_PROVIDER_NAME,\n defaultModel: piLeadModel(opts.profileId),\n defaultThinkingLevel: piLeadThinking(opts.profileId),\n enabledModels: modelIds.map((id) => `${PI_PROVIDER_NAME}/${id}`),\n defaultTools: [...PI_DEFAULT_TOOLS],\n modelThinkingLevels,\n terminal: { showImages: true, imageWidthCells: 60, showTerminalProgress: true },\n markdown: { mermaid: \"streaming\" },\n collapseChangelog: true,\n images: { autoResize: true, blockImages: false },\n transport: \"auto\",\n hideThinkingBlock: true,\n ...(ui\n ? {\n themeAdaptive: false,\n groupToolCalls: true,\n readOutputMode: \"summary\" as const,\n searchOutputMode: \"count\" as const,\n mcpOutputMode: \"summary\" as const,\n bashOutputMode: \"summary\" as const,\n toolBackground: \"transparent\" as const,\n theme: PI_CC_DARK_THEME,\n }\n : {}),\n branchSummary: { reserveTokens: 16384, skipPrompt: false },\n compaction: derivePiCompactionSettings(opts.catalog, modelIds),\n retry: { enabled: true, maxRetries: 3, provider: { maxRetries: 0 } },\n packages: [\n ...(peers\n ? [{ source: \"npm:pi-subagents\", skills: [], prompts: [] } as PiPackageEntry]\n : []),\n ...(helpers ? [PI_HELPERS_MCP_ADAPTER, PI_HELPERS_AGENT_EXTENSIONS] : []),\n ...(webAccess ? [PI_HELPERS_WEB_ACCESS] : []),\n ...(ui ? [...PI_UI_PACKAGES, PI_CC_THEME_PACKAGE] : []),\n \"local:gh-router-pi\",\n ],\n // Disabled builtins ride `peers` like the package itself: peerless\n // launches have no delegation floor at all, so nothing to disambiguate.\n ...(peers\n ? {\n subagents: {\n agentOverrides: {\n scout: { disabled: true },\n worker: { disabled: true },\n researcher: { disabled: true },\n \"evidence-auditor\": { disabled: true },\n // External-CLI families (0.71+): shell out to other CLIs\n // with ambient auth. Off-proxy and off-ledger — never in a\n // cost-controlled launch.\n \"claude-code\": { disabled: true },\n \"claude-code-writer\": { disabled: true },\n \"codex-exec\": { disabled: true },\n \"codex-exec-writer\": { disabled: true },\n \"cursor-agent\": { disabled: true },\n \"cursor-agent-writer\": { disabled: true },\n },\n },\n }\n : {}),\n }\n}\n\nfunction agentFileName(name: string): string {\n return `${name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\")}.md`\n}\n\n/**\n * Deep-merge the `subagents` settings key across the snapshot/user and\n * built layer. Only `agentOverrides` merges (per-agent, user wins);\n * every other `subagents` sub-key follows the standard rule (built wins\n * when present, else user survives). Non-object inputs are ignored so a\n * corrupt user file degrades to built-only instead of crashing launch.\n */\nexport function mergeSubagentsSettings(\n userSubagents: unknown,\n builtSubagents: PiSettingsJson[\"subagents\"],\n): Record<string, unknown> | undefined {\n const user =\n userSubagents && typeof userSubagents === \"object\" && !Array.isArray(userSubagents)\n ? (userSubagents as Record<string, unknown>)\n : undefined\n const built = (builtSubagents ?? undefined) as Record<string, unknown> | undefined\n if (!user && !built) return undefined\n const userOverrides =\n user?.[\"agentOverrides\"] && typeof user[\"agentOverrides\"] === \"object\" && !Array.isArray(user[\"agentOverrides\"])\n ? (user[\"agentOverrides\"] as Record<string, unknown>)\n : undefined\n const builtOverrides = built?.[\"agentOverrides\"] as Record<string, unknown> | undefined\n const mergedOverrides =\n userOverrides || builtOverrides\n ? { ...builtOverrides, ...userOverrides }\n : undefined\n return {\n ...user,\n ...built,\n ...(mergedOverrides ? { agentOverrides: mergedOverrides } : {}),\n }\n}\n\nfunction roleDescription(\n profileId: PiProfileId,\n role: PiNativeRole,\n): string {\n // Nested-delegation channel note: General-Purpose is the only native\n // role with a nesting grant, so only it can consult the oracle subagent\n // directly. Explore/reviewer are leaves; they surface open questions in\n // their report and the lead (or General-Purpose) consults oracle.\n const oracleNote =\n \"May consult the oracle subagent when a decision feels risky.\";\n if (role.name === \"Explore\") {\n return \"Fast read-only recon: locate code, answer evidence questions, return compressed context.\"\n }\n if (role.name === \"General-Purpose\") {\n return profileId === \"balanced\"\n ? `General implementation and follow-through on scoped tasks. May hand the result to reviewer only when the change alters behavior. ${oracleNote}`\n : `General implementation and follow-through on scoped tasks. May hand the result to reviewer for assessment. ${oracleNote}`\n }\n return profileId === \"balanced\"\n ? \"Behavior-changing review only: assess a change, narrow scope with search first, delegate targeted discovery to Explore rather than sweeping the repo.\"\n : \"Code review and assessment, including reproducing and root-causing a failure.\";\n}\n\n/**\n * Build `.md` agent definitions for the mode's native roster, in the\n * OpenCode/pi-subagents-lite frontmatter format Pi delegation tools\n * consume (`name/description/tools/model/thinking`, plus `allowedAgents`\n * where the delegation graph has an edge). Bodies are\n * short execution contracts; workflow prose lives in skills so agent\n * files stay small enough to inline cheaply.\n *\n * Load-bearing semantics (verified against pi-subagents docs + source):\n * - `reviewer`/`oracle` intentionally SHADOW the same-named builtins\n * wholesale (user scope wins; omitted fields are NOT inherited). That\n * is how the roster pins gh-router models/thinking for cost control.\n * The shadowed `advisor` alias dies with the builtin oracle definition,\n * which is why `advisor` ships as its own file on cheapest.\n * Shadowing deliberately does NOT inherit `contact_supervisor` on\n * reviewer (leaf) or `defaultContext: fork` on oracle (fresh keeps\n * the cold-start consultant contract).\n * - `allowedAgents` only narrows an existing nesting grant, so every\n * delegating agent also sets `allowNestedSubagents: true` and lists\n * `subagent` in `tools`. Depth reaches 3 on balanced\n * (lead → General-Purpose → reviewer → Explore), covered by\n * `PI_SUBAGENT_MAX_DEPTH=3` in the launch env (default guard is 2).\n * - `async: false` on every file: foreground children run in-process\n * with the parent's full tool registry. The detached background\n * runner demonstrably drops read/bash from its registry (observed\n * live as \"requested unavailable child tools: [read, bash]\"),\n * failing every strict-allowlist child it touches.\n * - Deliberately NO `output:`/`defaultReads`/`defaultProgress` file\n * bindings: single-shot launches resolve relative outputs under\n * per-run artifact dirs while `defaultReads` resolves against the\n * child cwd and skips missing files silently — a lead-mediated\n * Explore→General-Purpose file handoff never fires. Handoff is inline\n * prose via the delegating brief instead. `defaultProgress` is doubly\n * out: its default dir is the repo cwd (untracked litter, no cleanup).\n * - `advertise: true` puts custom agents in the parent prompt catalog\n * (default false); `aliases` catch habitual builtin invocations\n * (`scout`, `worker`, …) deterministically since those builtins are\n * disabled in settings.\n * - `inheritProjectContext: true` keeps bridged repo rules (AGENTS.md)\n * visible to children; `defaultContext: fresh` pins the cold-start\n * contract explicitly instead of relying on implicit fallback.\n */\nexport function buildPiAgentFiles(\n profileId: PiProfileId,\n): Record<string, string> {\n const files: Record<string, string> = {}\n for (const role of piNativeRoles(profileId)) {\n const isImplementer = role.name === \"General-Purpose\"\n const isReviewer = role.name === \"reviewer\"\n // `watchdog_diff` (diff-anchored review) is provided by the\n // pi-subagents runtime, like the delegation primitives — no extra\n // package needed. Balanced reviewer additionally lists `subagent`:\n // it holds the roster's other nesting grant (→ Explore) and the\n // grant is inert without it.\n //\n // Bare comma form (no brackets), matching every pi-subagents\n // builtin file. `contact_supervisor` appears ONLY on the writer:\n // it is a blocked-child escalation channel, meaningless on leaves\n // (reviewer/Explore just return; supervisor pings from them are\n // noise that costs a turn each).\n const tools = isImplementer\n ? \"read, grep, find, ls, bash, edit, write, subagent, contact_supervisor\"\n : isReviewer\n ? profileId === \"balanced\"\n ? \"read, grep, find, ls, watchdog_diff, subagent\"\n : \"read, grep, find, ls, watchdog_diff\"\n : \"read, grep, find, ls, bash\";\n const lines = [\n \"---\",\n `name: ${role.name}`,\n `description: ${roleDescription(profileId, role)}`,\n `tools: ${tools}`,\n `model: ${PI_PROVIDER_NAME}/${role.model}`,\n `thinking: ${role.thinking}`,\n \"advertise: true\",\n // Foreground by default. pi-subagents launches workflow children\n // async (detached runner) by default, and the runner's tool\n // registry demonstrably drops read/bash (observed live:\n // \"requested unavailable child tools: [read, bash]\"), failing\n // every strict-allowlist child. Foreground children run in-process\n // with the parent's full registry — nesting works, no spawn\n // overhead, no runner cost. Explicit call values still win.\n \"async: false\",\n \"systemPromptMode: replace\",\n \"inheritProjectContext: true\",\n \"defaultContext: fresh\",\n ];\n if (role.name === \"Explore\") {\n // `scout` alias absorbs habitual builtin invocations (the builtin is\n // disabled in settings). Handoff is inline prose: the lead pastes\n // brief excerpts into the next brief (see gh-delegate skill).\n // Bare form (no brackets): the aliases/allowedAgents splitter does\n // not understand YAML flow lists — `[reviewer, oracle]` parses as\n // `'[reviewer'` + `'oracle]'` and fails the run (observed live).\n lines.push(\"aliases: scout\");\n }\n if (isImplementer) {\n // Aliases absorb builtin `worker` traffic (`developer/coder` plus\n // `implementer/develop`, all builtin-worker aliases);\n // `acceptanceRole: writer` restores the builtin worker's acceptance\n // inference that shadowing would otherwise drop.\n lines.push(\n \"aliases: worker, developer, coder, implementer, develop\",\n \"acceptanceRole: writer\",\n \"allowNestedSubagents: true\",\n \"allowedAgents: reviewer, oracle\",\n );\n }\n if (profileId === \"balanced\" && isReviewer) {\n lines.push(\"allowNestedSubagents: true\", \"allowedAgents: Explore\");\n }\n lines.push(\"---\", \"\");\n if (role.name === \"Explore\") {\n lines.push(\n \"You are a read-only scout. Never modify files.\",\n \"Use bash only for non-interactive inspection.\",\n \"Search first, read second: return the smallest sufficient evidence — entry points,\",\n \"key types and functions, data flow, files likely to need changes, constraints and\",\n \"open questions — with exact file paths and line ranges.\",\n );\n } else if (isReviewer) {\n lines.push(\n \"You are a disciplined review subagent. Inspect the actual change; verify from code,\",\n \"tests, and docs — never guess. Cover intent match, correctness and edge cases,\",\n \"test coverage, side effects, and minimality.\",\n \"Report findings with file:line evidence ranked P0 (blocker) / P1 (should fix) / P2 (nit),\",\n \"ending with one of: Merge verdict: BLOCK, Merge verdict: OK, Merge verdict: OK with notes.\",\n \"You have no shell: cite the test commands for the lead to run rather than executing them.\",\n \"Do not rewrite code outside small, clearly-marked suggestions.\",\n );\n } else {\n lines.push(\n \"You are the single writer thread. Execute the assigned task with narrow, coherent edits;\",\n \"the lead remains the decision authority. Work from the brief's pasted context,\",\n \"then implement minimally and verify by running the relevant tests.\",\n \"If the work reveals an unapproved decision you cannot safely resolve, stop and escalate\",\n \"instead of guessing; never leave placeholders or TODOs.\",\n \"Hand behavior-changing results to reviewer when asked; otherwise summarize the diff,\",\n \"validation, risks, and next step.\",\n );\n }\n files[`agents/${agentFileName(role.name)}`] = `${lines.join(\"\\n\")}\\n`;\n }\n // Oracle consultant agent (both modes). Advisory only: challenges\n // assumptions, never edits. Cold-start fresh context matches the MCP\n // `peers/oracle` tool contract (stateless query + context, no transcript),\n // deliberately unlike the builtin's forked decision-consistency role.\n const oracle = [\n \"---\",\n \"name: oracle\",\n \"description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.\",\n \"tools: read, grep, find, ls, bash\",\n `model: ${PI_PROVIDER_NAME}/${piOracleModel(profileId)}`,\n `thinking: ${piOracleThinking(profileId)}`,\n \"advertise: true\",\n \"async: false\",\n \"systemPromptMode: replace\",\n \"inheritProjectContext: true\",\n \"defaultContext: fresh\",\n \"---\",\n \"\",\n \"You are an oracle: a second set of eyes. You see only the task context\",\n \"you are given — you have no repo memory beyond what you read now.\",\n \"Inspect the code yourself with read/grep/find/ls before opining.\",\n \"Challenge assumptions, name what is missing, recommend; never execute.\",\n ].join(\"\\n\");\n files[`agents/${agentFileName(\"oracle\")}`] = `${oracle}\\n`;\n // Advisor agent (cheapest only). Genuinely new role — the builtin has no\n // separate advisor file (`advisor` is just an alias of builtin oracle, lost\n // in shadowing). Balanced stays advisor-free: no file, no skill, no prompt,\n // no prose — asserted by tests.\n const advisor = piAdvisorModel(profileId);\n if (advisor) {\n const body = [\n \"---\",\n \"name: advisor\",\n \"description: Advisory plan review for the lead: review the final plan before it is presented. Never executes.\",\n \"tools: read, grep, find, ls\",\n `model: ${PI_PROVIDER_NAME}/${advisor.model}`,\n `thinking: ${advisor.thinking}`,\n \"advertise: true\",\n \"async: false\",\n \"systemPromptMode: replace\",\n \"inheritProjectContext: true\",\n \"defaultContext: fresh\",\n \"---\",\n \"\",\n \"You review the lead's final plan and give advisory feedback only.\",\n \"Confirm or challenge approach, scope, and verification steps.\",\n \"You never implement, and your verdict never substitutes for verification.\",\n ].join(\"\\n\");\n files[`agents/${agentFileName(\"advisor\")}`] = `${body}\\n`;\n }\n return files;\n}\n\nexport interface PiLaunchCardOpts {\n version: string\n profileId: PiProfileId\n accountType: string\n /** GitHub login; omitted when setup never resolved it. */\n login?: string\n copilotVersion?: string\n vsCodeVersion?: string\n lead: string\n modelCount: number\n peers: boolean\n helpers: boolean\n ui: boolean\n swe: boolean\n search: boolean\n browse: boolean\n /**\n * Azure MCP groups the launch actually wires into the Pi mirror, by their\n * flag names (`ado`, `kusto`). Empty or absent means none, which is also\n * what a peerless or helper-less launch resolves to: the groups travel\n * through `pi-mcp-adapter`, so without that bundle they are not in the\n * session at all. Passed from the resolved surface decision rather than\n * from `state`, so the card can never advertise a group the mirror lacks.\n */\n azureGroups?: Array<string> | undefined\n serverUrl: string\n}\n\n/**\n * One elegant three-line launch summary for the `pi` preamble,\n * written directly to stderr (no reporter icons or timestamps).\n * Missing facts are omitted, never printed as blanks — a first run\n * that never resolved versions still renders cleanly.\n */\nexport function buildPiLaunchCard(opts: PiLaunchCardOpts): string {\n const surface: Array<string> = []\n surface.push(opts.peers ? \"peers\" : \"peerless\")\n if (opts.peers && opts.helpers) surface.push(\"helpers\")\n if (opts.ui) surface.push(\"ui\")\n if (opts.swe) surface.push(\"swe\")\n if (opts.search) surface.push(\"search\")\n if (opts.browse) surface.push(\"browse\")\n for (const group of opts.azureGroups ?? []) surface.push(group)\n const identity = [\n opts.accountType,\n opts.login,\n opts.copilotVersion ? `copilot chat ${opts.copilotVersion}` : undefined,\n opts.vsCodeVersion ? `vscode ${opts.vsCodeVersion}` : undefined,\n ].filter((part): part is string => typeof part === \"string\" && part.length > 0)\n return [\n `github-router v${opts.version} · pi (${opts.profileId})`,\n ` ${identity.join(\" · \")}`,\n ` lead ${opts.lead} · ${opts.modelCount} models · ${surface.join(\" \")} · ${opts.serverUrl}`,\n ].join(\"\\n\")\n}\n\n/**\n * Short operating digest appended to APPEND_SYSTEM.md (prompt-cache-stable).\n * Mode identity — always injected. Peer consult sentences drop out under\n * `peers: false` so the digest never names tools that don't exist.\n */\nexport function buildPiAppendSystem(\n profileId: PiProfileId,\n opts: { peers?: boolean } = {},\n): string {\n const peers = opts.peers !== false;\n const advisor = peers ? piAdvisorModel(profileId) : undefined;\n const lines = [\n `# gh-router ${profileId} mode`,\n \"\",\n `- Lead owns planning directly; there is no Plan subagent.`,\n ];\n if (peers) {\n lines.push(\n `- Delegate FREELY to Explore for discovery and General-Purpose for scoped work.`,\n `- Call subagent directly (agent + task); save workflows for genuinely parallel fanout.`,\n profileId === \"balanced\"\n ? `- Send work to reviewer ONLY when the change alters behavior.`\n : `- Send finished work to reviewer for assessment.`,\n `- Ask oracle for a second opinion when the decision itself feels risky.`,\n advisor\n ? `- Review the final plan with advisor (advisory) before presenting it.`\n : `- There is no advisor in this mode: oracle is the only consultant.`,\n `- Verify, don't vote: consultant verdicts never substitute for running the tests.`,\n `- After any subagent work completes, always write the final answer yourself.`,\n );\n } else {\n lines.push(\n `- Peerless launch: no subagents or consultants in this session; plan, implement, and verify directly.`,\n );\n }\n if (advisor) {\n // The Claude launcher splits this contract two ways: a short pointer rides\n // the digest while the full text rides the mirrored CLAUDE.md, which\n // Claude Code loads every turn. Pi has no second always-resident surface\n // the launcher owns — APPEND_SYSTEM.md IS the digest, and the mirror's\n // AGENTS.md is bridge-synthesized PROJECT guidance, not ours — so a\n // pointer here would send the lead looking for a file that does not\n // exist. The full contract rides the digest instead; it is the same\n // exported constant the Claude directive uses, which is the property that\n // actually matters: the two front-ends cannot drift.\n lines.push(\"\", CHEAPEST_CONSULT_CONTRACT.trimEnd());\n }\n lines.push(\"\", `(${PI_MIN_VERSION_NOTE})`, \"\");\n return lines.join(\"\\n\");\n}\n","import type { PiProfileId } from \"./pi-models-settings\"\nimport {\n PI_PROVIDER_NAME,\n piAdvisorModel,\n piLeadModel,\n piLeadThinking,\n} from \"./pi-models-settings\"\nimport {\n AIC_STATUSLINE_DISABLE_ENV,\n} from \"./aic-statusline-settings\"\nimport {\n PI_STATUS_COMMAND_ENV,\n PI_STATUSLINE_DEBOUNCE_MS,\n PI_STATUSLINE_TIMEOUT_MS,\n PI_STATUSLINE_WIDTH_FALLBACK,\n buildPiStatusPayload,\n} from \"./pi-statusline\"\n\n/**\n * The gh-router Pi extension source, generated per launch into the\n * isolated mirror (`extensions/gh-router-pi/index.ts`).\n *\n * Design (Pi-cooperative): executable seams only — oracle/advisor\n * consult, semantic search, and browser dispatch all POST JSON-RPC\n * `tools/call` to the running proxy's `/mcp/<group>` with the\n * per-launch nonce (the same `GH_ROUTER_HOOK_MCP_URL/NONCE` channel the\n * Claude hooks use), then return the text. No custom provider, no\n * compaction replacement: `session_before_compact` only routes the\n * summary model and always falls back to Pi native on failure.\n *\n * Statusline footer (always on): this extension owns Pi's footer and\n * renders the SAME `internal-aic-status` runner Claude Code uses, fed a\n * natively-built Claude-shaped payload — one renderer, identical\n * segments. There is deliberately no third-party statusline package and\n * no `statusLine` settings block (the community bridge only reads the\n * user's real global/project settings, never the launch mirror).\n */\n\n/**\n * Statusline footer section for the generated extension. Owns Pi's footer\n * and renders the shared `internal-aic-status` runner (the same binary\n * Claude Code invokes) with a natively-built Claude-shaped payload, so Pi\n * shows byte-identical segments: `[AIC x.xx]` pinned ahead of the rich\n * session line.\n *\n * Fail-open everywhere: disabled via `GH_ROUTER_DISABLE_AIC_STATUSLINE=1`\n * or a missing command env (the launcher always sets it — see `src/pi.ts`);\n * every Pi API access is guarded (extension APIs drift across Pi versions);\n * a hung runner is killed at `PI_STATUSLINE_TIMEOUT_MS`; any error clears\n * back to Pi's native footer, never a broken session.\n *\n * Width: the runner drops segments right-to-left from `COLUMNS`; the last\n * footer width is fed back into the next spawn, and `render()` truncates\n * ANSI-aware as a backstop (same two-layer approach as the retired bridge).\n */\nexport function buildPiStatuslineFooterSection(): Array<string> {\n return [\n ` // Statusline footer: [AIC x.xx] + rich session line, identical to github-router claude.`,\n ` {`,\n ` const STATUS_COMMAND = (process.env.${PI_STATUS_COMMAND_ENV} ?? \"\").trim();`,\n ` const STATUS_DISABLED = process.env.${AIC_STATUSLINE_DISABLE_ENV} === \"1\";`,\n ` if (STATUS_COMMAND && !STATUS_DISABLED) {`,\n ` const buildPayload = (${buildPiStatusPayload.toString()});`,\n ` const DEBOUNCE_MS = ${PI_STATUSLINE_DEBOUNCE_MS};`,\n ` const TIMEOUT_MS = ${PI_STATUSLINE_TIMEOUT_MS};`,\n ` let sessionStartMs = 0;`,\n ` let lastSessionId = null;`,\n ` let lastWidth = ${PI_STATUSLINE_WIDTH_FALLBACK};`,\n ` let lines: Array<string> = [];`,\n ` let lastApplied = \"\\\\0none\";`,\n ` let timer: ReturnType<typeof setTimeout> | null = null;`,\n ` let controller: AbortController | null = null;`,\n ``,\n ` function truncateVisible(line: string, maxWidth: number): string {`,\n ` if (!(maxWidth > 0)) return line;`,\n ` let output = \"\";`,\n ` let width = 0;`,\n ` let i = 0;`,\n ` while (i < line.length) {`,\n ` const ch = line[i];`,\n ` if (ch === \"\\\\u001b\") {`,\n ` let j = i + 1;`,\n ` const next = line[j];`,\n ` if (next === \"[\") {`,\n ` j++;`,\n ` while (j < line.length) {`,\n ` const code = line.charCodeAt(j);`,\n ` if (code >= 64 && code <= 126) { j++; break; }`,\n ` j++;`,\n ` }`,\n ` } else if (next === \"]\") {`,\n ` j++;`,\n ` while (j < line.length) {`,\n ` if (line[j] === \"\\\\u0007\") { j++; break; }`,\n ` if (line[j] === \"\\\\u001b\" && line[j + 1] === \"\\\\\\\\\") { j += 2; break; }`,\n ` j++;`,\n ` }`,\n ` } else {`,\n ` j = Math.min(line.length, i + 2);`,\n ` }`,\n ` output += line.slice(i, j);`,\n ` i = j;`,\n ` continue;`,\n ` }`,\n ` if (width >= maxWidth) return output;`,\n ` output += ch;`,\n ` width++;`,\n ` i++;`,\n ` }`,\n ` return output;`,\n ` }`,\n ``,\n ` function runStatusCommand(command: string, input: string, cwd: string, signal: AbortSignal | undefined): Promise<string> {`,\n ` return new Promise((resolve) => {`,\n ` let child: ReturnType<typeof spawn> | undefined;`,\n ` try {`,\n ` child = spawn(command, { cwd, shell: true, stdio: [\"pipe\", \"pipe\", \"pipe\"], env: { ...process.env, COLUMNS: String(lastWidth) } });`,\n ` } catch { resolve(\"\"); return; }`,\n ` let stdout = \"\";`,\n ` let done = false;`,\n ` let timeout: ReturnType<typeof setTimeout> | null = null;`,\n ` const finish = (value: string): void => {`,\n ` if (done) return;`,\n ` done = true;`,\n ` if (timeout) clearTimeout(timeout);`,\n ` try { signal?.removeEventListener(\"abort\", onAbort); } catch {}`,\n ` resolve(value);`,\n ` };`,\n ` const onAbort = (): void => {`,\n ` try { child?.kill(\"SIGTERM\"); } catch {}`,\n ` finish(\"\");`,\n ` };`,\n ` if (signal) {`,\n ` if (signal.aborted) { onAbort(); return; }`,\n ` try { signal.addEventListener(\"abort\", onAbort, { once: true }); } catch {}`,\n ` }`,\n ` timeout = setTimeout(() => {`,\n ` try { child?.kill(\"SIGTERM\"); } catch {}`,\n ` finish(\"\");`,\n ` }, TIMEOUT_MS);`,\n ` child.stdout.on(\"data\", (chunk) => { stdout += String(chunk); });`,\n ` child.on(\"error\", () => finish(\"\"))`,\n ` child.on(\"close\", (code) => {`,\n ` if (code !== 0) { finish(\"\"); return; }`,\n ` finish(stdout.replace(/\\\\r\\\\n/g, \"\\\\n\").trim());`,\n ` });`,\n ` try { child.stdin.write(input); child.stdin.end(); } catch { finish(\"\"); }`,\n ` });`,\n ` }`,\n ``,\n ` function applyFooter(ctx: any): void {`,\n ` const key = lines.join(\"\\\\0\");`,\n ` if (key === lastApplied) return;`,\n ` lastApplied = key;`,\n ` try {`,\n ` if (lines.length === 0) { ctx.ui.setFooter(undefined); return; }`,\n ` const frozen = [...lines];`,\n ` ctx.ui.setFooter((_tui: any, _theme: any, footerData: any) => ({`,\n ` dispose() {},`,\n ` invalidate() {},`,\n ` render(width: number) {`,\n ` if (typeof width === \"number\" && width > 0) lastWidth = width;`,\n ` const out = frozen.map((l) => truncateVisible(l, lastWidth));`,\n ` try {`,\n ` const statuses = footerData?.getExtensionStatuses?.();`,\n ` const entries = statuses?.entries ? Array.from(statuses.entries()) : [];`,\n ` for (const pair of entries) {`,\n ` const text = String((pair as Array<unknown>)[1] ?? \"\").trim();`,\n ` if (text) out.push(truncateVisible(text, lastWidth));`,\n ` }`,\n ` } catch {}`,\n ` return out;`,\n ` },`,\n ` }));`,\n ` } catch {}`,\n ` }`,\n ``,\n ` async function refresh(ctx: any): Promise<void> {`,\n ` try {`,\n ` if (!ctx || !ctx.hasUI) return;`,\n ` } catch { return; }`,\n ` let entries: Array<unknown> = [];`,\n ` let modelInfo: Record<string, unknown> = {};`,\n ` let usageInfo: Record<string, unknown> | null = null;`,\n ` let sessionId: string | null = null;`,\n ` try {`,\n ` const sm = ctx.sessionManager;`,\n ` if (sm) {`,\n ` if (typeof sm.getBranch === \"function\") entries = sm.getBranch();`,\n ` else if (typeof sm.getEntries === \"function\") entries = sm.getEntries();`,\n ` if (typeof sm.getSessionId === \"function\") {`,\n ` const sid = sm.getSessionId();`,\n ` if (typeof sid === \"string\" && sid) sessionId = sid;`,\n ` }`,\n ` }`,\n ` } catch {}`,\n ` try {`,\n ` const m = ctx.model ?? {};`,\n ` modelInfo = { id: m.id, displayName: m.displayName, name: m.name, contextWindow: m.contextWindow };`,\n ` } catch {}`,\n ` try {`,\n ` if (typeof ctx.getContextUsage === \"function\") {`,\n ` const u = ctx.getContextUsage();`,\n ` if (u) usageInfo = { tokens: u.tokens, contextWindow: u.contextWindow, percent: u.percent };`,\n ` }`,\n ` } catch {}`,\n ` if (lastSessionId !== null && sessionId !== null && sessionId !== lastSessionId) {`,\n ` sessionStartMs = Date.now();`,\n ` lines = [];`,\n ` lastApplied = \"\\\\0reset\";`,\n ` }`,\n ` if (sessionId !== null) lastSessionId = sessionId;`,\n ` if (!sessionStartMs) sessionStartMs = Date.now();`,\n ` let payload: Record<string, unknown>;`,\n ` try {`,\n ` payload = buildPayload({ cwd: ctx.cwd, sessionId, model: modelInfo, contextUsage: usageInfo, entries }, { nowMs: Date.now(), sessionStartMs });`,\n ` } catch { return; }`,\n ` try { controller?.abort(); } catch {}`,\n ` controller = new AbortController();`,\n ` const signal = controller.signal;`,\n ` let text = \"\";`,\n ` try {`,\n ` text = await runStatusCommand(STATUS_COMMAND, JSON.stringify(payload), ctx.cwd, signal);`,\n ` } catch { text = \"\"; }`,\n ` if (signal.aborted) return;`,\n ` const first = (text.split(\"\\\\n\")[0] ?? \"\").trim();`,\n ` lines = first ? [first] : [];`,\n ` applyFooter(ctx);`,\n ` }`,\n ``,\n ` function schedule(ctx: any): void {`,\n ` try {`,\n ` if (timer) clearTimeout(timer);`,\n ` } catch {}`,\n ` try {`,\n ` timer = setTimeout(() => { timer = null; void refresh(ctx); }, DEBOUNCE_MS);`,\n ` } catch {}`,\n ` }`,\n ``,\n ` for (const event of [\"session_start\", \"turn_start\", \"turn_end\", \"model_select\", \"session_compact\", \"session_tree\", \"session_switch\", \"session_fork\"]) {`,\n ` try {`,\n ` pi.on(event, (_event: any, ctx: any) => { schedule(ctx); });`,\n ` } catch {}`,\n ` }`,\n ` try {`,\n ` pi.on(\"session_shutdown\", (_event: any, ctx: any) => {`,\n ` try { if (timer) clearTimeout(timer); } catch {}`,\n ` timer = null;`,\n ` try { controller?.abort(); } catch {}`,\n ` controller = null;`,\n ` lines = [];`,\n ` lastApplied = \"\\\\0none\";`,\n ` sessionStartMs = 0;`,\n ` lastSessionId = null;`,\n ` try { ctx?.ui?.setFooter(undefined); } catch {}`,\n ` });`,\n ` } catch {}`,\n ` }`,\n ` }`,\n ]\n}\n\nexport interface PiBridgeExtensionInput {\n stats: { staticFiles: number; scopedRules: number; imports: number; skipped: number }\n scopedRules: Array<{ file: string; body: string; globs: Array<string>; source: string }>\n}\n\n/**\n * Memory-bridge section for the generated extension: path-scoped rules\n * lazy-attach on `read/edit/write` tool results (once per rule per\n * session, mirroring `pi-code/claude-rules.ts`), plus `/memory` (bridge\n * inventory + auto-memory locations, on-demand only) and `/context`\n * (what bridged vs skipped). Fail-open: every handler is try/catch and\n * returns undefined on any error so Pi native behavior is preserved.\n */\nexport function buildPiMemoryBridgeSection(bridge: PiBridgeExtensionInput): Array<string> {\n // Cap embedded rule bodies so one giant rule can't bloat the mirror\n // extension source (static slice already has its own 24KB budget).\n // Strip NUL bytes: a single literal U+0000 in an embedded body breaks\n // strict downstream JSON consumers (observed as a workflow-preflight\n // `Unexpected character '\\u0000'` parse failure).\n const cappedRules = bridge.scopedRules.map((r) => ({\n file: r.file.replaceAll(\"\\0\", \"\"),\n body: (r.body.length > 8000 ? `${r.body.slice(0, 8000)}\\n…[truncated by gh-router memory bridge]` : r.body).replaceAll(\n \"\\0\",\n \"\",\n ),\n globs: r.globs,\n source: r.source,\n }))\n const payload = JSON.stringify({ stats: bridge.stats, scopedRules: cappedRules })\n return [\n ` // Memory bridge: lazy path-scoped rules + /memory + /context (on-demand only).`,\n ` {`,\n ` let BRIDGE = null;`,\n ` try { BRIDGE = ${payload}; } catch { BRIDGE = null; }`,\n ` const attached = new Set();`,\n ` function globToRegExp(glob) {`,\n ` let g = String(glob || \"\").trim().replace(/^\\\\.\\\\//, \"\").replace(/^\\\\/+/, \"\");`,\n ` let re = \"\";`,\n ` for (let k = 0; k < g.length;) {`,\n ` const c = g[k];`,\n ` if (c === \"*\") {`,\n ` if (g[k + 1] === \"*\") {`,\n ` if (g[k + 2] === \"/\") { re += \"(?:.*/)?\"; k += 3; }`,\n ` else { re += \".*\"; k += 2; }`,\n ` } else { re += \"[^/]*\"; k += 1; }`,\n ` continue;`,\n ` }`,\n ` if (c === \"?\") { re += \"[^/]\"; k += 1; continue; }`,\n ` if (\"+()|^$.{}[]\\\\\\\\\".includes(c)) re += \"\\\\\\\\\" + c; else re += c;`,\n ` k += 1;`,\n ` }`,\n ` if (!g.includes(\"/\")) re = \"(?:.*/)?\" + re;`,\n ` try { return new RegExp(\"^\" + re + \"$\"); } catch { return null; }`,\n ` }`,\n ` function ruleMatches(rule, touchedPath, cwd) {`,\n ` try {`,\n ` const cands = [touchedPath];`,\n ` const base = String(touchedPath || \"\").split(\"/\").pop() || \"\";`,\n ` if (base) cands.push(base);`,\n ` let rel = touchedPath || \"\";`,\n ` try {`,\n ` if (cwd && String(touchedPath).startsWith(String(cwd))) rel = String(touchedPath).slice(String(cwd).length).replace(/^\\\\/+/, \"\");`,\n ` } catch {}`,\n ` if (rel) cands.push(rel);`,\n ` for (const g of (rule.globs || [])) {`,\n ` const re = globToRegExp(g);`,\n ` if (!re) continue;`,\n ` for (const c of cands) { try { if (re.test(c)) return true; } catch {} }`,\n ` }`,\n ` } catch {}`,\n ` return false;`,\n ` }`,\n ` try {`,\n ` pi.on(\"tool_result\", async (event, ctx) => {`,\n ` try {`,\n ` if (!BRIDGE || !Array.isArray(BRIDGE.scopedRules) || BRIDGE.scopedRules.length === 0) return undefined;`,\n ` if (event.isError) return undefined;`,\n ` if (event.toolName !== \"read\" && event.toolName !== \"edit\" && event.toolName !== \"write\") return undefined;`,\n ` const rel = event.input && event.input.path;`,\n ` if (typeof rel !== \"string\" || !rel) return undefined;`,\n ` let abs = rel;`,\n ` try { const cwd = ctx.cwd || \"\"; abs = rel.startsWith(\"/\") ? rel : (cwd ? cwd + \"/\" + rel : rel); } catch {}`,\n ` const bodies = [];`,\n ` for (const rule of BRIDGE.scopedRules) {`,\n ` try {`,\n ` if (attached.has(rule.file)) continue;`,\n ` if (!ruleMatches(rule, abs, ctx.cwd || \"\")) continue;`,\n ` attached.add(rule.file);`,\n ` bodies.push(rule.body);`,\n ` } catch {}`,\n ` }`,\n ` if (bodies.length === 0) return undefined;`,\n ` return { content: [...(event.content || []), ...bodies.map((text) => ({ type: \"text\", text }))] };`,\n ` } catch { return undefined; }`,\n ` });`,\n ` } catch {}`,\n ` try {`,\n ` pi.registerCommand(\"memory\", {`,\n ` description: \"Show bridged memory inventory and auto-memory locations (on-demand; nothing auto-injected)\",`,\n ` handler: async (_args, ctx) => {`,\n ` try {`,\n ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,\n ` const lines = [\"Memory bridge (gh-router)\", \" Static files: \" + s.staticFiles, \" Scoped rules (lazy): \" + s.scopedRules, \" Imports: \" + s.imports, \" Skipped: \" + s.skipped, \" Auto-memory: ~/.claude/projects/<slug>/memory/MEMORY.md (on-demand read only)\", \" Pi memory: ~/.pi/agent/memory/ (your own pi-memory install, snapshotted)\"];`,\n ` try {`,\n ` const files = (BRIDGE.scopedRules || []).map((r) => r.file);`,\n ` if (files.length > 0) lines.push(\" Scoped files:\", ...files.slice(0, 20).map((f) => \" - \" + f));`,\n ` } catch {}`,\n ` lines.push(\"cwd: \" + (ctx.cwd || \"\"));`,\n ` ctx.ui.notify(lines.join(\"\\\\n\"), \"info\");`,\n ` } catch {}`,\n ` },`,\n ` });`,\n ` } catch {}`,\n ` try {`,\n ` pi.registerCommand(\"context\", {`,\n ` description: \"Show what the gh-router memory bridge loaded\",`,\n ` handler: async (_args, ctx) => {`,\n ` try {`,\n ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,\n ` ctx.ui.notify(\"Bridge context: \" + s.staticFiles + \" static, \" + s.scopedRules + \" scoped (attached \" + attached.size + \"), \" + s.imports + \" imports, \" + s.skipped + \" skipped. Native AGENTS.md/CLAUDE.md still load via Pi.\", \"info\");`,\n ` } catch {}`,\n ` },`,\n ` });`,\n ` } catch {}`,\n ` }`,\n ]\n}\n\nexport function buildPiExtensionSource(opts: {\n profileId: PiProfileId\n searchEnabled: boolean\n /**\n * Engine behind `code_search`. Under `bluebird` the tool reaches the Azure\n * DevOps index and a failure is `source:\"error\"` with NO local fallback\n * (`runUnifiedCodeSearch`), so the description must not promise one: a model\n * that believes in a fallback reads an empty `error` result as \"not found\".\n */\n searchBackend?: \"colbert\" | \"bluebird\"\n browseEnabled: boolean\n peers?: boolean\n bridge?: PiBridgeExtensionInput\n}): string {\n const peers = opts.peers !== false\n const advisor = peers ? piAdvisorModel(opts.profileId) : undefined\n // Cheapest-only, like the advisor: the brief is the front-end half of the\n // same floor-raising surface `buildPiAppendSystem` writes the consult contract\n // for, and `balanced` is deliberately floor-free on both counts.\n const promptBrief = opts.profileId === \"cheapest\"\n const lines: Array<string> = []\n lines.push(\n `// gh-router-pi extension (${opts.profileId} mode). Generated per launch; do not edit.`,\n `// Executable seams only. Workflow guidance lives in skills/, not here.`,\n `import { Type } from \"typebox\";`,\n `import { spawn } from \"node:child_process\";`,\n ``,\n ...(peers\n ? [\n `const OracleParams = Type.Object({`,\n ` decision: Type.String({ description: \"The risky decision to get a second opinion on\" }),`,\n ` options: Type.Optional(Type.String({ description: \"Options considered\" })),`,\n ` context: Type.String({ description: \"Missing-context gaps and background the cold-start oracle needs\" }),`,\n `});`,\n ]\n : []),\n ...(advisor\n ? [\n `const AdvisorParams = Type.Object({`,\n ` plan: Type.String({ description: \"The final plan to review (advisory)\" }),`,\n ` context: Type.Optional(Type.String({ description: \"Background context\" })),`,\n `});`,\n ]\n : []),\n ...(opts.searchEnabled\n ? [\n `const CodeSearchParams = Type.Object({`,\n ` query: Type.String({ description: \"What to find\" }),`,\n ` mode: Type.Optional(Type.String({ description: \"semantic (default), lexical, exact, regex, or ast\" })),`,\n ` limit: Type.Optional(Type.Number({ description: \"Max results\" })),`,\n ` workspace: Type.Optional(Type.String({ description: \"Absolute path to the project root to search. Defaults to the launch workspace.\" })),`,\n ` file_glob: Type.Optional(Type.String({ description: \"Optional ripgrep glob filter (e.g. src/**/*.ts)\" })),`,\n `});`,\n ]\n : []),\n ...(opts.browseEnabled\n ? [\n `const OpenTabParams = Type.Object({`,\n ` url: Type.String({ description: \"URL to load\" }),`,\n ` reuseActive: Type.Optional(Type.Boolean({ description: \"Navigate the active tab instead of opening a new one\" })),`,\n `});`,\n `const NavigateParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` action: Type.String({ description: \"goto, back, forward, or reload\" }),`,\n ` url: Type.Optional(Type.String({ description: \"URL for action=goto\" })),`,\n ` hard: Type.Optional(Type.Boolean({ description: \"Reload only: bypass cache\" })),`,\n `});`,\n `const ScreenshotParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` format: Type.Optional(Type.String({ description: \"png or jpeg\" })),`,\n ` quality: Type.Optional(Type.Number({ description: \"JPEG quality 1-100\" })),`,\n `});`,\n `const ActParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` intent: Type.Optional(Type.String({ description: \"Natural-language action (INTENT mode)\" })),`,\n ` ref: Type.Optional(Type.String({ description: \"Element ref for REF mode\" })),`,\n ` action: Type.Optional(Type.String({ description: \"REF mode action\" })),`,\n ` value: Type.Optional(Type.String({ description: \"Value for fill/type/select\" })),`,\n `});`,\n `const ObserveParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` intent: Type.Optional(Type.String({ description: \"Focus for the summary\" })),`,\n `});`,\n `const ExtractParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` schema: Type.Any({ description: \"JSON schema for the desired output shape\" }),`,\n ` instruction: Type.String({ description: \"What to extract\" }),`,\n `});`,\n ]\n : []),\n `function stripNul(s) { return String(s ?? \"\").replace(/\\\\0/g, \"\"); }`,\n `async function toolText(promise) {`,\n // Inbound NUL strip: MCP/tool results flow into workflowScript text and\n // strict downstream JSON consumers reject literal U+0000 (observed as a\n // subagent-workflow validate failure). Outbound params are stripped at\n // each call site; this covers the return path in one place.\n ` const text = await promise;`,\n ` return { content: [{ type: \"text\", text: stripNul(text) }], details: undefined };`,\n `}`,\n `function toolErrorText(text) {`,\n ` return { content: [{ type: \"text\", text }], details: undefined };`,\n `}`,\n `const MCP_URL = (process.env.GH_ROUTER_HOOK_MCP_URL ?? \"\").replace(/\\\\/+$/, \"\");`,\n `const MCP_NONCE = process.env.GH_ROUTER_HOOK_NONCE ?? \"\";`,\n `const PI_WORKSPACE = (process.env.GH_ROUTER_WORKSPACE ?? \"\").trim();`,\n ...(promptBrief\n ? [\n // Backstop only. The proxy bounds its own rewrite at\n // CHEAPEST_REWRITE_TIMEOUT_MS (30s) and answers with an empty text\n // block on a timeout, so this is what catches a hung socket rather\n // than the normal slow path. Kept above the proxy's bound on purpose:\n // below it we would abort work the proxy was about to return.\n `const BRIEF_TIMEOUT_MS = 45000;`,\n ]\n : []),\n `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`,\n `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`,\n `void LEAD_MODEL; void LEAD_THINKING;`,\n ``,\n `async function callMcp(group, tool, args, signal) {`,\n ` const headers = { \"content-type\": \"application/json\", accept: \"application/json\", authorization: \"Bearer \" + MCP_NONCE };`,\n ` if (PI_WORKSPACE && (group === \"search\" || group === \"workers\" || group === \"orchestrate\")) { headers[\"X-GH-Workspace\"] = PI_WORKSPACE; }`,\n ` const res = await fetch(MCP_URL + \"/mcp/\" + group, {`,\n ` method: \"POST\",`,\n ` headers,`,\n ` body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method: \"tools/call\", params: { name: tool, arguments: args } }),`,\n ` signal,`,\n ` });`,\n ` if (!res.ok) throw new Error(\"mcp \" + group + \"/\" + tool + \" -> HTTP \" + res.status);`,\n ` const body = await res.json();`,\n ` if (body.error) return \"Error: \" + body.error.message;`,\n ` const content = body.result && body.result.content;`,\n ` if (!Array.isArray(content)) return \"\";`,\n ` return content.map((c) => c.text || \"\").join(\"\\\\n\");`,\n `}`,\n ``,\n `export default function (pi) {`,\n ...(peers\n ? [\n ` pi.registerTool({`,\n ` name: \"oracle\",`,\n ` label: \"Oracle\",`,\n ` description: \"Second opinion before acting on a risky decision. Advisory only: challenges assumptions, never edits. Pass decision, options, and context.\",`,\n ` parameters: OracleParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` const query = stripNul(params.decision || \"\").trim();`,\n ` const opts = stripNul(params.options || \"\").trim();`,\n ` const ctx = stripNul(params.context || \"\").trim();`,\n ` const context = (opts ? \"Options considered:\\\\n\" + opts + \"\\\\n\\\\n\" : \"\") + ctx;`,\n ` if (!query || !context.trim()) return toolErrorText(\"oracle: decision and context are required (non-empty strings)\");`,\n ` return await toolText(callMcp(\"peers\", \"oracle\", { query, context }, signal));`,\n ` },`,\n ` });`,\n ]\n : []),\n )\n if (advisor) {\n lines.push(\n ` pi.registerTool({`,\n ` name: \"advisor\",`,\n ` label: \"Advisor\",`,\n ` description: \"Advisory plan review for the lead: review the final plan before presenting it. Never executes.\",`,\n ` parameters: AdvisorParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` const plan = stripNul(params.plan || \"\").trim();`,\n ` const ctx = stripNul(params.context || \"\").trim();`,\n ` const context = (plan ? \"Plan under review:\\\\n\" + plan : \"\") + (ctx ? \"\\\\n\\\\nBackground:\\\\n\" + ctx : \"\");`,\n ` if (!plan || !context.trim()) return toolErrorText(\"advisor: plan and context are required (non-empty strings)\");`,\n ` return await toolText(callMcp(\"peers\", \"oracle\", { query: \"Review this plan (advisory)\", context }, signal));`,\n ` },`,\n ` });`,\n )\n }\n if (opts.searchEnabled) {\n const codeSearchDescription =\n opts.searchBackend === \"bluebird\"\n ? \"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.\"\n : \"Semantic-first code search over the workspace index (falls back to lexical with a label). Use for finding code by meaning.\"\n lines.push(\n ` pi.registerTool({`,\n ` name: \"code_search\",`,\n ` label: \"Code search\",`,\n ` description: \"${codeSearchDescription}\",`,\n ` parameters: CodeSearchParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` const query = stripNul(params.query || \"\").trim();`,\n ` if (!query) return toolErrorText(\"code_search: query is required (non-empty string)\");`,\n ` const workspace = (typeof params.workspace === \"string\" && params.workspace.trim()) ? params.workspace.trim() : PI_WORKSPACE;`,\n ` if (!workspace) return toolErrorText(\"code_search: a workspace is required. Pass the absolute project path as workspace.\");`,\n ` const args = { query, mode: params.mode || \"semantic\", limit: params.limit || 15, workspace };`,\n ` if (typeof params.file_glob === \"string\" && params.file_glob) args.file_glob = params.file_glob;`,\n ` return await toolText(callMcp(\"search\", \"code\", args, signal));`,\n ` },`,\n ` });`,\n )\n }\n if (opts.browseEnabled) {\n lines.push(\n ` pi.registerTool({`,\n ` name: \"open_tab\",`,\n ` label: \"Browser open tab\",`,\n ` 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.\",`,\n ` parameters: OpenTabParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` const url = stripNul(params.url || \"\").trim();`,\n ` if (!url) return toolErrorText(\"open_tab: url is required\");`,\n ` const args = { url };`,\n ` if (typeof params.reuseActive === \"boolean\") args.reuseActive = params.reuseActive;`,\n ` return await toolText(callMcp(\"browser\", \"open_tab\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"navigate\",`,\n ` label: \"Browser navigate\",`,\n ` description: \"Navigate an existing tab (MCP browser/navigate). Requires tabId + action; url only for action=goto.\",`,\n ` parameters: NavigateParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"navigate: tabId is required (number from open_tab)\");`,\n ` if (!params.action) return toolErrorText(\"navigate: action is required (goto, back, forward, reload)\");`,\n ` const args = { tabId: params.tabId, action: params.action };`,\n ` if (typeof params.url === \"string\" && params.url) args.url = params.url;`,\n ` if (typeof params.hard === \"boolean\") args.hard = params.hard;`,\n ` return await toolText(callMcp(\"browser\", \"navigate\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"screenshot\",`,\n ` label: \"Browser screenshot\",`,\n ` description: \"Screenshot a tab (MCP browser/screenshot). Requires tabId.\",`,\n ` parameters: ScreenshotParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"screenshot: tabId is required (number from open_tab)\");`,\n ` const args = { tabId: params.tabId };`,\n ` if (typeof params.format === \"string\" && params.format) args.format = params.format;`,\n ` if (typeof params.quality === \"number\") args.quality = params.quality;`,\n ` return await toolText(callMcp(\"browser\", \"screenshot\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"act\",`,\n ` label: \"Browser act\",`,\n ` description: \"Interact with a tab (MCP browser/act). Requires tabId plus intent or ref.\",`,\n ` parameters: ActParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"act: tabId is required (number from open_tab)\");`,\n ` if (!params.intent && !params.ref) return toolErrorText(\"act: intent or ref is required\");`,\n ` const args = { tabId: params.tabId };`,\n ` if (typeof params.intent === \"string\" && params.intent) args.intent = params.intent;`,\n ` if (typeof params.ref === \"string\" && params.ref) args.ref = params.ref;`,\n ` if (typeof params.action === \"string\" && params.action) args.action = params.action;`,\n ` if (typeof params.value === \"string\") args.value = params.value;`,\n ` return await toolText(callMcp(\"browser\", \"act\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"observe\",`,\n ` label: \"Browser observe\",`,\n ` description: \"Summarize a tab (MCP browser/observe). Requires tabId.\",`,\n ` parameters: ObserveParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"observe: tabId is required (number from open_tab)\");`,\n ` const args = { tabId: params.tabId };`,\n ` if (typeof params.intent === \"string\" && params.intent) args.intent = params.intent;`,\n ` return await toolText(callMcp(\"browser\", \"observe\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"extract\",`,\n ` label: \"Browser extract\",`,\n ` description: \"Extract structured data from a tab (MCP browser/extract). Requires tabId, schema, instruction.\",`,\n ` parameters: ExtractParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"extract: tabId is required (number from open_tab)\");`,\n ` if (!params.instruction) return toolErrorText(\"extract: instruction is required\");`,\n ` if (params.schema === undefined) return toolErrorText(\"extract: schema is required\");`,\n ` return await toolText(callMcp(\"browser\", \"extract\", { tabId: params.tabId, schema: params.schema, instruction: params.instruction }, signal));`,\n ` },`,\n ` });`,\n )\n }\n if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) {\n lines.push(...buildPiMemoryBridgeSection(opts.bridge))\n }\n lines.push(\n // Statusline footer (always on — like Claude's operating defaults, not a\n // flag surface): owns Pi's footer with the shared internal-aic-status\n // runner. No third-party statusline package, no settings block.\n ...buildPiStatuslineFooterSection(),\n ` // Route compaction summaries to the mode's cheap capable model;`,\n ` // ALWAYS fall back to Pi native (return undefined) on any failure.`,\n ` pi.on(\"session_before_compact\", async (event) => {`,\n ` try {`,\n ` const preparation = event.preparation;`,\n ` if (!preparation || !Array.isArray(preparation.messagesToSummarize)) return undefined;`,\n ` return undefined; // v1: observe only; native pipeline stays authoritative.`,\n ` } catch {`,\n ` return undefined;`,\n ` }`,\n ` });`,\n ...(promptBrief\n ? [\n // The Claude front-end for this is the `UserPromptSubmit` hook\n // (`internal-prompt-submit`), which runs in its own process and can\n // import the rewrite code. This extension cannot: it is a generated\n // STRING whose only imports are typebox and node:child_process. So the\n // rewrite runs in the PROXY and this handler is a thin relay.\n ` // Cheapest-profile execution brief, injected ABOVE the model's turn.`,\n ` // Produced server-side; this only relays the prompt and re-emits the`,\n ` // result as a custom message. Additive: the user prompt stays the user`,\n ` // turn and systemPrompt is never replaced.`,\n ` let briefShapeWarned = false;`,\n ` pi.on(\"before_agent_start\", async (event, ctx) => {`,\n ` try {`,\n ` if (!event || typeof event !== \"object\") return undefined;`,\n ` // Shape probe: Pi 1.3 carries messageType; the older flat shape does`,\n ` // not, and a missing discriminator would make the brief silently`,\n ` // never fire. Report once rather than no-op forever.`,\n ` if (!(\"messageType\" in event)) {`,\n ` if (!briefShapeWarned) {`,\n ` briefShapeWarned = true;`,\n ` try { ctx.ui.notify(\"gh-router: this Pi build's before_agent_start has no messageType, so the cheapest prompt brief is inactive. Re-run github-router pi to update Pi.\", \"warning\"); } catch {}`,\n ` }`,\n ` return undefined;`,\n ` }`,\n ` if (event.messageType !== \"user\") return undefined;`,\n ` // Stand down inside a pi-subagents async runner: that process hosts`,\n ` // CHILD sessions which load this extension too, and every child would`,\n ` // otherwise spend a brief of its own. pi-subagents marks the process`,\n ` // with PI_SUBAGENT_CHILD=1 (subagent-runner.js). Foreground subagents`,\n ` // run with ambient extensions off, so they never reach here.`,\n ` if (process.env.PI_SUBAGENT_CHILD === \"1\") return undefined;`,\n ` const prompt = String(event.prompt || \"\").trim();`,\n ` if (!prompt) return undefined;`,\n ` const sm = ctx && ctx.sessionManager;`,\n ` const sid = sm && typeof sm.getSessionId === \"function\" ? sm.getSessionId() : \"\";`,\n ` if (typeof sid !== \"string\" || !sid) return undefined;`,\n ` const ac = new AbortController();`,\n ` const timer = setTimeout(() => { try { ac.abort(); } catch {} }, BRIEF_TIMEOUT_MS);`,\n ` let reply = \"\";`,\n ` try {`,\n ` reply = await callMcp(\"search\", \"prompt_brief\", PI_WORKSPACE ? { prompt, session_id: sid, workspace: PI_WORKSPACE } : { prompt, session_id: sid }, ac.signal);`,\n ` } finally { clearTimeout(timer); }`,\n ` const text = stripNul(String(reply || \"\")).trim();`,\n ` // Fail open: a miss, a refusal, or a transport error injects NOTHING`,\n ` // and never blocks the prompt. callMcp returns an \"Error: \" string`,\n ` // for a JSON-RPC error and throws on a non-OK HTTP status. The`,\n ` // proxy answers a decline (wrong profile, trivial prompt, already`,\n ` // spent, rewrite timeout) with an empty text block.`,\n ` if (!text || text.indexOf(\"Error: \") === 0 || text.indexOf(\"prompt_brief\") === 0) return undefined;`,\n ` // display:false keeps it context, not conversation (convertToLlm maps`,\n ` // every custom message to a user message regardless of display).`,\n ` return { message: { customType: \"gh-router-prompt-brief\", content: text, display: false } };`,\n ` } catch {`,\n ` return undefined;`,\n ` }`,\n ` });`,\n ]\n : []),\n `}`,\n ``,\n )\n return `${lines.join(\"\\n\")}\\n`\n}\n\nexport interface PiSkillDoc {\n dir: string\n content: string\n}\n\n/**\n * Workflow guidance as skills (progressive disclosure, not tools).\n * Ownership mirrors the Claude launcher: peer consult prose rides\n * `--peers`, semantic-search prose rides `--search`, and the\n * delegation/review pipeline rides `--swe` AND `--peers` — without\n * agents + the subagent provider its prose dangles, so peerless+swe\n * emits none. A bare launch emits NO skills at all.\n */\nexport function buildPiSkills(opts: {\n profileId: PiProfileId\n peers?: boolean\n swe?: boolean\n search?: boolean\n}): Array<PiSkillDoc> {\n const peers = opts.peers !== false\n const skills: Array<PiSkillDoc> = []\n if (peers) {\n skills.push({\n dir: \"gh-oracle\",\n content: [\n \"---\",\n \"name: gh-oracle\",\n \"description: Consult the oracle for a second opinion on risky decisions. Use when the decision itself feels risky.\",\n \"---\",\n \"\",\n \"# Oracle consult\",\n \"\",\n \"Call the `oracle` tool with the decision, the options considered, and the\",\n \"missing-context gaps. The oracle is cold-start: it sees only what you pass.\",\n \"Its verdict is advisory — verify with tests and code, never substitute votes\",\n \"for verification. (The `oracle` tool is the one-shot consult; the `oracle`\",\n \"subagent is the same role for interactive follow-ups — same name, different\",\n \"invocation. Prefer the tool for a single verdict.)\",\n ].join(\"\\n\"),\n })\n }\n if (opts.search === true) {\n skills.push({\n dir: \"gh-search-first\",\n content: [\n \"---\",\n \"name: gh-search-first\",\n \"description: Search the workspace semantically before reading broadly. Use when locating code by meaning.\",\n \"---\",\n \"\",\n \"# Search first\",\n \"\",\n \"Use `code_search` (semantic by default) before broad reads. The response\",\n \"labels its `source`: `semantic`, `lexical`, or `lexical-fallback` — a\",\n \"fallback is never silent, so retry narrower on fallback rather than\",\n \"assuming full coverage.\",\n ].join(\"\\n\"),\n })\n }\n if (opts.swe === true && peers) {\n // Balanced is advisor-free: the roster line must not name a consultant\n // that has neither tool nor agent file on that profile.\n const consults =\n opts.profileId === \"balanced\" ? \"`oracle` for consults\" : \"`oracle`/`advisor` for consults\"\n skills.push({\n dir: \"gh-delegate\",\n content: [\n \"---\",\n \"name: gh-delegate\",\n \"description: Delegate scoped work to subagents with isolated context. Use for recon, implementation, and review loops.\",\n \"---\",\n \"\",\n \"# Delegate\",\n \"\",\n \"You may delegate via the `subagent` tool to this roster only: `Explore`\",\n \"for discovery, `General-Purpose` for scoped implementation, `reviewer`\",\n `for verification, ${consults}. (Builtin \\`scout\\` and`,\n \"`worker` are disabled in this session; their aliases resolve here.)\",\n \"Recommended loop: `Explore` to map the code, paste the brief excerpts\",\n \"into the `General-Purpose` brief to implement, `reviewer` to check,\",\n \"`General-Purpose` to apply feedback. Keep delegated tasks\",\n \"scoped with file:line evidence on return.\",\n \"Call `subagent` directly (agent + task). Reserve `workflowScript`\",\n \"workflows for genuinely parallel or scripted multi-step fanout —\",\n \"our agents run foreground and background runs add spawn overhead.\",\n \"After any subagent work completes, always write the final answer\",\n \"yourself; never end on tool output or completion notices alone.\",\n opts.profileId === \"balanced\"\n ? \"Send work to reviewer ONLY when the change alters behavior.\"\n : \"Send finished work to reviewer for assessment.\",\n ].join(\"\\n\"),\n })\n if (peers && piAdvisorModel(opts.profileId)) {\n skills.push({\n dir: \"gh-advisor\",\n content: [\n \"---\",\n \"name: gh-advisor\",\n \"description: Advisory review of the final plan before presenting it. Use when the lead has a plan ready.\",\n \"---\",\n \"\",\n \"# Advisor review\",\n \"\",\n \"The lead plans directly (there is no Plan subagent). Review the final plan\",\n \"with the `advisor` tool before presenting it. Advisory only: it never\",\n \"executes and never overrides verification.\",\n ].join(\"\\n\"),\n })\n }\n }\n return skills\n}\n\nexport interface PiPromptDoc {\n name: string\n content: string\n}\n\n/**\n * Saved workflow shortcuts as prompt templates (`/name`). The review\n * pipeline is SWE-pipeline surface: only `--swe` AND `--peers` emit\n * prompts (peerless launches have no agents behind them), so a bare\n * launch advertises none.\n *\n * `/parallel-review` intentionally shadows the packaged pi-subagents\n * prompt of the same name (package prompts are filtered to `[]` in\n * settings): ours routes to our pinned-model `reviewer`, not the\n * default-model builtin. `/review` is novel — no packaged collision.\n */\nexport function buildPiPrompts(opts: {\n profileId: PiProfileId\n swe?: boolean\n peers?: boolean\n}): Array<PiPromptDoc> {\n if (opts.swe !== true || opts.peers === false) return []\n const prompts: Array<PiPromptDoc> = [\n {\n name: \"review\",\n content: [\n \"---\",\n 'description: Review the current changes with the reviewer subagent',\n 'argument-hint: \"[focus]\"',\n \"---\",\n \"Have the reviewer subagent review the current changes. Focus on ${1:-correctness, tests, and simplicity}.\",\n ].join(\"\\n\"),\n },\n {\n name: \"parallel-review\",\n content: [\n \"---\",\n 'description: Run parallel reviewer passes over the change',\n 'argument-hint: \"[focus]\"',\n \"---\",\n \"Run parallel reviewers: one for correctness, one for tests, one for unnecessary complexity. Focus: ${1:-the current diff}.\",\n ].join(\"\\n\"),\n },\n ]\n if (piAdvisorModel(opts.profileId)) {\n prompts.push({\n name: \"plan-review\",\n content: [\n \"---\",\n 'description: Advisory review of the current plan before presenting',\n 'argument-hint: \"[plan]\"',\n \"---\",\n \"Review the final plan with the advisor tool (advisory) before presenting it: ${1:-the current plan}.\",\n ].join(\"\\n\"),\n })\n }\n return prompts\n}\n","import fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\n/**\n * Pi's MCP surface for the router's scoped groups.\n *\n * `<Pi agent dir>/mcp.json` is Pi's own MCP configuration (the file `pi mcp add`\n * writes), and `pi-mcp-adapter` reads it as a compatibility input on Pi 0.99+.\n * Pi's agent dir in a router launch IS the per-launch mirror\n * (`PI_CODING_AGENT_DIR`, `getPiLaunchEnvVars`), so this file is per-launch and\n * swept with the mirror. Nothing here touches the user's real `~/.pi/agent`.\n *\n * Precedence is the reason every key carries the `gh-router-` prefix. In the\n * adapter's load order the mirror file is #4, while `.mcp.json` (#7),\n * `.pi/mcp.json` (#8) and `.pi/mcp-adapter.json` (#9) all win over it and\n * replace a same-named server as a whole. Keying a group as `ado` would\n * therefore hand the model the workspace's own `ado` server under a name we\n * meant for ours; `gh-router-ado` cannot be shadowed by accident.\n *\n * The bearer is written as an interpolation placeholder rather than a literal:\n * the adapter expands `${VAR}` in `headers` from the child environment at\n * connection time, and `GH_ROUTER_HOOK_NONCE` is already in the Pi launch env\n * (`src/pi.ts`). A literal token would put a live secret on disk for the life\n * of the mirror.\n *\n * The mirror file is read-merge-written, and a file we cannot parse is left\n * exactly as it is: a config we do not understand is not ours to overwrite.\n */\n\n/** Key prefix reserved for router-owned entries. Never emit a bare group name. */\nexport const PI_MCP_SERVER_PREFIX = \"gh-router-\"\n\n/** Placeholder the adapter expands from the Pi child env at connect time. */\nexport const PI_MCP_NONCE_PLACEHOLDER = \"Bearer ${GH_ROUTER_HOOK_NONCE}\"\n\nexport interface PiMcpGroupEntry {\n /** Scoped MCP group name; also the suffix of the server key. */\n group: string\n /** One-line capability note. The adapter forwards `description` verbatim. */\n description: string\n}\n\n/** Router-owned server key for a scoped group, e.g. `ado` -> `gh-router-ado`. */\nexport function piMcpServerKey(group: string): string {\n return `${PI_MCP_SERVER_PREFIX}${group}`\n}\n\n/**\n * Server keys a config declares, or `null` when the file is absent,\n * unreadable, or not a JSON object. `null` and `[]` are different answers:\n * one means \"no evidence\", the other \"read it, nothing declared\" — and the\n * shadow scan must not report a warning it cannot support.\n */\nexport function readMcpServerKeys(raw: string): Array<string> | null {\n try {\n const parsed = JSON.parse(raw) as unknown\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null\n const servers = (parsed as Record<string, unknown>)[\"mcpServers\"]\n if (!servers || typeof servers !== \"object\" || Array.isArray(servers)) return []\n return Object.keys(servers as Record<string, unknown>)\n } catch {\n return null\n }\n}\n\n/**\n * The adapter forwards `description` verbatim, so this is the model's only\n * pre-search signal for what a server is. Kept to what every tool in the group\n * actually does; read-only is a property of the group's default surface, not a\n * promise about every call.\n */\nconst GROUP_DESCRIPTIONS: Record<string, string> = {\n ado: \"Azure DevOps for the open repository: repositories, work items, pipelines and wikis.\",\n kusto: \"Azure Data Explorer: query and management commands against the cluster named on each call, or the launch default.\",\n}\n\nexport interface PiSurfaceDecision {\n /** ColBERT / `--search` surfaces: `pi-web-access`, the semantic skill, the launch card. */\n search: boolean\n /** The generated `code_search` seam. Bluebird serves the same tool, different engine. */\n codeSearch: boolean\n /** Which engine answers `code_search`; Bluebird wins when both are on. */\n codeSearchBackend: \"colbert\" | \"bluebird\"\n /** Azure groups to publish to Pi. Empty unless the adapter ships. */\n groups: Array<PiMcpGroupEntry>\n}\n\n/**\n * The one place that decides which Pi surfaces this launch emits.\n *\n * `search` and `codeSearch` are deliberately separate. `searchEnabled` feeds\n * three consumers today, and Bluebird must move exactly one of them: it does\n * not serve `pi-web-access` (a Copilot-backed fetch/find package gated on the\n * same flag), and the skill prose it would enable is ColBERT-specific. What\n * Bluebird does serve is `code` — `runUnifiedCodeSearch` routes `semantic` and\n * `lexical` through it whenever `state.bluebirdEnabled` is set — so an Azure\n * checkout with Bluebird auto-enabled and no `--search` still deserves the seam.\n *\n * The Azure groups ride the adapter, which only exists when `helpers` and\n * `peers` both hold (`buildPiSettingsJson` adds it as `helpers && peers`).\n * Writing the config without the adapter would leave it inert at best: the file\n * is also Pi's own built-in MCP config, so an ungated write would expose the\n * groups through a backend this path has never validated.\n */\nexport function resolvePiSurfaces(opts: {\n searchEnabled: boolean\n bluebirdEnabled: boolean\n adoEnabled: boolean\n kustoEnabled: boolean\n helpersEnabled: boolean\n peersEnabled: boolean\n}): PiSurfaceDecision {\n const codeSearchBackend = opts.bluebirdEnabled ? \"bluebird\" : \"colbert\"\n const groups: Array<PiMcpGroupEntry> = []\n if (opts.helpersEnabled && opts.peersEnabled) {\n if (opts.adoEnabled) groups.push({ group: \"ado\", description: GROUP_DESCRIPTIONS[\"ado\"]! })\n if (opts.kustoEnabled) {\n groups.push({ group: \"kusto\", description: GROUP_DESCRIPTIONS[\"kusto\"]! })\n }\n }\n return {\n search: opts.searchEnabled,\n codeSearch: opts.searchEnabled || opts.bluebirdEnabled,\n codeSearchBackend,\n groups,\n }\n}\n\n/** File text, or `null` when it is absent or unreadable. */\nasync function readIfPresent(file: string): Promise<string | null> {\n try {\n return await fs.readFile(file, \"utf8\")\n } catch {\n return null\n }\n}\n\nexport interface PiMcpJsonResult {\n /** The mirror file, written or not. */\n path: string\n /** Keys written by this call. */\n added: Array<string>\n /** Pre-existing keys preserved untouched, ours sorted first. */\n preserved: Array<string>\n /**\n * Project-scoped definitions that would replace one of ours, with the file\n * that declares them. Reported, never repaired: those files belong to the\n * user.\n */\n shadowed: Array<{ key: string; file: string }>\n /** Set when an existing mirror file could not be parsed; nothing was written. */\n skippedReason?: string\n}\n\n/** Project-scoped files the adapter reads, in its own precedence order. */\nconst PROJECT_MCP_FILES = [\n path.join(\".mcp.json\"),\n path.join(\".pi\", \"mcp.json\"),\n path.join(\".pi\", \"mcp-adapter.json\"),\n]\n\n/**\n * Write one remote entry per group into `<mirrorDir>/mcp.json`.\n *\n * Never throws for an unreadable or malformed existing file: it returns a\n * result the caller can warn about. Callers gate on the group being enabled\n * before calling; this function trusts the list it is given.\n */\nexport async function writePiMcpJson(opts: {\n mirrorDir: string\n workspace: string\n serverUrl: string\n groups: Array<PiMcpGroupEntry>\n}): Promise<PiMcpJsonResult> {\n const target = path.join(opts.mirrorDir, \"mcp.json\")\n let existing: Record<string, unknown> = {}\n let existingServers: Record<string, unknown> = {}\n\n const raw = await readIfPresent(target)\n if (raw !== null) {\n try {\n const parsed = JSON.parse(raw) as unknown\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {\n path: target,\n added: [],\n preserved: [],\n shadowed: [],\n skippedReason: \"not a JSON object\",\n }\n }\n existing = parsed as Record<string, unknown>\n const servers = existing[\"mcpServers\"]\n existingServers =\n servers && typeof servers === \"object\" && !Array.isArray(servers)\n ? (servers as Record<string, unknown>)\n : {}\n } catch {\n return {\n path: target,\n added: [],\n preserved: [],\n shadowed: [],\n skippedReason: \"malformed JSON\",\n }\n }\n }\n\n const added: Array<string> = []\n const nextServers: Record<string, unknown> = { ...existingServers }\n for (const group of opts.groups) {\n const key = piMcpServerKey(group.group)\n added.push(key)\n // The key namespace is router-owned, so an existing entry under our own\n // name is a replacement, not a user asset. Anything else is left alone.\n nextServers[key] = {\n type: \"http\",\n url: `${opts.serverUrl}/mcp/${group.group}`,\n headers: { Authorization: PI_MCP_NONCE_PLACEHOLDER },\n description: group.description,\n }\n }\n\n const shadowed = await findShadowedKeys(opts.workspace, added)\n const preserved = Object.keys(existingServers)\n .filter((key) => !added.includes(key))\n .sort()\n\n await fs.mkdir(opts.mirrorDir, { recursive: true })\n await fs.writeFile(\n target,\n `${JSON.stringify({ ...existing, mcpServers: nextServers }, null, 2)}\\n`,\n { mode: 0o600 },\n )\n\n return { path: target, added, preserved, shadowed }\n}\n\n/**\n * Which of `keys` a project-scoped file would replace. A file that cannot be\n * read or parsed is skipped silently: it yields no evidence either way, and a\n * false warning about a config we merely failed to parse is worse than a\n * missing one.\n */\nasync function findShadowedKeys(\n workspace: string,\n keys: Array<string>,\n): Promise<Array<{ key: string; file: string }>> {\n const found: Array<{ key: string; file: string }> = []\n for (const rel of PROJECT_MCP_FILES) {\n const file = path.join(workspace, rel)\n const raw = await readIfPresent(file)\n if (raw === null) continue\n const declared = readMcpServerKeys(raw)\n if (!declared) continue\n for (const key of keys) {\n if (declared.includes(key)) found.push({ key, file })\n }\n }\n return found\n}\n","import { randomBytes } from \"node:crypto\"\nimport { existsSync } from \"node:fs\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport { defineCommand, type ArgsDef } from \"citty\"\nimport consola from \"consola\"\n\nimport {\n ensurePiInstalled,\n getInstalledPiVersion,\n meetsPiMinVersion,\n PI_MIN_VERSION,\n refreshPiInBackground,\n resolvePiRegistry,\n updatePi,\n} from \"./lib/pi-version-check\"\nimport { warnOnTierPriceDriftForModels } from \"./lib/pi-tier-windows\"\nimport {\n AIC_LEDGER_ENV,\n buildAicStatusHookCommand,\n} from \"./lib/aic-statusline-settings\"\nimport { PI_STATUS_COMMAND_ENV } from \"./lib/pi-statusline\"\nimport {\n aicLedgerPath,\n aicSnapshot,\n formatAicExitSummary,\n removeAicLedgerFile,\n sweepStaleAicLedgerFiles,\n} from \"./lib/aic-ledger\"\nimport {\n discountedUsdForSnapshot,\n formatDiscountedCostTable,\n} from \"./lib/copilot-discount\"\nimport { resolveSelfInvocation } from \"./lib/hook-launcher/self-invocation\"\nimport {\n ensurePiAgentMirror,\n removeOwnPiAgentMirror,\n sweepStalePiAgentMirrors,\n} from \"./lib/pi-paths\"\nimport {\n seedPiPackageCache,\n savePiPackageCache,\n sweepStalePiPackageCaches,\n} from \"./lib/pi-package-cache\"\nimport {\n buildPiExtensionSource,\n buildPiPrompts,\n buildPiSkills,\n} from \"./lib/pi-extension\"\nimport {\n applyCosmeticUserOverrides,\n buildPiAgentFiles,\n buildPiAppendSystem,\n buildPiLaunchCard,\n buildPiModelsJson,\n buildPiSettingsJson,\n mergeSubagentsSettings,\n piLeadModel,\n piProfileModelIds,\n piUsdCostFor,\n type PiPackageEntry,\n type PiProfileId,\n} from \"./lib/pi-models-settings\"\nimport { launchChild } from \"./lib/launch\"\nimport { registerLaunch, unregisterLaunch } from \"./lib/launch-registry\"\nimport { PATHS } from \"./lib/paths\"\nimport { state } from \"./lib/state\"\nimport { runSelfUpdate } from \"./lib/self-update\"\nimport { enableFileLogging } from \"./lib/file-log-reporter\"\nimport { toolbeltEnabled } from \"./lib/toolbelt\"\nimport { provisionToolbelt } from \"./lib/toolbelt/provision\"\nimport { getPackageVersion } from \"./lib/version\"\nimport { colbertDegradedWarning, provisionAndIndexColbert } from \"./lib/colbert\"\nimport { startKeepAwake, stopKeepAwake } from \"./lib/keep-awake\"\nimport { warmTreeSitterPool } from \"./lib/tree-sitter-pool/pool\"\nimport { provisionBrowserAssets } from \"./lib/browser-mcp/provision\"\nimport { browserToolsEnabled, adoToolsEnabled, kustoToolsEnabled } from \"./lib/mcp-capabilities\"\nimport { resolvePiSurfaces, writePiMcpJson } from \"./lib/pi-mcp-config\"\nimport {\n formatBalancedPrerequisiteFailure,\n formatCheapestPrerequisiteFailure,\n profileDescriptor,\n resolveLaunchProfile,\n validateBalancedProfilePrerequisites,\n validateCheapestProfilePrerequisites,\n} from \"./lib/launch-profile\"\nimport {\n getPiLaunchEnvVars,\n parseSharedArgs,\n setupAndServe,\n sharedServerArgs,\n} from \"./lib/server-setup\"\n\nexport const piArgs = {\n ...sharedServerArgs,\n model: {\n alias: \"m\",\n type: \"string\",\n description:\n \"Pi launch profile: cheapest (Luna-led, cheapest tier) or balanced (Sol-led, most-complex-tasks tier). Only these two aliases are supported for `github-router pi`.\",\n },\n \"update-check\": {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Verify Pi is installed and above the supported floor on launch (fast local probe), and refresh it in the background (throttled hourly). Set to false (--no-update-check) to skip both (offline/CI).\",\n },\n \"auto-update\": {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Refresh Pi in the background (throttled hourly): probe npm and queue a post-exit install when newer, without delaying launch. Set to false (--no-auto-update) to disable background updates (the install floor is still enforced).\",\n },\n swe: {\n type: \"boolean\" as const,\n default: false,\n description:\n \"Enable the SWE pipeline surface: delegation/review skills (gh-delegate, cheapest-only gh-advisor) and the review prompt shortcuts (/review, /parallel-review, cheapest-only /plan-review). Off by default; a bare launch advertises no skills or prompts.\",\n },\n peers: {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Wire the peer/subagent floor: native agent files, the oracle tool (plus cheapest-only 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.\",\n },\n helpers: {\n type: \"boolean\" as const,\n default: true,\n description:\n \"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.\",\n },\n ui: {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Load the Claude-look transcript UI (pi-claude-code-ui: grouped rows, Shiki diffs, Ctrl+O previews). Presentational only, zero model cost. Set to false (--no-ui) for stock Pi rendering.\",\n },\n \"memory-bridge\": {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Bridge Copilot (.github/copilot-instructions.md, .github/instructions/*.instructions.md) and Claude (.claude/rules/, .claude/CLAUDE.md, ~/.claude/CLAUDE.md) memory into Pi. Static repo-wide slice synthesizes into the mirror AGENTS.md; path-scoped rules lazy-attach. Set to false (--no-memory-bridge) for Pi-native discovery only.\",\n },\n} satisfies ArgsDef\n\n/**\n * Forward child args: every raw token that is NOT one of github-router's\n * own declared flags (or that flag's consumed value); everything after a\n * literal `--` flows verbatim. Local copy of the claude.ts walk so this\n * module doesn't import the Claude launch graph.\n */\nexport function collectPiPassthroughArgs(\n rawArgs: ReadonlyArray<string>,\n argsDef: ArgsDef,\n): string[] {\n const known = new Set<string>()\n const stringTyped = new Set<string>()\n for (const [name, def] of Object.entries(argsDef)) {\n const rawAlias = \"alias\" in def ? def.alias : undefined\n const aliases =\n rawAlias === undefined ? [] : Array.isArray(rawAlias) ? rawAlias : [rawAlias]\n for (const n of [name, ...aliases]) {\n known.add(n)\n if (def.type === \"string\") stringTyped.add(n)\n }\n }\n const forwarded: string[] = []\n for (let i = 0; i < rawArgs.length; i++) {\n const tok = rawArgs[i]\n if (tok === \"--\") {\n forwarded.push(...rawArgs.slice(i + 1))\n break\n }\n if (tok === \"-\" || !tok.startsWith(\"-\")) {\n forwarded.push(tok)\n continue\n }\n const doubleDash = tok.startsWith(\"--\")\n const afterDashes = tok.slice(doubleDash ? 2 : 1)\n const eq = afterDashes.indexOf(\"=\")\n const rawName = eq >= 0 ? afterDashes.slice(0, eq) : afterDashes\n const hasInlineValue = eq >= 0\n const negated = doubleDash && rawName.startsWith(\"no-\")\n const baseName = negated ? rawName.slice(3) : rawName\n const isKnown = known.has(rawName) || (negated && known.has(baseName))\n if (!isKnown) {\n forwarded.push(tok)\n continue\n }\n const consumesValue =\n !negated\n && !hasInlineValue\n && stringTyped.has(rawName)\n && i + 1 < rawArgs.length\n && rawArgs[i + 1] !== \"--\"\n && !rawArgs[i + 1].startsWith(\"-\")\n if (consumesValue) i++\n }\n return forwarded\n}\n\nasync function writeJsonFile(file: string, value: unknown): Promise<void> {\n await fs.mkdir(path.dirname(file), { recursive: true })\n await fs.writeFile(file, `${JSON.stringify(value, null, 2)}\\n`, { mode: 0o600 })\n}\n\nasync function writeTextFile(file: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(file), { recursive: true })\n await fs.writeFile(file, content, { mode: 0o600 })\n}\n\nexport const pi = defineCommand({\n meta: {\n name: \"pi\",\n description: \"Start the proxy server and launch the Pi coding agent (cheapest/balanced)\",\n },\n args: piArgs,\n async run({ args, rawArgs }) {\n const headless = rawArgs.includes(\"--print\") || rawArgs.includes(\"--mode\")\n if (!process.stdout.isTTY && !headless) {\n consola.error(\"The pi subcommand requires a TTY (interactive terminal), or use --print/--mode for headless runs.\")\n process.exit(1)\n }\n\n const parsed = parseSharedArgs(args as unknown as Record<string, unknown>)\n const launchProfileId = resolveLaunchProfile(args.model)\n if (launchProfileId !== \"cheapest\" && launchProfileId !== \"balanced\") {\n process.stderr.write(\n `github-router pi supports only -m cheapest and -m balanced (got ${JSON.stringify(args.model ?? \"\")}). ` +\n `Run plain \\`github-router pi -m cheapest\\` or \\`github-router pi -m balanced\\`.\\n`,\n )\n process.exit(1)\n }\n const profileId = launchProfileId as PiProfileId\n\n let server: Awaited<ReturnType<typeof setupAndServe>>[\"server\"]\n let serverUrl: string\n // Pi install / update (default-on, throttled, best-effort).\n const updateCheck = (args as Record<string, unknown>)[\"update-check\"] !== false\n const autoUpdate = (args as Record<string, unknown>)[\"auto-update\"] !== false\n // Fast foreground gate: `pi --version` is local (milliseconds) and\n // decides everything launch-critical. Network (npm view) and installs\n // never block a healthy launch — see below.\n let installedVersion: string | null = null\n // Pending fresh install when Pi is absent: started before server boot\n // so the two overlap, joined fail-closed right after setup.\n const pendingInstall: { promise: Promise<string> | null; abort: (() => void) | null } = {\n promise: null,\n abort: null,\n }\n if (updateCheck) {\n try {\n installedVersion = await getInstalledPiVersion()\n } catch (err) {\n consola.debug(\"Pi presence probe failed:\", err)\n }\n if (installedVersion === null) {\n // Pi absent: it must be installed before launch, but the install\n // starts NOW so it overlaps server boot instead of following it.\n // Joined (fail-closed) right after setup; aborted if setup fails\n // so a doomed launch never leaves a half-written global install.\n const controller = new AbortController()\n pendingInstall.abort = () => controller.abort()\n pendingInstall.promise = ensurePiInstalled({ signal: controller.signal })\n pendingInstall.promise.catch(() => {\n // Observed at the join below; never an unhandled rejection.\n })\n }\n }\n try {\n // Quiet boot: with stored auth there is no interactive flow to\n // display, so info-level setup chatter (versions, re-login,\n // token refreshes) is held back and the launch card below carries\n // the same facts elegantly. Warn+error always show. Skipped for\n // explicit --verbose/--show-token, and never applied without\n // stored auth (first-time device flow must stay visible).\n const quietBoot =\n existsSync(PATHS.GITHUB_TOKEN_PATH) && !parsed.verbose && !parsed.showToken\n const priorLevel = consola.level\n if (quietBoot) consola.level = 1\n let setupResult: Awaited<ReturnType<typeof setupAndServe>>\n try {\n setupResult = await setupAndServe({\n ...parsed,\n port: parsed.port,\n silent: true,\n })\n } finally {\n if (quietBoot) consola.level = priorLevel\n }\n server = setupResult.server\n serverUrl = setupResult.serverUrl\n } catch (error) {\n pendingInstall.abort?.()\n consola.error(\"Failed to start server:\", error instanceof Error ? error.message : error)\n process.exit(1)\n }\n\n void runSelfUpdate({ selfUpdate: args[\"self-update\"] !== false })\n\n if (pendingInstall.promise) {\n // The blocking join: without Pi there is nothing to launch.\n // Same failure contract as a sequential install, minus the wait.\n try {\n installedVersion = await pendingInstall.promise\n } catch (err) {\n consola.error(\n `Pi is not installed and automatic install failed (${err instanceof Error ? err.message : String(err)}). Install it with \\`npm install -g @earendil-works/pi-coding-agent --registry=${resolvePiRegistry()}\\`, then retry.`,\n )\n process.exit(1)\n } finally {\n pendingInstall.promise = null\n pendingInstall.abort = null\n }\n }\n\n if (updateCheck && installedVersion !== null) {\n if (!meetsPiMinVersion(installedVersion)) {\n // Below the floor Pi cannot serve the roster correctly: upgrade\n // foreground and re-verify, fail closed. `latest` needs no\n // registry probe — npm resolves it at install time.\n if (autoUpdate) {\n try {\n await updatePi(\"latest\")\n installedVersion = await getInstalledPiVersion()\n } catch (err) {\n consola.error(\n `Installed Pi v${installedVersion} is below the supported floor and auto-upgrade failed (${err instanceof Error ? err.message : String(err)}). Upgrade manually: \\`npm install -g @earendil-works/pi-coding-agent@latest --registry=${resolvePiRegistry()}\\`.`,\n )\n process.exit(1)\n }\n }\n if (!meetsPiMinVersion(installedVersion)) {\n consola.error(\n `Installed Pi v${installedVersion} is below the supported floor (v${PI_MIN_VERSION}). Upgrade: \\`npm install -g @earendil-works/pi-coding-agent@latest --registry=${resolvePiRegistry()}\\`.`,\n )\n process.exit(1)\n }\n } else {\n // Healthy: freshness refreshes in the background (throttled npm\n // probe, detached post-exit install when newer). Never blocks,\n // never throws, never touches this session's validated install.\n refreshPiInBackground({ autoUpdate })\n }\n }\n\n // Flag policy (mirrors the Claude launcher's house rules): peers are\n // default-ON (opt out with --no-peers); the SWE pipeline, like its\n // Claude namesake, is opt-IN with --swe. A bare launch advertises no\n // skills or prompts — only what Pi ships plus the mode identity.\n const peersEnabled = (args as Record<string, unknown>)[\"peers\"] !== false\n const sweEnabled = (args as Record<string, unknown>)[\"swe\"] === true\n const helpersEnabled = (args as Record<string, unknown>)[\"helpers\"] !== false\n const uiEnabled = (args as Record<string, unknown>)[\"ui\"] !== false\n const searchEnabled =\n parsed.searchEnabled || process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const browseEnabled = browserToolsEnabled()\n // Which Pi surfaces this launch emits, in one place. `codeSearch` is the\n // Bluebird seam: Bluebird answers the `code` tool without `--search`, so\n // the generated seam follows it, while `pi-web-access` and the ColBERT\n // skill prose keep following `--search`. See `resolvePiSurfaces`.\n const surfaces = resolvePiSurfaces({\n searchEnabled,\n bluebirdEnabled: state.bluebirdEnabled === true,\n adoEnabled: adoToolsEnabled(),\n kustoEnabled: kustoToolsEnabled(),\n helpersEnabled,\n peersEnabled,\n })\n\n // Pin-mode prerequisites against the live catalog (fail-closed).\n // Peerless launches validate the lead only (nothing else is consumed).\n const prereqCheck =\n profileId === \"cheapest\"\n ? validateCheapestProfilePrerequisites(state.models, { peers: peersEnabled })\n : validateBalancedProfilePrerequisites(state.models, { peers: peersEnabled })\n if (!prereqCheck.ok) {\n const message =\n profileId === \"cheapest\"\n ? formatCheapestPrerequisiteFailure(prereqCheck.missing)\n : formatBalancedPrerequisiteFailure(prereqCheck.missing)\n consola.error(message)\n process.stderr.write(`${message}\\n`)\n process.exit(1)\n }\n\n // Isolated Pi mirror + stale sweep (never the user's real ~/.pi/agent).\n let mirror: string\n try {\n mirror = await ensurePiAgentMirror()\n await sweepStalePiAgentMirrors()\n void sweepStalePiPackageCaches()\n } catch (err) {\n consola.error(\n `Failed to provision Pi config mirror: ${err instanceof Error ? err.message : String(err)}.`,\n )\n process.exit(1)\n }\n\n enableFileLogging()\n\n // The exact `packages[]` slice for this launch (flag-dependent), used\n // to key the persistent npm-package cache: seed before Pi boots, save\n // on shutdown before the mirror is removed.\n let packagesForCache: Array<PiPackageEntry> = []\n\n // Generate the mode's Pi files into the mirror.\n try {\n const catalog = state.models?.data.map((m) => {\n const cost = piUsdCostFor(m.billing?.token_prices)\n return {\n id: m.id,\n maxContextTokens: m.capabilities?.limits?.max_context_window_tokens ?? 0,\n maxPromptTokens: m.capabilities?.limits?.max_prompt_tokens ?? 0,\n maxOutputTokens: m.capabilities?.limits?.max_output_tokens ?? 0,\n efforts: m.capabilities?.supports?.reasoning_effort ?? [],\n endpoints: m.supported_endpoints ?? [],\n vision: m.capabilities?.supports?.vision,\n maxImageBytes: m.capabilities?.limits?.vision?.max_prompt_image_size,\n ...(cost ? { cost } : {}),\n }\n })\n await writeJsonFile(\n path.join(mirror, \"models.json\"),\n buildPiModelsJson({ serverUrl, profileId, catalog, peers: peersEnabled }),\n )\n\n // Merge over snapshotted user settings: our keys win, user keys survive.\n const settingsPath = path.join(mirror, \"settings.json\")\n let userSettings: Record<string, unknown> = {}\n try {\n const raw = await fs.readFile(settingsPath, \"utf8\")\n const parsedSettings = JSON.parse(raw) as unknown\n if (parsedSettings && typeof parsedSettings === \"object\") {\n userSettings = parsedSettings as Record<string, unknown>\n }\n } catch {\n userSettings = {}\n }\n // Merge over snapshotted user settings: our keys win, user keys survive.\n // Exception: `subagents.agentOverrides` deep-merges (ours as defaults,\n // user's entries win per-agent) so emitting our builtin disables never\n // wipes a user's own overrides — a shallow spread would replace the\n // whole object.\n const builtSettings = buildPiSettingsJson({ profileId, searchEnabled, browseEnabled, catalog, peers: peersEnabled, helpers: helpersEnabled, ui: uiEnabled })\n const mergedSubagents = mergeSubagentsSettings(\n userSettings[\"subagents\"],\n builtSettings.subagents,\n )\n // Presentational keys stay user-customizable: a look the user set\n // in their own settings (thinking visibility, Claude palette,\n // one-line tool rows, terminal/images) wins over our defaults,\n // while load-bearing keys stay built-wins (cost contract).\n const cosmeticOverrides = applyCosmeticUserOverrides(userSettings, builtSettings)\n await writeJsonFile(settingsPath, {\n ...userSettings,\n ...builtSettings,\n ...cosmeticOverrides,\n ...(mergedSubagents ? { subagents: mergedSubagents } : {}),\n })\n // Pre-seed <mirror>/npm from the durable package cache so Pi's\n // per-boot `packages[]` install is a no-op on a hit (faster + silent:\n // npm's `added N packages` summary bypasses npm_config_loglevel).\n // Misses (cold/stale/flag-changed cache) install from the registry\n // as before and are saved back on shutdown for the next launch.\n packagesForCache = [...builtSettings.packages]\n const cacheHit = await seedPiPackageCache(mirror, packagesForCache)\n if (cacheHit) {\n consola.debug(\"Pi package cache hit: mirror pre-seeded, skipping registry install.\")\n }\n\n // Memory bridge collection runs BEFORE the extension build so scoped\n // rules + stats can be embedded for lazy attach + /memory + /context.\n // Best-effort, never fatal. Honors --no-memory-bridge,\n // GH_ROUTER_PI_BRIDGE=0 / GH_ROUTER_DISABLE_PI_BRIDGE=1, and Pi's own\n // --no-context-files/-nc passthrough (never fight an explicit `-nc`).\n const bridgeDisabled =\n (args as Record<string, unknown>)[\"memory-bridge\"] === false\n || process.env.GH_ROUTER_PI_BRIDGE === \"0\"\n || process.env.GH_ROUTER_DISABLE_PI_BRIDGE === \"1\"\n let bridgeStats: { staticFiles: number; scopedRules: number; imports: number; skipped: number } | undefined\n let bridgeScoped: Array<{ file: string; body: string; globs: Array<string>; source: string }> = []\n if (!bridgeDisabled) {\n const passthrough = collectPiPassthroughArgs(rawArgs, piArgs)\n const noContext = passthrough.includes(\"--no-context-files\") || passthrough.includes(\"-nc\")\n if (!noContext) {\n try {\n const { collectBridgeInputs } = await import(\"./lib/pi-memory-bridge\")\n const collected = await collectBridgeInputs(process.cwd())\n bridgeStats = {\n staticFiles:\n collected.copilotInstructions.length\n + collected.unscopedRules.length\n + collected.userGlobal.length,\n scopedRules: collected.scopedRules.length,\n imports: collected.imports.length,\n skipped: collected.skipped.length,\n }\n bridgeScoped = collected.scopedRules\n // Stash full collection for the AGENTS.md synthesis below.\n ;(globalThis as Record<string, unknown>).__ghRouterBridgeCollected = collected\n } catch (err) {\n consola.debug(\"Pi memory bridge collection skipped:\", err)\n }\n }\n }\n\n await writeTextFile(\n path.join(mirror, \"extensions\", \"gh-router-pi\", \"index.ts\"),\n buildPiExtensionSource({\n profileId,\n searchEnabled: surfaces.codeSearch,\n searchBackend: surfaces.codeSearchBackend,\n browseEnabled,\n peers: peersEnabled,\n bridge: bridgeStats ? { stats: bridgeStats, scopedRules: bridgeScoped } : undefined,\n }),\n )\n // The Azure groups reach Pi through Pi's own `mcp.json` in the mirror,\n // which `pi-mcp-adapter` reads (`<Pi agent dir>/mcp.json`, Pi 0.99+).\n // Pi reaches `peers` / `search` / `browser` through the generated\n // extension instead; these two have no extension seam, so the adapter is\n // their only route. A user-owned `mcp.json` is merged over, never\n // replaced, and a project file that would shadow an entry is reported\n // rather than repaired.\n if (surfaces.groups.length > 0) {\n const written = await writePiMcpJson({\n mirrorDir: mirror,\n workspace: process.cwd(),\n serverUrl,\n groups: surfaces.groups,\n })\n if (written.skippedReason) {\n consola.warn(\n `Pi MCP: left ${written.path} alone (${written.skippedReason}); the Azure groups are not exposed to Pi this launch.`,\n )\n } else {\n for (const { key, file } of written.shadowed) {\n consola.warn(\n `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.`,\n )\n }\n }\n }\n // Peer floor (agents + consult skills) rides --peers; the SWE\n // pipeline (delegate/advisor skills, review prompts) rides --swe AND\n // --peers (without agents + the subagent provider its prose dangles,\n // so peerless+swe emits none — see the heads-up below).\n // semantic-search prose rides --search. Bare launches write none.\n if (peersEnabled) {\n const agentFiles = buildPiAgentFiles(profileId)\n for (const [rel, content] of Object.entries(agentFiles)) {\n await writeTextFile(path.join(mirror, rel), content)\n }\n }\n for (const skill of buildPiSkills({ profileId, peers: peersEnabled, swe: sweEnabled, search: searchEnabled })) {\n await writeTextFile(path.join(mirror, \"skills\", skill.dir, \"SKILL.md\"), skill.content)\n }\n for (const prompt of buildPiPrompts({ profileId, swe: sweEnabled, peers: peersEnabled })) {\n await writeTextFile(path.join(mirror, \"prompts\", `${prompt.name}.md`), prompt.content)\n }\n await writeTextFile(path.join(mirror, \"APPEND_SYSTEM.md\"), buildPiAppendSystem(profileId, { peers: peersEnabled }))\n\n // Static bridge synthesis into mirror AGENTS.md (Pi-native candidate).\n // Uses the collection stashed above; idempotent via fenced replace.\n try {\n const collected = (globalThis as Record<string, unknown>).__ghRouterBridgeCollected as\n | import(\"./lib/pi-memory-bridge\").PiBridgeCollected\n | undefined\n if (collected) {\n const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import(\"./lib/pi-memory-bridge\")\n const { section } = buildMirrorBridgeSection(collected, { repoRoot: process.cwd() })\n const agentsPath = path.join(mirror, \"AGENTS.md\")\n let existing: string | undefined\n try {\n existing = await fs.readFile(agentsPath, \"utf8\")\n } catch {\n existing = undefined\n }\n await writeTextFile(agentsPath, mergeBridgeIntoAgentsMd(existing, section))\n await writeJsonFile(path.join(mirror, \".gh-router-bridge.json\"), {\n stats: bridgeStats ?? null,\n scopedRuleFiles: bridgeScoped.map((r) => r.file),\n })\n }\n } catch (err) {\n consola.debug(\"Pi memory bridge synthesis skipped:\", err)\n } finally {\n try {\n delete (globalThis as Record<string, unknown>).__ghRouterBridgeCollected\n } catch {\n // ignore\n }\n }\n } catch (err) {\n consola.error(\n `Failed to write Pi launch files: ${err instanceof Error ? err.message : String(err)}.`,\n )\n process.exit(1)\n }\n\n // Tier-table drift guard: loud warning when live catalog input prices\n // disagree with the pinned cheap-tier thresholds. Separate block (own\n // try/catch) so a drift-check bug can never fail a launch. Warn-only.\n try {\n warnOnTierPriceDriftForModels(state.models?.data)\n } catch (err) {\n consola.debug(\"Pi tier drift check skipped:\", err)\n }\n\n // AIC status line: this session's AI-credit total (`[AIC 12.42]`) plus\n // the discounted actual (`~$`) in Pi's footer, rendered by the mode's\n // own `gh-router-pi` extension (same `internal-aic-status` runner the\n // Claude launcher drives — one renderer, identical segments). The\n // command travels via `GH_ROUTER_AIC_STATUS_COMMAND` env, never a\n // settings block: the community bridge only reads the user's real\n // global/project settings and never sees the launch mirror, so a\n // mirror-injected block would be dead config. Router-wins by\n // architecture (the footer is extension-owned); opt out with\n // GH_ROUTER_DISABLE_AIC_STATUSLINE=1. Fail-open: a broken runner\n // degrades to no statusline, never a broken launch.\n let aicLedgerEnv: string | undefined\n let aicStatusCommandEnv: string | undefined\n if (process.env.GH_ROUTER_DISABLE_AIC_STATUSLINE !== \"1\") {\n try {\n void sweepStaleAicLedgerFiles()\n const selfInvocation = await resolveSelfInvocation()\n aicStatusCommandEnv = buildAicStatusHookCommand(selfInvocation)\n aicLedgerEnv = aicLedgerPath()\n consola.info(\n `Status line wired via the gh-router-pi footer for ${profileId} (shared internal-aic-status runner).`,\n )\n } catch (err) {\n consola.warn(\n `AIC status line skipped: ${\n err instanceof Error ? err.message : String(err)\n }.`,\n )\n }\n }\n\n if (toolbeltEnabled()) {\n void provisionToolbelt().catch((err) =>\n consola.debug(\"Toolbelt provisioning failed:\", err),\n )\n }\n void provisionAndIndexColbert()\n void colbertDegradedWarning(undefined, { logsToFile: true })\n .then((warning) => {\n if (warning) process.stderr.write(`${warning}\\n`)\n })\n .catch(() => {})\n void warmTreeSitterPool()\n startKeepAwake()\n if (browserToolsEnabled()) {\n void provisionBrowserAssets().catch((err) =>\n consola.debug(\"Browser extension provisioning failed:\", err),\n )\n }\n\n // Launch binding: the Pi extension reaches the proxy's /mcp with this\n // nonce (same channel as the Claude hooks). Descriptor carries the\n // mode's group/persona allow-list so /mcp enforces it server-side;\n // peerless launches drop the peers group + persona allow-list to match\n // the unwritten tools.\n const descriptor = profileDescriptor(profileId)\n const nonce = randomBytes(32).toString(\"hex\")\n const secret = randomBytes(32).toString(\"hex\")\n const entry = registerLaunch({\n profileId,\n nonce,\n secret,\n allowedGroups: peersEnabled\n ? descriptor.allowedGroups\n : new Set(\n [...(descriptor.allowedGroups ?? [])].filter((g) => g !== \"peers\"),\n ),\n allowedPersonas: peersEnabled ? descriptor.personaAllowlist : new Set<string>(),\n })\n\n const extraArgs = collectPiPassthroughArgs(rawArgs, piArgs)\n const lead = piLeadModel(profileId)\n const modelIds = piProfileModelIds(profileId, { peers: peersEnabled })\n // One elegant preamble (stderr, no reporter icons or timestamps).\n // Replaces both the gated setup chatter and the old single line:\n // same facts, three aligned lines.\n process.stderr.write(\n `${buildPiLaunchCard({\n version: getPackageVersion(),\n profileId,\n accountType: parsed.accountType,\n login: state.githubUserLogin,\n copilotVersion: state.copilotVersion,\n vsCodeVersion: state.vsCodeVersion,\n lead,\n modelCount: modelIds.length,\n peers: peersEnabled,\n helpers: helpersEnabled && peersEnabled,\n ui: uiEnabled,\n swe: sweEnabled,\n search: searchEnabled,\n browse: browseEnabled,\n // From the resolved decision, not from `state`: the Azure groups only\n // reach the session through the helpers bundle, so the card must name\n // exactly what the mirror carries.\n azureGroups: surfaces.groups.map((g) => g.group),\n serverUrl,\n })}\\n`,\n )\n if (sweEnabled && !peersEnabled) {\n process.stderr.write(\n \"Note: --swe without --peers emits no delegate/review skills or prompts (no agents behind them in a peerless launch).\\n\",\n )\n }\n\n const { disposeBluebirdClients } = await import(\"./lib/bluebird-client\")\n const { disposeAdoClients } = await import(\"./lib/ado-tools\")\n launchChild(\n {\n kind: \"pi\",\n envVars: {\n ...getPiLaunchEnvVars(mirror),\n GH_ROUTER_HOOK_MCP_URL: serverUrl,\n GH_ROUTER_HOOK_NONCE: nonce,\n // Launch workspace for the Pi MCP bridge (code_search default +\n // X-GH-Workspace header). The proxy is long-lived; the agent is\n // not — only the launcher knows where the caller actually is.\n GH_ROUTER_WORKSPACE: process.cwd(),\n // Balanced nests reviewer→Explore under General-Purpose, i.e.\n // lead→General-Purpose→reviewer→Explore (3 deep); the default\n // nesting guard is 2 and would fail the deepest edge closed.\n PI_SUBAGENT_MAX_DEPTH: \"3\",\n ...(aicLedgerEnv ? { [AIC_LEDGER_ENV]: aicLedgerEnv } : {}),\n ...(aicStatusCommandEnv\n ? { [PI_STATUS_COMMAND_ENV]: aicStatusCommandEnv }\n : {}),\n },\n extraArgs,\n model: lead,\n serverUrl,\n },\n server,\n {\n onShutdown: async () => {\n unregisterLaunch(entry.launchId)\n await stopKeepAwake()\n await disposeBluebirdClients()\n await disposeAdoClients()\n // Persist this launch's installed <mirror>/npm for the next\n // launch's pre-seed (keyed by the exact packages[] slice), then\n // remove the per-launch mirror as before. Best-effort, never\n // fatal — a failed save just means the next boot reinstalls.\n await savePiPackageCache(mirror, packagesForCache)\n await removeOwnPiAgentMirror()\n await removeAicLedgerFile()\n },\n // Session AIC total + discounted per-model cost table, printed\n // after cleanup on every exit path. The table is default-on (not\n // debug-gated): every value in it is upstream-measured, and the\n // ~$ column carries the same static-discount approximation as the\n // status line. Per-model credit splits stay verbose-only — they\n // imply billing-grade attribution the estimates can't support.\n onExitSummary: () => {\n const snapshot = aicSnapshot()\n if (snapshot.requests === 0 || snapshot.totalNanoAiu <= 0) {\n return undefined\n }\n const summary = formatAicExitSummary(snapshot, {\n verbose: consola.level >= 4,\n })\n const table = formatDiscountedCostTable(\n snapshot,\n discount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;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;;;;;;;;;AAeA,SAAgB,2BAA2B,QAA+C;CAMxF,MAAM,cAAc,OAAO,YAAY,KAAK,OAAO;EACjD,MAAM,EAAE,KAAK,WAAW,MAAM,EAAE;EAChC,OAAO,EAAE,KAAK,SAAS,MAAO,GAAG,EAAE,KAAK,MAAM,GAAG,GAAI,EAAE,6CAA6C,EAAE,KAAA,CAAM,WAC1G,MACA,EACF;EACA,OAAO,EAAE;EACT,QAAQ,EAAE;CACZ,EAAE;CAEF,OAAO;EACL;EACA;EACA;EACA,sBALc,KAAK,UAAU;GAAE,OAAO,OAAO;GAAO,aAAa;EAAY,CAKjD,EAAE;EAC9B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;AAEA,SAAgB,uBAAuB,MAa5B;CACT,MAAM,QAAQ,KAAK,UAAU;CAC7B,MAAM,UAAU,QAAQ,eAAe,KAAK,SAAS,IAAI,KAAA;CAIzD,MAAM,cAAc,KAAK,cAAc;CACvC,MAAM,QAAuB,CAAC;CAC9B,MAAM,KACJ,8BAA8B,KAAK,UAAU,6CAC7C,2EACA,mCACA,+CACA,IACA,GAAI,QACA;EACE;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,GAAI,UACA;EACE;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,GAAI,KAAK,gBACL;EACE;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,GAAI,KAAK,gBACL;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,wEACA,sCAKA,iCACA,uFACA,KACA,kCACA,uEACA,KACA,oFACA,6DACA,wEACA,GAAI,cACA,CAME,iCACF,IACA,CAAC,GACL,sBAAsB,KAAK,UAAU,GAAG,iBAAiB,GAAG,YAAY,KAAK,SAAS,GAAG,EAAE,IAC3F,yBAAyB,KAAK,UAAU,eAAe,KAAK,SAAS,CAAC,EAAE,IACxE,wCACA,IACA,uDACA,+HACA,+IACA,0DACA,uBACA,gBACA,uHACA,eACA,SACA,2FACA,oCACA,4DACA,yDACA,6CACA,0DACA,KACA,IACA,kCACA,GAAI,QACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,CACP;CACA,IAAI,SACF,MAAM,KACJ,uBACA,wBACA,yBACA,sHACA,kCACA,oDACA,0DACA,4DACA,mHACA,2HACA,uHACA,UACA,OACF;CAEF,IAAI,KAAK,eAAe;EACtB,MAAM,wBACJ,KAAK,kBAAkB,aACnB,mUACA;EACN,MAAM,KACJ,uBACA,4BACA,6BACA,qBAAqB,sBAAsB,KAC3C,qCACA,oDACA,4DACA,gGACA,uIACA,qIACA,wGACA,0GACA,yEACA,UACA,OACF;CACF;CACA,IAAI,KAAK,eACP,MAAM,KACJ,uBACA,yBACA,kCACA,2JACA,kCACA,oDACA,wDACA,sEACA,+BACA,6FACA,8EACA,UACA,SACA,uBACA,yBACA,kCACA,2HACA,mCACA,oDACA,2HACA,iHACA,sEACA,kFACA,wEACA,8EACA,UACA,SACA,uBACA,2BACA,oCACA,kFACA,qCACA,oDACA,6HACA,+CACA,8FACA,gFACA,gFACA,UACA,SACA,uBACA,oBACA,6BACA,iGACA,8BACA,oDACA,sHACA,oGACA,+CACA,8FACA,kFACA,8FACA,0EACA,yEACA,UACA,SACA,uBACA,wBACA,iCACA,8EACA,kCACA,oDACA,0HACA,+CACA,8FACA,6EACA,UACA,SACA,uBACA,wBACA,iCACA,sHACA,kCACA,oDACA,0HACA,4FACA,+FACA,wJACA,UACA,OACF;CAEF,IAAI,KAAK,UAAU,KAAK,OAAO,YAAY,SAAS,KAAK,OAAO,MAAM,cAAc,GAClF,MAAM,KAAK,GAAG,2BAA2B,KAAK,MAAM,CAAC;CAEvD,MAAM,KAIJ,GAAG,+BAA+B,GAClC,sEACA,yEACA,wDACA,aACA,gDACA,gGACA,qFACA,iBACA,2BACA,SACA,SACA,GAAI,cACA;EAME;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,KACA,EACF;CACA,OAAO,GAAG,MAAM,KAAK,IAAI,EAAE;AAC7B;;;;;;;;;AAeA,SAAgB,cAAc,MAKR;CACpB,MAAM,QAAQ,KAAK,UAAU;CAC7B,MAAM,SAA4B,CAAC;CACnC,IAAI,OACF,OAAO,KAAK;EACV,KAAK;EACL,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,IAAI;CACb,CAAC;CAEH,IAAI,KAAK,WAAW,MAClB,OAAO,KAAK;EACV,KAAK;EACL,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,IAAI;CACb,CAAC;CAEH,IAAI,KAAK,QAAQ,QAAQ,OAAO;EAG9B,MAAM,WACJ,KAAK,cAAc,aAAa,0BAA0B;EAC5D,OAAO,KAAK;GACV,KAAK;GACL,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,qBAAqB,SAAS;IAC9B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,KAAK,cAAc,aACf,gEACA;GACN,CAAC,CAAC,KAAK,IAAI;EACb,CAAC;EACD,IAAI,SAAS,eAAe,KAAK,SAAS,GACxC,OAAO,KAAK;GACV,KAAK;GACL,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF,CAAC,CAAC,KAAK,IAAI;EACb,CAAC;CAEL;CACA,OAAO;AACT;;;;;;;;;;;;AAkBA,SAAgB,eAAe,MAI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