github-router 0.3.343 → 0.3.344
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/README.md +13 -8
- package/dist/{attribution-settings-DJEBjfJQ.js → attribution-settings-BkhBJn_K.js} +4 -4
- package/dist/{attribution-settings-DJEBjfJQ.js.map → attribution-settings-BkhBJn_K.js.map} +1 -1
- package/dist/{auth-DjKEIiqG.js → auth-Cgsy2T0s.js} +2 -2
- package/dist/{auth-DjKEIiqG.js.map → auth-Cgsy2T0s.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-B7UrDwD8.js → check-usage-26G2hw_F.js} +3 -3
- package/dist/{check-usage-B7UrDwD8.js.map → check-usage-26G2hw_F.js.map} +1 -1
- package/dist/{claude-DJeYKVL2.js → claude-CarqHLsD.js} +7 -7
- package/dist/{claude-DJeYKVL2.js.map → claude-CarqHLsD.js.map} +1 -1
- package/dist/{codex-cUYAC32x.js → codex-AdG6FZIV.js} +5 -5
- package/dist/{codex-cUYAC32x.js.map → codex-AdG6FZIV.js.map} +1 -1
- package/dist/engine-gOzWnh6S.js +2 -0
- package/dist/{gate-discovery-BIBgN6mA.js → gate-discovery-ByujYipc.js} +2 -2
- package/dist/{gate-discovery-BIBgN6mA.js.map → gate-discovery-ByujYipc.js.map} +1 -1
- package/dist/{get-copilot-usage-CGaV01dC.js → get-copilot-usage-C_6ast5h.js} +2 -2
- package/dist/{get-copilot-usage-CGaV01dC.js.map → get-copilot-usage-C_6ast5h.js.map} +1 -1
- package/dist/{internal-stop-hook-Dyn0fRpZ.js → internal-stop-hook-DEMbF-hU.js} +2 -2
- package/dist/{internal-stop-hook-Dyn0fRpZ.js.map → internal-stop-hook-DEMbF-hU.js.map} +1 -1
- package/dist/main.js +9 -9
- package/dist/{models-68HDOEPK.js → models-BGCeGVXl.js} +2 -2
- package/dist/{models-68HDOEPK.js.map → models-BGCeGVXl.js.map} +1 -1
- package/dist/{peer-mcp-personas-Dt0VRKYz.js → peer-mcp-personas-CvqVopTx.js} +2 -2
- package/dist/{peer-mcp-personas-Dt0VRKYz.js.map → peer-mcp-personas-CvqVopTx.js.map} +1 -1
- package/dist/{pi-CnsdJGF0.js → pi-C8jxbK_2.js} +512 -88
- package/dist/pi-C8jxbK_2.js.map +1 -0
- package/dist/{provision-D_aHUCXt.js → provision-CJ3Zzs_Q.js} +2 -2
- package/dist/{provision-D_aHUCXt.js.map → provision-CJ3Zzs_Q.js.map} +1 -1
- package/dist/{serve-CwaKseAj.js → serve-DQhAmfp2.js} +6 -6
- package/dist/{serve-CwaKseAj.js.map → serve-DQhAmfp2.js.map} +1 -1
- package/dist/{server-setup-CtzSW7Ms.js → server-setup-BBbpJRWv.js} +25 -10
- package/dist/server-setup-BBbpJRWv.js.map +1 -0
- package/dist/{start-DqfQyqxD.js → start-C34seGtb.js} +3 -3
- package/dist/{start-DqfQyqxD.js.map → start-C34seGtb.js.map} +1 -1
- package/dist/state-CVp30CBF.js.map +1 -1
- package/dist/{token-DATA_OQK.js → token-s5Wd-Kwr.js} +2 -1
- package/dist/{token-DATA_OQK.js.map → token-s5Wd-Kwr.js.map} +1 -1
- package/package.json +2 -2
- package/dist/engine-DvGukHty.js +0 -2
- package/dist/pi-CnsdJGF0.js.map +0 -1
- package/dist/server-setup-CtzSW7Ms.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "github-router",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.344",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "A reverse proxy that exposes GitHub Copilot as OpenAI and Anthropic compatible API endpoints.",
|
|
6
6
|
"keywords": [
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|
|
86
86
|
"@eslint/js": "^10.0.1",
|
|
87
|
-
"@types/bun": "^1.
|
|
87
|
+
"@types/bun": "^1.4.2",
|
|
88
88
|
"@types/proxy-from-env": "^1.0.4",
|
|
89
89
|
"@types/ws": "^8.18.1",
|
|
90
90
|
"eslint": "^10.8.0",
|
package/dist/engine-DvGukHty.js
DELETED
package/dist/pi-CnsdJGF0.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pi-CnsdJGF0.js","names":["process"],"sources":["../src/lib/pi-version-check.ts","../src/lib/pi-tier-windows.ts","../src/lib/pi-statusline.ts","../src/lib/pi-paths.ts","../src/lib/pi-models-settings.ts","../src/lib/pi-extension.ts","../src/pi.ts"],"sourcesContent":["import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport {\n resolveExecutable,\n runCommandCapture,\n runCommandVoid,\n} from \"./exec\"\nimport { withInstallLock } from \"./update-lock\"\n\nexport const PI_NPM_PACKAGE = \"@earendil-works/pi-coding-agent\"\n/** Minimum Pi version the `pi` launcher supports. */\nexport const PI_MIN_VERSION = \"0.80.10\"\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\nconst PI_VERSION_TIMEOUT_MS = 3000\nconst NPM_INSTALL_TIMEOUT_MS = 300_000 // 5 min — pi pulls a larger tree than claude\n\ninterface PiVersionCheckCache {\n /** ISO timestamp of last check */\n checkedAt: string\n /** Installed version at last check */\n installedVersion: string | null\n /** Latest version on npm at last check */\n latestVersion: string | null\n}\n\n/** Path to the throttle cache. Created on demand. Separate file from the Claude check. */\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n \"last-pi-update-check\",\n )\n}\n\nasync function readCache(): Promise<PiVersionCheckCache | null> {\n try {\n const raw = await fs.readFile(cacheFilePath(), \"utf8\")\n const parsed = JSON.parse(raw) as PiVersionCheckCache\n if (\n typeof parsed.checkedAt !== \"string\"\n || (parsed.installedVersion !== null\n && typeof parsed.installedVersion !== \"string\")\n || (parsed.latestVersion !== null\n && typeof parsed.latestVersion !== \"string\")\n ) {\n return null\n }\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: PiVersionCheckCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n consola.debug(\"Failed to write pi version-check cache:\", err)\n }\n}\n\nfunction shouldCheckNow(cache: PiVersionCheckCache | null): boolean {\n if (!cache) return true\n const lastCheck = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(lastCheck)) return true\n const hoursSince = (Date.now() - lastCheck) / 1000 / 3600\n return hoursSince >= THROTTLE_HOURS\n}\n\n/**\n * Read the installed `pi` version. Returns null if pi is not on PATH\n * or the version probe fails.\n *\n * Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path\n * (excluding the cwd) before invocation via the shared exec helper.\n */\nexport async function getInstalledPiVersion(): Promise<string | null> {\n const piPath = resolveExecutable(\"pi\")\n if (!piPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [piPath, \"--version\"],\n { timeoutMs: PI_VERSION_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const match = stdout.match(/(\\d+\\.\\d+\\.\\d+)/)\n return match ? match[1] : null\n } catch {\n return null\n }\n}\n\n/** Fetch the latest Pi version from npm. Null on network/npm failure. */\nasync function getLatestPiVersion(): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [npmPath, \"view\", PI_NPM_PACKAGE, \"version\", \"--silent\"],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Compare two semver-shaped strings (leading X.Y.Z only). True when\n * `latest` is strictly higher than `installed`.\n */\nexport function isPiNewer(\n installed: string | null,\n latest: string | null,\n): boolean {\n if (!installed || !latest) return false\n const a = installed.split(\".\").map((n) => parseInt(n, 10))\n const b = latest.split(\".\").map((n) => parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = a[i] ?? 0\n const bv = b[i] ?? 0\n if (av < bv) return true\n if (av > bv) return false\n }\n return false\n}\n\n/** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */\nexport function meetsPiMinVersion(version: string | null): boolean {\n if (!version) return false\n return !isPiNewer(version, PI_MIN_VERSION)\n}\n\nexport interface PiVersionCheckResult {\n /** Whether pi is on PATH at all */\n installed: boolean\n installedVersion: string | null\n latestVersion: string | null\n /** True if a newer version is available */\n needsUpdate: boolean\n /** True if the installed version is below the supported floor */\n needsMinUpgrade: boolean\n /** Whether the check was skipped (throttled or disabled) */\n skipped: boolean\n skipReason?: \"throttled\" | \"disabled\" | \"no-npm\" | \"no-pi\"\n}\n\n/** Run a version check (subject to throttle). Side-effect: updates the cache. */\nexport async function checkPiVersion(opts: {\n noCheck?: boolean\n force?: boolean\n} = {}): Promise<PiVersionCheckResult> {\n if (opts.noCheck) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: false,\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) {\n const installedVersion = cache?.installedVersion ?? null\n const latestVersion = cache?.latestVersion ?? null\n return {\n installed: installedVersion !== null,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"throttled\",\n }\n }\n\n const installedVersion = await getInstalledPiVersion()\n if (installedVersion === null) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: true,\n skipped: true,\n skipReason: \"no-pi\",\n }\n }\n\n const latestVersion = await getLatestPiVersion()\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n\n if (latestVersion === null) {\n return {\n installed: true,\n installedVersion,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"no-npm\",\n }\n }\n\n return {\n installed: true,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: false,\n }\n}\n\n/**\n * Install (or upgrade) Pi from npm under the cross-process install lock.\n * Best-effort: throws on failure; callers fall back to the installed\n * version with a visible warning rather than stranding the launch.\n */\nexport async function updatePi(version: string): Promise<void> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) {\n throw new Error(\"npm not found on PATH; cannot install Pi automatically\")\n }\n await withInstallLock(\"pi-install.lock\", async () => {\n consola.info(`Installing ${PI_NPM_PACKAGE}@${version}...`)\n await runCommandVoid(\n [npmPath, \"install\", \"-g\", `${PI_NPM_PACKAGE}@${version}`],\n { timeoutMs: NPM_INSTALL_TIMEOUT_MS },\n )\n })\n}\n","import consola from \"consola\"\n\nimport type { Model } from \"~/services/copilot/get-models\"\n\n/**\n * Copilot Default-tier (cheap) input-token thresholds per model.\n *\n * Sourced from https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing\n * (per 1M tokens; tiers key on per-request INPUT tokens):\n * - gpt-6-luna: Default ≤ 272K ($0.10 in) vs Long > 272K ($0.20 in)\n * - gpt-6-sol: Default ≤ 272K ($2.00 in) vs Long > 272K ($4.00 in)\n * - grok-4.6: Default ≤ 200K ($2.00 in) vs Long > 200K ($4.00 in)\n *\n * The live catalog carries no tier data (flat `billing.token_prices` +\n * single `limits.*` only), so this table is hardcoded by exact model id —\n * same precedent as `FALLBACK_TOKEN_PRICES`. Anything not listed here\n * runs at the 200K default window. LAST_VERIFIED 2026-09-24: refresh the\n * values (and the drift expectations below) when the billing doc changes.\n */\nexport const PI_TIER_THRESHOLDS: Readonly<Record<string, number>> = Object.freeze({\n \"gpt-6-luna\": 272_000,\n \"gpt-6-sol\": 272_000,\n \"grok-4.6\": 200_000,\n})\n\n/** Window for models with no pinned tier threshold. */\nexport const PI_TIER_FALLBACK_TOKENS = 200_000 as const\n\n/** Pinned Default-tier threshold for a model id, or the 200K fallback. */\nexport function piTierThresholdFor(modelId: string): number {\n return PI_TIER_THRESHOLDS[modelId] ?? PI_TIER_FALLBACK_TOKENS\n}\n\n/**\n * Effective Pi `contextWindow` for a model: its cheap-tier threshold,\n * defensively capped at the catalog-advertised total window so a stale\n * table can never budget above what Copilot serves.\n */\nexport function piContextWindowFor(\n modelId: string,\n advertisedMaxContextTokens?: number,\n): number {\n const threshold = piTierThresholdFor(modelId)\n if (\n typeof advertisedMaxContextTokens === \"number\"\n && Number.isFinite(advertisedMaxContextTokens)\n && advertisedMaxContextTokens > 0\n ) {\n return Math.min(threshold, Math.floor(advertisedMaxContextTokens))\n }\n return threshold\n}\n\n/**\n * Expected Default-tier input prices in CATALOG normalized units\n * (`price/1e9*1e6/batch`, same as `livePricesFor`), NOT billing-doc USD.\n * Empirically catalog units = USD × 100 (live luna 10/50 vs $0.10/$1.20,\n * sol 200/1000 vs $2/$10, opus-5.5 400/2000 vs $4/$20 — all ×100).\n * grok-4.6's 200 is inferred the same way (doc $2.00 × 100); if live\n * disagrees the warning fires, which is the guard working, not failing.\n */\nconst EXPECTED_DEFAULT_INPUT_PER_1M: Readonly<Record<string, number>> =\n Object.freeze({\n \"gpt-6-luna\": 10,\n \"gpt-6-sol\": 200,\n \"grok-4.6\": 200,\n })\n\n/**\n * Warn loudly when live catalog input prices disagree with the pinned\n * tier table's implied Default rates — the table (or the billing doc)\n * drifted and needs a refresh. Warn-only; never blocks a launch.\n * Pure over caller-supplied rows so it is unit-testable.\n */\nexport function tierPriceDriftWarnings(\n rows: ReadonlyArray<{ id: string; inputPer1M: number | undefined }>,\n): Array<string> {\n const warnings: Array<string> = []\n for (const row of rows) {\n const expected = EXPECTED_DEFAULT_INPUT_PER_1M[row.id]\n if (expected === undefined) continue\n if (row.inputPer1M === undefined) continue\n if (Math.abs(row.inputPer1M - expected) > 1e-9) {\n warnings.push(\n `Copilot catalog prices for \"${row.id}\" (${row.inputPer1M}/1M input, catalog units) disagree with the pinned Pi tier table (${expected}/1M Default). Refresh PI_TIER_THRESHOLDS in src/lib/pi-tier-windows.ts.`,\n )\n }\n }\n return warnings\n}\n\n/** Emit drift warnings to stderr (launch-time seam). */\nexport function warnOnTierPriceDrift(\n rows: ReadonlyArray<{ id: string; inputPer1M: number | undefined }>,\n): void {\n for (const warning of tierPriceDriftWarnings(rows)) {\n consola.warn(warning)\n }\n}\n\n/**\n * Normalize live catalog input prices to per-1M rows for the drift guard.\n * Same validation as `livePricesFor` (batch must be a positive safe\n * integer, prices finite and non-negative); anything else yields\n * `undefined` (unknown — skipped, never treated as drift).\n */\nexport function liveInputPer1M(\n models: ReadonlyArray<Model> | undefined,\n): Array<{ id: string; inputPer1M: number | undefined }> {\n return (models ?? []).map((m) => {\n const prices = m.billing?.token_prices\n const batch = prices?.batch_size\n const input = prices?.input_price\n const valid =\n typeof batch === \"number\" && Number.isSafeInteger(batch) && batch > 0\n && typeof input === \"number\" && Number.isFinite(input) && input >= 0\n return {\n id: m.id,\n inputPer1M: valid ? input / 1e9 * 1e6 / (batch as number) : undefined,\n }\n })\n}\n\n/** One-call launch seam: normalize the live catalog and warn on drift. */\nexport function warnOnTierPriceDriftForModels(\n models: ReadonlyArray<Model> | undefined,\n): void {\n warnOnTierPriceDrift(liveInputPer1M(models))\n}\n","/**\n * Pi footer statusline: Claude-shaped payload builder + launch constants.\n *\n * `github-router pi` does NOT use the community `npm:pi-statusline` bridge\n * (verified live against v0.0.2: it reads `statusLine` from the user's real\n * `~/.pi/agent/settings.json` / project `.pi/settings.json` and never sees\n * the router-owned mirror behind `PI_CODING_AGENT_DIR`, so a mirror-injected\n * block is dead config; its payload also hardcodes\n * `cost.total_lines_*` to null and derives `used_percentage` from the\n * latest turn only). Instead the mode's own `local:gh-router-pi` extension\n * (see `src/lib/pi-extension.ts`) builds this payload natively from the Pi\n * extension context and spawns the SAME `internal-aic-status` runner Claude\n * uses — one renderer, byte-identical segments.\n *\n * `buildPiStatusPayload` is intentionally dependency-free (no imports, no\n * module-scope references — every helper is nested inside): the generated\n * extension embeds its source via `Function.prototype.toString()`, and a\n * drift test pins that the embedded copy equals this function exactly.\n */\n\nexport const PI_STATUS_COMMAND_ENV = \"GH_ROUTER_AIC_STATUS_COMMAND\"\n\n/** Debounce between Pi refresh events before re-spawning the runner. */\nexport const PI_STATUSLINE_DEBOUNCE_MS = 300\n/** Hard cap for one runner invocation; a hung script must never wedge the footer. */\nexport const PI_STATUSLINE_TIMEOUT_MS = 5000\n/** Width fallback when the footer has never rendered (mirrors default-statusline). */\nexport const PI_STATUSLINE_WIDTH_FALLBACK = 120\n\nexport interface PiStatusModel {\n id?: unknown\n displayName?: unknown\n name?: unknown\n contextWindow?: unknown\n}\n\nexport interface PiStatusContextUsage {\n tokens?: unknown\n contextWindow?: unknown\n percent?: unknown\n}\n\nexport interface PiStatusSource {\n cwd?: unknown\n sessionId?: unknown\n model?: PiStatusModel\n contextUsage?: PiStatusContextUsage | null | undefined\n /** `sessionManager.getBranch()` preferred; `getEntries()` accepted. */\n entries?: ReadonlyArray<unknown>\n}\n\nexport function buildPiStatusPayload(\n source: PiStatusSource,\n opts: { nowMs: number; sessionStartMs?: number },\n): Record<string, unknown> {\n function asRecord(value: unknown): Record<string, unknown> {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>\n }\n return {}\n }\n function finiteNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined\n }\n function nonNegativeInt(value: unknown): number | undefined {\n const n = finiteNumber(value)\n if (n === undefined || n < 0) return undefined\n return Math.floor(n)\n }\n function nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined\n }\n function timestampMs(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value) && value > 0) {\n // Pi message timestamps are epoch-ms; entry timestamps are ISO strings.\n return value < 1e12 ? Math.floor(value * 1000) : Math.floor(value)\n }\n if (typeof value === \"string\" && value.length > 0) {\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n }\n\n const src = asRecord(source)\n const cwd = nonEmptyString(src.cwd) ?? \"\"\n const sessionId = nonEmptyString(src.sessionId) ?? null\n const model = asRecord(src.model)\n const modelId = nonEmptyString(model.id) ?? null\n const displayName =\n nonEmptyString(model.displayName) ?? nonEmptyString(model.name) ?? modelId\n const usage = asRecord(src.contextUsage)\n const usedPct = finiteNumber(usage.percent)\n const windowSize =\n nonNegativeInt(usage.contextWindow) ?? nonNegativeInt(model.contextWindow) ?? null\n\n const rawEntries = Array.isArray(src.entries) ? src.entries : []\n let totalIn = 0\n let totalOut = 0\n let seenUsage = false\n let linesAdded = 0\n let linesRemoved = 0\n let latestInput: number | null = null\n let latestOutput: number | null = null\n let latestCacheWrite: number | null = null\n let latestCacheRead: number | null = null\n let firstTs: number | undefined\n let lastTs: number | undefined\n\n function noteTimestamp(value: unknown): void {\n const ms = timestampMs(value)\n if (ms === undefined) return\n if (firstTs === undefined || ms < firstTs) firstTs = ms\n if (lastTs === undefined || ms > lastTs) lastTs = ms\n }\n function addLines(details: unknown): void {\n const record = asRecord(details)\n if (Object.keys(record).length === 0) return\n const added = finiteNumber(record.linesAdded)\n const removed = finiteNumber(record.linesRemoved)\n if (added !== undefined && added >= 0) linesAdded += Math.floor(added)\n if (removed !== undefined && removed >= 0) linesRemoved += Math.floor(removed)\n // One nesting level (namespaced tool details); deeper shapes are ignored\n // rather than risking double-counts.\n for (const key of [\"details\", \"result\", \"data\"]) {\n const nested = asRecord(record[key])\n if (Object.keys(nested).length === 0) continue\n const nestedAdded = finiteNumber(nested.linesAdded)\n const nestedRemoved = finiteNumber(nested.linesRemoved)\n const consumedParent = added !== undefined || removed !== undefined\n if (!consumedParent) {\n if (nestedAdded !== undefined && nestedAdded >= 0) {\n linesAdded += Math.floor(nestedAdded)\n }\n if (nestedRemoved !== undefined && nestedRemoved >= 0) {\n linesRemoved += Math.floor(nestedRemoved)\n }\n }\n }\n }\n\n for (const entry of rawEntries) {\n const record = asRecord(entry)\n if (record.type !== \"message\") continue\n const message = asRecord(record.message)\n noteTimestamp(record.timestamp)\n noteTimestamp(message.timestamp)\n if (message.role === \"assistant\") {\n if (message.stopReason === \"aborted\" || message.stopReason === \"error\") continue\n const entryUsage = asRecord(message.usage)\n const input = nonNegativeInt(entryUsage.input)\n const output = nonNegativeInt(entryUsage.output)\n if (input !== undefined) {\n totalIn += input\n seenUsage = true\n }\n if (output !== undefined) {\n totalOut += output\n seenUsage = true\n }\n latestInput = input ?? latestInput\n latestOutput = output ?? latestOutput\n const cacheWrite = nonNegativeInt(entryUsage.cacheWrite)\n const cacheRead = nonNegativeInt(entryUsage.cacheRead)\n if (cacheWrite !== undefined) latestCacheWrite = cacheWrite\n if (cacheRead !== undefined) latestCacheRead = cacheRead\n } else if (message.role === \"toolResult\") {\n addLines(message.details)\n }\n }\n\n // Duration: wall-clock from session start when the extension tracked it\n // (matches Claude's total_duration_ms, idle included); transcript-derived\n // span as the restart-proof fallback; null until either is available.\n let durationMs: number | null = null\n const startMs = finiteNumber(opts.sessionStartMs)\n if (startMs !== undefined && startMs > 0) {\n durationMs = Math.max(0, Math.floor(opts.nowMs - startMs))\n } else if (firstTs !== undefined && lastTs !== undefined) {\n durationMs = Math.max(0, lastTs - firstTs)\n }\n\n return {\n cwd,\n session_id: sessionId,\n transcript_path: null,\n model: { id: modelId, display_name: displayName },\n workspace: { current_dir: cwd, project_dir: cwd },\n version: null,\n output_style: { name: \"default\" },\n cost: {\n // List-price USD is deliberately never forwarded (same rule as the\n // Claude path: it contradicts the AIC billing unit). The runner reads\n // duration + line counts from this block.\n total_cost_usd: null,\n total_duration_ms: durationMs,\n total_api_duration_ms: null,\n total_lines_added: linesAdded,\n total_lines_removed: linesRemoved,\n },\n context_window: {\n total_input_tokens: seenUsage ? totalIn : null,\n total_output_tokens: seenUsage ? totalOut : null,\n context_window_size: windowSize,\n // Authoritative Pi percent only — never a latest-turn ratio (the\n // bridge's 3%-vs-42% failure mode). Null renders the `--%` placeholder.\n used_percentage:\n usedPct !== undefined ? Math.max(0, Math.round(usedPct)) : null,\n remaining_percentage:\n usedPct !== undefined ? Math.max(0, 100 - Math.round(usedPct)) : null,\n current_usage:\n latestInput !== null || latestOutput !== null\n ? {\n input_tokens: latestInput,\n output_tokens: latestOutput,\n cache_creation_input_tokens: latestCacheWrite,\n cache_read_input_tokens: latestCacheRead,\n }\n : null,\n },\n exceeds_200k_tokens: false,\n rate_limits: null,\n vim: null,\n agent: null,\n worktree: null,\n }\n}\n","import { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nfunction appDir(): string {\n return path.join(os.homedir(), \".local\", \"share\", \"github-router\")\n}\n\n/** Where the user's real Pi agent dir lives (`PI_CODING_AGENT_DIR` wins). */\nexport function userPiAgentDir(): string {\n const override = (process.env.PI_CODING_AGENT_DIR ?? \"\").trim()\n if (override.length > 0) return override\n return path.join(os.homedir(), \".pi\", \"agent\")\n}\n\n/**\n * Per-launch suffix for the Pi mirror. Lazily generated once per process\n * so every path getter in this module agrees on the directory.\n */\nlet launchSuffix: string | undefined\n\nfunction perLaunchSuffix(): string {\n launchSuffix ??= `pi-agent-${process.pid}-${randomBytes(4).toString(\"hex\")}`\n return launchSuffix\n}\n\n/** Router-owned, per-launch Pi agent dir for the spawned `pi` child. */\nexport function piMirrorDir(): string {\n return path.join(appDir(), \"pi-mirrors\", perLaunchSuffix())\n}\n\n/**\n * Provision the per-launch Pi mirror: snapshot-copy the user's real Pi\n * agent dir (settings, models, skills, prompts, extensions the user owns)\n * so the spawned `pi` starts from the user's own setup, then let the\n * launcher overlay the mode's generated files on top.\n *\n * Copy failures of individual user files are debug-logged and skipped —\n * a corrupt user file must not strand the launch. Throws only when the\n * mirror directory itself cannot be created.\n */\nexport async function ensurePiAgentMirror(): Promise<string> {\n const mirror = piMirrorDir()\n await fs.mkdir(mirror, { recursive: true })\n const source = userPiAgentDir()\n let entries: Array<string>\n try {\n entries = await fs.readdir(source)\n } catch {\n // No user Pi dir yet (fresh machine) — the mirror starts empty and\n // the launcher writes every file Pi needs.\n return mirror\n }\n // Snapshot user-owned resources; never auth.json (credentials stay the\n // user's — Pi resolves its dummy/provider key from our generated\n // models.json, and copying OAuth tokens into a swept dir risks stranding\n // them), never sessions/ (per-project history must not leak across the\n // isolation boundary), never models-store.json. User `extensions/` are\n // excluded by default: third-party workflow orchestrators (background\n // lanes / preflight tools) otherwise ride into the cost-controlled\n // profile and break its fixed roster contract. Opt back in with\n // GH_ROUTER_PI_KEEP_USER_EXTENSIONS=1.\n const keepUserExtensions = process.env.GH_ROUTER_PI_KEEP_USER_EXTENSIONS === \"1\"\n const SKIP = new Set([\n \"auth.json\",\n \"sessions\",\n \"models-store.json\",\n ...(keepUserExtensions ? [] : [\"extensions\"]),\n ])\n await Promise.all(\n entries\n .filter((e) => !SKIP.has(e))\n .map(async (entry) => {\n try {\n await fs.cp(path.join(source, entry), path.join(mirror, entry), {\n recursive: true,\n })\n } catch (err) {\n consola.debug(`Pi mirror: skipping ${entry}:`, err)\n }\n }),\n )\n return mirror\n}\n\n/** Remove THIS launch's Pi mirror on shutdown. Best-effort, never throws. */\nexport async function removeOwnPiAgentMirror(): Promise<void> {\n try {\n await fs.rm(piMirrorDir(), { recursive: true, force: true })\n } catch (err) {\n consola.debug(\"Pi mirror cleanup failed:\", err)\n }\n}\n\n/**\n * Sweep stale Pi mirrors left behind by crashed launches (dirs whose PID\n * no longer exists, or older than 24h). Best-effort, never throws.\n */\nexport async function sweepStalePiAgentMirrors(): Promise<void> {\n const root = path.join(appDir(), \"pi-mirrors\")\n let entries: Array<string>\n try {\n entries = await fs.readdir(root)\n } catch {\n return\n }\n await Promise.all(\n entries.map(async (entry) => {\n const dir = path.join(root, entry)\n try {\n const stat = await fs.stat(dir)\n const ageMs = Date.now() - stat.mtimeMs\n const pidMatch = /^pi-agent-(\\d+)-[0-9a-f]+$/.exec(entry)\n let dead = ageMs > 24 * 3600 * 1000\n if (pidMatch && !dead) {\n const pid = Number.parseInt(pidMatch[1], 10)\n try {\n process.kill(pid, 0)\n } catch {\n dead = true // ESRCH — PID is gone\n }\n }\n if (dead) await fs.rm(dir, { recursive: true, force: true })\n } catch (err) {\n consola.debug(`Pi mirror sweep: skipping ${entry}:`, err)\n }\n }),\n )\n}\n","import {\n BALANCED_PROFILE_MODELS,\n BALANCED_PROFILE_NATIVE_EFFORTS,\n BALANCED_PROFILE_ORACLE_EFFORT,\n BALANCED_PROFILE_ORACLE_MODEL,\n} from \"./balanced-profile-contract\"\nimport {\n CHEAPEST_PROFILE_ADVISOR_EFFORT,\n CHEAPEST_PROFILE_ADVISOR_MODEL,\n CHEAPEST_PROFILE_MODELS,\n CHEAPEST_PROFILE_NATIVE_EFFORTS,\n CHEAPEST_PROFILE_ORACLE_EFFORT,\n CHEAPEST_PROFILE_ORACLE_MODEL,\n} from \"./cheapest-profile-contract\"\nimport { piContextWindowFor } from \"./pi-tier-windows\"\n\nexport type PiProfileId = \"cheapest\" | \"balanced\"\n\n/** Minimal catalog view the Pi builders need (adapted from state.models). */\nexport interface PiCatalogModel {\n id: string\n maxContextTokens: number\n maxPromptTokens: number\n maxOutputTokens?: number\n efforts: ReadonlyArray<string>\n /** Canonical endpoint kinds, e.g. \"responses\" | \"chat\" | \"messages\". */\n endpoints: ReadonlyArray<string>\n /**\n * 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 * 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 >= 0.80.10 and Node >= 22.19.\"\n\nexport function piLeadModel(profileId: PiProfileId): string {\n return profileId === \"cheapest\"\n ? CHEAPEST_PROFILE_MODELS.lead\n : BALANCED_PROFILE_MODELS.lead\n}\n\nexport function piLeadThinking(profileId: PiProfileId): string {\n // Cheapest lead runs at max effort; balanced at medium (frontier\n // reasoning without the pricey tiers).\n return profileId === \"cheapest\" ? \"max\" : \"medium\"\n}\n\nexport function piOracleModel(profileId: PiProfileId): string {\n return profileId === \"cheapest\"\n ? CHEAPEST_PROFILE_ORACLE_MODEL\n : BALANCED_PROFILE_ORACLE_MODEL\n}\n\nexport function piOracleThinking(profileId: PiProfileId): string {\n return profileId === \"cheapest\"\n ? CHEAPEST_PROFILE_ORACLE_EFFORT\n : BALANCED_PROFILE_ORACLE_EFFORT\n}\n\n/** Cheapest-only advisor. Balanced is advisor-free by design: undefined. */\nexport function piAdvisorModel(\n profileId: PiProfileId,\n): { model: string; thinking: string } | undefined {\n if (profileId !== \"cheapest\") return undefined\n return {\n model: CHEAPEST_PROFILE_ADVISOR_MODEL,\n thinking: CHEAPEST_PROFILE_ADVISOR_EFFORT,\n }\n}\n\nexport interface PiNativeRole {\n name: \"Explore\" | \"General-Purpose\" | \"reviewer\"\n model: string\n thinking: string\n readOnly: boolean\n}\n\nexport function piNativeRoles(profileId: PiProfileId): Array<PiNativeRole> {\n if (profileId === \"cheapest\") {\n return [\n {\n name: \"Explore\",\n model: CHEAPEST_PROFILE_MODELS.explore,\n thinking: CHEAPEST_PROFILE_NATIVE_EFFORTS.Explore,\n readOnly: true,\n },\n {\n name: \"General-Purpose\",\n model: CHEAPEST_PROFILE_MODELS[\"General-Purpose\"],\n thinking: CHEAPEST_PROFILE_NATIVE_EFFORTS[\"General-Purpose\"],\n readOnly: false,\n },\n {\n name: \"reviewer\",\n model: CHEAPEST_PROFILE_MODELS.reviewer,\n thinking: CHEAPEST_PROFILE_NATIVE_EFFORTS.reviewer,\n readOnly: true,\n },\n ]\n }\n return [\n {\n name: \"Explore\",\n model: BALANCED_PROFILE_MODELS.explore,\n thinking: BALANCED_PROFILE_NATIVE_EFFORTS.Explore,\n readOnly: true,\n },\n {\n name: \"General-Purpose\",\n model: BALANCED_PROFILE_MODELS[\"General-Purpose\"],\n thinking: BALANCED_PROFILE_NATIVE_EFFORTS[\"General-Purpose\"],\n readOnly: false,\n },\n {\n name: \"reviewer\",\n model: BALANCED_PROFILE_MODELS.reviewer,\n thinking: BALANCED_PROFILE_NATIVE_EFFORTS.reviewer,\n readOnly: true,\n },\n ]\n}\n\n/**\n * Every model id Pi must see for this profile. Peerless launches\n * (`peers: false`) register the lead only — no peer or native-role model\n * is consumed, so none is exposed to the picker or budgeted.\n */\nexport function piProfileModelIds(\n profileId: PiProfileId,\n opts: { peers?: boolean } = {},\n): Array<string> {\n const ids = new Set<string>([piLeadModel(profileId)])\n if (opts.peers !== false) {\n ids.add(piOracleModel(profileId))\n for (const r of piNativeRoles(profileId)) ids.add(r.model)\n const advisor = piAdvisorModel(profileId)\n if (advisor) ids.add(advisor.model)\n }\n return [...ids]\n}\n\nexport type PiModelApi = \"openai-completions\" | \"openai-responses\"\n\nexport interface PiModelsJson {\n providers: Record<\n string,\n {\n baseUrl: string\n api: PiModelApi\n apiKey: string\n /** Send the dummy bearer; the proxy ignores auth but Pi treats\n * auth-present providers as picker-usable. */\n authHeader: true\n models: Array<{\n id: string\n name: string\n reasoning: true\n input: Array<string>\n contextWindow: number\n /** Pi requires an output limit; the proxy 400s values < 16. */\n maxTokens: number\n cost?: {\n input: number\n output: number\n cacheRead?: number\n cacheWrite?: number\n }\n /** Per-model API override (documented Pi capability) for a\n * future chat-served model on this provider. Omitted when it\n * matches the provider default. */\n api?: PiModelApi\n }>\n }\n >\n}\n\n/**\n * Fallback per-request output cap when the catalog carries no\n * max_output_tokens. Matches the documented Luna/Grok 128K ceiling;\n * the live catalog always wins. Never below the proxy's 16-token floor.\n */\nexport const PI_MAX_TOKENS_FALLBACK = 128_000 as const\n\n/** Catalog price units per USD (billing-doc USD x 100 — verified on\n * luna/sol/opus live-vs-doc pairs). Pi cost metadata wants USD/1M;\n * the ratio is spike-verified against the footer math at runtime. */\nexport const PI_CATALOG_UNITS_PER_USD = 100 as const\n\nexport interface PiCatalogTokenPrices {\n batch_size?: number\n input_price?: number\n output_price?: number\n cache_price?: number\n cache_read_price?: number\n cache_write_price?: number\n}\n\n/**\n * Per-1M USD cost for a models.json row, or undefined when unknown.\n *\n * ALL-OR-NOTHING (verified live): Pi silently rejects the entire\n * provider when any of the four figures is missing, surfacing only as\n * `Unknown provider`. A missing figure therefore omits `cost`\n * entirely — guessing zero would under-report real spend, and a\n * partial object breaks the launch.\n */\nexport function piUsdCostFor(\n prices: PiCatalogTokenPrices | undefined,\n): { input: number; output: number; cacheRead: number; cacheWrite: number } | undefined {\n const batch = prices?.batch_size\n const usdPer1M = (v: number | undefined): number | undefined =>\n typeof batch === \"number\" && Number.isSafeInteger(batch) && batch > 0\n && typeof v === \"number\" && Number.isFinite(v) && v >= 0\n ? v / 1e9 * 1e6 / batch / PI_CATALOG_UNITS_PER_USD\n : undefined\n const input = usdPer1M(prices?.input_price)\n const output = usdPer1M(prices?.output_price)\n const cacheRead = usdPer1M(prices?.cache_read_price ?? prices?.cache_price)\n const cacheWrite = usdPer1M(prices?.cache_write_price)\n if (\n input === undefined\n || output === undefined\n || cacheRead === undefined\n || cacheWrite === undefined\n ) {\n return undefined\n }\n return { input, output, cacheRead, cacheWrite }\n}\n\n/**\n * Build the `models.json` provider entry pointing Pi at the running\n * proxy as an ordinary OpenAI-compatible endpoint (the documented\n * Ollama/vLLM pattern — no provider-override extension needed).\n *\n * The provider speaks `openai-responses`: every roster model is\n * Responses-only on Copilot, and Pi POSTs `{baseUrl}/responses` for\n * that API — i.e. our `/v1/responses`, the Codex-proven path. Sending\n * these models to `/v1/chat/completions` is a Copilot 400 (observed).\n *\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 */\nexport function buildPiModelsJson(opts: {\n serverUrl: string\n profileId: PiProfileId\n catalog?: ReadonlyArray<PiCatalogModel>\n peers?: boolean\n /** Provider-level API; uniform Responses roster needs no overrides. */\n api?: PiModelApi\n apiOverrides?: Readonly<Record<string, PiModelApi>>\n}): PiModelsJson {\n const baseUrl = `${opts.serverUrl.replace(/\\/+$/, \"\")}/v1`\n const providerApi = opts.api ?? \"openai-responses\"\n return {\n providers: {\n [PI_PROVIDER_NAME]: {\n baseUrl,\n api: providerApi,\n apiKey: \"dummy\",\n authHeader: true as const,\n models: piProfileModelIds(opts.profileId, { peers: opts.peers }).map((id) => {\n const entry = opts.catalog?.find((m) => m.id === id)\n const out = entry?.maxOutputTokens\n const maxTokens =\n typeof out === \"number\" && Number.isFinite(out) && out >= 16\n ? Math.floor(out)\n : PI_MAX_TOKENS_FALLBACK\n const override = opts.apiOverrides?.[id]\n return {\n id,\n name: id,\n reasoning: true as const,\n input: [\"text\"],\n contextWindow: piContextWindowFor(id, entry?.maxContextTokens),\n maxTokens,\n ...(entry?.cost ? { cost: entry.cost } : {}),\n ...(override && override !== providerApi ? { api: override } : {}),\n }\n }),\n },\n },\n }\n}\n\nexport interface PiCompactionSettings {\n enabled: true\n reserveTokens: number\n keepRecentTokens: number\n modelOverrides: Record<\n string,\n { reserveTokens: number; keepRecentTokens: number }\n >\n}\n\n/**\n * Derive Pi compaction budgets from live catalog `max_prompt_tokens`\n * ceilings AND each model's cheap-tier window — the Pi-native analogue\n * of `deriveAutoCompactWindowTokens`. Pi triggers at\n * `contextWindow − reserveTokens` per active model; the trigger must sit\n * below BOTH the tier price cliff and Copilot's acceptance ceiling:\n * reserve(id) = window(id) − floor(min(prompt, window) × 0.85),\n * clamped to [16384, 100000]. keepRecentTokens stays 20000.\n * The global reserve is the max over models (every model's trigger is\n * safe); overrides carry each model's own value. Unknown catalog (no\n * prompt metadata) → Pi built-in defaults so a missing signal can never\n * disable compaction.\n */\nexport function derivePiCompactionSettings(\n catalog: ReadonlyArray<PiCatalogModel> | undefined,\n modelIds: ReadonlyArray<string>,\n): PiCompactionSettings {\n const FALLBACK = {\n enabled: true as const,\n reserveTokens: 16384,\n keepRecentTokens: 20000,\n modelOverrides: {},\n }\n if (!catalog || catalog.length === 0) return FALLBACK\n const perModel = new Map<string, number>()\n for (const id of modelIds) {\n const entry = catalog.find((m) => m.id === id)\n const window = piContextWindowFor(id, entry?.maxContextTokens)\n const prompt = entry?.maxPromptTokens ?? 0\n const ceiling =\n Number.isFinite(prompt) && prompt > 0 ? Math.min(prompt, window) : window\n perModel.set(\n id,\n Math.min(100_000, Math.max(16384, window - Math.floor(ceiling * 0.85))),\n )\n }\n if (perModel.size === 0) return FALLBACK\n const global = Math.max(...perModel.values())\n const modelOverrides: PiCompactionSettings[\"modelOverrides\"] = {}\n for (const [id, reserve] of perModel) {\n modelOverrides[`${PI_PROVIDER_NAME}/${id}`] = {\n reserveTokens: reserve,\n keepRecentTokens: 20000,\n }\n }\n return {\n enabled: true,\n reserveTokens: global,\n keepRecentTokens: 20000,\n modelOverrides,\n }\n}\n\n/**\n * A Pi `packages[]` entry: either a bare source string (load everything\n * the package declares) or the object form narrowing which resource types\n * load. Object filters can only NARROW the package manifest — they never\n * expose undeclared resources.\n */\nexport type PiPackageEntry =\n | string\n | {\n source: string\n extensions?: Array<string>\n skills?: Array<string>\n prompts?: Array<string>\n themes?: Array<string>\n }\n\nexport interface PiSettingsJson {\n defaultProvider: string\n defaultModel: string\n defaultThinkingLevel: string\n enabledModels: Array<string>\n defaultTools: Array<string>\n compaction: PiCompactionSettings\n retry: { enabled: boolean; maxRetries: number }\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 * `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 * 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 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}): PiSettingsJson {\n const peers = opts.peers !== false\n const modelIds = piProfileModelIds(opts.profileId, { peers })\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: [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"],\n compaction: derivePiCompactionSettings(opts.catalog, modelIds),\n retry: { enabled: true, maxRetries: 3 },\n packages: [\n ...(peers\n ? [{ source: \"npm:pi-subagents\", skills: [], prompts: [] } as PiPackageEntry]\n : []),\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 },\n },\n }\n : {}),\n }\n}\n\nfunction agentFileName(name: string): string {\n return `${name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\")}.md`\n}\n\n/**\n * Deep-merge the `subagents` settings key across the snapshot/user and\n * built layer. Only `agentOverrides` merges (per-agent, user wins);\n * every other `subagents` sub-key follows the standard rule (built wins\n * when present, else user survives). Non-object inputs are ignored so a\n * corrupt user file degrades to built-only instead of crashing launch.\n */\nexport function mergeSubagentsSettings(\n userSubagents: unknown,\n builtSubagents: PiSettingsJson[\"subagents\"],\n): Record<string, unknown> | undefined {\n const user =\n userSubagents && typeof userSubagents === \"object\" && !Array.isArray(userSubagents)\n ? (userSubagents as Record<string, unknown>)\n : undefined\n const built = (builtSubagents ?? undefined) as Record<string, unknown> | undefined\n if (!user && !built) return undefined\n const userOverrides =\n user?.[\"agentOverrides\"] && typeof user[\"agentOverrides\"] === \"object\" && !Array.isArray(user[\"agentOverrides\"])\n ? (user[\"agentOverrides\"] as Record<string, unknown>)\n : undefined\n const builtOverrides = built?.[\"agentOverrides\"] as Record<string, unknown> | undefined\n const mergedOverrides =\n userOverrides || builtOverrides\n ? { ...builtOverrides, ...userOverrides }\n : undefined\n return {\n ...user,\n ...built,\n ...(mergedOverrides ? { agentOverrides: mergedOverrides } : {}),\n }\n}\n\nfunction roleDescription(\n profileId: PiProfileId,\n role: PiNativeRole,\n): string {\n // Nested-delegation channel note: General-Purpose is the only native\n // role with a nesting grant, so only it can consult the oracle subagent\n // directly. Explore/reviewer are leaves; they surface open questions in\n // their report and the lead (or General-Purpose) consults oracle.\n const oracleNote =\n \"May consult the oracle subagent when a decision feels risky.\";\n if (role.name === \"Explore\") {\n return \"Fast read-only recon: locate code, answer evidence questions, return compressed context.\"\n }\n if (role.name === \"General-Purpose\") {\n return profileId === \"balanced\"\n ? `General implementation and follow-through on scoped tasks. May hand the result to reviewer only when the change alters behavior. ${oracleNote}`\n : `General implementation and follow-through on scoped tasks. May hand the result to reviewer for assessment. ${oracleNote}`\n }\n return profileId === \"balanced\"\n ? \"Behavior-changing review only: assess a change, narrow scope with search first, delegate targeted discovery to Explore rather than sweeping the repo.\"\n : \"Code review and assessment, including reproducing and root-causing a failure.\";\n}\n\n/**\n * Build `.md` agent definitions for the mode's native roster, in the\n * OpenCode/pi-subagents-lite frontmatter format Pi delegation tools\n * consume (`name/description/tools/model/thinking`, plus `allowedAgents`\n * where the delegation graph has an edge). Bodies are\n * short execution contracts; workflow prose lives in skills so agent\n * files stay small enough to inline cheaply.\n *\n * Load-bearing semantics (verified against pi-subagents docs + source):\n * - `reviewer`/`oracle` intentionally SHADOW the same-named builtins\n * wholesale (user scope wins; omitted fields are NOT inherited). That\n * is how the roster pins gh-router models/thinking for cost control.\n * The shadowed `advisor` alias dies with the builtin oracle definition,\n * which is why `advisor` ships as its own file on cheapest.\n * - `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 * - 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) and `contact_supervisor`\n // (blocked-child escalation) are provided by the pi-subagents runtime,\n // like the delegation primitives — no extra package needed. Balanced\n // reviewer additionally lists `subagent`: it holds the roster's other\n // nesting grant (→ Explore) and the grant is inert without it.\n const tools = isImplementer\n ? \"[read, grep, find, ls, bash, edit, write, subagent, contact_supervisor]\"\n : isReviewer\n ? profileId === \"balanced\"\n ? \"[read, grep, find, ls, watchdog_diff, contact_supervisor, subagent]\"\n : \"[read, grep, find, ls, watchdog_diff, contact_supervisor]\"\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 \"systemPromptMode: replace\",\n \"inheritProjectContext: true\",\n \"defaultContext: fresh\",\n ];\n if (role.name === \"Explore\") {\n // `scout` alias absorbs habitual builtin invocations (the builtin is\n // disabled in settings). Handoff is inline prose: the lead pastes\n // brief excerpts into the next brief (see gh-delegate skill).\n // Bare form (no brackets): the aliases/allowedAgents splitter does\n // not understand YAML flow lists — `[reviewer, oracle]` parses as\n // `'[reviewer'` + `'oracle]'` and fails the run (observed live).\n lines.push(\"aliases: scout\");\n }\n if (isImplementer) {\n // Aliases absorb builtin `worker` traffic (`developer/coder` plus\n // `implementer/develop`, all builtin-worker aliases);\n // `acceptanceRole: writer` restores the builtin worker's acceptance\n // inference that shadowing would otherwise drop.\n lines.push(\n \"aliases: worker, developer, coder, implementer, develop\",\n \"acceptanceRole: writer\",\n \"allowNestedSubagents: true\",\n \"allowedAgents: reviewer, oracle\",\n );\n }\n if (profileId === \"balanced\" && isReviewer) {\n lines.push(\"allowNestedSubagents: true\", \"allowedAgents: Explore\");\n }\n lines.push(\"---\", \"\");\n if (role.name === \"Explore\") {\n lines.push(\n \"You are a read-only scout. Never modify files.\",\n \"Use bash only for non-interactive inspection.\",\n \"Search first, read second: return the smallest sufficient evidence — entry points,\",\n \"key types and functions, data flow, files likely to need changes, constraints and\",\n \"open questions — with exact file paths and line ranges.\",\n );\n } else if (isReviewer) {\n lines.push(\n \"You are a disciplined review subagent. Inspect the actual change; verify from code,\",\n \"tests, and docs — never guess. Cover intent match, correctness and edge cases,\",\n \"test coverage, side effects, and minimality.\",\n \"Report findings with file:line evidence ranked P0 (blocker) / P1 (should fix) / P2 (nit),\",\n \"ending with one of: Merge verdict: BLOCK, Merge verdict: OK, Merge verdict: OK with notes.\",\n \"You have no shell: cite the test commands for the lead to run rather than executing them.\",\n \"Do not rewrite code outside small, clearly-marked suggestions.\",\n );\n } else {\n lines.push(\n \"You are the single writer thread. Execute the assigned task with narrow, coherent edits;\",\n \"the lead remains the decision authority. Work from the brief's pasted context,\",\n \"then implement minimally and verify by running the relevant tests.\",\n \"If the work reveals an unapproved decision you cannot safely resolve, stop and escalate\",\n \"instead of guessing; never leave placeholders or TODOs.\",\n \"Hand behavior-changing results to reviewer when asked; otherwise summarize the diff,\",\n \"validation, risks, and next step.\",\n );\n }\n files[`agents/${agentFileName(role.name)}`] = `${lines.join(\"\\n\")}\\n`;\n }\n // Oracle consultant agent (both modes). Advisory only: challenges\n // assumptions, never edits. Cold-start fresh context matches the MCP\n // `peers/oracle` tool contract (stateless query + context, no transcript),\n // deliberately unlike the builtin's forked decision-consistency role.\n const oracle = [\n \"---\",\n \"name: oracle\",\n \"description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.\",\n \"tools: [read, grep, find, ls, bash]\",\n `model: ${PI_PROVIDER_NAME}/${piOracleModel(profileId)}`,\n `thinking: ${piOracleThinking(profileId)}`,\n \"advertise: true\",\n \"systemPromptMode: replace\",\n \"inheritProjectContext: true\",\n \"defaultContext: fresh\",\n \"---\",\n \"\",\n \"You are an oracle: a second set of eyes. You see only the task context\",\n \"you are given — you have no repo memory beyond what you read now.\",\n \"Inspect the code yourself with read/grep/find/ls before opining.\",\n \"Challenge assumptions, name what is missing, recommend; never execute.\",\n ].join(\"\\n\");\n files[`agents/${agentFileName(\"oracle\")}`] = `${oracle}\\n`;\n // Advisor agent (cheapest only). Genuinely new role — the builtin has no\n // separate advisor file (`advisor` is just an alias of builtin oracle, lost\n // in shadowing). Balanced stays advisor-free: no file, no skill, no prompt,\n // no prose — asserted by tests.\n const advisor = piAdvisorModel(profileId);\n if (advisor) {\n const body = [\n \"---\",\n \"name: advisor\",\n \"description: Advisory plan review for the lead: review the final plan before it is presented. Never executes.\",\n \"tools: [read, grep, find, ls]\",\n `model: ${PI_PROVIDER_NAME}/${advisor.model}`,\n `thinking: ${advisor.thinking}`,\n \"advertise: true\",\n \"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\n/**\n * Short operating digest appended to APPEND_SYSTEM.md (prompt-cache-stable).\n * Mode identity — always injected. Peer consult sentences drop out under\n * `peers: false` so the digest never names tools that don't exist.\n */\nexport function buildPiAppendSystem(\n profileId: PiProfileId,\n opts: { peers?: boolean } = {},\n): string {\n const peers = opts.peers !== false;\n const advisor = peers ? piAdvisorModel(profileId) : undefined;\n const lines = [\n `# gh-router ${profileId} mode`,\n \"\",\n `- Lead owns planning directly; there is no Plan subagent.`,\n ];\n if (peers) {\n lines.push(\n `- Delegate FREELY to Explore for discovery and General-Purpose for scoped work.`,\n profileId === \"balanced\"\n ? `- Send work to reviewer ONLY when the change alters behavior.`\n : `- Send finished work to reviewer for assessment.`,\n `- Ask oracle for a second opinion when the decision itself feels risky.`,\n advisor\n ? `- Review the final plan with advisor (advisory) before presenting it.`\n : `- There is no advisor in this mode: oracle is the only consultant.`,\n `- Verify, don't vote: consultant verdicts never substitute for running the tests.`,\n );\n } else {\n lines.push(\n `- Peerless launch: no subagents or consultants in this session; plan, implement, and verify directly.`,\n );\n }\n lines.push(\"\", `(${PI_MIN_VERSION_NOTE})`, \"\");\n return lines.join(\"\\n\");\n}\n","import type { PiProfileId } from \"./pi-models-settings\"\nimport {\n PI_PROVIDER_NAME,\n piAdvisorModel,\n piLeadModel,\n piLeadThinking,\n} from \"./pi-models-settings\"\nimport {\n AIC_STATUSLINE_DISABLE_ENV,\n} from \"./aic-statusline-settings\"\nimport {\n PI_STATUS_COMMAND_ENV,\n PI_STATUSLINE_DEBOUNCE_MS,\n PI_STATUSLINE_TIMEOUT_MS,\n PI_STATUSLINE_WIDTH_FALLBACK,\n buildPiStatusPayload,\n} from \"./pi-statusline\"\n\n/**\n * The gh-router Pi extension source, generated per launch into the\n * isolated mirror (`extensions/gh-router-pi/index.ts`).\n *\n * Design (Pi-cooperative): executable seams only — oracle/advisor\n * consult, semantic search, and browser dispatch all POST JSON-RPC\n * `tools/call` to the running proxy's `/mcp/<group>` with the\n * per-launch nonce (the same `GH_ROUTER_HOOK_MCP_URL/NONCE` channel the\n * Claude hooks use), then return the text. No custom provider, no\n * compaction replacement: `session_before_compact` only routes the\n * summary model and always falls back to Pi native on failure.\n *\n * Statusline footer (always on): this extension owns Pi's footer and\n * renders the SAME `internal-aic-status` runner Claude Code uses, fed a\n * natively-built Claude-shaped payload — one renderer, identical\n * segments. There is deliberately no third-party statusline package and\n * no `statusLine` settings block (the community bridge only reads the\n * user's real global/project settings, never the launch mirror).\n */\n\n/**\n * Statusline footer section for the generated extension. Owns Pi's footer\n * and renders the shared `internal-aic-status` runner (the same binary\n * Claude Code invokes) with a natively-built Claude-shaped payload, so Pi\n * shows byte-identical segments: `[AIC x.xx]` pinned ahead of the rich\n * session line.\n *\n * Fail-open everywhere: disabled via `GH_ROUTER_DISABLE_AIC_STATUSLINE=1`\n * or a missing command env (the launcher always sets it — see `src/pi.ts`);\n * every Pi API access is guarded (extension APIs drift across Pi versions);\n * a hung runner is killed at `PI_STATUSLINE_TIMEOUT_MS`; any error clears\n * back to Pi's native footer, never a broken session.\n *\n * Width: the runner drops segments right-to-left from `COLUMNS`; the last\n * footer width is fed back into the next spawn, and `render()` truncates\n * ANSI-aware as a backstop (same two-layer approach as the retired bridge).\n */\nexport function buildPiStatuslineFooterSection(): Array<string> {\n return [\n ` // Statusline footer: [AIC x.xx] + rich session line, identical to github-router claude.`,\n ` {`,\n ` const STATUS_COMMAND = (process.env.${PI_STATUS_COMMAND_ENV} ?? \"\").trim();`,\n ` const STATUS_DISABLED = process.env.${AIC_STATUSLINE_DISABLE_ENV} === \"1\";`,\n ` if (STATUS_COMMAND && !STATUS_DISABLED) {`,\n ` const buildPayload = (${buildPiStatusPayload.toString()});`,\n ` const DEBOUNCE_MS = ${PI_STATUSLINE_DEBOUNCE_MS};`,\n ` const TIMEOUT_MS = ${PI_STATUSLINE_TIMEOUT_MS};`,\n ` let sessionStartMs = 0;`,\n ` let lastSessionId = null;`,\n ` let lastWidth = ${PI_STATUSLINE_WIDTH_FALLBACK};`,\n ` let lines: Array<string> = [];`,\n ` let lastApplied = \"\\\\0none\";`,\n ` let timer: ReturnType<typeof setTimeout> | null = null;`,\n ` let controller: AbortController | null = null;`,\n ``,\n ` function truncateVisible(line: string, maxWidth: number): string {`,\n ` if (!(maxWidth > 0)) return line;`,\n ` let output = \"\";`,\n ` let width = 0;`,\n ` let i = 0;`,\n ` while (i < line.length) {`,\n ` const ch = line[i];`,\n ` if (ch === \"\\\\u001b\") {`,\n ` let j = i + 1;`,\n ` const next = line[j];`,\n ` if (next === \"[\") {`,\n ` j++;`,\n ` while (j < line.length) {`,\n ` const code = line.charCodeAt(j);`,\n ` if (code >= 64 && code <= 126) { j++; break; }`,\n ` j++;`,\n ` }`,\n ` } else if (next === \"]\") {`,\n ` j++;`,\n ` while (j < line.length) {`,\n ` if (line[j] === \"\\\\u0007\") { j++; break; }`,\n ` if (line[j] === \"\\\\u001b\" && line[j + 1] === \"\\\\\\\\\") { j += 2; break; }`,\n ` j++;`,\n ` }`,\n ` } else {`,\n ` j = Math.min(line.length, i + 2);`,\n ` }`,\n ` output += line.slice(i, j);`,\n ` i = j;`,\n ` continue;`,\n ` }`,\n ` if (width >= maxWidth) return output;`,\n ` output += ch;`,\n ` width++;`,\n ` i++;`,\n ` }`,\n ` return output;`,\n ` }`,\n ``,\n ` function runStatusCommand(command: string, input: string, cwd: string, signal: AbortSignal | undefined): Promise<string> {`,\n ` return new Promise((resolve) => {`,\n ` let child: ReturnType<typeof spawn> | undefined;`,\n ` try {`,\n ` child = spawn(command, { cwd, shell: true, stdio: [\"pipe\", \"pipe\", \"pipe\"], env: { ...process.env, COLUMNS: String(lastWidth) } });`,\n ` } catch { resolve(\"\"); return; }`,\n ` let stdout = \"\";`,\n ` let done = false;`,\n ` let timeout: ReturnType<typeof setTimeout> | null = null;`,\n ` const finish = (value: string): void => {`,\n ` if (done) return;`,\n ` done = true;`,\n ` if (timeout) clearTimeout(timeout);`,\n ` try { signal?.removeEventListener(\"abort\", onAbort); } catch {}`,\n ` resolve(value);`,\n ` };`,\n ` const onAbort = (): void => {`,\n ` try { child?.kill(\"SIGTERM\"); } catch {}`,\n ` finish(\"\");`,\n ` };`,\n ` if (signal) {`,\n ` if (signal.aborted) { onAbort(); return; }`,\n ` try { signal.addEventListener(\"abort\", onAbort, { once: true }); } catch {}`,\n ` }`,\n ` timeout = setTimeout(() => {`,\n ` try { child?.kill(\"SIGTERM\"); } catch {}`,\n ` finish(\"\");`,\n ` }, TIMEOUT_MS);`,\n ` child.stdout.on(\"data\", (chunk) => { stdout += String(chunk); });`,\n ` child.on(\"error\", () => finish(\"\"))`,\n ` child.on(\"close\", (code) => {`,\n ` if (code !== 0) { finish(\"\"); return; }`,\n ` finish(stdout.replace(/\\\\r\\\\n/g, \"\\\\n\").trim());`,\n ` });`,\n ` try { child.stdin.write(input); child.stdin.end(); } catch { finish(\"\"); }`,\n ` });`,\n ` }`,\n ``,\n ` function applyFooter(ctx: any): void {`,\n ` const key = lines.join(\"\\\\0\");`,\n ` if (key === lastApplied) return;`,\n ` lastApplied = key;`,\n ` try {`,\n ` if (lines.length === 0) { ctx.ui.setFooter(undefined); return; }`,\n ` const frozen = [...lines];`,\n ` ctx.ui.setFooter((_tui: any, _theme: any, footerData: any) => ({`,\n ` dispose() {},`,\n ` invalidate() {},`,\n ` render(width: number) {`,\n ` if (typeof width === \"number\" && width > 0) lastWidth = width;`,\n ` const out = frozen.map((l) => truncateVisible(l, lastWidth));`,\n ` try {`,\n ` const statuses = footerData?.getExtensionStatuses?.();`,\n ` const entries = statuses?.entries ? Array.from(statuses.entries()) : [];`,\n ` for (const pair of entries) {`,\n ` const text = String((pair as Array<unknown>)[1] ?? \"\").trim();`,\n ` if (text) out.push(truncateVisible(text, lastWidth));`,\n ` }`,\n ` } catch {}`,\n ` return out;`,\n ` },`,\n ` }));`,\n ` } catch {}`,\n ` }`,\n ``,\n ` async function refresh(ctx: any): Promise<void> {`,\n ` try {`,\n ` if (!ctx || !ctx.hasUI) return;`,\n ` } catch { return; }`,\n ` let entries: Array<unknown> = [];`,\n ` let modelInfo: Record<string, unknown> = {};`,\n ` let usageInfo: Record<string, unknown> | null = null;`,\n ` let sessionId: string | null = null;`,\n ` try {`,\n ` const sm = ctx.sessionManager;`,\n ` if (sm) {`,\n ` if (typeof sm.getBranch === \"function\") entries = sm.getBranch();`,\n ` else if (typeof sm.getEntries === \"function\") entries = sm.getEntries();`,\n ` if (typeof sm.getSessionId === \"function\") {`,\n ` const sid = sm.getSessionId();`,\n ` if (typeof sid === \"string\" && sid) sessionId = sid;`,\n ` }`,\n ` }`,\n ` } catch {}`,\n ` try {`,\n ` const m = ctx.model ?? {};`,\n ` modelInfo = { id: m.id, displayName: m.displayName, name: m.name, contextWindow: m.contextWindow };`,\n ` } catch {}`,\n ` try {`,\n ` if (typeof ctx.getContextUsage === \"function\") {`,\n ` const u = ctx.getContextUsage();`,\n ` if (u) usageInfo = { tokens: u.tokens, contextWindow: u.contextWindow, percent: u.percent };`,\n ` }`,\n ` } catch {}`,\n ` if (lastSessionId !== null && sessionId !== null && sessionId !== lastSessionId) {`,\n ` sessionStartMs = Date.now();`,\n ` lines = [];`,\n ` lastApplied = \"\\\\0reset\";`,\n ` }`,\n ` if (sessionId !== null) lastSessionId = sessionId;`,\n ` if (!sessionStartMs) sessionStartMs = Date.now();`,\n ` let payload: Record<string, unknown>;`,\n ` try {`,\n ` payload = buildPayload({ cwd: ctx.cwd, sessionId, model: modelInfo, contextUsage: usageInfo, entries }, { nowMs: Date.now(), sessionStartMs });`,\n ` } catch { return; }`,\n ` try { controller?.abort(); } catch {}`,\n ` controller = new AbortController();`,\n ` const signal = controller.signal;`,\n ` let text = \"\";`,\n ` try {`,\n ` text = await runStatusCommand(STATUS_COMMAND, JSON.stringify(payload), ctx.cwd, signal);`,\n ` } catch { text = \"\"; }`,\n ` if (signal.aborted) return;`,\n ` const first = (text.split(\"\\\\n\")[0] ?? \"\").trim();`,\n ` lines = first ? [first] : [];`,\n ` applyFooter(ctx);`,\n ` }`,\n ``,\n ` function schedule(ctx: any): void {`,\n ` try {`,\n ` if (timer) clearTimeout(timer);`,\n ` } catch {}`,\n ` try {`,\n ` timer = setTimeout(() => { timer = null; void refresh(ctx); }, DEBOUNCE_MS);`,\n ` } catch {}`,\n ` }`,\n ``,\n ` for (const event of [\"session_start\", \"turn_start\", \"turn_end\", \"model_select\", \"session_compact\", \"session_tree\", \"session_switch\", \"session_fork\"]) {`,\n ` try {`,\n ` pi.on(event, (_event: any, ctx: any) => { schedule(ctx); });`,\n ` } catch {}`,\n ` }`,\n ` try {`,\n ` pi.on(\"session_shutdown\", (_event: any, ctx: any) => {`,\n ` try { if (timer) clearTimeout(timer); } catch {}`,\n ` timer = null;`,\n ` try { controller?.abort(); } catch {}`,\n ` controller = null;`,\n ` lines = [];`,\n ` lastApplied = \"\\\\0none\";`,\n ` sessionStartMs = 0;`,\n ` lastSessionId = null;`,\n ` try { ctx?.ui?.setFooter(undefined); } catch {}`,\n ` });`,\n ` } catch {}`,\n ` }`,\n ` }`,\n ]\n}\n\nexport interface PiBridgeExtensionInput {\n stats: { staticFiles: number; scopedRules: number; imports: number; skipped: number }\n scopedRules: Array<{ file: string; body: string; globs: Array<string>; source: string }>\n}\n\n/**\n * Memory-bridge section for the generated extension: path-scoped rules\n * lazy-attach on `read/edit/write` tool results (once per rule per\n * session, mirroring `pi-code/claude-rules.ts`), plus `/memory` (bridge\n * inventory + auto-memory locations, on-demand only) and `/context`\n * (what bridged vs skipped). Fail-open: every handler is try/catch and\n * returns undefined on any error so Pi native behavior is preserved.\n */\nexport function buildPiMemoryBridgeSection(bridge: PiBridgeExtensionInput): Array<string> {\n // Cap embedded rule bodies so one giant rule can't bloat the mirror\n // extension source (static slice already has its own 24KB budget).\n // Strip NUL bytes: a single literal U+0000 in an embedded body breaks\n // strict downstream JSON consumers (observed as a workflow-preflight\n // `Unexpected character '\\u0000'` parse failure).\n const cappedRules = bridge.scopedRules.map((r) => ({\n file: r.file.replaceAll(\"\\0\", \"\"),\n body: (r.body.length > 8000 ? `${r.body.slice(0, 8000)}\\n…[truncated by gh-router memory bridge]` : r.body).replaceAll(\n \"\\0\",\n \"\",\n ),\n globs: r.globs,\n source: r.source,\n }))\n const payload = JSON.stringify({ stats: bridge.stats, scopedRules: cappedRules })\n return [\n ` // Memory bridge: lazy path-scoped rules + /memory + /context (on-demand only).`,\n ` {`,\n ` let BRIDGE = null;`,\n ` try { BRIDGE = ${payload}; } catch { BRIDGE = null; }`,\n ` const attached = new Set();`,\n ` function globToRegExp(glob) {`,\n ` let g = String(glob || \"\").trim().replace(/^\\\\.\\\\//, \"\").replace(/^\\\\/+/, \"\");`,\n ` let re = \"\";`,\n ` for (let k = 0; k < g.length;) {`,\n ` const c = g[k];`,\n ` if (c === \"*\") {`,\n ` if (g[k + 1] === \"*\") {`,\n ` if (g[k + 2] === \"/\") { re += \"(?:.*/)?\"; k += 3; }`,\n ` else { re += \".*\"; k += 2; }`,\n ` } else { re += \"[^/]*\"; k += 1; }`,\n ` continue;`,\n ` }`,\n ` if (c === \"?\") { re += \"[^/]\"; k += 1; continue; }`,\n ` if (\"+()|^$.{}[]\\\\\\\\\".includes(c)) re += \"\\\\\\\\\" + c; else re += c;`,\n ` k += 1;`,\n ` }`,\n ` if (!g.includes(\"/\")) re = \"(?:.*/)?\" + re;`,\n ` try { return new RegExp(\"^\" + re + \"$\"); } catch { return null; }`,\n ` }`,\n ` function ruleMatches(rule, touchedPath, cwd) {`,\n ` try {`,\n ` const cands = [touchedPath];`,\n ` const base = String(touchedPath || \"\").split(\"/\").pop() || \"\";`,\n ` if (base) cands.push(base);`,\n ` let rel = touchedPath || \"\";`,\n ` try {`,\n ` if (cwd && String(touchedPath).startsWith(String(cwd))) rel = String(touchedPath).slice(String(cwd).length).replace(/^\\\\/+/, \"\");`,\n ` } catch {}`,\n ` if (rel) cands.push(rel);`,\n ` for (const g of (rule.globs || [])) {`,\n ` const re = globToRegExp(g);`,\n ` if (!re) continue;`,\n ` for (const c of cands) { try { if (re.test(c)) return true; } catch {} }`,\n ` }`,\n ` } catch {}`,\n ` return false;`,\n ` }`,\n ` try {`,\n ` pi.on(\"tool_result\", async (event, ctx) => {`,\n ` try {`,\n ` if (!BRIDGE || !Array.isArray(BRIDGE.scopedRules) || BRIDGE.scopedRules.length === 0) return undefined;`,\n ` if (event.isError) return undefined;`,\n ` if (event.toolName !== \"read\" && event.toolName !== \"edit\" && event.toolName !== \"write\") return undefined;`,\n ` const rel = event.input && event.input.path;`,\n ` if (typeof rel !== \"string\" || !rel) return undefined;`,\n ` let abs = rel;`,\n ` try { const cwd = ctx.cwd || \"\"; abs = rel.startsWith(\"/\") ? rel : (cwd ? cwd + \"/\" + rel : rel); } catch {}`,\n ` const bodies = [];`,\n ` for (const rule of BRIDGE.scopedRules) {`,\n ` try {`,\n ` if (attached.has(rule.file)) continue;`,\n ` if (!ruleMatches(rule, abs, ctx.cwd || \"\")) continue;`,\n ` attached.add(rule.file);`,\n ` bodies.push(rule.body);`,\n ` } catch {}`,\n ` }`,\n ` if (bodies.length === 0) return undefined;`,\n ` return { content: [...(event.content || []), ...bodies.map((text) => ({ type: \"text\", text }))] };`,\n ` } catch { return undefined; }`,\n ` });`,\n ` } catch {}`,\n ` try {`,\n ` pi.registerCommand(\"memory\", {`,\n ` description: \"Show bridged memory inventory and auto-memory locations (on-demand; nothing auto-injected)\",`,\n ` handler: async (_args, ctx) => {`,\n ` try {`,\n ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,\n ` const lines = [\"Memory bridge (gh-router)\", \" Static files: \" + s.staticFiles, \" Scoped rules (lazy): \" + s.scopedRules, \" Imports: \" + s.imports, \" Skipped: \" + s.skipped, \" Auto-memory: ~/.claude/projects/<slug>/memory/MEMORY.md (on-demand read only)\", \" Pi memory: ~/.pi/agent/memory/ (your own pi-memory install, snapshotted)\"];`,\n ` try {`,\n ` const files = (BRIDGE.scopedRules || []).map((r) => r.file);`,\n ` if (files.length > 0) lines.push(\" Scoped files:\", ...files.slice(0, 20).map((f) => \" - \" + f));`,\n ` } catch {}`,\n ` lines.push(\"cwd: \" + (ctx.cwd || \"\"));`,\n ` ctx.ui.notify(lines.join(\"\\\\n\"), \"info\");`,\n ` } catch {}`,\n ` },`,\n ` });`,\n ` } catch {}`,\n ` try {`,\n ` pi.registerCommand(\"context\", {`,\n ` description: \"Show what the gh-router memory bridge loaded\",`,\n ` handler: async (_args, ctx) => {`,\n ` try {`,\n ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,\n ` ctx.ui.notify(\"Bridge context: \" + s.staticFiles + \" static, \" + s.scopedRules + \" scoped (attached \" + attached.size + \"), \" + s.imports + \" imports, \" + s.skipped + \" skipped. Native AGENTS.md/CLAUDE.md still load via Pi.\", \"info\");`,\n ` } catch {}`,\n ` },`,\n ` });`,\n ` } catch {}`,\n ` }`,\n ]\n}\n\nexport function buildPiExtensionSource(opts: {\n profileId: PiProfileId\n searchEnabled: boolean\n browseEnabled: boolean\n peers?: boolean\n bridge?: PiBridgeExtensionInput\n}): string {\n const peers = opts.peers !== false\n const advisor = peers ? piAdvisorModel(opts.profileId) : undefined\n const lines: Array<string> = []\n lines.push(\n `// gh-router-pi extension (${opts.profileId} mode). Generated per launch; do not edit.`,\n `// Executable seams only. Workflow guidance lives in skills/, not here.`,\n `import { Type } from \"typebox\";`,\n `import { spawn } from \"node:child_process\";`,\n ``,\n ...(peers\n ? [\n `const OracleParams = Type.Object({`,\n ` decision: Type.String({ description: \"The risky decision to get a second opinion on\" }),`,\n ` options: Type.Optional(Type.String({ description: \"Options considered\" })),`,\n ` context: Type.String({ description: \"Missing-context gaps and background the cold-start oracle needs\" }),`,\n `});`,\n ]\n : []),\n ...(advisor\n ? [\n `const AdvisorParams = Type.Object({`,\n ` plan: Type.String({ description: \"The final plan to review (advisory)\" }),`,\n ` context: Type.Optional(Type.String({ description: \"Background context\" })),`,\n `});`,\n ]\n : []),\n ...(opts.searchEnabled\n ? [\n `const CodeSearchParams = Type.Object({`,\n ` query: Type.String({ description: \"What to find\" }),`,\n ` mode: Type.Optional(Type.String({ description: \"semantic (default), lexical, exact, regex, or ast\" })),`,\n ` limit: Type.Optional(Type.Number({ description: \"Max results\" })),`,\n ` workspace: Type.Optional(Type.String({ description: \"Absolute path to the project root to search. Defaults to the launch workspace.\" })),`,\n ` file_glob: Type.Optional(Type.String({ description: \"Optional ripgrep glob filter (e.g. src/**/*.ts)\" })),`,\n `});`,\n ]\n : []),\n ...(opts.browseEnabled\n ? [\n `const OpenTabParams = Type.Object({`,\n ` url: Type.String({ description: \"URL to load\" }),`,\n ` reuseActive: Type.Optional(Type.Boolean({ description: \"Navigate the active tab instead of opening a new one\" })),`,\n `});`,\n `const NavigateParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` action: Type.String({ description: \"goto, back, forward, or reload\" }),`,\n ` url: Type.Optional(Type.String({ description: \"URL for action=goto\" })),`,\n ` hard: Type.Optional(Type.Boolean({ description: \"Reload only: bypass cache\" })),`,\n `});`,\n `const ScreenshotParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` format: Type.Optional(Type.String({ description: \"png or jpeg\" })),`,\n ` quality: Type.Optional(Type.Number({ description: \"JPEG quality 1-100\" })),`,\n `});`,\n `const ActParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` intent: Type.Optional(Type.String({ description: \"Natural-language action (INTENT mode)\" })),`,\n ` ref: Type.Optional(Type.String({ description: \"Element ref for REF mode\" })),`,\n ` action: Type.Optional(Type.String({ description: \"REF mode action\" })),`,\n ` value: Type.Optional(Type.String({ description: \"Value for fill/type/select\" })),`,\n `});`,\n `const ObserveParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` intent: Type.Optional(Type.String({ description: \"Focus for the summary\" })),`,\n `});`,\n `const ExtractParams = Type.Object({`,\n ` tabId: Type.Number({ description: \"Tab id from open_tab\" }),`,\n ` schema: Type.Any({ description: \"JSON schema for the desired output shape\" }),`,\n ` instruction: Type.String({ description: \"What to extract\" }),`,\n `});`,\n ]\n : []),\n `function stripNul(s) { return String(s ?? \"\").replace(/\\\\0/g, \"\"); }`,\n `async function toolText(promise) {`,\n // Inbound NUL strip: MCP/tool results flow into workflowScript text and\n // strict downstream JSON consumers reject literal U+0000 (observed as a\n // subagent-workflow validate failure). Outbound params are stripped at\n // each call site; this covers the return path in one place.\n ` const text = await promise;`,\n ` return { content: [{ type: \"text\", text: stripNul(text) }], details: undefined };`,\n `}`,\n `function toolErrorText(text) {`,\n ` return { content: [{ type: \"text\", text }], details: undefined };`,\n `}`,\n `const MCP_URL = (process.env.GH_ROUTER_HOOK_MCP_URL ?? \"\").replace(/\\\\/+$/, \"\");`,\n `const MCP_NONCE = process.env.GH_ROUTER_HOOK_NONCE ?? \"\";`,\n `const PI_WORKSPACE = (process.env.GH_ROUTER_WORKSPACE ?? \"\").trim();`,\n `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`,\n `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`,\n `void LEAD_MODEL; void LEAD_THINKING;`,\n ``,\n `async function callMcp(group, tool, args, signal) {`,\n ` const headers = { \"content-type\": \"application/json\", accept: \"application/json\", authorization: \"Bearer \" + MCP_NONCE };`,\n ` if (PI_WORKSPACE && (group === \"search\" || group === \"workers\" || group === \"orchestrate\")) { headers[\"X-GH-Workspace\"] = PI_WORKSPACE; }`,\n ` const res = await fetch(MCP_URL + \"/mcp/\" + group, {`,\n ` method: \"POST\",`,\n ` headers,`,\n ` body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method: \"tools/call\", params: { name: tool, arguments: args } }),`,\n ` signal,`,\n ` });`,\n ` if (!res.ok) throw new Error(\"mcp \" + group + \"/\" + tool + \" -> HTTP \" + res.status);`,\n ` const body = await res.json();`,\n ` if (body.error) return \"Error: \" + body.error.message;`,\n ` const content = body.result && body.result.content;`,\n ` if (!Array.isArray(content)) return \"\";`,\n ` return content.map((c) => c.text || \"\").join(\"\\\\n\");`,\n `}`,\n ``,\n `export default function (pi) {`,\n ...(peers\n ? [\n ` pi.registerTool({`,\n ` name: \"oracle\",`,\n ` label: \"Oracle\",`,\n ` description: \"Second opinion before acting on a risky decision. Advisory only: challenges assumptions, never edits. Pass decision, options, and context.\",`,\n ` parameters: OracleParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` const query = stripNul(params.decision || \"\").trim();`,\n ` const opts = stripNul(params.options || \"\").trim();`,\n ` const ctx = stripNul(params.context || \"\").trim();`,\n ` const context = (opts ? \"Options considered:\\\\n\" + opts + \"\\\\n\\\\n\" : \"\") + ctx;`,\n ` if (!query || !context.trim()) return toolErrorText(\"oracle: decision and context are required (non-empty strings)\");`,\n ` return await toolText(callMcp(\"peers\", \"oracle\", { query, context }, signal));`,\n ` },`,\n ` });`,\n ]\n : []),\n )\n if (advisor) {\n lines.push(\n ` pi.registerTool({`,\n ` name: \"advisor\",`,\n ` label: \"Advisor\",`,\n ` description: \"Advisory plan review for the lead: review the final plan before presenting it. Never executes.\",`,\n ` parameters: AdvisorParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` const plan = stripNul(params.plan || \"\").trim();`,\n ` const ctx = stripNul(params.context || \"\").trim();`,\n ` const context = (plan ? \"Plan under review:\\\\n\" + plan : \"\") + (ctx ? \"\\\\n\\\\nBackground:\\\\n\" + ctx : \"\");`,\n ` if (!plan || !context.trim()) return toolErrorText(\"advisor: plan and context are required (non-empty strings)\");`,\n ` return await toolText(callMcp(\"peers\", \"oracle\", { query: \"Review this plan (advisory)\", context }, signal));`,\n ` },`,\n ` });`,\n )\n }\n if (opts.searchEnabled) {\n lines.push(\n ` pi.registerTool({`,\n ` name: \"code_search\",`,\n ` label: \"Code search\",`,\n ` description: \"Semantic-first code search over the workspace index (falls back to lexical with a label). Use for finding code by meaning.\",`,\n ` parameters: CodeSearchParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` const query = stripNul(params.query || \"\").trim();`,\n ` if (!query) return toolErrorText(\"code_search: query is required (non-empty string)\");`,\n ` const workspace = (typeof params.workspace === \"string\" && params.workspace.trim()) ? params.workspace.trim() : PI_WORKSPACE;`,\n ` if (!workspace) return toolErrorText(\"code_search: a workspace is required. Pass the absolute project path as workspace.\");`,\n ` const args = { query, mode: params.mode || \"semantic\", limit: params.limit || 15, workspace };`,\n ` if (typeof params.file_glob === \"string\" && params.file_glob) args.file_glob = params.file_glob;`,\n ` return await toolText(callMcp(\"search\", \"code\", args, signal));`,\n ` },`,\n ` });`,\n )\n }\n if (opts.browseEnabled) {\n lines.push(\n ` pi.registerTool({`,\n ` name: \"open_tab\",`,\n ` label: \"Browser open tab\",`,\n ` description: \"Open a URL in a new browser tab (MCP browser/open_tab). Returns install_required with setup steps when the extension is not loaded.\",`,\n ` parameters: OpenTabParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` const url = stripNul(params.url || \"\").trim();`,\n ` if (!url) return toolErrorText(\"open_tab: url is required\");`,\n ` const args = { url };`,\n ` if (typeof params.reuseActive === \"boolean\") args.reuseActive = params.reuseActive;`,\n ` return await toolText(callMcp(\"browser\", \"open_tab\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"navigate\",`,\n ` label: \"Browser navigate\",`,\n ` description: \"Navigate an existing tab (MCP browser/navigate). Requires tabId + action; url only for action=goto.\",`,\n ` parameters: NavigateParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"navigate: tabId is required (number from open_tab)\");`,\n ` if (!params.action) return toolErrorText(\"navigate: action is required (goto, back, forward, reload)\");`,\n ` const args = { tabId: params.tabId, action: params.action };`,\n ` if (typeof params.url === \"string\" && params.url) args.url = params.url;`,\n ` if (typeof params.hard === \"boolean\") args.hard = params.hard;`,\n ` return await toolText(callMcp(\"browser\", \"navigate\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"screenshot\",`,\n ` label: \"Browser screenshot\",`,\n ` description: \"Screenshot a tab (MCP browser/screenshot). Requires tabId.\",`,\n ` parameters: ScreenshotParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"screenshot: tabId is required (number from open_tab)\");`,\n ` const args = { tabId: params.tabId };`,\n ` if (typeof params.format === \"string\" && params.format) args.format = params.format;`,\n ` if (typeof params.quality === \"number\") args.quality = params.quality;`,\n ` return await toolText(callMcp(\"browser\", \"screenshot\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"act\",`,\n ` label: \"Browser act\",`,\n ` description: \"Interact with a tab (MCP browser/act). Requires tabId plus intent or ref.\",`,\n ` parameters: ActParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"act: tabId is required (number from open_tab)\");`,\n ` if (!params.intent && !params.ref) return toolErrorText(\"act: intent or ref is required\");`,\n ` const args = { tabId: params.tabId };`,\n ` if (typeof params.intent === \"string\" && params.intent) args.intent = params.intent;`,\n ` if (typeof params.ref === \"string\" && params.ref) args.ref = params.ref;`,\n ` if (typeof params.action === \"string\" && params.action) args.action = params.action;`,\n ` if (typeof params.value === \"string\") args.value = params.value;`,\n ` return await toolText(callMcp(\"browser\", \"act\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"observe\",`,\n ` label: \"Browser observe\",`,\n ` description: \"Summarize a tab (MCP browser/observe). Requires tabId.\",`,\n ` parameters: ObserveParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"observe: tabId is required (number from open_tab)\");`,\n ` const args = { tabId: params.tabId };`,\n ` if (typeof params.intent === \"string\" && params.intent) args.intent = params.intent;`,\n ` return await toolText(callMcp(\"browser\", \"observe\", args, signal));`,\n ` },`,\n ` });`,\n ` pi.registerTool({`,\n ` name: \"extract\",`,\n ` label: \"Browser extract\",`,\n ` description: \"Extract structured data from a tab (MCP browser/extract). Requires tabId, schema, instruction.\",`,\n ` parameters: ExtractParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` if (typeof params.tabId !== \"number\") return toolErrorText(\"extract: tabId is required (number from open_tab)\");`,\n ` if (!params.instruction) return toolErrorText(\"extract: instruction is required\");`,\n ` if (params.schema === undefined) return toolErrorText(\"extract: schema is required\");`,\n ` return await toolText(callMcp(\"browser\", \"extract\", { tabId: params.tabId, schema: params.schema, instruction: params.instruction }, signal));`,\n ` },`,\n ` });`,\n )\n }\n if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) {\n lines.push(...buildPiMemoryBridgeSection(opts.bridge))\n }\n lines.push(\n // Statusline footer (always on — like Claude's operating defaults, not a\n // flag surface): owns Pi's footer with the shared internal-aic-status\n // runner. No third-party statusline package, no settings block.\n ...buildPiStatuslineFooterSection(),\n ` // Route compaction summaries to the mode's cheap capable model;`,\n ` // ALWAYS fall back to Pi native (return undefined) on any failure.`,\n ` pi.on(\"session_before_compact\", async (event) => {`,\n ` try {`,\n ` const preparation = event.preparation;`,\n ` if (!preparation || !Array.isArray(preparation.messagesToSummarize)) return undefined;`,\n ` return undefined; // v1: observe only; native pipeline stays authoritative.`,\n ` } catch {`,\n ` return undefined;`,\n ` }`,\n ` });`,\n `}`,\n ``,\n )\n return `${lines.join(\"\\n\")}\\n`\n}\n\nexport interface PiSkillDoc {\n dir: string\n content: string\n}\n\n/**\n * Workflow guidance as skills (progressive disclosure, not tools).\n * Ownership mirrors the Claude launcher: peer consult prose rides\n * `--peers`, semantic-search prose rides `--search`, and the\n * delegation/review pipeline rides `--swe` AND `--peers` — without\n * agents + the subagent provider its prose dangles, so peerless+swe\n * emits none. A bare launch emits NO skills at all.\n */\nexport function buildPiSkills(opts: {\n profileId: PiProfileId\n peers?: boolean\n swe?: boolean\n search?: boolean\n}): Array<PiSkillDoc> {\n const peers = opts.peers !== false\n const skills: Array<PiSkillDoc> = []\n if (peers) {\n skills.push({\n dir: \"gh-oracle\",\n content: [\n \"---\",\n \"name: gh-oracle\",\n \"description: Consult the oracle for a second opinion on risky decisions. Use when the decision itself feels risky.\",\n \"---\",\n \"\",\n \"# Oracle consult\",\n \"\",\n \"Call the `oracle` tool with the decision, the options considered, and the\",\n \"missing-context gaps. The oracle is cold-start: it sees only what you pass.\",\n \"Its verdict is advisory — verify with tests and code, never substitute votes\",\n \"for verification. (The `oracle` tool is the one-shot consult; the `oracle`\",\n \"subagent is the same role for interactive follow-ups — same name, different\",\n \"invocation. Prefer the tool for a single verdict.)\",\n ].join(\"\\n\"),\n })\n }\n if (opts.search === true) {\n skills.push({\n dir: \"gh-search-first\",\n content: [\n \"---\",\n \"name: gh-search-first\",\n \"description: Search the workspace semantically before reading broadly. Use when locating code by meaning.\",\n \"---\",\n \"\",\n \"# Search first\",\n \"\",\n \"Use `code_search` (semantic by default) before broad reads. The response\",\n \"labels its `source`: `semantic`, `lexical`, or `lexical-fallback` — a\",\n \"fallback is never silent, so retry narrower on fallback rather than\",\n \"assuming full coverage.\",\n ].join(\"\\n\"),\n })\n }\n if (opts.swe === true && peers) {\n // Balanced is advisor-free: the roster line must not name a consultant\n // that has neither tool nor agent file on that profile.\n const consults =\n opts.profileId === \"balanced\" ? \"`oracle` for consults\" : \"`oracle`/`advisor` for consults\"\n skills.push({\n dir: \"gh-delegate\",\n content: [\n \"---\",\n \"name: gh-delegate\",\n \"description: Delegate scoped work to subagents with isolated context. Use for recon, implementation, and review loops.\",\n \"---\",\n \"\",\n \"# Delegate\",\n \"\",\n \"You may delegate via the `subagent` tool to this roster only: `Explore`\",\n \"for discovery, `General-Purpose` for scoped implementation, `reviewer`\",\n `for verification, ${consults}. (Builtin \\`scout\\` and`,\n \"`worker` are disabled in this session; their aliases resolve here.)\",\n \"Recommended loop: `Explore` to map the code, paste the brief excerpts\",\n \"into the `General-Purpose` brief to implement, `reviewer` to check,\",\n \"`General-Purpose` to apply feedback. Keep delegated tasks\",\n \"scoped with file:line evidence on return.\",\n opts.profileId === \"balanced\"\n ? \"Send work to reviewer ONLY when the change alters behavior.\"\n : \"Send finished work to reviewer for assessment.\",\n ].join(\"\\n\"),\n })\n if (peers && piAdvisorModel(opts.profileId)) {\n skills.push({\n dir: \"gh-advisor\",\n content: [\n \"---\",\n \"name: gh-advisor\",\n \"description: Advisory review of the final plan before presenting it. Use when the lead has a plan ready.\",\n \"---\",\n \"\",\n \"# Advisor review\",\n \"\",\n \"The lead plans directly (there is no Plan subagent). Review the final plan\",\n \"with the `advisor` tool before presenting it. Advisory only: it never\",\n \"executes and never overrides verification.\",\n ].join(\"\\n\"),\n })\n }\n }\n return skills\n}\n\nexport interface PiPromptDoc {\n name: string\n content: string\n}\n\n/**\n * Saved workflow shortcuts as prompt templates (`/name`). The review\n * pipeline is SWE-pipeline surface: only `--swe` AND `--peers` emit\n * prompts (peerless launches have no agents behind them), so a bare\n * launch advertises none.\n *\n * `/parallel-review` intentionally shadows the packaged pi-subagents\n * prompt of the same name (package prompts are filtered to `[]` in\n * settings): ours routes to our pinned-model `reviewer`, not the\n * default-model builtin. `/review` is novel — no packaged collision.\n */\nexport function buildPiPrompts(opts: {\n profileId: PiProfileId\n swe?: boolean\n peers?: boolean\n}): Array<PiPromptDoc> {\n if (opts.swe !== true || opts.peers === false) return []\n const prompts: Array<PiPromptDoc> = [\n {\n name: \"review\",\n content: [\n \"---\",\n 'description: Review the current changes with the reviewer subagent',\n 'argument-hint: \"[focus]\"',\n \"---\",\n \"Have the reviewer subagent review the current changes. Focus on ${1:-correctness, tests, and simplicity}.\",\n ].join(\"\\n\"),\n },\n {\n name: \"parallel-review\",\n content: [\n \"---\",\n 'description: Run parallel reviewer passes over the change',\n 'argument-hint: \"[focus]\"',\n \"---\",\n \"Run parallel reviewers: one for correctness, one for tests, one for unnecessary complexity. Focus: ${1:-the current diff}.\",\n ].join(\"\\n\"),\n },\n ]\n if (piAdvisorModel(opts.profileId)) {\n prompts.push({\n name: \"plan-review\",\n content: [\n \"---\",\n 'description: Advisory review of the current plan before presenting',\n 'argument-hint: \"[plan]\"',\n \"---\",\n \"Review the final plan with the advisor tool (advisory) before presenting it: ${1:-the current plan}.\",\n ].join(\"\\n\"),\n })\n }\n return prompts\n}\n","import { randomBytes } from \"node:crypto\"\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 { checkPiVersion, updatePi } 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 { aicLedgerPath, sweepStaleAicLedgerFiles } from \"./lib/aic-ledger\"\nimport { resolveSelfInvocation } from \"./lib/hook-launcher/self-invocation\"\nimport {\n ensurePiAgentMirror,\n removeOwnPiAgentMirror,\n sweepStalePiAgentMirrors,\n} from \"./lib/pi-paths\"\nimport {\n buildPiExtensionSource,\n buildPiPrompts,\n buildPiSkills,\n} from \"./lib/pi-extension\"\nimport {\n buildPiAgentFiles,\n buildPiAppendSystem,\n buildPiModelsJson,\n buildPiSettingsJson,\n mergeSubagentsSettings,\n piLeadModel,\n piProfileModelIds,\n piUsdCostFor,\n type PiProfileId,\n} from \"./lib/pi-models-settings\"\nimport { launchChild } from \"./lib/launch\"\nimport { registerLaunch, unregisterLaunch } from \"./lib/launch-registry\"\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 { colbertDegradedWarning, provisionAndIndexColbert } from \"./lib/colbert\"\nimport { startKeepAwake, stopKeepAwake } from \"./lib/keep-awake\"\nimport { warmTreeSitterPool } from \"./lib/tree-sitter-pool/pool\"\nimport { provisionBrowserAssets } from \"./lib/browser-mcp/provision\"\nimport { browserToolsEnabled } from \"./lib/mcp-capabilities\"\nimport {\n formatBalancedPrerequisiteFailure,\n formatCheapestPrerequisiteFailure,\n profileDescriptor,\n resolveLaunchProfile,\n validateBalancedProfilePrerequisites,\n validateCheapestProfilePrerequisites,\n} from \"./lib/launch-profile\"\nimport {\n getPiLaunchEnvVars,\n parseSharedArgs,\n setupAndServe,\n sharedServerArgs,\n} from \"./lib/server-setup\"\n\nexport const piArgs = {\n ...sharedServerArgs,\n model: {\n alias: \"m\",\n type: \"string\",\n description:\n \"Pi launch profile: cheapest (Luna-led, cheapest tier) or balanced (Sol-led, most-complex-tasks tier). Only these two aliases are supported for `github-router pi`.\",\n },\n \"update-check\": {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Check the npm registry for a newer Pi release on launch (throttled hourly). Set to false (--no-update-check) to skip (offline/CI).\",\n },\n \"auto-update\": {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Install the latest Pi on launch when stale (default). Set to false (--no-auto-update) to warn only.\",\n },\n swe: {\n type: \"boolean\" as const,\n default: false,\n description:\n \"Enable the SWE pipeline surface: delegation/review skills (gh-delegate, cheapest-only gh-advisor) and the review prompt shortcuts (/review, /parallel-review, cheapest-only /plan-review). Off by default; a bare launch advertises no skills or prompts.\",\n },\n peers: {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Wire the peer/subagent floor: native agent files, the oracle tool (plus cheapest-only advisor), the gh-oracle skill, and the pi-subagents package. Set to false (--no-peers) for a lead-only session; prereqs then validate the lead model only.\",\n },\n \"memory-bridge\": {\n type: \"boolean\" as const,\n default: true,\n description:\n \"Bridge Copilot (.github/copilot-instructions.md, .github/instructions/*.instructions.md) and Claude (.claude/rules/, .claude/CLAUDE.md, ~/.claude/CLAUDE.md) memory into Pi. Static repo-wide slice synthesizes into the mirror AGENTS.md; path-scoped rules lazy-attach. Set to false (--no-memory-bridge) for Pi-native discovery only.\",\n },\n} satisfies ArgsDef\n\n/**\n * Forward child args: every raw token that is NOT one of github-router's\n * own declared flags (or that flag's consumed value); everything after a\n * literal `--` flows verbatim. Local copy of the claude.ts walk so this\n * module doesn't import the Claude launch graph.\n */\nexport function collectPiPassthroughArgs(\n rawArgs: ReadonlyArray<string>,\n argsDef: ArgsDef,\n): string[] {\n const known = new Set<string>()\n const stringTyped = new Set<string>()\n for (const [name, def] of Object.entries(argsDef)) {\n const rawAlias = \"alias\" in def ? def.alias : undefined\n const aliases =\n rawAlias === undefined ? [] : Array.isArray(rawAlias) ? rawAlias : [rawAlias]\n for (const n of [name, ...aliases]) {\n known.add(n)\n if (def.type === \"string\") stringTyped.add(n)\n }\n }\n const forwarded: string[] = []\n for (let i = 0; i < rawArgs.length; i++) {\n const tok = rawArgs[i]\n if (tok === \"--\") {\n forwarded.push(...rawArgs.slice(i + 1))\n break\n }\n if (tok === \"-\" || !tok.startsWith(\"-\")) {\n forwarded.push(tok)\n continue\n }\n const doubleDash = tok.startsWith(\"--\")\n const afterDashes = tok.slice(doubleDash ? 2 : 1)\n const eq = afterDashes.indexOf(\"=\")\n const rawName = eq >= 0 ? afterDashes.slice(0, eq) : afterDashes\n const hasInlineValue = eq >= 0\n const negated = doubleDash && rawName.startsWith(\"no-\")\n const baseName = negated ? rawName.slice(3) : rawName\n const isKnown = known.has(rawName) || (negated && known.has(baseName))\n if (!isKnown) {\n forwarded.push(tok)\n continue\n }\n const consumesValue =\n !negated\n && !hasInlineValue\n && stringTyped.has(rawName)\n && i + 1 < rawArgs.length\n && rawArgs[i + 1] !== \"--\"\n && !rawArgs[i + 1].startsWith(\"-\")\n if (consumesValue) i++\n }\n return forwarded\n}\n\nasync function writeJsonFile(file: string, value: unknown): Promise<void> {\n await fs.mkdir(path.dirname(file), { recursive: true })\n await fs.writeFile(file, `${JSON.stringify(value, null, 2)}\\n`, { mode: 0o600 })\n}\n\nasync function writeTextFile(file: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(file), { recursive: true })\n await fs.writeFile(file, content, { mode: 0o600 })\n}\n\nexport const pi = defineCommand({\n meta: {\n name: \"pi\",\n description: \"Start the proxy server and launch the Pi coding agent (cheapest/balanced)\",\n },\n args: piArgs,\n async run({ args, rawArgs }) {\n const headless = rawArgs.includes(\"--print\") || rawArgs.includes(\"--mode\")\n if (!process.stdout.isTTY && !headless) {\n consola.error(\"The pi subcommand requires a TTY (interactive terminal), or use --print/--mode for headless runs.\")\n process.exit(1)\n }\n\n const parsed = parseSharedArgs(args as unknown as Record<string, unknown>)\n const launchProfileId = resolveLaunchProfile(args.model)\n if (launchProfileId !== \"cheapest\" && launchProfileId !== \"balanced\") {\n process.stderr.write(\n `github-router pi supports only -m cheapest and -m balanced (got ${JSON.stringify(args.model ?? \"\")}). ` +\n `Run plain \\`github-router pi -m cheapest\\` or \\`github-router pi -m balanced\\`.\\n`,\n )\n process.exit(1)\n }\n const profileId = launchProfileId as PiProfileId\n\n let server: Awaited<ReturnType<typeof setupAndServe>>[\"server\"]\n let serverUrl: string\n try {\n const result = await setupAndServe({\n ...parsed,\n port: parsed.port,\n silent: true,\n })\n server = result.server\n serverUrl = result.serverUrl\n } catch (error) {\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 // 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 if (updateCheck) {\n try {\n const check = await checkPiVersion()\n if (!check.installed) {\n try {\n await updatePi(\"latest\")\n const retry = await checkPiVersion({ force: true })\n if (!retry.installed) {\n throw new Error(\"install did not place pi on PATH\")\n }\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\\`, then retry.`,\n )\n process.exit(1)\n }\n } else if (check.needsMinUpgrade) {\n if (autoUpdate && check.latestVersion) {\n try {\n await updatePi(check.latestVersion)\n } catch (err) {\n consola.error(\n `Installed Pi v${check.installedVersion} is below the supported floor and auto-upgrade failed. Upgrade manually: \\`npm install -g @earendil-works/pi-coding-agent@latest\\`.`,\n )\n void err\n process.exit(1)\n }\n } else {\n consola.error(\n `Installed Pi v${check.installedVersion} is below the supported floor. Upgrade: \\`npm install -g @earendil-works/pi-coding-agent@latest\\`.`,\n )\n process.exit(1)\n }\n } else if (check.needsUpdate && check.latestVersion) {\n if (autoUpdate) {\n try {\n await updatePi(check.latestVersion)\n } catch (err) {\n consola.warn(\n `Auto-update of Pi to ${check.latestVersion} failed (${err instanceof Error ? err.message : String(err)}); continuing with installed v${check.installedVersion}.`,\n )\n }\n } else {\n consola.warn(\n `Pi v${check.installedVersion} is installed; v${check.latestVersion} is available. Run with --auto-update (the default) to install on launch.`,\n )\n }\n }\n } catch (err) {\n consola.debug(\"Pi version check failed:\", err)\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\n // Pin-mode prerequisites against the live catalog (fail-closed).\n // Peerless launches validate the lead only (nothing else is consumed).\n const prereqCheck =\n profileId === \"cheapest\"\n ? validateCheapestProfilePrerequisites(state.models, { peers: peersEnabled })\n : validateBalancedProfilePrerequisites(state.models, { peers: peersEnabled })\n if (!prereqCheck.ok) {\n const message =\n profileId === \"cheapest\"\n ? formatCheapestPrerequisiteFailure(prereqCheck.missing)\n : formatBalancedPrerequisiteFailure(prereqCheck.missing)\n consola.error(message)\n process.stderr.write(`${message}\\n`)\n process.exit(1)\n }\n\n // Isolated Pi mirror + stale sweep (never the user's real ~/.pi/agent).\n let mirror: string\n try {\n mirror = await ensurePiAgentMirror()\n await sweepStalePiAgentMirrors()\n } 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 // Generate the mode's Pi files into the mirror.\n try {\n const searchEnabled =\n parsed.searchEnabled || process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const browseEnabled = browserToolsEnabled()\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 ...(cost ? { cost } : {}),\n }\n })\n await writeJsonFile(\n path.join(mirror, \"models.json\"),\n buildPiModelsJson({ serverUrl, profileId, catalog, peers: peersEnabled }),\n )\n\n // Merge over snapshotted user settings: our keys win, user keys survive.\n const settingsPath = path.join(mirror, \"settings.json\")\n let userSettings: Record<string, unknown> = {}\n try {\n const raw = await fs.readFile(settingsPath, \"utf8\")\n const parsedSettings = JSON.parse(raw) as unknown\n if (parsedSettings && typeof parsedSettings === \"object\") {\n userSettings = parsedSettings as Record<string, unknown>\n }\n } catch {\n userSettings = {}\n }\n // Merge over snapshotted user settings: our keys win, user keys survive.\n // Exception: `subagents.agentOverrides` deep-merges (ours as defaults,\n // user's entries win per-agent) so emitting our builtin disables never\n // wipes a user's own overrides — a shallow spread would replace the\n // whole object.\n const builtSettings = buildPiSettingsJson({ profileId, searchEnabled, browseEnabled, catalog, peers: peersEnabled })\n const mergedSubagents = mergeSubagentsSettings(\n userSettings[\"subagents\"],\n builtSettings.subagents,\n )\n await writeJsonFile(settingsPath, {\n ...userSettings,\n ...builtSettings,\n ...(mergedSubagents ? { subagents: mergedSubagents } : {}),\n })\n\n // Memory bridge collection runs BEFORE the extension build so scoped\n // rules + stats can be embedded for lazy attach + /memory + /context.\n // Best-effort, never fatal. Honors --no-memory-bridge,\n // GH_ROUTER_PI_BRIDGE=0 / GH_ROUTER_DISABLE_PI_BRIDGE=1, and Pi's own\n // --no-context-files/-nc passthrough (never fight an explicit `-nc`).\n const bridgeDisabled =\n (args as Record<string, unknown>)[\"memory-bridge\"] === false\n || process.env.GH_ROUTER_PI_BRIDGE === \"0\"\n || process.env.GH_ROUTER_DISABLE_PI_BRIDGE === \"1\"\n let bridgeStats: { staticFiles: number; scopedRules: number; imports: number; skipped: number } | undefined\n let bridgeScoped: Array<{ file: string; body: string; globs: Array<string>; source: string }> = []\n if (!bridgeDisabled) {\n const passthrough = collectPiPassthroughArgs(rawArgs, piArgs)\n const noContext = passthrough.includes(\"--no-context-files\") || passthrough.includes(\"-nc\")\n if (!noContext) {\n try {\n const { collectBridgeInputs } = await import(\"./lib/pi-memory-bridge\")\n const collected = await collectBridgeInputs(process.cwd())\n bridgeStats = {\n staticFiles:\n collected.copilotInstructions.length\n + collected.unscopedRules.length\n + collected.userGlobal.length,\n scopedRules: collected.scopedRules.length,\n imports: collected.imports.length,\n skipped: collected.skipped.length,\n }\n bridgeScoped = collected.scopedRules\n // Stash full collection for the AGENTS.md synthesis below.\n ;(globalThis as Record<string, unknown>).__ghRouterBridgeCollected = collected\n } catch (err) {\n consola.debug(\"Pi memory bridge collection skipped:\", err)\n }\n }\n }\n\n await writeTextFile(\n path.join(mirror, \"extensions\", \"gh-router-pi\", \"index.ts\"),\n buildPiExtensionSource({\n profileId,\n searchEnabled,\n browseEnabled,\n peers: peersEnabled,\n bridge: bridgeStats ? { stats: bridgeStats, scopedRules: bridgeScoped } : undefined,\n }),\n )\n // Peer floor (agents + consult skills) rides --peers; the SWE\n // pipeline (delegate/advisor skills, review prompts) rides --swe AND\n // --peers (without agents + the subagent provider its prose dangles,\n // so peerless+swe emits none — see the heads-up below).\n // semantic-search prose rides --search. Bare launches write none.\n if (peersEnabled) {\n const agentFiles = buildPiAgentFiles(profileId)\n for (const [rel, content] of Object.entries(agentFiles)) {\n await writeTextFile(path.join(mirror, rel), content)\n }\n }\n for (const skill of buildPiSkills({ profileId, peers: peersEnabled, swe: sweEnabled, search: searchEnabled })) {\n await writeTextFile(path.join(mirror, \"skills\", skill.dir, \"SKILL.md\"), skill.content)\n }\n for (const prompt of buildPiPrompts({ profileId, swe: sweEnabled, peers: peersEnabled })) {\n await writeTextFile(path.join(mirror, \"prompts\", `${prompt.name}.md`), prompt.content)\n }\n await writeTextFile(path.join(mirror, \"APPEND_SYSTEM.md\"), buildPiAppendSystem(profileId, { peers: peersEnabled }))\n\n // Static bridge synthesis into mirror AGENTS.md (Pi-native candidate).\n // Uses the collection stashed above; idempotent via fenced replace.\n try {\n const collected = (globalThis as Record<string, unknown>).__ghRouterBridgeCollected as\n | import(\"./lib/pi-memory-bridge\").PiBridgeCollected\n | undefined\n if (collected) {\n const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import(\"./lib/pi-memory-bridge\")\n const { section } = buildMirrorBridgeSection(collected, { repoRoot: process.cwd() })\n const agentsPath = path.join(mirror, \"AGENTS.md\")\n let existing: string | undefined\n try {\n existing = await fs.readFile(agentsPath, \"utf8\")\n } catch {\n existing = undefined\n }\n await writeTextFile(agentsPath, mergeBridgeIntoAgentsMd(existing, section))\n await writeJsonFile(path.join(mirror, \".gh-router-bridge.json\"), {\n stats: bridgeStats ?? null,\n scopedRuleFiles: bridgeScoped.map((r) => r.file),\n })\n }\n } catch (err) {\n consola.debug(\"Pi memory bridge synthesis skipped:\", err)\n } finally {\n try {\n delete (globalThis as Record<string, unknown>).__ghRouterBridgeCollected\n } catch {\n // ignore\n }\n }\n } catch (err) {\n consola.error(\n `Failed to write Pi launch files: ${err instanceof Error ? err.message : String(err)}.`,\n )\n process.exit(1)\n }\n\n // Tier-table drift guard: loud warning when live catalog input prices\n // disagree with the pinned cheap-tier thresholds. Separate block (own\n // try/catch) so a drift-check bug can never fail a launch. Warn-only.\n try {\n warnOnTierPriceDriftForModels(state.models?.data)\n } catch (err) {\n consola.debug(\"Pi tier drift check skipped:\", err)\n }\n\n // AIC status line: this session's AI-credit total (`[AIC 12.42]`) plus\n // the discounted actual (`~$`) in Pi's footer, rendered by the mode's\n // own `gh-router-pi` extension (same `internal-aic-status` runner the\n // Claude launcher drives — one renderer, identical segments). The\n // command travels via `GH_ROUTER_AIC_STATUS_COMMAND` env, never a\n // settings block: the community bridge only reads the user's real\n // global/project settings and never sees the launch mirror, so a\n // mirror-injected block would be dead config. Router-wins by\n // architecture (the footer is extension-owned); opt out with\n // GH_ROUTER_DISABLE_AIC_STATUSLINE=1. Fail-open: a broken runner\n // degrades to no statusline, never a broken launch.\n let aicLedgerEnv: string | undefined\n let aicStatusCommandEnv: string | undefined\n if (process.env.GH_ROUTER_DISABLE_AIC_STATUSLINE !== \"1\") {\n try {\n void sweepStaleAicLedgerFiles()\n const selfInvocation = await resolveSelfInvocation()\n aicStatusCommandEnv = buildAicStatusHookCommand(selfInvocation)\n aicLedgerEnv = aicLedgerPath()\n consola.info(\n `Status line wired via the gh-router-pi footer for ${profileId} (shared internal-aic-status runner).`,\n )\n } catch (err) {\n consola.warn(\n `AIC status line skipped: ${\n err instanceof Error ? err.message : String(err)\n }.`,\n )\n }\n }\n\n if (toolbeltEnabled()) {\n void provisionToolbelt().catch((err) =>\n consola.debug(\"Toolbelt provisioning failed:\", err),\n )\n }\n void provisionAndIndexColbert()\n void colbertDegradedWarning(undefined, { logsToFile: true })\n .then((warning) => {\n if (warning) process.stderr.write(`${warning}\\n`)\n })\n .catch(() => {})\n void warmTreeSitterPool()\n startKeepAwake()\n if (browserToolsEnabled()) {\n void provisionBrowserAssets().catch((err) =>\n consola.debug(\"Browser extension provisioning failed:\", err),\n )\n }\n\n // Launch binding: the Pi extension reaches the proxy's /mcp with this\n // nonce (same channel as the Claude hooks). Descriptor carries the\n // mode's group/persona allow-list so /mcp enforces it server-side;\n // peerless launches drop the peers group + persona allow-list to match\n // the unwritten tools.\n const descriptor = profileDescriptor(profileId)\n const nonce = randomBytes(32).toString(\"hex\")\n const secret = randomBytes(32).toString(\"hex\")\n const entry = registerLaunch({\n profileId,\n nonce,\n secret,\n allowedGroups: peersEnabled\n ? descriptor.allowedGroups\n : new Set(\n [...(descriptor.allowedGroups ?? [])].filter((g) => g !== \"peers\"),\n ),\n allowedPersonas: peersEnabled ? descriptor.personaAllowlist : new Set<string>(),\n })\n\n const extraArgs = collectPiPassthroughArgs(rawArgs, piArgs)\n const lead = piLeadModel(profileId)\n const modelIds = piProfileModelIds(profileId, { peers: peersEnabled })\n const surface = [\n `peers=${peersEnabled ? \"on\" : \"off\"}`,\n `swe=${sweEnabled ? \"on\" : \"off\"}`,\n ].join(\" \")\n process.stderr.write(\n `Server ready on ${serverUrl}, launching Pi (${profileId} lead ${lead}, models ${modelIds.length}, ${surface})...\\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 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 removeOwnPiAgentMirror()\n },\n },\n )\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;AAaA,MAAa,iBAAiB;;AAE9B,MAAa,iBAAiB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AAC,KAAK,IAAI;CACX,MAAM,UAAU,cAAc,QAAQ,OAAO,GAAG,OAAO;CAKvD,MAAM,UAAU,eAAe,SAAS;CACxC,IAAI,SAAS;EACX,MAAM,OAAO;GACX;GACA;GACA;GACA;GACA,UAAU,iBAAiB,GAAG,QAAQ;GACtC,aAAa,QAAQ;GACrB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,IAAI;EACX,MAAM,UAAU,cAAc,SAAS,OAAO,GAAG,KAAK;CACxD;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,oBACd,WACA,OAA4B,CAAC,GACrB;CACR,MAAM,QAAQ,KAAK,UAAU;CAC7B,MAAM,UAAU,QAAQ,eAAe,SAAS,IAAI,KAAA;CACpD,MAAM,QAAQ;EACZ,eAAe,UAAU;EACzB;EACA;CACF;CACA,IAAI,OACF,MAAM,KACJ,mFACA,cAAc,aACV,kEACA,oDACJ,2EACA,UACI,0EACA,sEACJ,mFACF;MAEA,MAAM,KACJ,uGACF;CAEF,MAAM,KAAK,IAAI,IAAI,oBAAoB,IAAI,EAAE;CAC7C,OAAO,MAAM,KAAK,IAAI;AACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AChqBA,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,MAM5B;CACT,MAAM,QAAQ,KAAK,UAAU;CAC7B,MAAM,UAAU,QAAQ,eAAe,KAAK,SAAS,IAAI,KAAA;CACzD,MAAM,QAAuB,CAAC;CAC9B,MAAM,KACJ,8BAA8B,KAAK,UAAU,6CAC7C,2EACA,mCACA,+CACA,IACA,GAAI,QACA;EACE;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,GAAI,UACA;EACE;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,GAAI,KAAK,gBACL;EACE;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,GAAI,KAAK,gBACL;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,GACL,wEACA,sCAKA,iCACA,uFACA,KACA,kCACA,uEACA,KACA,oFACA,6DACA,wEACA,sBAAsB,KAAK,UAAU,GAAG,iBAAiB,GAAG,YAAY,KAAK,SAAS,GAAG,EAAE,IAC3F,yBAAyB,KAAK,UAAU,eAAe,KAAK,SAAS,CAAC,EAAE,IACxE,wCACA,IACA,uDACA,+HACA,+IACA,0DACA,uBACA,gBACA,uHACA,eACA,SACA,2FACA,oCACA,4DACA,yDACA,6CACA,0DACA,KACA,IACA,kCACA,GAAI,QACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,CACP;CACA,IAAI,SACF,MAAM,KACJ,uBACA,wBACA,yBACA,sHACA,kCACA,oDACA,0DACA,4DACA,mHACA,2HACA,uHACA,UACA,OACF;CAEF,IAAI,KAAK,eACP,MAAM,KACJ,uBACA,4BACA,6BACA,kJACA,qCACA,oDACA,4DACA,gGACA,uIACA,qIACA,wGACA,0GACA,yEACA,UACA,OACF;CAEF,IAAI,KAAK,eACP,MAAM,KACJ,uBACA,yBACA,kCACA,2JACA,kCACA,oDACA,wDACA,sEACA,+BACA,6FACA,8EACA,UACA,SACA,uBACA,yBACA,kCACA,2HACA,mCACA,oDACA,2HACA,iHACA,sEACA,kFACA,wEACA,8EACA,UACA,SACA,uBACA,2BACA,oCACA,kFACA,qCACA,oDACA,6HACA,+CACA,8FACA,gFACA,gFACA,UACA,SACA,uBACA,oBACA,6BACA,iGACA,8BACA,oDACA,sHACA,oGACA,+CACA,8FACA,kFACA,8FACA,0EACA,yEACA,UACA,SACA,uBACA,wBACA,iCACA,8EACA,kCACA,oDACA,0HACA,+CACA,8FACA,6EACA,UACA,SACA,uBACA,wBACA,iCACA,sHACA,kCACA,oDACA,0HACA,4FACA,+FACA,wJACA,UACA,OACF;CAEF,IAAI,KAAK,UAAU,KAAK,OAAO,YAAY,SAAS,KAAK,OAAO,MAAM,cAAc,GAClF,MAAM,KAAK,GAAG,2BAA2B,KAAK,MAAM,CAAC;CAEvD,MAAM,KAIJ,GAAG,+BAA+B,GAClC,sEACA,yEACA,wDACA,aACA,gDACA,gGACA,qFACA,iBACA,2BACA,SACA,SACA,KACA,EACF;CACA,OAAO,GAAG,MAAM,KAAK,IAAI,EAAE;AAC7B;;;;;;;;;AAeA,SAAgB,cAAc,MAKR;CACpB,MAAM,QAAQ,KAAK,UAAU;CAC7B,MAAM,SAA4B,CAAC;CACnC,IAAI,OACF,OAAO,KAAK;EACV,KAAK;EACL,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF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