github-router 0.3.372 → 0.3.373
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.
- package/dist/ado-tools-WDyisN8w.js +1 -0
- package/dist/{attribution-settings-HI_5bN_-.js → attribution-settings-DZ8fEfvP.js} +5 -5
- package/dist/{attribution-settings-HI_5bN_-.js.map → attribution-settings-DZ8fEfvP.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude-BBSsqwln.js → claude-8ksmV0dC.js} +10 -10
- package/dist/{claude-BBSsqwln.js.map → claude-8ksmV0dC.js.map} +1 -1
- package/dist/{claude-md-injection-BMon6WUD.js → claude-md-injection-BnzVv_aB.js} +2 -2
- package/dist/{claude-md-injection-BMon6WUD.js.map → claude-md-injection-BnzVv_aB.js.map} +1 -1
- package/dist/{codex-PRWoBiOH.js → codex-C89FoaaG.js} +6 -6
- package/dist/{codex-PRWoBiOH.js.map → codex-C89FoaaG.js.map} +1 -1
- package/dist/engine-C207cikp.js +1 -0
- package/dist/{gate-discovery-BNy8GKsC.js → gate-discovery-Bc9FdRwg.js} +2 -2
- package/dist/{gate-discovery-BNy8GKsC.js.map → gate-discovery-Bc9FdRwg.js.map} +1 -1
- package/dist/{index-cmd-CjRcmYk3.js → index-cmd-DOhwt92u.js} +2 -2
- package/dist/{index-cmd-CjRcmYk3.js.map → index-cmd-DOhwt92u.js.map} +1 -1
- package/dist/{internal-stop-hook-CXlOsW63.js → internal-stop-hook-nS91Jkda.js} +2 -2
- package/dist/{internal-stop-hook-CXlOsW63.js.map → internal-stop-hook-nS91Jkda.js.map} +1 -1
- package/dist/main.js +7 -7
- package/dist/{peer-mcp-personas-Dxxw5X1g.js → peer-mcp-personas-BSxDj9sJ.js} +2 -2
- package/dist/{peer-mcp-personas-Dxxw5X1g.js.map → peer-mcp-personas-BSxDj9sJ.js.map} +1 -1
- package/dist/{pi-IYAvKF50.js → pi-BglhJ6n_.js} +286 -62
- package/dist/pi-BglhJ6n_.js.map +1 -0
- package/dist/{provision-CIn6I4w_.js → provision-B0GNohdl.js} +3 -3
- package/dist/{provision-CIn6I4w_.js.map → provision-B0GNohdl.js.map} +1 -1
- package/dist/{serve-CttHP8dJ.js → serve-BxZq9vNl.js} +7 -7
- package/dist/{serve-CttHP8dJ.js.map → serve-BxZq9vNl.js.map} +1 -1
- package/dist/{server-setup-D7XHUrhM.js → server-setup-BLdWCcby.js} +4 -4
- package/dist/{server-setup-D7XHUrhM.js.map → server-setup-BLdWCcby.js.map} +1 -1
- package/dist/{service-backend-B6D_DY1Z.js → service-backend-BV2hHjuB.js} +35 -17
- package/dist/service-backend-BV2hHjuB.js.map +1 -0
- package/dist/{start-XU5HwLd9.js → start-C3Zb8XMT.js} +4 -4
- package/dist/{start-XU5HwLd9.js.map → start-C3Zb8XMT.js.map} +1 -1
- package/dist/{workiq-tools-CMoDjrO0.js → workiq-tools-C6LAF_vA.js} +1 -1
- package/package.json +2 -3
- package/dist/ado-tools-CAtopk36.js +0 -1
- package/dist/engine-CDZdAx8N.js +0 -1
- package/dist/pi-IYAvKF50.js.map +0 -1
- package/dist/service-backend-B6D_DY1Z.js.map +0 -1
package/dist/pi-IYAvKF50.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pi-IYAvKF50.js","names":["fs","fs","fs","process"],"sources":["../src/lib/pi-tier-windows.ts","../src/lib/pi-statusline.ts","../src/lib/pi-package-cache.ts","../src/lib/pi-models-settings.ts","../src/lib/pi-plan-mode.ts","../src/lib/pi-extension.ts","../src/lib/pi-mcp-config.ts","../src/pi.ts"],"sourcesContent":["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 * - gpt-6.1-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 * - grok-4.7: 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-10-21: the six\n * rows above were re-read from the billing doc, and the catalog input\n * prices for the two newest ids (`gpt-6.1-sol`, `grok-4.7`) were checked\n * against it the same day. Refresh the values (and the drift\n * 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 \"gpt-6.1-sol\": 272_000,\n \"grok-4.6\": 200_000,\n \"grok-4.7\": 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 \"gpt-6.1-sol\": 200,\n \"grok-4.6\": 200,\n \"grok-4.7\": 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 { 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 * the max age are treated as a miss so unpinned packages periodically\n * refresh to upstream latest; the fresh install is then saved back over\n * the entry. Opt out entirely with `GH_ROUTER_PI_NO_PACKAGE_CACHE=1`.\n *\n * Max age defaults to 24h, not the original 7d. Pi resolves an unpinned\n * `npm:name` spec to whatever is already installed, so the max age IS the\n * worst-case staleness of every extension the user runs — a week of it meant a\n * fix published upstream on Monday was still missing the following Sunday.\n * A day bounds the lag without making the cache pointless: the npm install it\n * avoids takes ~5s, so one refresh per day is paid back by every other launch\n * that day. Override with `GH_ROUTER_PI_PACKAGE_CACHE_HOURS`.\n */\n\nexport const PI_PACKAGE_CACHE_MAX_AGE_MS = 24 * 3600 * 1000\n\nexport const PI_PACKAGE_CACHE_HOURS_ENV = \"GH_ROUTER_PI_PACKAGE_CACHE_HOURS\"\n\n/**\n * Effective max age. Read per call rather than at module load so a test (or a\n * long-lived process re-reading config) can change the env and observe it, and\n * so a malformed value degrades to the default instead of `NaN` day math —\n * `Date.now() - mtime > NaN` is always false, which would make every entry\n * eternally fresh.\n */\nexport function piPackageCacheMaxAgeMs(): number {\n const raw = (process.env[PI_PACKAGE_CACHE_HOURS_ENV] ?? \"\").trim()\n if (!raw) return PI_PACKAGE_CACHE_MAX_AGE_MS\n const hours = Number(raw)\n if (!Number.isFinite(hours) || hours <= 0) return PI_PACKAGE_CACHE_MAX_AGE_MS\n return hours * 3600 * 1000\n}\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 const maxAge = piPackageCacheMaxAgeMs()\n if (Date.now() - mtime > maxAge) {\n const ageHours = Math.floor((Date.now() - mtime) / 3600000)\n consola.debug(\n `Pi package cache ${key} is stale (${ageHours}h old, max ${Math.round(maxAge / 3600000)}h); refreshing from registry.`,\n )\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 > piPackageCacheMaxAgeMs()) {\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 { FRESH_CONSULT_CONTRACT } from \"./claude-md-injection\"\nimport {\n LOCAL_CONSULT_REDACTION_LINE,\n LOCAL_CONSULT_REDACTION_NOTE,\n} from \"./local-consult-redaction\"\nimport { profileDescriptor } from \"./launch-profile\"\nimport { LOCAL_PROFILE_TIER_MODELS } from \"./local-profile-contract\"\nimport { LAUNCH_SECRET_HEADER } from \"./messages-identity-preflight\"\nimport {\n balancedContractFor,\n cheapestContractFor,\n consultIsLocalTransport,\n isBalancedFamily,\n isCheapestFamily,\n isLocalFamily,\n local2AdvisorContract,\n localContractFor,\n type LocalProfileId,\n} from \"./profile-family\"\nimport { PI_MIN_VERSION } from \"./pi-version-check\"\nimport { piContextWindowFor } from \"./pi-tier-windows\"\n\nexport type PiProfileId =\n | \"cheapest\"\n | \"cheapest2\"\n | \"balanced\"\n | \"balanced2\"\n | LocalProfileId\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\n/**\n * The Copilot-backed family contract for a Pi profile. `cheapest2` and\n * `balanced2` are derived from their bases, so every resolver below reads one\n * object and a `-2` launch cannot pick up a base literal by omission.\n *\n * Typed to exclude the local family: `LOCAL_PROFILE_CONTRACT` has no\n * `leadEffort` at all (the local endpoint's effort ladder is unknown), so\n * reading that field through a widened union would be a compile hazard. Only\n * the callers that need `leadEffort` use this narrower accessor.\n */\ntype PiCopilotProfileId = Exclude<PiProfileId, LocalProfileId>\n\nfunction piCopilotContractFor(profileId: PiCopilotProfileId) {\n return isCheapestFamily(profileId)\n ? cheapestContractFor(profileId)\n : balancedContractFor(profileId)\n}\n\n/**\n * The family contract for a Pi profile, across all three families. Local is a\n * third family, not a cheapest sibling: its egress and model ids differ even\n * though it inherits the cheapest roster and prose. Only the fields common to\n * every family are reachable here.\n */\nfunction piContractFor(profileId: PiProfileId) {\n return isLocalFamily(profileId)\n ? localContractFor(profileId)\n : piCopilotContractFor(profileId)\n}\n\nexport function piLeadModel(profileId: PiProfileId): string {\n return piContractFor(profileId).models.lead\n}\n\n/**\n * Pi's default thinking level for the lead.\n *\n * Local profiles answer `high` because that is the reachable ceiling, not a\n * guess about the server: Pi exposes `xhigh`/`max` only when a row's\n * `thinkingLevelMap` explicitly defines them, and the local rows deliberately\n * carry no map (we do not assume the endpoint's effort ladder), so\n * `clampThinkingLevel` walks any higher request down to `high`.\n */\nexport function piLeadThinking(profileId: PiProfileId): string {\n return isLocalFamily(profileId)\n ? \"high\"\n : piCopilotContractFor(profileId).leadEffort\n}\n\n/**\n * The `peers` persona allow-list this profile registers with the launch\n * registry, or `undefined` when every persona is reachable.\n *\n * Pi's discovery prose (a group's `mcp.json` description) and its skills are\n * the model's only signal for what a group holds, so they have to be derived\n * from the same list the MCP handler enforces. A group described with personas\n * the launch filters out sends the model hunting for tools that answer\n * -32601. `local` is the one Pi profile with an empty list: it keeps the group\n * for the artifact review tools and nothing else.\n */\nexport function piPersonaAllowlist(\n profileId: PiProfileId,\n): ReadonlySet<string> | undefined {\n return profileDescriptor(profileId).personaAllowlist\n}\n\n/** Whether the Copilot-served `oracle` MCP tool is callable on this profile. */\nexport function piOracleToolReachable(profileId: PiProfileId): boolean {\n const allowlist = piPersonaAllowlist(profileId)\n return allowlist === undefined || allowlist.has(\"oracle\")\n}\n\n/**\n * Whether this profile has a consultant at all.\n *\n * Every Pi profile does. `local` used to be the exception on the reading that\n * the Oracle is necessarily a Copilot call — it is not: the contract's\n * `consultTransport` decides, and `local` declares `\"local\"`, so its Oracle is\n * a consult of the same endpoint its lead already uses. The role therefore\n * exists on every profile and `piOracleModel` never returns `undefined` for one\n * of them; the transport, not the presence, is what differs.\n */\nexport function piOracleEnabled(_profileId: PiProfileId): boolean {\n return true\n}\n\n/**\n * Which model answers the `oracle` subagent.\n *\n * Always a real id: a Copilot slug on every profile whose consult is billed,\n * and the local lead tier (`opus`) on `local`, whose consult goes to the local\n * endpoint like the rest of its turns. The transport is not this function's\n * business — `piContractFor(profileId).consultTransport` is — so a caller that\n * needs to know where the consult runs must ask the contract.\n */\nexport function piOracleModel(profileId: PiProfileId): string | undefined {\n return piOracleEnabled(profileId)\n ? piContractFor(profileId).oracleModel\n : undefined\n}\n\nexport function piOracleThinking(profileId: PiProfileId): string | undefined {\n return piOracleEnabled(profileId)\n ? piContractFor(profileId).oracleEffort\n : undefined\n}\n\n/**\n * Advisor row. Cheapest-family launches carry one; `balanced` is advisor-free\n * by design and `local` mirrors that (no Advisor). `local2` is the one local\n * profile with an Advisor, and it is Copilot-served (`gpt-6.1-sol`) — the\n * Advisor always runs on a real Copilot model, never on the local endpoint.\n */\nexport function piAdvisorModel(\n profileId: PiProfileId,\n): { model: string; thinking: string } | undefined {\n if (isCheapestFamily(profileId)) {\n const contract = cheapestContractFor(profileId)\n return { model: contract.advisorModel, thinking: contract.advisorEffort }\n }\n if (profileId === \"local2\") {\n const contract = local2AdvisorContract()\n return { model: contract.advisorModel, thinking: contract.advisorEffort }\n }\n return undefined\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 const { nativeModels, nativeEfforts: efforts } = piContractFor(profileId)\n return [\n {\n name: \"Explore\",\n model: nativeModels.Explore,\n thinking: efforts.Explore,\n readOnly: true,\n },\n {\n name: \"General-Purpose\",\n model: nativeModels[\"General-Purpose\"],\n thinking: efforts[\"General-Purpose\"],\n readOnly: false,\n },\n {\n name: \"reviewer\",\n model: nativeModels.reviewer,\n thinking: 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 const oracle = piOracleModel(profileId)\n if (oracle) ids.add(oracle)\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 =\n | \"openai-completions\"\n | \"openai-responses\"\n | \"anthropic-messages\"\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 * Per-model base URL. Pi resolves `definition.baseUrl ??\n * provider.baseUrl`, so a local provider whose rows do not all\n * speak the same wire format sets the root each row needs. A row\n * that inherits the provider value omits this.\n */\n baseUrl?: string\n /**\n * Per-model extra request headers. Pi's runtime merges these into the\n * auth headers it would otherwise send (`Models.getAuth`), which is\n * the only header path provable in the vendored slice — a\n * provider-level `headers` key is not. Local profiles use it to carry\n * the stable per-conversation session id the endpoint routes and\n * caches by.\n */\n headers?: Record<string, string>\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 * provider-override pattern — no 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 *\n * LOCAL PROFILES speak `anthropic-messages` instead: the provider default\n * becomes Anthropic's wire format, the tier rows (`opus`/`sonnet`/`haiku`)\n * are the endpoint's own ids and stay on it, and every Copilot-served row\n * (the local2 advisor, which is the only Copilot row a local profile has) is\n * pinned to `openai-responses`. That split is load-bearing: a Copilot row\n * left on the provider default would send a real Copilot model id to the\n * LOCAL server,\n * while the tier rows must never be diverted to `/v1/responses` (that route\n * always leaves for Copilot). Catalog endpoint discovery cannot make this\n * call — a local id has no catalog entry, and a Copilot id's endpoints\n * describe Copilot, not whatever is behind the local port. The tier rows\n * also carry the launch's stable session id as a per-model header, since\n * the endpoint requires one for routing and prompt caching, plus the launch\n * secret that makes the proxy route them locally at all (see\n * `launchSecret` below).\n *\n * The two wire formats also disagree about where the version prefix lives,\n * so the local provider's base URL is the proxy ORIGIN and each\n * Copilot-served row overrides it with the `/v1` root.\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 /**\n * Stable per-conversation id. Local profiles send it as\n * `x-claude-code-session-id` on the tier rows, matching what the Claude\n * Code launcher's own local egress sends.\n */\n sessionId?: string\n /**\n * The launch's `/v1/messages` identity secret. Local tier rows send it as\n * `X-GH-Router-Launch-Secret` so the proxy binds them to a `local`/`local2`\n * launch; unbound traffic is treated as BYO and routed to Copilot, where a\n * bare `opus` id does not exist. Copilot-served rows deliberately omit it.\n */\n launchSecret?: string\n}): PiModelsJson {\n const origin = opts.serverUrl.replace(/\\/+$/, \"\")\n const local = isLocalFamily(opts.profileId)\n // The two wire formats append their own versioned path to the base URL:\n // Pi's OpenAI client POSTs `{baseUrl}/responses` (so the root must carry\n // `/v1`, our `/v1/responses`), while its bundled Anthropic client POSTs\n // `{baseUrl}/v1/messages` (so the root must NOT). Measured against the\n // installed Pi bundle: a local provider left on the `/v1` root requested\n // `/v1/v1/messages` and the proxy answered 404. Copilot-served rows keep\n // the Responses root per model.\n const responsesBaseUrl = `${origin}/v1`\n const providerBaseUrl = local ? origin : responsesBaseUrl\n const providerApi: PiModelApi =\n opts.api ?? (local ? \"anthropic-messages\" : \"openai-responses\")\n const localTierIds = new Set<string>(Object.values(LOCAL_PROFILE_TIER_MODELS))\n const sessionId = opts.sessionId?.trim()\n const launchSecret = opts.launchSecret?.trim()\n const localHeaders =\n local && (sessionId || launchSecret)\n ? {\n ...(sessionId ? { \"x-claude-code-session-id\": sessionId } : {}),\n ...(launchSecret ? { [LAUNCH_SECRET_HEADER]: launchSecret } : {}),\n }\n : undefined\n return {\n providers: {\n [PI_PROVIDER_NAME]: {\n baseUrl: providerBaseUrl,\n api: providerApi,\n apiKey: \"dummy\",\n authHeader: true as const,\n models: piProfileModelIds(opts.profileId, { peers: opts.peers }).map((id) => {\n const isLocalTier = local && localTierIds.has(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 = local\n ? isLocalTier\n ? undefined\n : (\"openai-responses\" as const)\n : (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 ...(isLocalTier && localHeaders ? { headers: localHeaders } : {}),\n ...(thinkingLevelMap ? { thinkingLevelMap } : {}),\n ...(inputLimits ? { inputLimits } : {}),\n ...(override && override !== providerApi ? { api: override } : {}),\n ...(local && !isLocalTier ? { baseUrl: responsesBaseUrl } : {}),\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 * Interactive TUI mode. Pinned to `regular` (Pi's own default is\n * `fullscreen`): the terminal keeps its native scrollback, so\n * select/copy/scroll are the terminal's own bindings rather than an\n * app-level reimplementation. `--tui-mode fullscreen` still reaches\n * Pi through the passthrough args for anyone who prefers the\n * app-owned viewport.\n */\n tuiMode?: \"regular\" | \"fullscreen\"\n /**\n * Startup banner suppression. The router prints its own banner\n * before spawning Pi, so Pi's header plus its loaded-resource\n * listing is duplicate noise. `\"header\"` (keep the version/key-hint\n * line only) remains available as a user override.\n */\n quietStartup?: boolean | \"header\"\n /**\n * The four fullscreen knobs below are PINNED to Pi's current\n * defaults rather than left absent, so the `--tui-mode fullscreen`\n * opt-in cannot silently regress when Pi changes a default. They are\n * inert in the `regular` mode this launcher emits.\n */\n fullscreenExitOutput?: \"transcript\" | \"resume-hint\"\n fullscreenScrollbar?: \"auto\" | \"always\" | \"hidden\"\n fullscreenCopyOnSelect?: boolean\n fullscreenWheelScrollLines?: \"auto\" | number\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 `system`: Pi builds every color from the\n * terminal's own palette, and (with the bundled cc-ui) re-reads that\n * palette when the terminal regains focus, so light/dark terminal\n * switches are followed instead of fought. The `better-claude-code-ui`\n * palettes still ship (themes-only), so `claude-code-dark` /\n * `claude-code-light` / any installed theme stays one `/settings` pick —\n * and, like every other look key, a user's own snapshot value wins.\n */\n theme?: string\n /**\n * cc-ui: keep Pi's theme on the terminal's palette. Its own default is\n * also `true`; emitted explicitly so a future upstream default flip\n * cannot silently pin the router back to a fixed palette. This is the\n * setting that used to fight our `claude-code-dark` pin — cc-ui rewrote\n * it to `system` at `session_start` anyway, so emitting `theme: \"system\"`\n * is the same outcome without a startup flash.\n */\n terminalTheme?: boolean\n /**\n * cc-ui: how finished thinking blocks are drawn. `live` shows thinking\n * while it streams and collapses it to `Thought for Xs` afterwards — the\n * closest surface to Claude Code's transcript, and what stock Pi does not\n * do. Display only; the thinking still happens at the configured effort.\n */\n thinkingMode?: \"live\" | \"full\" | \"latest\"\n /**\n * cc-ui: bash row labels. Default upstream is `\"model\"` since 1.0.112,\n * which adds a field to the bash tool and a line to the model's\n * instructions — a real (if small) token cost on every turn. Pinned to\n * `\"off\"` on cost grounds: rows show the command itself, which is also\n * what Claude Code does when it has no description to show.\n */\n bashIntent?: boolean | \"off\" | \"model\" | \"local\"\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 \"tuiMode\",\n \"quietStartup\",\n \"fullscreenExitOutput\",\n \"fullscreenScrollbar\",\n \"fullscreenCopyOnSelect\",\n \"fullscreenWheelScrollLines\",\n \"theme\",\n \"terminalTheme\",\n \"thinkingMode\",\n \"bashIntent\",\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-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_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 palettes from `better-claude-code-ui`, which ships six CC\n * variants (`claude-code-dark`, `claude-code-light`, …). 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 pure\n * JSON data — loading the whole `./theme` dir costs nothing at runtime and\n * leaves all six CC variants pickable via `/settings`.\n *\n * These are no longer the DEFAULT. The launch now follows the terminal\n * (`PI_FOLLOW_TERMINAL_THEME`), which is what cc-ui did to our pin at\n * `session_start` regardless: it rewrote `theme` to `system` and stashed\n * `claude-code-dark` in `terminalThemePrevious`. Emitting the pin only\n * bought a startup flash and a lying settings file, so the palettes stay\n * as data and users who want the fixed CC look pick one.\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).\n themes: [\"theme/*.json\"],\n extensions: [],\n skills: [],\n prompts: [],\n}\n\n/**\n * Default Pi theme: follow the terminal's own palette. Pi's built-in\n * `system` theme derives every color from the terminal and already exists in\n * `PI_MIN_VERSION` (1.3.0) — see `modes/interactive/theme/system-theme.js`,\n * where it is also sorted first in `getAvailableThemesWithPaths()` because it\n * is Pi's own default when no `theme` setting is present.\n */\nexport const PI_FOLLOW_TERMINAL_THEME = \"system\" as const\n\n/** The fixed Claude Code dark palette, kept for `/settings` picks and docs. */\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 * allowlisted `pi-agent-extensions` always, plus `pi-web-access` only\n * when neither search nor browse is on (otherwise it double-pays our\n * ColBERT/browser surfaces). `pi-mcp-adapter` is deliberately NOT in the\n * bundle any more: an installed extension that registers `/mcp` replaces\n * Pi's built-in MCP, and the router's scoped groups are published through\n * native MCP (`<mirror>/mcp.json`) precisely so the model gets\n * `tool_search` and the `mcp_servers` roster. 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 const oracle = piOracleModel(opts.profileId)\n if (oracle) {\n modelThinkingLevels[`${PI_PROVIDER_NAME}/${oracle}`] =\n piOracleThinking(opts.profileId) as string\n }\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 // Terminal-native interaction by default: regular mode leaves\n // scrollback and mouse selection to the terminal, which is what\n // \"mouse support\" means for most users. The fullscreen knobs are\n // pinned so opting in later is not a behavior change.\n tuiMode: \"regular\",\n quietStartup: true,\n fullscreenExitOutput: \"transcript\",\n fullscreenScrollbar: \"auto\",\n fullscreenCopyOnSelect: true,\n fullscreenWheelScrollLines: \"auto\",\n ...(ui\n ? {\n themeAdaptive: true,\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 // Follow the terminal instead of pinning a palette. cc-ui's\n // `terminalTheme` (its own default, emitted here so an upstream\n // default flip cannot pin us) switches Pi to the `system` theme at\n // session_start either way; emitting the same value up front just\n // removes the flash between Pi's first frame and that switch.\n theme: PI_FOLLOW_TERMINAL_THEME,\n terminalTheme: true,\n // Claude Code's transcript draws thinking while it streams and then\n // collapses it to a one-liner. Display only — effort is unchanged.\n thinkingMode: \"live\" as const,\n // Upstream default since cc-ui 1.0.112 is \"model\", which buys bash\n // labels by adding a tool field and an instruction line to every\n // turn. Emitted as \"off\" to keep that standing token cost off the\n // defaults; it stays a cosmetic key, so a user who writes\n // `bashIntent: \"model\"` in their own settings still wins\n // (`applyCosmeticUserOverrides`).\n bashIntent: \"off\" as const,\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_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 // Every profile emits an oracle file today, so this entry is the\n // belt: a profile that ever drops its own file would otherwise\n // hand the slot to the builtin `oracle`, which also owns the\n // `advisor` alias, on a model of its choosing.\n ...(piOracleEnabled(opts.profileId) ? {} : { oracle: { 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 * The oracle's tool set: empty, on purpose.\n *\n * The Oracle contract is ONE SHOT — ask and answer — on every transport. The\n * MCP persona already conforms (`dispatchModelCall` sends `instructions` plus a\n * single user message over `/v1/responses`, `stream: false`, `writeCapable:\n * false`); a Pi subagent with read/grep/bash was the odd one out, because it\n * could run its own investigation loop and answer from something the caller\n * never saw. A consult that reads its own evidence is not a second opinion on\n * the caller's evidence, it is a third party guessing at it.\n *\n * `tools: \"\"` parses to an EMPTY allowlist with `explicitToolAllowlist: true`\n * (pi-subagents `parseFrontmatterList(\"\")` → `[]`), which is a genuinely\n * tool-less child, verified by driving `discoverAgentsAll` against an emitted\n * mirror. Dropping the key would instead leave `explicitToolAllowlist: false`\n * and inherit EVERY tool — the opposite of the intent.\n */\nconst ORACLE_TOOLS = \"\"\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. `local`\n // may have no oracle, and the note must not name one then: an advertised\n // target the roster lacks is a wasted turn for whoever follows it.\n const consultNote = piOracleEnabled(profileId)\n ? \" May consult the oracle subagent when a decision feels risky.\"\n : \"\"\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 const isBalanced = isBalancedFamily(profileId)\n const base = isBalanced\n ? \"General implementation and follow-through on scoped tasks. May hand the result to reviewer only when the change alters behavior.\"\n : \"General implementation and follow-through on scoped tasks. May hand the result to reviewer for assessment.\"\n return `${base}${consultNote}`\n }\n return isBalancedFamily(profileId)\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 ? isBalancedFamily(profileId)\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. The oracle edge is\n // conditional on the role actually existing: a grant naming an agent the\n // roster lacks is a dangling target, and an advertised target the model\n // cannot reach is a wasted turn for whoever follows it.\n lines.push(\n \"aliases: worker, developer, coder, implementer, develop\",\n \"acceptanceRole: writer\",\n \"allowNestedSubagents: true\",\n piOracleEnabled(profileId)\n ? \"allowedAgents: reviewer, oracle\"\n : \"allowedAgents: reviewer\",\n );\n }\n if (isBalancedFamily(profileId) && 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 (every profile except `local`, which has no\n // consultant at all — see `piOracleEnabled`). 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 oracleModel = piOracleModel(profileId)\n if (oracleModel) {\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 // Empty on purpose — see ORACLE_TOOLS. The consult is one shot.\n `tools: ${ORACLE_TOOLS ? ORACLE_TOOLS : '\"\"'}`,\n `model: ${PI_PROVIDER_NAME}/${oracleModel}`,\n `thinking: ${piOracleThinking(profileId) as string}`,\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, consulted once per question.\",\n \"You have no tools on purpose. You cannot read the repository, run\",\n \"anything, or fetch what the caller did not paste in — so do not ask to.\",\n \"Answer from the context you are given: name the assumptions it rests on,\",\n \"say which missing fact would change your recommendation, and recommend.\",\n \"Never claim to have verified, executed, approved, or merged anything.\",\n // The consultant half of the redaction contract, on the transport that\n // needs it. This body is the ORACLE's own prompt, so it gets the note\n // (\"what you receive is a placeholder\"), not the caller's instruction; the\n // caller half rides the lead digest — see `buildPiAgentsMd`. Neither\n // existed for `local` before: the pair only ever shipped in the cheaplocal\n // prose, so the profile whose Oracle IS a local consult had no redaction\n // contract on any surface.\n ...(consultIsLocalTransport(profileId) ? [LOCAL_CONSULT_REDACTION_NOTE] : []),\n ].join(\"\\n\");\n files[`agents/${agentFileName(\"oracle\")}`] = `${oracle}\\n`;\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 * MCP groups the launch actually publishes into the Pi mirror, by their\n * bare group names (`ado`, `kusto`, `cloudagent`, `peers`, ...). Empty or\n * absent means none. Passed from the resolved surface decision rather than\n * from `state`, so the card can never advertise a group the mirror lacks.\n */\n mcpGroups?: 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 // The group list is the mirror's own truth, so it also carries `peers` and\n // `search`, which the flags above already named. Dedupe rather than drop\n // them: a group the flags missed still has to appear.\n for (const group of opts.mcpGroups ?? []) {\n if (!surface.includes(group)) surface.push(group)\n }\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 const oracle = piOracleEnabled(profileId)\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 isBalancedFamily(profileId)\n ? `- Send work to reviewer ONLY when the change alters behavior.`\n : `- Send finished work to reviewer for assessment.`,\n )\n // The consult sentences describe the consultant this profile HAS. `local`\n // has none: it runs every agent turn on the local endpoint, so a sentence\n // pointing at an oracle would route the lead into a role the roster and\n // the peer group both refuse.\n if (oracle) {\n lines.push(\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 )\n // The caller half of the redaction contract. Pi has no mirrored CLAUDE.md\n // for the launcher to write, so `buildPiAgentsMd` is the only surface the\n // lead reads every turn: without this line a `local` consult would send a\n // brief — and whatever credential it quoted — to an endpoint nobody here\n // operates. The Claude launcher derives the same sentence from the same\n // transport, so the two front-ends cannot drift.\n if (consultIsLocalTransport(profileId)) lines.push(`- ${LOCAL_CONSULT_REDACTION_LINE}`)\n }\n lines.push(\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 FRESH\n // variant of the same text the Claude directive uses, which is the\n // property that actually matters: the consult policy cannot drift\n // between the two front-ends. What does differ is the transport, and it\n // has to: Pi's `advisor` subagent is `defaultContext: fresh` with a\n // read-only toolset, so it reads only the brief the lead writes, while\n // the Claude path forwards a curated transcript view.\n lines.push(\"\", FRESH_CONSULT_CONTRACT.trimEnd());\n }\n lines.push(\"\", `(${PI_MIN_VERSION_NOTE})`, \"\");\n return lines.join(\"\\n\");\n}\n","/**\n * Plan mode: a Claude Code-style planning mode for `github-router pi`.\n *\n * Pi ships no plan mode (upstream README: \"skips features like sub-agents and\n * plan mode\"); the reference implementation is an *example*\n * (`examples/extensions/plan-mode/`) that the user must install separately.\n * This module ports the behaviour into the router's own generated extension so\n * every launch has it, tuned for FRONTIER models rather than for a defensive\n * worst case.\n *\n * The design follows Claude Code's own plan mode (`2.1.322`), whose prompt is\n * reproduced here as behaviour rather than quoted, plus the published\n * guidance from Anthropic and OpenAI on planning before coding:\n *\n * 1. **One barrier, the one that matters.** `edit`, `write` and `apply_patch`\n * leave the active set, and a call that arrives anyway is refused. Nothing\n * else is gated: bash, powershell, MCP tools, delegation and todo writes are\n * all available, because a frontier model asked to investigate a codebase\n * needs them and a hand-maintained read-only command table is both\n * impossible to keep correct (`awk 'BEGIN{system(\"sh\")}'`) and insulting to\n * a model that was told what the mode is for. Claude Code gates tools by\n * capability, not by parsing command strings, and so does this.\n * 2. **One file may be written: the plan.** Claude Code's plan mode is not\n * read-only, it is *one-write* mode — the model builds its plan\n * incrementally in a single designated file and the user can open, edit and\n * approve that file. The file is pinned by the extension (never chosen by\n * the model), so the exception cannot widen: `write`/`edit` are refused\n * unless the resolved path is exactly the plan path.\n * 3. **Always on, no `--plan` flag.** The user toggles with `Ctrl+Alt+P` or\n * `/plan`. A registered flag would have to survive `collectPiPassthroughArgs`\n * and pi's own unknown-flag rejection; registering nothing keeps that path\n * untouched.\n * 4. **The tool set is never touched.** Upstream both re-derives \"normal mode\"\n * from a hardcoded `NORMAL_MODE_TOOLS` and narrows the set on entry. We do\n * neither: narrowing put the model's tool list in front of the `tool_call`\n * gate, so pi answered `Tool write not found` before the gate ran and the\n * one-write exception below could never admit anything. Adding a roster\n * mutation also meant a resumed snapshot could widen the roster a narrower\n * current launch had installed. Plan mode owns the *gate*, not the roster.\n * 5. **No `@earendil-works/pi-agent-core` import.** Upstream imports its message\n * types; generated extensions may only import host-provided specifiers\n * (`typebox`, `@earendil-works/pi-ai`, `@earendil-works/pi-coding-agent`,\n * `@earendil-works/pi-tui`), so the emitted source carries local structural\n * types and zero runtime imports.\n * 6. **Step text keeps its verb.** Upstream strips a leading `Read`/`Add`/`Use`,\n * turning \"Read the launcher\" into \"Launcher\"; the checklist is what the user\n * reads while the plan runs, so the action stays.\n *\n * The prompt itself is two blocks, not two hundred lines: the mode contract\n * (what is closed and why) and the workflow (explore, ask, design, write the\n * plan, hand over). Both are modelled on Claude Code's, including its tolerance\n * for the model's judgement — \"read-only actions\" is a rule the model applies,\n * not a table the harness enforces.\n *\n * Every API the emitted source touches was verified against the pi 1.3.0 tarball\n * (`PI_MIN_VERSION`), not just the current docs: `registerShortcut` (:1233),\n * `registerCommand` (:1231), `appendEntry` (:1272), `getAllTools` (:1285),\n * `ui.setStatus` (:84), `ui.setWidget` (:101), `ui.theme` (:179),\n * `sessionManager.getEntries` (session-manager.d.ts:334), and\n * `before_agent_start` carrying `messageType` (:729/737). No 1.4/1.5-only API is\n * used, so the 1.3.0 floor stands.\n *\n * Fail-open by construction: the emitted factory feature-probes every API it\n * uses, so a pi that grew or dropped one degrades to \"no plan mode\" rather than\n * a broken session — the same contract as the statusline footer.\n */\n\n/** A step parsed out of the model's `Plan:` block. */\nexport interface PlanStep {\n step: number\n text: string\n completed: boolean\n}\n\n/**\n * Strip markdown noise from one step's text.\n *\n * Upstream also strips a leading imperative (`Read`/`Add`/`Use`…), which\n * turns \"Read the launcher\" into \"Launcher\". Divergence 5: keep the verb. The\n * checklist is what the user reads while the plan runs, and a bare noun loses\n * the action it is meant to check off.\n */\nexport function cleanPlanStepText(text: string): string {\n return String(text ?? \"\")\n .replace(/\\*{1,2}([^*]+)\\*{1,2}/g, \"$1\")\n .replace(/`([^`]+)`/g, \"$1\")\n .replace(/\\s+/g, \" \")\n .trim()\n}\n\n/**\n * Parse the model's numbered plan into steps.\n *\n * Takes the LAST matching heading on purpose: the caller feeds this everything\n * the model wrote for a turn, including thinking blocks, and with reasoning-max\n * models a draft plan often lands in thinking before the visible one. The\n * visible text block comes last in content order, so last-wins picks the plan\n * the user actually saw.\n *\n * Fenced code is stripped first: a numbered list inside a snippet is not a plan.\n *\n * Which headings count: the brief asks for a `Plan:` list, and that is what an\n * obedient reply ends with. It is not the only shape a good reply takes — the\n * brief also says to write Context / recommended approach / critical files /\n * verification, and a reply that follows THAT structure and closes its summary\n * under `## Recommended approach` used to parse as ZERO steps, leaving the\n * checklist, the \"what next?\" prompt and the Execute kick silently unreachable.\n * So the conventional headings are accepted too. The heading must be alone on\n * its line (prose like \"Steps: we will ...\" never matches).\n *\n * The regex is inline, not module scope: this function is serialized with\n * `toString()` into the generated extension, where module scope does not exist.\n */\nexport function extractPlanSteps(message: string): Array<PlanStep> {\n const items: Array<PlanStep> = []\n const text = String(message ?? \"\").replace(/^[ \\t]*(?:```|~~~)[\\s\\S]*?^[ \\t]*(?:```|~~~)[ \\t]*$/gm, \"\")\n const headers = [\n ...text.matchAll(\n /^[ \\t]*(?:#{1,6}[ \\t]*)?(?:\\*\\*|__)?[ \\t]*(?:plan|recommended approach|steps|implementation plan)[ \\t]*(?::[ \\t]*)?(?:\\*\\*|__)?[ \\t]*$/gim,\n ),\n ]\n if (headers.length === 0) return items\n const lastHeader = headers[headers.length - 1]!\n let planSection = text.slice((lastHeader.index ?? 0) + lastHeader[0].length)\n // A section ends at the next heading of the same or a higher level, so a\n // `## Verification` list after `## Recommended approach` is not mistaken for\n // plan steps. A headingless marker (`Plan:` / `**Plan:**`) has no level to\n // compare against and keeps the historical whole-tail behaviour.\n const level = (lastHeader[0].match(/^[ \\t]*(#{1,6})/) || [])[1]\n if (level) {\n const boundary = new RegExp(\"^[ \\\\t]*#{1,\" + level.length + \"}[ \\\\t]+\", \"m\")\n const rest = planSection.slice(1)\n const hit = rest.search(boundary)\n if (hit >= 0) planSection = planSection.slice(0, hit + 1)\n }\n // A step may be a list item or a sub-heading (`### 3. Do the thing`); both are\n // how a model writes an ordered plan, and the checklist reads the same.\n const numbered = /^[ \\t]*(?:#{1,6}[ \\t]*)?(\\d+)[.)][ \\t]+(.+)$/gm\n const used = new Set<number>()\n for (const match of planSection.matchAll(numbered)) {\n const raw = (match[2] ?? \"\").trim().replace(/\\*{1,2}$/, \"\").trim()\n if (raw.length > 5 && !raw.startsWith(\"/\") && !raw.startsWith(\"-\")) {\n const cleaned = cleanPlanStepText(raw)\n if (cleaned.length > 3) {\n // Keep the model's own number when it is usable: the checklist echoes it\n // back, and a plan that starts at \"5.\" would otherwise be renumbered\n // 1..N while the model keeps tagging `[DONE:5]`, which would never match.\n // A duplicate or a zero falls back to position so every step has a key.\n const declared = Number(match[1])\n const step = Number.isInteger(declared) && declared > 0 && !used.has(declared) ? declared : items.length + 1\n used.add(step)\n items.push({ step, text: cleaned, completed: false })\n }\n }\n }\n return items\n}\n\n/**\n * Steps the model reported as finished. Accepts `[DONE:2]`, `[DONE 2]`,\n * `Done: 2`, and \"Step 2 is complete\" — the last one adjacency-anchored so\n * \"Step 9 is not done\" never marks anything.\n */\nexport function extractDoneSteps(message: string): Array<number> {\n const text = String(message ?? \"\")\n const steps: Array<number> = []\n for (const match of text.matchAll(/\\[DONE\\s*:?\\s*(\\d+)\\]/gi)) {\n steps.push(Number(match[1]))\n }\n for (const match of text.matchAll(/\\bDone\\s*:\\s*(\\d+)\\b/gi)) {\n steps.push(Number(match[1]))\n }\n for (const match of text.matchAll(\n /\\bStep\\s*(\\d+)\\s+(?:is\\s+)?(?:done|complete|completed|finished)\\b/gi,\n )) {\n steps.push(Number(match[1]))\n }\n return [...new Set(steps)]\n}\n\n/** Mark reported steps complete in place; returns how many became complete. */\nexport function applyDoneSteps(text: string, items: Array<PlanStep>): number {\n let marked = 0\n for (const step of extractDoneSteps(text)) {\n const item = items.find((candidate) => candidate.step === step && !candidate.completed)\n if (item) {\n item.completed = true\n marked++\n }\n }\n return marked\n}\n\n/**\n * Whole-plan completion phrasing, consulted only on a run's final message as a\n * fallback for a model that summarizes instead of tagging each step.\n */\nexport function planAllStepsComplete(message: string): boolean {\n const text = String(message ?? \"\")\n return (\n /(?:all|every)\\s+steps?\\s+(?:are|is\\s+)?(?:done|complete|completed|finished)/i.test(text) ||\n /\\b(?:the\\s+)?plan\\s+(?:is\\s+)?(?:complete|completed|done)\\b/i.test(text)\n )\n}\n\n/**\n * Tools plan mode refuses, by name, through the `tool_call` handler.\n *\n * These stay ACTIVE. An earlier revision also removed them from the active\n * tool set, described as \"two independent barriers\" — they were not\n * independent, they were *stacked*: pi resolves a call against the declared\n * tool list in `prepareToolCall()` and answers `Tool <name> not found` BEFORE\n * `beforeToolCall` (the `tool_call` hook) ever runs. So the narrower barrier\n * sat in front of the wider one, the path exception below was unreachable, the\n * model was told a tool it had just been told to use did not exist, and the\n * documented refusal string was never displayed. An obedient model fell back to\n * `bash` — which is allowed — so the unsanctioned route silently won.\n *\n * With the narrowing gone there is ONE barrier and it is reachable: the model\n * gets a call it can make, and a refusal sentence it can act on. The honest\n * scope is unchanged and already documented: `bash` is allowed, so this\n * redirects a cooperative model, it does not contain a hostile one.\n *\n * `apply_patch` has no single target path to compare and is therefore refused\n * outright — that refusal is also reachable for the first time.\n */\nexport const PLAN_BLOCKED_TOOLS: ReadonlyArray<string> = Object.freeze([\n \"edit\",\n \"write\",\n \"apply_patch\",\n])\n\n/**\n * The plan file, relative to the workspace.\n *\n * Claude Code pins one path per session and tells the model \"this is the only\n * file you are allowed to edit\". Ours is the repository's existing convention\n * (`.github-router/plans/<slug>/plan.md`, the same artifact `/gh-plan` writes and\n * `/gh-implement` reads), with a stable slug so a resumed session keeps editing\n * the plan it started rather than opening a second one.\n */\nexport function planFilePath(): string {\n return \".github-router/plans/pi-plan/plan.md\"\n}\n\n/** Session entry type for persisting plan state across resume. */\nexport const PLAN_MODE_ENTRY = \"gh-router-plan-mode\"\n\n/** Status/widget keys, namespaced so another extension cannot collide. */\nexport const PLAN_STATUS_KEY = \"gh-router-plan\"\nexport const PLAN_WIDGET_KEY = \"gh-router-plan-steps\"\n\n/** Custom message types the emitted extension emits and later filters. */\nexport const PLAN_CONTEXT_TYPE = \"gh-router-plan-context\"\nexport const PLAN_EXEC_TYPE = \"gh-router-plan-exec\"\nexport const PLAN_DONE_TYPE = \"gh-router-plan-done\"\nexport const PLAN_LIST_TYPE = \"gh-router-plan-list\"\n\n/**\n * Resolve `path` against `cwd` and decide whether it IS the plan file.\n *\n * Deliberately dumb and deliberately strict: this is the one hole in the write\n * barrier, so it compares `path.resolve`d strings rather than doing prefix\n * arithmetic on the raw input. A model that writes `plan.md` in the right\n * directory passes; `../plan.md`, `<cwd>/plan.md/../secret`, and a symlink-free\n * absolute path to the same target all normalize to the same string, which is\n * the property that matters.\n *\n * The emitted copy cannot import `node:path` (the generated extension and this\n * module have different allowed specifiers), so it carries its own tiny\n * resolver: POSIX normalisation plus a Windows drive/UNC guard. It is not a\n * general path library — it only has to agree with itself between the\n * comparison here and the value `planFilePath()` produces, which is why the\n * relative plan path is a PARAMETER: a `toString()`-serialized function cannot\n * see module scope, and a captured constant would be `undefined` at runtime.\n */\nexport function isPlanFilePath(cwd: string, target: unknown, rel: string): boolean {\n const raw = typeof target === \"string\" ? target.trim() : \"\"\n if (!raw) return false\n const normalize = (input: string): string => {\n const isWindows = /^[a-zA-Z]:[\\\\/]/.test(input) || input.indexOf(\"\\\\\") >= 0\n const sep = isWindows ? /\\\\+/g : /\\/+/g\n const unified = input.replace(sep, \"/\")\n const absolute = isWindows ? unified : unified.startsWith(\"/\") ? unified : \"/\" + unified\n const parts: Array<string> = []\n for (const segment of absolute.split(\"/\")) {\n if (!segment || segment === \".\") continue\n if (segment === \"..\") {\n parts.pop()\n continue\n }\n parts.push(segment)\n }\n return (isWindows ? \"\" : \"/\") + parts.join(\"/\")\n }\n if (typeof rel !== \"string\" || !rel) return false\n const base = typeof cwd === \"string\" && cwd.trim() ? cwd.trim() : \"/\"\n const resolved = raw.startsWith(\"/\") || /^[a-zA-Z]:[\\\\/]/.test(raw) || raw.indexOf(\"\\\\\") === 0\n ? normalize(raw)\n : normalize(base + \"/\" + raw)\n return resolved === normalize(base + \"/\" + rel)\n}\n\n/**\n * The emitted extension section.\n *\n * Pure helpers ride `.toString()` (the same technique the statusline footer\n * uses for `buildPiStatusPayload`) so the code that runs in the product is\n * byte-identical to the code the unit tests exercise — a hand-copied duplicate\n * could drift from its tested twin without any test noticing.\n */\nexport function buildPiPlanModeSection(): Array<string> {\n return [\n ` // ---- plan mode: Claude-Code-style planning (always on) ----`,\n ` // /plan or Ctrl+Alt+P toggles it. The tool set is NEVER touched: it used to`,\n ` // be snapshotted on entry and restored on exit, and removing the writers from`,\n ` // it made the path gate below unreachable (pi answers \"Tool write not found\"`,\n ` // before any handler runs), plus a restored snapshot could widen the roster a`,\n ` // narrower launch installed. ONE barrier instead: the writers stay offered`,\n ` // and the gate refuses every target except the plan file. Everything else`,\n ` // stays, because a frontier model told to explore and not implement needs a`,\n ` // shell and can be trusted with one.`,\n ` try {`,\n ` const PLAN_STATUS_KEY = ${JSON.stringify(PLAN_STATUS_KEY)};`,\n ` const PLAN_WIDGET_KEY = ${JSON.stringify(PLAN_WIDGET_KEY)};`,\n ` const PLAN_ENTRY = ${JSON.stringify(PLAN_MODE_ENTRY)};`,\n ` const PLAN_CONTEXT_TYPE = ${JSON.stringify(PLAN_CONTEXT_TYPE)};`,\n ` const PLAN_EXEC_TYPE = ${JSON.stringify(PLAN_EXEC_TYPE)};`,\n ` const PLAN_DONE_TYPE = ${JSON.stringify(PLAN_DONE_TYPE)};`,\n ` const PLAN_LIST_TYPE = ${JSON.stringify(PLAN_LIST_TYPE)};`,\n ` const PLAN_BLOCKED = new Set(${JSON.stringify([...PLAN_BLOCKED_TOOLS])});`,\n ` const PLAN_FILE_REL = ${JSON.stringify(planFilePath())};`,\n ` const isPlanFilePath = (${isPlanFilePath.toString()});`,\n ` const cleanPlanStepText = (${cleanPlanStepText.toString()});`,\n ` const extractPlanSteps = (${extractPlanSteps.toString()});`,\n ` const extractDoneSteps = (${extractDoneSteps.toString()});`,\n ` const applyDoneSteps = (${applyDoneSteps.toString()});`,\n ` const planAllStepsComplete = (${planAllStepsComplete.toString()});`,\n ``,\n ` let planEnabled = false;`,\n ` let planExecuting = false;`,\n ` let planSteps = [];`,\n ` let planCwd = \"\";`,\n ` // Set while the \"what next?\" prompt is open. agent_end can fire again for`,\n ` // the same plan (a queued follow-up run ends too), and a second prompt on`,\n ` // top of the first would let two Execute answers each send an execution`,\n ` // kick, resetting progress and paying for a redundant turn.`,\n ` let planPromptOpen = false;`,\n ``,\n ` function planPaint(ctx, text, color) {`,\n ` try {`,\n ` const theme = ctx && ctx.ui && ctx.ui.theme;`,\n ` if (theme && typeof theme.fg === \"function\") return theme.fg(color, text);`,\n ` } catch {}`,\n ` return text;`,\n ` }`,\n ``,\n ` // Resident checklist: a footer status badge plus a widget above the editor.`,\n ` // The router's own statusline footer already forwards extension statuses,`,\n ` // so the badge is visible without this extension owning the footer.`,\n ` function planUpdateUi(ctx) {`,\n ` try {`,\n ` const ui = ctx && ctx.ui;`,\n ` if (!ui) return;`,\n ` if (planExecuting && planSteps.length > 0) {`,\n ` const done = planSteps.filter((s) => s.completed).length;`,\n ` try { ui.setStatus(PLAN_STATUS_KEY, planPaint(ctx, \"\\\\u{1F4CB} \" + done + \"/\" + planSteps.length, \"accent\")); } catch {}`,\n ` } else if (planEnabled) {`,\n ` try { ui.setStatus(PLAN_STATUS_KEY, planPaint(ctx, \"\\\\u{23F8} plan\", \"warning\")); } catch {}`,\n ` } else {`,\n ` try { ui.setStatus(PLAN_STATUS_KEY, undefined); } catch {}`,\n ` }`,\n ` if (planSteps.length > 0 && (planEnabled || planExecuting)) {`,\n ` const lines = planSteps.map((s) => {`,\n ` const text = s.text.length > 60 ? s.text.slice(0, 57) + \"...\" : s.text;`,\n ` if (s.completed) return planPaint(ctx, \"\\\\u2611 \", \"success\") + planPaint(ctx, text, \"muted\");`,\n ` return planPaint(ctx, \"\\\\u2610 \", \"muted\") + text;`,\n ` });`,\n ` try { ui.setWidget(PLAN_WIDGET_KEY, lines); } catch {}`,\n ` } else {`,\n ` try { ui.setWidget(PLAN_WIDGET_KEY, undefined); } catch {}`,\n ` }`,\n ` } catch {}`,\n ` }`,\n ``,\n ` // State survives resume through a custom entry; custom entries never reach`,\n ` // the model, so this carries NO context cost. Redundant writes are skipped:`,\n ` // turn_end and agent_end both fire per run, and a long execution would`,\n ` // otherwise append a duplicate entry per turn for the whole transcript.`,\n ` let planPersistKey = null;`,\n ` function planPersist() {`,\n ` try {`,\n ` const data = {`,\n ` enabled: planEnabled,`,\n ` executing: planExecuting,`,\n ` steps: planSteps.map((s) => ({ step: s.step, text: s.text, completed: s.completed })),`,\n ` };`,\n ` const key = JSON.stringify(data);`,\n ` if (key === planPersistKey) return;`,\n ` planPersistKey = key;`,\n ` pi.appendEntry(PLAN_ENTRY, data);`,\n ` } catch {}`,\n ` }`,\n ``,\n ` function planEnter(ctx) {`,\n ` if (planEnabled) return;`,\n ` planEnabled = true;`,\n ` planExecuting = false;`,\n ` planPromptOpen = false;`,\n ` planSteps = [];`,\n ` try { if (ctx && typeof ctx.cwd === \"string\" && ctx.cwd) planCwd = ctx.cwd; } catch {}`,\n ` try { ctx.ui.notify(\"Plan mode on: writes refused except \" + PLAN_FILE_REL + \". Investigate, then write the plan there. Ctrl+Alt+P or /plan to leave.\", \"info\"); } catch {}`,\n ` planUpdateUi(ctx);`,\n ` planPersist();`,\n ` }`,\n ``,\n ` function planExit(ctx) {`,\n ` if (!planEnabled && !planExecuting) return;`,\n ` planEnabled = false;`,\n ` planExecuting = false;`,\n ` planPromptOpen = false;`,\n ` planSteps = [];`,\n ` try { ctx.ui.notify(\"Plan mode off: writes allowed everywhere again.\", \"info\"); } catch {}`,\n ` planUpdateUi(ctx);`,\n ` planPersist();`,\n ` }`,\n ``,\n ` function planToggle(ctx) {`,\n ` if (planEnabled || planExecuting) planExit(ctx);`,\n ` else planEnter(ctx);`,\n ` }`,\n ``,\n ` try {`,\n ` pi.registerCommand(\"plan\", {`,\n ` description: \"Toggle plan mode (edits disabled; plan file only)\",`,\n ` handler: async (_args, ctx) => { planToggle(ctx); },`,\n ` });`,\n ` } catch {}`,\n ` try {`,\n ` // Literal KeyId rather than Key.ctrlAlt(\"p\"): the generated source then`,\n ` // needs no pi-tui import at all, which keeps it loadable on every build`,\n ` // whose host-provided specifier list is smaller than today's. The value`,\n ` // is exactly what Key.ctrlAlt(\"p\") returns (pi-tui keys.js:118).`,\n ` pi.registerShortcut(\"ctrl+alt+p\", {`,\n ` description: \"Toggle plan mode\",`,\n ` handler: async (ctx) => { planToggle(ctx); },`,\n ` });`,\n ` } catch {}`,\n ` try {`,\n ` pi.registerCommand(\"plan-status\", {`,\n ` description: \"Show plan mode state and the current step list\",`,\n ` handler: async (_args, ctx) => {`,\n ` if (!planEnabled && !planExecuting && planSteps.length === 0) {`,\n ` try { ctx.ui.notify(\"Plan mode is off. /plan (or Ctrl+Alt+P) to start planning.\", \"info\"); } catch {}`,\n ` return;`,\n ` }`,\n ` const done = planSteps.filter((s) => s.completed).length;`,\n ` const body = planSteps.length === 0`,\n ` ? \"No steps parsed yet. Ask for a numbered Plan: block.\"`,\n ` : planSteps.map((s) => (s.completed ? \"\\\\u2713 \" : \"\\\\u25CB \") + s.step + \". \" + s.text).join(\"\\\\n\");`,\n ` const head = planExecuting ? \"Executing plan (\" + done + \"/\" + planSteps.length + \")\" : \"Plan mode active\";`,\n ` try { ctx.ui.notify(head + \"\\\\n\" + body, \"info\"); } catch {}`,\n ` },`,\n ` });`,\n ` } catch {}`,\n ``,\n ` // THE barrier: one write exception, enforced by resolved path. A write or`,\n ` // edit whose target is the pinned plan file passes; every other target is`,\n ` // refused whatever the model believes. The path comes from the extension`,\n ` // and never from the model, which is what keeps the exception from widening`,\n ` // into a general write permission. It has to be the ONLY barrier: narrowing`,\n ` // the tool set as well would hide these tools from the model, so pi would`,\n ` // answer \"Tool write not found\" before this handler and the exception could`,\n ` // never fire — see PLAN_BLOCKED_TOOLS.`,\n ` try {`,\n ` pi.on(\"tool_call\", async (event, ctx) => {`,\n ` if (!planEnabled || !event) return undefined;`,\n ` const name = String(event.toolName || \"\");`,\n ` if (!PLAN_BLOCKED.has(name)) return undefined;`,\n ` try { if (ctx && typeof ctx.cwd === \"string\" && ctx.cwd) planCwd = ctx.cwd; } catch {}`,\n ` const input = (event.input || {});`,\n ` const target = input.path !== undefined ? input.path : input.file_path;`,\n ` if (isPlanFilePath(planCwd, target, PLAN_FILE_REL)) return undefined;`,\n ` return {`,\n ` block: true,`,\n ` reason: \"Plan mode: this write is refused. The only file you may write is \" + PLAN_FILE_REL + \" (pass exactly that path). Record the plan there, or leave plan mode (/plan or Ctrl+Alt+P) to change code.\",`,\n ` };`,\n ` });`,\n ` } catch {}`,\n ``,\n ` // Plan-injected context is dropped once neither mode is engaged, so a later`,\n ` // turn is not still told it is read-only or mid-execution. Custom messages`,\n ` // reach this handler as role \"custom\" with customType intact, which is the`,\n ` // load-bearing check; the text marker is the belt for a host (or an`,\n ` // imported transcript) that flattened the custom role into a user message.`,\n ` const PLAN_STALE_MARKERS = [`,\n ` { marker: \"[PLAN MODE ACTIVE]\", live: () => planEnabled },`,\n ` { marker: \"[EXECUTING PLAN\", live: () => planExecuting },`,\n ` ];`,\n ` function planIsStaleContext(m) {`,\n ` if (!m || m.role !== \"user\" || (m.customType !== undefined)) return false;`,\n ` const content = m.content;`,\n ` const stale = (text) => {`,\n ` if (typeof text !== \"string\") return false;`,\n ` return PLAN_STALE_MARKERS.some((entry) => !entry.live() && text.indexOf(entry.marker) >= 0);`,\n ` };`,\n ` if (typeof content === \"string\") return stale(content);`,\n ` if (Array.isArray(content)) return content.some((c) => c && c.type === \"text\" && stale(c.text));`,\n ` return false;`,\n ` }`,\n ``,\n ` // before_agent_start messages are APPENDED and PERSISTED per run, so a`,\n ` // plan-mode session accrues one block per turn. Two rules keep that from`,\n ` // costing anything or lying to the model:`,\n ` // - a block is valid only while ITS mode is engaged: the read-only block`,\n ` // dies the moment execution starts (the model is told full access is`,\n ` // back), and the execution block dies when the mode ends;`,\n ` // - of the valid blocks, only the newest of each kind is kept, so a long`,\n ` // plan does not pay for N copies of the same instructions.`,\n ` try {`,\n ` pi.on(\"context\", async (event) => {`,\n ` if (!event || !Array.isArray(event.messages)) return undefined;`,\n ` const seen = new Set();`,\n ` const output = [];`,\n ` for (let i = event.messages.length - 1; i >= 0; i--) {`,\n ` const m = event.messages[i];`,\n ` const type = m && m.customType;`,\n ` if (type === PLAN_CONTEXT_TYPE || type === PLAN_EXEC_TYPE) {`,\n ` const valid = type === PLAN_CONTEXT_TYPE ? planEnabled : planExecuting;`,\n ` if (!valid || seen.has(type)) continue;`,\n ` seen.add(type);`,\n ` } else if (planIsStaleContext(m)) {`,\n ` continue;`,\n ` }`,\n ` output.push(m);`,\n ` }`,\n ` if (output.length === event.messages.length) return undefined;`,\n ` output.reverse();`,\n ` return { messages: output };`,\n ` });`,\n ` } catch {}`,\n ``,\n ` // The planning contract, modelled on Claude Code's plan-mode reminder: the`,\n ` // mode is closed, the plan file is the ONE exception, and the model is`,\n ` // trusted with everything else. Frontier-model tuning lives here — a`,\n ` // command allowlist, a delegation ban and an MCP namespace deny all told a`,\n ` // capable model to be less useful than it is, and none of them is needed`,\n ` // now that \"edits are disabled\" is the whole rule and the plan file is the`,\n ` // only write. The workflow is Claude's five phases compressed to what Pi`,\n ` // has: Explore/General-Purpose subagents exist, but the roster is`,\n ` // profile-dependent, so the phase text names the intent, not an agent.`,\n ` const PLAN_BRIEF = [`,\n ` \"[PLAN MODE ACTIVE]\",`,\n ` \"\",`,\n ` \"Plan mode is active. The user does not want you to execute yet -- you must not edit files,\",`,\n ` \"run a command that changes the code, or otherwise act on the plan. This supersedes any other\",`,\n ` \"instruction you have received about doing the work now.\",`,\n ` \"\",`,\n ` \"One exception, and it is the whole of it: you may write your plan to\",`,\n ` \" \" + PLAN_FILE_REL,`,\n ` \"Edit and write are refused for every other path. Read, search, and run read-only commands\",`,\n ` \"freely -- explore enough that the plan is grounded in what the code actually does.\",`,\n ` \"\",`,\n ` \"Work the plan like this:\",`,\n ` \"1. Understand the request, and look for what already exists (functions, utilities, patterns)\",`,\n ` \" before proposing anything new. Delegate broad or parallel discovery when that is faster\",`,\n ` \" than reading serially yourself.\",`,\n ` \"2. Ask the user whatever you cannot settle from the code. Do it once, up front, and never\",`,\n ` \" ask what exploration could answer.\",`,\n ` \"3. Design the approach far enough that an implementer would have no open decisions left:\",`,\n ` \" which files, what changes in each, what each change is done when, and what would prove it.\",`,\n ` \"4. Write the plan to the plan file: a short Context section, the recommended approach only,\",`,\n ` \" the critical files, the verification steps, and any residual risk. Keep it scannable.\",`,\n ` \"5. Summarise the plan in your reply too, so the user can answer without opening the file,\",`,\n ` \" finishing with a numbered list of the steps -- that list becomes the checklist.\",`,\n ` \"\",`,\n ` \"Do NOT open an ask_user question or a prose prompt for plan approval. Leaving plan mode is\",`,\n ` \"the user's action (/plan or Ctrl+Alt+P) -- asking permission to stop planning is the one\",`,\n ` \"question this mode does not want, and approval you grant yourself is not approval.\",`,\n ` \"If the user asks for changes, revise the SAME plan file rather than writing a second one.\",`,\n ` \"The test for every other action: if it would reasonably be described as DOING the work\",`,\n ` \"rather than planning it, it waits until plan mode is off.\",`,\n ` ].join(\"\\\\n\");`,\n ``,\n ` // Cost contract: inject NOTHING unless plan mode is actually engaged, and`,\n ` // only for a real user turn (a background notification must not re-add it).`,\n ` try {`,\n ` pi.on(\"before_agent_start\", async (event) => {`,\n ` if (!event || event.messageType !== \"user\") return undefined;`,\n ` if (planEnabled) {`,\n ` return { message: { customType: PLAN_CONTEXT_TYPE, content: PLAN_BRIEF, display: false } };`,\n ` }`,\n ` if (planExecuting && planSteps.length > 0) {`,\n ` const remaining = planSteps.filter((s) => !s.completed).map((s) => s.step + \". \" + s.text).join(\"\\\\n\");`,\n ` const content = [`,\n ` \"[EXECUTING PLAN - full tool access enabled]\",`,\n ` \"\",`,\n ` \"Remaining steps:\",`,\n ` remaining,`,\n ` \"\",`,\n ` \"Execute each step in order.\",`,\n ` \"After completing a step, include a [DONE:n] tag in your response.\",`,\n ` ].join(\"\\\\n\");`,\n ` return { message: { customType: PLAN_EXEC_TYPE, content, display: false } };`,\n ` }`,\n ` return undefined;`,\n ` });`,\n ` } catch {}`,\n ``,\n ` // Progress tracking after each turn. Reads text AND thinking blocks: with`,\n ` // reasoning-max models the [DONE:n] tags often land in thinking, not text.`,\n ` try {`,\n ` pi.on(\"turn_end\", async (event, ctx) => {`,\n ` if (!planExecuting || planSteps.length === 0 || !event) return;`,\n ` const msg = event.message;`,\n ` if (!msg || msg.role !== \"assistant\" || !Array.isArray(msg.content)) return;`,\n ` const text = msg.content.map((b) => {`,\n ` if (!b) return \"\";`,\n ` if (b.type === \"text\") return b.text || \"\";`,\n ` if (b.type === \"thinking\") return b.thinking || \"\";`,\n ` return \"\";`,\n ` }).join(\"\\\\n\");`,\n ` applyDoneSteps(text, planSteps);`,\n ` planUpdateUi(ctx);`,\n ` planPersist();`,\n ` });`,\n ` } catch {}`,\n ``,\n ` // End of a run: parse the plan (planning) or finish the execution.`,\n ` try {`,\n ` pi.on(\"agent_end\", async (event, ctx) => {`,\n ` if (!event || !Array.isArray(event.messages)) return;`,\n ` const last = [...event.messages].reverse().find((m) => m && m.role === \"assistant\" && Array.isArray(m.content));`,\n ` const lastText = last`,\n ` ? last.content.map((b) => {`,\n ` if (!b) return \"\";`,\n ` if (b.type === \"text\") return b.text || \"\";`,\n ` if (b.type === \"thinking\") return b.thinking || \"\";`,\n ` return \"\";`,\n ` }).join(\"\\\\n\")`,\n ` : \"\";`,\n ` if (planExecuting && planSteps.length > 0) {`,\n ` if (planAllStepsComplete(lastText)) {`,\n ` for (const s of planSteps) s.completed = true;`,\n ` }`,\n ` if (planSteps.every((s) => s.completed)) {`,\n ` const list = planSteps.map((s) => \"- ~~\" + s.text + \"~~\").join(\"\\\\n\");`,\n ` // nextTurn, not a triggerTurn: acknowledging the card with an extra`,\n ` // (reasoning-max) model turn would cost real money for a checkmark.`,\n ` try { pi.sendMessage({ customType: PLAN_DONE_TYPE, content: \"**Plan complete** \\\\u2713\" + \"\\\\n\" + list, display: true }, { deliverAs: \"nextTurn\" }); } catch {}`,\n ` planExecuting = false;`,\n ` planSteps = [];`,\n ` planUpdateUi(ctx);`,\n ` planPersist();`,\n ` }`,\n ` return;`,\n ` }`,\n ` if (!planEnabled) return;`,\n ` const parsed = extractPlanSteps(lastText);`,\n ` if (parsed.length > 0) planSteps = parsed;`,\n ` if (planSteps.length === 0) return;`,\n ` planUpdateUi(ctx);`,\n ` planPersist();`,\n ` // One prompt at a time: a queued follow-up run also ends here, and a`,\n ` // second Execute answer would re-kick a plan that is already running.`,\n ` if (planPromptOpen) return;`,\n ` let hasUI = false;`,\n ` try { hasUI = !!ctx.hasUI; } catch {}`,\n ` if (!hasUI || typeof ctx.ui.select !== \"function\") return;`,\n ` planPromptOpen = true;`,\n ` let choice = undefined;`,\n ` try {`,\n ` choice = await ctx.ui.select(\"Plan mode - what next?\", [`,\n ` \"Execute the plan (track progress)\",`,\n ` \"Stay in plan mode\",`,\n ` \"Refine the plan\",`,\n ` ]);`,\n ` } catch { planPromptOpen = false; return; }`,\n ` planPromptOpen = false;`,\n ` if (!choice) return;`,\n ` // The user may have left plan mode while the prompt was open (slash`,\n ` // /plan, Ctrl+Alt+P, /new). Honouring Execute there would silently`,\n ` // re-enter a mode they just exited.`,\n ` if (!planEnabled) return;`,\n ` if (String(choice).indexOf(\"Execute\") === 0) {`,\n ` planEnabled = false;`,\n ` planExecuting = true;`,\n ` planUpdateUi(ctx);`,\n ` planPersist();`,\n ` const list = planSteps.map((s) => s.step + \". \" + s.text).join(\"\\\\n\");`,\n ` const first = planSteps[0] ? planSteps[0].text : \"\";`,\n ` try {`,\n ` pi.sendMessage({ customType: PLAN_LIST_TYPE, content: \"**Plan steps (\" + planSteps.length + \")**\" + \"\\\\n\" + list, display: true }, { deliverAs: \"followUp\" });`,\n ` pi.sendMessage({ customType: PLAN_EXEC_TYPE, content: \"Execute the plan.\" + \"\\\\n\" + \"Remaining steps:\" + \"\\\\n\" + list + \"\\\\n\" + \"Start with: \" + first + \"\\\\n\" + \"After completing a step, include a [DONE:n] tag.\" }, { triggerTurn: true, deliverAs: \"followUp\" });`,\n ` } catch {}`,\n ` } else if (choice === \"Refine the plan\" && typeof ctx.ui.editor === \"function\") {`,\n ` let refinement = undefined;`,\n ` try { refinement = await ctx.ui.editor(\"Refine the plan:\", \"\"); } catch { return; }`,\n ` const trimmed = String(refinement || \"\").trim();`,\n ` if (!trimmed) return;`,\n ` try { pi.sendUserMessage(trimmed, { deliverAs: \"followUp\" }); } catch {}`,\n ` }`,\n ` });`,\n ` } catch {}`,\n ``,\n ` // Restore after resume: the ENTRY is the source of truth for the mode, the`,\n ` // step list and the badge — and nothing else. The gate below needs no`,\n ` // restore because it reads the live flag.`,\n ` // State is assigned UNCONDITIONALLY: a fresh session (/new, /fork into an`,\n ` // empty branch) has no entry, and leaving the previous session's flags in`,\n ` // place would keep a stale badge for a mode that is not gating anything.`,\n ` try {`,\n ` pi.on(\"session_start\", async (_event, ctx) => {`,\n ` try {`,\n ` if (ctx && typeof ctx.cwd === \"string\" && ctx.cwd) planCwd = ctx.cwd;`,\n ` const entries = ctx.sessionManager && typeof ctx.sessionManager.getEntries === \"function\"`,\n ` ? ctx.sessionManager.getEntries()`,\n ` : [];`,\n ` let saved = undefined;`,\n ` for (const entry of entries) {`,\n ` if (entry && entry.type === \"custom\" && entry.customType === PLAN_ENTRY) saved = entry.data;`,\n ` }`,\n ` const nextEnabled = !!saved && saved.enabled === true;`,\n ` const nextExecuting = !!saved && saved.executing === true;`,\n ` // Nothing here touches the active tool set. Plan mode does not own`,\n ` // it: the only thing that ever changed the roster was the restriction`,\n ` // this design deleted, and a resumed snapshot must never widen the`,\n ` // roster a narrower current launch installed (that was a real bug:`,\n ` // resuming under --tools read,bash silently restored grep).`,\n ` planEnabled = nextEnabled;`,\n ` planExecuting = nextExecuting;`,\n ` planPromptOpen = false;`,\n ` planPersistKey = null;`,\n ` planSteps = saved && Array.isArray(saved.steps)`,\n ` ? saved.steps.map((s) => ({ step: Number(s.step) || 0, text: String(s.text || \"\"), completed: s.completed === true }))`,\n ` : [];`,\n ` // An execution with no steps is a dead end: the checklist is empty and`,\n ` // every execution branch bails on steps.length, so treat it as off.`,\n ` if (planExecuting && planSteps.length === 0) planExecuting = false;`,\n ` } catch {}`,\n ` planUpdateUi(ctx);`,\n ` });`,\n ` } catch {}`,\n ` } catch {}`,\n ``,\n ]\n}\n","import type { PiProfileId } from \"./pi-models-settings\"\nimport {\n PI_PROVIDER_NAME,\n piAdvisorModel,\n piLeadModel,\n piLeadThinking,\n piOracleEnabled,\n piOracleToolReachable,\n} from \"./pi-models-settings\"\nimport { isBalancedFamily, isCheapestFamily } from \"./profile-family\"\nimport {\n AIC_STATUSLINE_DISABLE_ENV,\n} from \"./aic-statusline-settings\"\nimport { buildPiPlanModeSection } from \"./pi-plan-mode\"\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. Model-facing tools are\n * NOT registered here — every scoped MCP group is published as a native Pi\n * server in the mirror's `mcp.json` (`src/lib/pi-mcp-config.ts`), which\n * brings `tool_search`, the `mcp_servers` roster and per-server `exposure`\n * that a hand-wrapped `registerTool` cannot. What stays is the work no MCP\n * server can do: the statusline footer, plan mode, the memory bridge, and\n * (cheapest family only) the prompt-submit relay, which POSTs JSON-RPC\n * `tools/call` to the running proxy with the per-launch nonce (the same\n * `GH_ROUTER_HOOK_MCP_URL/NONCE` channel the Claude hooks use).\n *\n * No custom provider, no compaction replacement: `session_before_compact`\n * only routes the summary model and always falls back to Pi native on\n * 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 * Plan mode (always on): Claude Code ships plan mode as a mode; Pi ships it\n * only as an example extension a user has to install. `src/lib/pi-plan-mode.ts`\n * generates the equivalent into this same package — see\n * `buildPiPlanModeSection` for the single reachable write barrier (the path\n * gate; the tool roster is deliberately untouched) and the divergences from\n * upstream.\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 bridge?: PiBridgeExtensionInput\n}): string {\n // Cheapest-only, like the advisor some profiles carry: the brief is the\n // front-end half of the same floor-raising surface `buildPiAppendSystem`\n // writes the consult contract for, and `balanced` is deliberately floor-free\n // on both counts.\n const promptBrief = isCheapestFamily(opts.profileId)\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 { spawn } from \"node:child_process\";`,\n ``,\n `function stripNul(s) { return String(s ?? \"\").replace(/\\\\0/g, \"\"); }`,\n ...(promptBrief\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 // 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 ...(promptBrief\n ? [\n // The prompt-submit relay is the extension's only MCP call now. Every\n // model-facing tool arrives through Pi's own `mcp.json` (native MCP),\n // so the workspace header is set on the server entry rather than\n // here; this call still sends it because the hook channel is a raw\n // fetch and the proxy reads the header, not a workspace argument.\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) { 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 ]\n : []),\n `export default function (pi) {`,\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 // Plan mode: always on, no flag. Claude Code ships plan mode as a mode; Pi\n // ships it as an example extension, so parity means generating it per launch.\n ...buildPiPlanModeSection(),\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 && piOracleEnabled(opts.profileId)) {\n // The oracle is reachable two ways, and the skill must name the one this\n // profile actually has. Copilot profiles carry the stateless MCP persona\n // (and the same-named subagent for follow-ups); a profile whose peer group\n // filters the persona out carries only the subagent, so naming the MCP tool\n // there would send the model after a tool that answers -32601. Every shipped\n // profile reaches the persona today (including `local`, whose consult runs\n // on the local tier); the subagent-only wording stays for a profile that\n // ever narrows the allowlist back.\n const oracleReachable = piOracleToolReachable(opts.profileId)\n const oracleBody = oracleReachable\n ? [\n \"Call `mcp__gh-router-peers__oracle` (load it with `tool_search` if it is\",\n \"not in the tool list yet) with the decision, the options considered, and\",\n \"the missing-context gaps. The oracle is cold-start: it sees only what you\",\n \"pass. Its verdict is advisory — verify with tests and code, never\",\n \"substitute votes for verification. (The MCP tool is the one-shot consult;\",\n \"the `oracle` subagent is the same role for interactive follow-ups — same\",\n \"name, different invocation. Prefer the tool for a single verdict.)\",\n ]\n : [\n \"Delegate to the `oracle` subagent through the `subagent` tool with the\",\n \"decision, the options considered, and the missing-context gaps. The\",\n \"oracle is cold-start and tool-less: it sees only what you pass, and it\",\n \"cannot read the repository on its own. Its verdict is advisory — verify\",\n \"with tests and code, never substitute votes for verification.\",\n ]\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 ...oracleBody,\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 `mcp__gh-router-search__code` (semantic by default; load it with\",\n \"`tool_search` if it is not in the tool list yet) before broad reads. The\",\n \"response labels its `source`: `semantic`, `lexical`, or\",\n \"`lexical-fallback` — a fallback is never silent, so retry narrower on\",\n \"fallback rather than assuming full coverage.\",\n ].join(\"\\n\"),\n })\n }\n if (opts.swe === true && peers) {\n // The roster line must not name a consultant this profile has neither a\n // tool nor an agent file for: balanced and `local` are advisor-free, so\n // they name the oracle alone. Composing the sentence per case keeps a `, .`\n // (or a comma before nothing) out of the prose — which is also what a\n // profile with neither consultant would get.\n const advisor = piAdvisorModel(opts.profileId)\n const oracle = piOracleEnabled(opts.profileId)\n const consults = advisor\n ? \"`oracle`/`advisor` for consults\"\n : oracle\n ? \"`oracle` for consults\"\n : undefined\n const rosterLine = consults\n ? `for verification, ${consults} (builtin \\`scout\\` and`\n : \"for verification. (Builtin `scout` and\"\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 rosterLine,\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 isBalancedFamily(opts.profileId)\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 (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` subagent 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 subagent (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\nimport { profileDescriptor } from \"./launch-profile\"\nimport type { PiProfileId } from \"./pi-models-settings\"\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: built-in MCP reads\n * it at session start (`builtin:mcp`, Pi 0.99+), and the router's agent dir in\n * a Pi launch IS the per-launch mirror (`PI_CODING_AGENT_DIR`,\n * `getPiLaunchEnvVars`), so this file is per-launch and swept with the mirror.\n * Nothing here touches the user's real `~/.pi/agent`.\n *\n * Built-in MCP is why `pi-mcp-adapter` is gone from the helper bundle. Per Pi's\n * own `docs/mcp.md`, an installed extension that registers `/mcp` REPLACES\n * built-in MCP for the session, and Pi then never reads this file at all. The\n * adapter was a prerequisite for MCP before native support landed and is a\n * blocker for it now, so the two cannot coexist.\n *\n * Precedence is the reason every key carries the `gh-router-` prefix. Native Pi\n * reads user-level servers from this file and project servers from\n * `.pi/mcp.json` (once the project is trusted), and a project entry replaces a\n * same-named user-level entry 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 * Pi expands `${VAR}` in `headers` from the child environment at connection\n * 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 Pi expands from the Pi child env at connect time. */\nexport const PI_MCP_NONCE_PLACEHOLDER = \"Bearer ${GH_ROUTER_HOOK_NONCE}\"\n\n/**\n * Workspace header placeholder.\n *\n * Native MCP sends no workspace of its own, and the worker tools refuse a call\n * that names neither an explicit `workspace` argument nor this header. The\n * generated extension set it by hand on its own `search`/`workers`/\n * `orchestrate` calls; with those calls gone, the header has to ride the server\n * entry or every worker call fails for want of a workspace. Sent on every\n * group: the proxy ignores it where it is unused.\n */\nexport const PI_MCP_WORKSPACE_PLACEHOLDER = \"${GH_ROUTER_WORKSPACE}\"\n\n/**\n * Header carrying the launch's conversation id on the MCP connection.\n *\n * Pi's MCP client, like Claude Code's, sends no conversation header, and a\n * `cheaplocal` Oracle call has nothing else to key the local endpoint's\n * prompt-cache routing on. `cheaplocal` is the only profile that reads it, so\n * on every other Pi launch the value is inert; writing it unconditionally\n * keeps the entry shape uniform rather than making one profile's config look\n * different for a header nobody else consumes.\n */\nexport const PI_MCP_SESSION_ID_HEADER = \"x-claude-code-session-id\"\n\n/**\n * Deferred, not direct.\n *\n * `deferred` keeps the tools out of the declared tool set until `tool_search`\n * loads a match, which Pi activates automatically for a deferred server. Two\n * reasons this is the right default rather than `direct`:\n *\n * - every group is listed in the `mcp_servers` system-prompt section with its\n * `description`, so discovery is intact without paying the declaration cost\n * of ~60 tools on every request;\n * - Pi waits up to 10 s at the first prompt for servers with `direct` tools\n * to connect. `deferred` servers are not in that wait, so a slow or absent\n * proxy cannot stall the session.\n */\nexport const PI_MCP_EXPOSURE = \"deferred\"\n\nexport interface PiMcpGroupEntry {\n /** Scoped MCP group name; also the suffix of the server key. */\n group: string\n /** One-line capability note, surfaced in the `mcp_servers` system prompt. */\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 * Under `deferred` exposure this line is the model's ONLY pre-search signal for\n * what a server is, so each one says what the group does and when to reach for\n * it rather than naming the server back at the model.\n *\n * Only the eight groups a Pi profile can reach are listed. `orchestrate`,\n * `decide`, `fleet` and `first-mate` sit outside every Pi profile's\n * `allowedGroups` (`src/lib/launch-profile.ts`), so `resolvePiSurfaces` can\n * never emit them and a description for them would be dead text.\n */\nconst GROUP_DESCRIPTIONS: Record<string, string> = {\n peers: \"Cross-lab adversarial reviewers (codex_critic, codex_reviewer, gemini_critic, gemini_reviewer, opus_critic) plus oracle, a stateless expert consultant. Reach for a critic when a plan or a diff needs a second lab's judgement; reach for oracle when repository evidence alone cannot settle a self-contained technical trade-off.\",\n search: \"Code and web search for this workspace. code is semantic-first with a labelled lexical fallback and reports which engine answered; web runs a Copilot-backed web search. Reach for code before broad file reads when you are locating code by meaning rather than by exact text.\",\n workers: \"Autonomous worker subagents that run their own agent loop on a scoped task: explore reads and searches, review also runs commands to verify, implement edits files in an isolated git worktree and returns the diff. Reach for a worker when the task is big enough that its context should not land in yours.\",\n browser: \"Drive a real Chrome or Edge tab: open, navigate, read the page, screenshot, click, type, evaluate JavaScript. Reach for it when the answer lives in a web UI rather than in the repository.\",\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 cloudagent: \"Microsoft Cloud Agent jobs: hand a prompt plus an Azure DevOps repository to a cloud coding agent, then poll it for hours and collect the answer. create_job, create_pr_job and cancel_job spend compute; confirm with the user before creating a job the user did not ask for.\",\n workiq: \"Microsoft 365 research through Work IQ: ask a question across mail, files, chats, meetings and sites, retrieve with citations, or fetch specific entity URLs. Reach for it when the answer lives in the user's M365 data rather than in the repository.\",\n}\n\n/** The `peers` half of `GROUP_DESCRIPTIONS.peers`, split out so the oracle's\n * availability can be stated rather than assumed. */\nconst PEERS_ORACLE_SENTENCE =\n \"oracle, a stateless expert consultant. Reach for oracle when repository evidence alone cannot settle a self-contained technical trade-off.\"\n\n/** What the artifact tools do, in the same one-line voice. */\nconst PEERS_ARTIFACT_SENTENCE =\n \"The artifact_* tools open a workspace file in the human review panel and drain the reviewer's comments and actions; reach for them when a human has to look at the result before work continues.\"\n\n/**\n * The `peers` description for a profile's persona allow-list.\n *\n * `deferred` exposure makes this line the model's only pre-search signal, so\n * it may name only personas the MCP handler will actually answer: every\n * pinned profile registers a list (`undefined` means unrestricted), and\n * naming a critic a filtered launch answers with -32601 wastes the model's\n * turn. The critics are named only on an unrestricted surface; the oracle\n * and the artifact tools are named when their own gates admit them.\n *\n * Returns `\"\"` when the group would hold nothing, so the caller can leave the\n * server unpublished rather than advertise an empty one.\n */\nexport function peersGroupDescription(\n personas: ReadonlySet<string> | undefined,\n artifactAvailable: boolean,\n): string {\n if (personas === undefined) return GROUP_DESCRIPTIONS.peers\n const parts: Array<string> = []\n if (personas.has(\"oracle\")) parts.push(PEERS_ORACLE_SENTENCE)\n if (artifactAvailable) parts.push(PEERS_ARTIFACT_SENTENCE)\n return parts.join(\" \")\n}\n\nexport interface PiSurfaceDecision {\n /** ColBERT / `--search` surfaces: `pi-web-access`, the semantic skill, the launch card. */\n search: boolean\n /** The semantic search seam. Bluebird serves the same tool, different engine. */\n codeSearch: boolean\n /** Which engine answers `code`; Bluebird wins when both are on. */\n codeSearchBackend: \"colbert\" | \"bluebird\"\n /** Scoped groups to publish to Pi as native MCP servers. */\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\n * group.\n *\n * Group selection reproduces the pinned-profile branch of the Claude launcher\n * (`src/claude.ts`) instead of inventing a second policy, so a Pi session and a\n * `github-router claude -m cheapest2` session see the same servers:\n * `peers` (unless `--no-peers`), `search`, `workers` only when the browse agent\n * is available, `browser` under `--browse`, and the three Azure groups under\n * their own predicates. Everything is then filtered through\n * `profileDescriptor(profileId).allowedGroups`, which is\n * `{peers, search, browser, ado, kusto, cloudagent, workiq}` for `local`/`local2` and\n * adds `workers` for the other four Pi profiles — so `orchestrate`, `decide`,\n * `fleet` and `first-mate` stay off everywhere.\n */\nexport function resolvePiSurfaces(opts: {\n profileId: PiProfileId\n searchEnabled: boolean\n bluebirdEnabled: boolean\n adoEnabled: boolean\n kustoEnabled: boolean\n cloudAgentEnabled: boolean\n workiqEnabled: boolean\n /** Browse-worker gate (`browseAgentEnabled()`), which also requires the model. */\n browseAgentAvailable: boolean\n /** Direct browser-control gate (`browserToolsEnabled()`), the `--browse` opt-in. */\n directBrowserAvailable: boolean\n /** Artifact review gate (`artifactToolsEnabled()`), which lives in `peers`. */\n artifactToolsAvailable: boolean\n peersEnabled: boolean\n}): PiSurfaceDecision {\n const codeSearchBackend = opts.bluebirdEnabled ? \"bluebird\" : \"colbert\"\n const descriptor = profileDescriptor(opts.profileId)\n const allowed = descriptor.allowedGroups\n const groups: Array<PiMcpGroupEntry> = []\n const push = (group: string, description = GROUP_DESCRIPTIONS[group]): void => {\n if (allowed && !allowed.has(group)) return\n if (!description) return\n groups.push({ group, description })\n }\n\n if (opts.peersEnabled) {\n // `local` registers an empty persona allow-list and keeps the group for\n // the artifact tools, so the description follows the allow-list and the\n // group is published only when it will hold at least one tool.\n push(\"peers\", peersGroupDescription(descriptor.personaAllowlist, opts.artifactToolsAvailable))\n }\n push(\"search\")\n if (opts.browseAgentAvailable) push(\"workers\")\n if (opts.directBrowserAvailable) push(\"browser\")\n if (opts.adoEnabled) push(\"ado\")\n if (opts.kustoEnabled) push(\"kusto\")\n if (opts.cloudAgentEnabled) push(\"cloudagent\")\n if (opts.workiqEnabled) push(\"workiq\")\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/**\n * The project-scoped file native Pi reads. `.mcp.json` and\n * `.pi/mcp-adapter.json` were adapter-only inputs and are gone with it: warning\n * about a file Pi never reads would be a false positive.\n */\nconst PROJECT_MCP_FILES = [path.join(\".pi\", \"mcp.json\")]\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 /**\n * Conversation id to send as `x-claude-code-session-id` on every entry.\n *\n * A literal, unlike the bearer and workspace: this value is a random UUID,\n * not a secret, and the mirror file it lands in is already per-launch and\n * swept with it. Omitted means no header, which is what every launch did\n * before `cheaplocal` needed one.\n */\n sessionId?: string\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 const sessionId = opts.sessionId?.trim()\n for (const group of opts.groups) {\n const key = piMcpServerKey(group.group)\n added.push(key)\n const headers: Record<string, string> = {\n Authorization: PI_MCP_NONCE_PLACEHOLDER,\n \"X-GH-Workspace\": PI_MCP_WORKSPACE_PLACEHOLDER,\n }\n if (sessionId !== undefined && sessionId.length > 0) {\n headers[PI_MCP_SESSION_ID_HEADER] = sessionId\n }\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,\n exposure: PI_MCP_EXPOSURE,\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 {\n artifactToolsEnabled,\n browseAgentEnabled,\n browserToolsEnabled,\n adoToolsEnabled,\n cloudAgentToolsEnabled,\n kustoToolsEnabled,\n workiqToolsEnabled,\n} from \"./lib/mcp-capabilities\"\nimport { resolvePiSurfaces, writePiMcpJson } from \"./lib/pi-mcp-config\"\nimport {\n formatBalancedPrerequisiteFailure,\n formatCheapestPrerequisiteFailure,\n formatLocalPrerequisiteFailure,\n profileDescriptor,\n resolveLaunchProfile,\n validateBalancedProfilePrerequisites,\n validateCheapestProfilePrerequisites,\n validateLocalProfilePrerequisites,\n} from \"./lib/launch-profile\"\nimport { configureLocalEgress, localBaseUrl } from \"./lib/local-egress\"\nimport {\n isBalancedFamily,\n isCheapestFamily,\n isCheaplocalProfile,\n isLocalFamily,\n} from \"./lib/profile-family\"\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/cheapest2 (Luna-led, cheapest tier), balanced/balanced2 (Sol-led, most-complex-tasks tier), or local/local2 (the main loop and every subagent run against a local inference endpoint instead of Copilot; local allows no Copilot model at all, local2 allows only the Advisor and the Oracle, both on Sol). The `-2` aliases move the Sol tier from 5.6 to 6.1; cheapest2 also raises the Advisor to high, and balanced2's Oracle is Grok 4.7. Only these six aliases are supported for `github-router pi`.\",\n },\n localport: {\n type: \"string\" as const,\n description:\n \"Port of the LOCAL MODEL SERVER that `-m local` / `-m local2` forward the main loop to (not the proxy's own --port). Default 11111, giving https://localhost:11111/v1. Inert on every other profile.\",\n },\n localurl: {\n type: \"string\" as const,\n description:\n \"Full base URL, including the /v1 prefix, of the local inference endpoint for `-m local` / `-m local2` (e.g. http://localhost:11111/v1). Sets scheme/host/path, which --localport cannot. Mutually exclusive with --localport. Inert on every other profile.\",\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-family gh-advisor) and the review prompt shortcuts (/review, /parallel-review, cheapest-family /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 gh-oracle skill, the pi-subagents package, and the gh-router-peers MCP group (the personas and artifact review tools the chosen profile allows). Set to false (--no-peers) for a lead-only session; prereqs then validate the lead model only.\",\n },\n helpers: {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Wire the helpful bundle: allowlisted pi-agent-extensions (sessions, ask_user, todos, handoff, context, analytics — no review/loop/footer, no files picker so Ctrl+Shift+O stays unambiguous for the UI), and pi-web-access when neither --search nor --browse is on. MCP is native Pi MCP now, so no adapter package is bundled. Set to false (--no-helpers) for pi-subagents + gh-router-pi only.\",\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:\n \"Start the proxy server and launch the Pi coding agent (cheapest/balanced families, or a local model server)\",\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 // `cheaplocal` is a cheapest-family member, so the family check below\n // would accept it and then build a cheapest-shaped launch that names no\n // local provider at all. Pi support would need its model settings to\n // declare two providers for one profile; until then this is a refusal,\n // not a silent downgrade to `cheapest`.\n if (isCheaplocalProfile(launchProfileId)) {\n process.stderr.write(\n \"github-router pi does not support -m cheaplocal: Pi's model settings bind one provider per profile, and cheaplocal's Advisor and Oracle are served by the local endpoint. Use -m cheapest or -m cheapest2 on Pi, or run `github-router claude -m cheaplocal`.\\n\",\n )\n process.exit(1)\n }\n if (\n !isCheapestFamily(launchProfileId) &&\n !isBalancedFamily(launchProfileId) &&\n !isLocalFamily(launchProfileId)\n ) {\n process.stderr.write(\n `github-router pi supports only -m cheapest, -m cheapest2, -m balanced, -m balanced2, -m local, and -m local2 (got ${JSON.stringify(args.model ?? \"\")}).\\n`,\n )\n process.exit(1)\n }\n const profileId: PiProfileId = launchProfileId\n\n // Local egress is resolved once, before the server accepts requests, so\n // the same `--localport` / `--localurl` resolution serves both subcommands.\n try {\n configureLocalEgress({\n ...(typeof args.localurl === \"string\" ? { baseUrl: args.localurl } : {}),\n ...(typeof args.localport === \"string\" ? { port: args.localport } : {}),\n profileId,\n })\n if (isLocalFamily(profileId)) {\n consola.info(`[local] upstream ${localBaseUrl()}`)\n }\n } catch (error) {\n process.stderr.write(\n `${error instanceof Error ? error.message : String(error)}\\n`,\n )\n process.exit(1)\n }\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`. The group list mirrors the pinned\n // branch of `src/claude.ts` so both clients see the same servers for the\n // same profile. See `resolvePiSurfaces`.\n const surfaces = resolvePiSurfaces({\n profileId,\n searchEnabled,\n bluebirdEnabled: state.bluebirdEnabled === true,\n adoEnabled: adoToolsEnabled(),\n kustoEnabled: kustoToolsEnabled(),\n cloudAgentEnabled: cloudAgentToolsEnabled(),\n workiqEnabled: workiqToolsEnabled(),\n browseAgentAvailable: browseAgentEnabled(),\n directBrowserAvailable: browseEnabled,\n artifactToolsAvailable: artifactToolsEnabled(),\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 // Local profiles need no catalog entry for any role they run locally;\n // `local2` validates only its Copilot-served Advisor.\n const prereqCheck = isLocalFamily(profileId)\n ? validateLocalProfilePrerequisites(state.models, profileId)\n : isCheapestFamily(profileId)\n ? validateCheapestProfilePrerequisites(\n state.models,\n { peers: peersEnabled },\n profileId,\n )\n : validateBalancedProfilePrerequisites(\n state.models,\n { peers: peersEnabled },\n profileId,\n )\n if (!prereqCheck.ok) {\n const message = isLocalFamily(profileId)\n ? formatLocalPrerequisiteFailure(prereqCheck.missing, profileId, \"pi\")\n : isCheapestFamily(profileId)\n ? formatCheapestPrerequisiteFailure(prereqCheck.missing, profileId)\n : formatBalancedPrerequisiteFailure(prereqCheck.missing, profileId)\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 // `/v1/messages` launch binding. Minted here, before models.json is\n // written, because the local tier rows must carry it as a per-model\n // header: without the secret the proxy sees Pi's lead traffic as\n // unbound BYO and routes it to Copilot, so a local session gets\n // Copilot's \"model is not supported\" 400 for the bare `opus` id.\n // Registered further down with the same value.\n const launchSecret = randomBytes(32).toString(\"hex\")\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({\n serverUrl,\n profileId,\n catalog,\n peers: peersEnabled,\n // Local tier rows carry `x-claude-code-session-id` (the local server\n // rejects a request without one). Pi has no such header of its own,\n // so the launch seeds the same process-level id the proxy falls back\n // to for Claude Code.\n sessionId: state.sessionId,\n // Binds Pi's lead turns to THIS launch, the same channel Claude Code\n // gets through `ANTHROPIC_CUSTOM_HEADERS`. Copilot-served rows never\n // carry it: a bound launch whose profile is local routes to the\n // local endpoint, which is not where those ids belong.\n launchSecret,\n }),\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 bridge: bridgeStats ? { stats: bridgeStats, scopedRules: bridgeScoped } : undefined,\n }),\n )\n // Every scoped group reaches Pi through Pi's own `mcp.json` in the\n // mirror, which built-in MCP reads at session start\n // (`<Pi agent dir>/mcp.json`, Pi 0.99+). A user-owned `mcp.json` is\n // merged over, never replaced, and a project file that would shadow an\n // entry is reported 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 // Same id the local tier rows carry. No Pi profile reaches the two\n // local consultants today, so the header is inert on every launch it\n // is written for; it exists so a consult issued over `/mcp` is keyed\n // to this conversation the moment one does.\n sessionId: state.sessionId,\n })\n if (written.skippedReason) {\n consola.warn(\n `Pi MCP: left ${written.path} alone (${written.skippedReason}); the scoped 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 entry = registerLaunch({\n profileId,\n nonce,\n secret: launchSecret,\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 mcpGroups: 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 discountedUsdForSnapshot(snapshot),\n )\n return table ? `${summary}\\n${table}` : summary\n },\n },\n )\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,qBAAuD,OAAO,OAAO;CAChF,cAAc;CACd,eAAe;CACf,aAAa;CACb,eAAe;CACf,YAAY;CACZ,YAAY;AACd,CAAC;;AAMD,SAAgB,mBAAmB,SAAyB;CAC1D,OAAO,mBAAmB,YAAA;AAC5B;;;;;;AAOA,SAAgB,mBACd,SACA,4BACQ;CACR,MAAM,YAAY,mBAAmB,OAAO;CAC5C,IACE,OAAO,+BAA+B,YACnC,OAAO,SAAS,0BAA0B,KAC1C,6BAA6B,GAEhC,OAAO,KAAK,IAAI,WAAW,KAAK,MAAM,0BAA0B,CAAC;CAEnE,OAAO;AACT;;;;;;;;;AAUA,MAAM,gCACJ,OAAO,OAAO;CACZ,cAAc;CACd,eAAe;CACf,aAAa;CACb,eAAe;CACf,YAAY;CACZ,YAAY;AACd,CAAC;;;;;;;AAQH,SAAgB,uBACd,MACe;CACf,MAAM,WAA0B,CAAC;CACjC,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,WAAW,8BAA8B,I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UAAU,eAAe,EAAE;EAC/D,0BAA0B,KAAK,UAAU,eAAe,EAAE;EAC1D,iCAAiC,KAAK,UAAU,iBAAiB,EAAE;EACnE,8BAA8B,KAAK,UAAU,cAAc,EAAE;EAC7D,8BAA8B,KAAK,UAAU,cAAc,EAAE;EAC7D,8BAA8B,KAAK,UAAU,cAAc,EAAE;EAC7D,oCAAoC,KAAK,UAAU,CAAC,GAAG,kBAAkB,CAAC,EAAE;EAC5E,6BAA6B,KAAK,UAAU,aAAa,CAAC,EAAE;EAC5D,+BAA+B,eAAe,SAAS,EAAE;EACzD,kCAAkC,kBAAkB,SAAS,EAAE;EAC/D,iCAAiC,iBAAiB,SAAS,EAAE;EAC7D,iCAAiC,iBAAiB,SAAS,EAAE;EAC7D,+BAA+B,eAAe,SAAS,EAAE;EACzD,qCAAqC,qBAAqB,SAAS,EAAE;EACrE;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;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;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AClqBA,SAAgB,iCAAgD;CAC9D,OAAO;EACL;EACA;EACA,2CAA2C,sBAAsB;EACjE,2CAA2C,2BAA2B;EACtE;EACA,+BAA+B,qBAAqB,SAAS,EAAE;EAC/D;EACA,4BAA4B,yBAAyB;EACrD;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;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,MAG5B;CAKT,MAAM,cAAc,iBAAiB,KAAK,SAAS;CACnD,MAAM,QAAuB,CAAC;CAC9B,MAAM,KACJ,8BAA8B,KAAK,UAAU,6CAC7C,2EACA,+CACA,IACA,wEACA,GAAI,cACA;EACE;EACA;EACA;EAMA;CACF,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,GAAI,cACA;EAME;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,gCACF;CACA,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,GAGlC,GAAG,uBAAuB,GAC1B,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,SAAS,gBAAgB,KAAK,SAAS,GAAG;EAU5C,MAAM,aADkB,sBAAsB,KAAK,SAClB,IAC7B;GACE;GACA;GACA;GACA;GACA;GACA;GACA;EACF,IACA;GACE;GACA;GACA;GACA;GACA;EACF;EACJ,OAAO,KAAK;GACV,KAAK;GACL,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA,GAAG;GACL,CAAC,CAAC,KAAK,IAAI;EACb,CAAC;CACH;CACA,IAAI,KAAK,WAAW,MAClB,OAAO,KAAK;EACV,KAAK;EACL,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,IAAI;CACb,CAAC;CAEH,IAAI,KAAK,QAAQ,QAAQ,OAAO;EAM9B,MAA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