github-router 0.3.339 → 0.3.340

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/aic-statusline-settings-Chf-IT45.js +137 -0
  2. package/dist/aic-statusline-settings-Chf-IT45.js.map +1 -0
  3. package/dist/{attribution-settings-DpDZcVka.js → attribution-settings-BTfKm-RU.js} +4 -4
  4. package/dist/{attribution-settings-DpDZcVka.js.map → attribution-settings-BTfKm-RU.js.map} +1 -1
  5. package/dist/browser-ext/manifest.json +1 -1
  6. package/dist/{claude-D0SUYfyr.js → claude-DUpp7B4X.js} +11 -141
  7. package/dist/claude-DUpp7B4X.js.map +1 -0
  8. package/dist/{codex-CzV-I2h3.js → codex-Xn1xsoOw.js} +4 -4
  9. package/dist/{codex-CzV-I2h3.js.map → codex-Xn1xsoOw.js.map} +1 -1
  10. package/dist/engine-DvGukHty.js +2 -0
  11. package/dist/{gate-discovery-BKjq0x66.js → gate-discovery-BIBgN6mA.js} +2 -2
  12. package/dist/{gate-discovery-BKjq0x66.js.map → gate-discovery-BIBgN6mA.js.map} +1 -1
  13. package/dist/{internal-stop-hook-DV7o7chW.js → internal-stop-hook-Dyn0fRpZ.js} +2 -2
  14. package/dist/{internal-stop-hook-DV7o7chW.js.map → internal-stop-hook-Dyn0fRpZ.js.map} +1 -1
  15. package/dist/main.js +6 -5
  16. package/dist/main.js.map +1 -1
  17. package/dist/{peer-mcp-personas-CmR3f7nO.js → peer-mcp-personas-Dt0VRKYz.js} +20 -13
  18. package/dist/{peer-mcp-personas-CmR3f7nO.js.map → peer-mcp-personas-Dt0VRKYz.js.map} +1 -1
  19. package/dist/pi-DwfSuefC.js +1175 -0
  20. package/dist/pi-DwfSuefC.js.map +1 -0
  21. package/dist/{provision-CxulCZpS.js → provision-D_aHUCXt.js} +11 -2
  22. package/dist/provision-D_aHUCXt.js.map +1 -0
  23. package/dist/{serve-DVq-m7p5.js → serve-DWL5kmB_.js} +5 -5
  24. package/dist/{serve-DVq-m7p5.js.map → serve-DWL5kmB_.js.map} +1 -1
  25. package/dist/{server-setup-Df9BxQ-V.js → server-setup-UWugox0I.js} +84 -52
  26. package/dist/server-setup-UWugox0I.js.map +1 -0
  27. package/dist/{start-C4wi5ccP.js → start-4OTehsYq.js} +3 -3
  28. package/dist/{start-C4wi5ccP.js.map → start-4OTehsYq.js.map} +1 -1
  29. package/package.json +1 -1
  30. package/dist/claude-D0SUYfyr.js.map +0 -1
  31. package/dist/engine-vxnquZvh.js +0 -2
  32. package/dist/provision-CxulCZpS.js.map +0 -1
  33. package/dist/server-setup-Df9BxQ-V.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi-DwfSuefC.js","names":["process"],"sources":["../src/lib/pi-version-check.ts","../src/lib/pi-tier-windows.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","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).\n const SKIP = new Set([\"auth.json\", \"sessions\", \"models-store.json\"])\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\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 * `pi-statusline` is extension-only by manifest and always present.\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 \"npm:pi-statusline\",\n \"local:gh-router-pi\",\n ],\n }\n}\n\nfunction agentFileName(name: string): string {\n return `${name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\")}.md`\n}\n\nfunction roleDescription(\n profileId: PiProfileId,\n role: PiNativeRole,\n): string {\n const oracleNote =\n \"For risky decisions, ask the oracle subagent for a second opinion before acting.\";\n if (role.name === \"Explore\") {\n return `Fast read-only recon: locate code, answer evidence questions, return compressed context. ${oracleNote}`\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/max_turns`, plus\n * `allowedAgents` 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 */\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 tools =\n role.name === \"General-Purpose\"\n ? \"[read, bash, edit, write, grep, find, ls]\"\n : \"[read, grep, find, ls]\";\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 \"max_turns: 80\",\n ];\n if (profileId === \"balanced\" && role.name === \"reviewer\") {\n lines.push(\"allowedAgents: [Explore]\");\n }\n if (role.name === \"General-Purpose\") {\n lines.push(\"allowedAgents: [reviewer]\");\n }\n lines.push(\"---\", \"\");\n if (role.name === \"Explore\") {\n lines.push(\n \"You are a read-only scout. Never modify files. Search first, read second,\",\n \"return the smallest sufficient evidence: file paths, line spans, and short quotes.\",\n );\n } else if (role.name === \"reviewer\") {\n lines.push(\n \"You review a change that already exists. Reproduce failures before diagnosing.\",\n \"Report findings with file:line references; do not rewrite code outside small,\",\n \"clearly-marked suggestions.\",\n );\n } else {\n lines.push(\n \"You implement the scoped task and verify it (run the relevant tests).\",\n \"Hand behavior-changing results to reviewer when asked; otherwise summarize\",\n \"the diff and how it was verified.\",\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.\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]\",\n `model: ${PI_PROVIDER_NAME}/${piOracleModel(profileId)}`,\n `thinking: ${piOracleThinking(profileId)}`,\n \"max_turns: 40\",\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 \"Challenge assumptions, name what is missing, recommend; never execute.\",\n ].join(\"\\n\");\n files[`agents/${agentFileName(\"oracle\")}`] = `${oracle}\\n`;\n // Advisor agent (cheapest only). Balanced stays advisor-free: no file,\n // no skill, no prompt, 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 \"max_turns: 40\",\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 piOracleModel,\n piOracleThinking,\n} from \"./pi-models-settings\"\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\nexport function buildPiExtensionSource(opts: {\n profileId: PiProfileId\n searchEnabled: boolean\n browseEnabled: boolean\n peers?: boolean\n}): string {\n const peers = opts.peers !== false\n const advisor = peers ? piAdvisorModel(opts.profileId) : undefined\n const oracleModel = piOracleModel(opts.profileId)\n const oracleThinking = piOracleThinking(opts.profileId)\n const lines: Array<string> = []\n lines.push(\n `// gh-router-pi extension (${opts.profileId} mode). Generated per launch; do not edit.`,\n `// Executable seams only. Workflow guidance lives in skills/, not here.`,\n `import { Type } from \"typebox\";`,\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 `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 `});`,\n `const BrowserParams = Type.Object({`,\n ` url: Type.Optional(Type.String({ description: \"URL to act on\" })),`,\n ` intent: Type.Optional(Type.String({ description: \"What to do on the page\" })),`,\n `});`,\n `async function toolText(promise) {`,\n ` const text = await promise;`,\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 ...(peers\n ? [\n `const ORACLE_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${oracleModel}`)};`,\n `const ORACLE_THINKING = ${JSON.stringify(oracleThinking)};`,\n ]\n : []),\n ...(advisor\n ? [\n `const ADVISOR_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${advisor.model}`)};`,\n `const ADVISOR_THINKING = ${JSON.stringify(advisor.thinking)};`,\n ]\n : []),\n `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`,\n `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`,\n ``,\n `async function callMcp(group, tool, args, signal) {`,\n ` const res = await fetch(MCP_URL + \"/mcp/\" + group, {`,\n ` method: \"POST\",`,\n ` headers: { \"content-type\": \"application/json\", accept: \"application/json\", authorization: \"Bearer \" + MCP_NONCE },`,\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 ` return await toolText(callMcp(\"peers\", \"oracle\", { decision: params.decision, options: params.options || \"\", context: params.context, model: ORACLE_MODEL, thinking: ORACLE_THINKING }, 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 ` return await toolText(callMcp(\"peers\", \"oracle\", { decision: \"Review this plan (advisory)\", options: params.plan, context: params.context || \"\", model: ADVISOR_MODEL, thinking: ADVISOR_THINKING }, 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 ` return await toolText(callMcp(\"search\", \"code\", { query: params.query, mode: params.mode || \"semantic\", limit: params.limit || 15 }, signal));`,\n ` },`,\n ` });`,\n )\n }\n if (opts.browseEnabled) {\n lines.push(\n ` const BROWSER_TOOLS = [\"browser_open_tab\", \"browser_navigate\", \"browser_screenshot\", \"browser_act\", \"browser_observe\", \"browser_extract\"];`,\n ` for (const wireName of BROWSER_TOOLS) {`,\n ` pi.registerTool({`,\n ` name: wireName,`,\n ` description: \"Browser control (\" + wireName + \"). Returns install_required with setup steps when the extension is not loaded.\",`,\n ` parameters: BrowserParams,`,\n ` async execute(_toolCallId, params, signal) {`,\n ` return await toolText(callMcp(\"browser\", wireName, { url: params.url || \"\", intent: params.intent || \"\" }, signal));`,\n ` },`,\n ` });`,\n ` }`,\n )\n }\n lines.push(\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`. A bare launch emits NO\n * 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.\",\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) {\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 \"Recommended loop: scout (Explore) before you understand the code, worker\",\n \"(General-Purpose) to implement, fresh reviewers to check, worker to apply\",\n \"feedback. Keep delegated tasks 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` emits prompts, so a\n * bare launch advertises none.\n */\nexport function buildPiPrompts(opts: {\n profileId: PiProfileId\n swe?: boolean\n}): Array<PiPromptDoc> {\n if (opts.swe !== true) 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 AIC_USER_STATUSLINE_ENV,\n buildAicStatusHookCommand,\n injectAicStatusLineIntoSettingsFile,\n} from \"./lib/aic-statusline-settings\"\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 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} 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 await writeJsonFile(settingsPath, {\n ...userSettings,\n ...buildPiSettingsJson({ profileId, searchEnabled, browseEnabled, catalog, peers: peersEnabled }),\n })\n\n await writeTextFile(\n path.join(mirror, \"extensions\", \"gh-router-pi\", \"index.ts\"),\n buildPiExtensionSource({ profileId, searchEnabled, browseEnabled, peers: peersEnabled }),\n )\n // Peer floor (agents + consult skills) rides --peers; the SWE\n // pipeline (delegate/advisor skills, review prompts) rides --swe;\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 })) {\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 } 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 via the `pi-statusline`\n // package (Claude-command contract: `internal-aic-status` runs\n // unchanged). The mirror is disposable, so router-wins is safe; a\n // user command is still sidecarred, never executed. Best-effort;\n // opt out with GH_ROUTER_DISABLE_AIC_STATUSLINE=1. Fail-open: a\n // broken runner degrades to no statusline, never a broken launch.\n let aicLedgerEnv: string | undefined\n let aicUserStatuslineEnv: string | undefined\n if (process.env.GH_ROUTER_DISABLE_AIC_STATUSLINE !== \"1\") {\n try {\n void sweepStaleAicLedgerFiles()\n const selfInvocation = await resolveSelfInvocation()\n const statusCommand = buildAicStatusHookCommand(selfInvocation)\n const injected = await injectAicStatusLineIntoSettingsFile(\n path.join(mirror, \"settings.json\"),\n statusCommand,\n { routerWins: true },\n )\n if (injected.written) {\n aicLedgerEnv = aicLedgerPath()\n if (injected.mode === \"wrapped\" && injected.userCommand) {\n aicUserStatuslineEnv = injected.userCommand\n }\n if (injected.mode === \"forced\") {\n consola.info(\n `Pinned status line installed natively for ${profileId}; a pre-existing statusLine was backed up in this launch's isolated settings and will not run.`,\n )\n }\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\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 ...(aicLedgerEnv ? { [AIC_LEDGER_ENV]: aicLedgerEnv } : {}),\n ...(aicUserStatuslineEnv\n ? { [AIC_USER_STATUSLINE_ENV]: aicUserStatuslineEnv }\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;AAC9B,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;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,IAC3F,yBAAyB,KAAK,UAAU,eAAe,KAAK,SAAS,CAAC,EAAE,IACxE,IACA,uDACA,0DACA,uBACA,0HACA,uHACA,eACA,SACA,2FACA,oCACA,4DACA,yDACA,6CACA,0DACA,KACA,IACA,kCACA,GAAI,QACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA,CAAC,CACP;CACA,IAAI,SACF,MAAM,KACJ,uBACA,wBACA,yBACA,sHACA,kCACA,oDACA,wNACA,UACA,OACF;CAEF,IAAI,KAAK,eACP,MAAM,KACJ,uBACA,4BACA,6BACA,kJACA,qCACA,oDACA,wJACA,UACA,OACF;CAEF,IAAI,KAAK,eACP,MAAM,KACJ,gJACA,6CACA,yBACA,yBACA,yIACA,oCACA,sDACA,gIACA,YACA,WACA,KACF;CAEF,MAAM,KACJ,sEACA,yEACA,wDACA,aACA,gDACA,gGACA,qFACA,iBACA,2BACA,SACA,SACA,KACA,EACF;CACA,OAAO,GAAG,MAAM,KAAK,IAAI,EAAE;AAC7B;;;;;;;;AAcA,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;EACF,CAAC,CAAC,KAAK,IAAI;CACb,CAAC;CAEH,IAAI,KAAK,WAAW,MAClB,OAAO,KAAK;EACV,KAAK;EACL,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,IAAI;CACb,CAAC;CAEH,IAAI,KAAK,QAAQ,MAAM;EACrB,OAAO,KAAK;GACV,KAAK;GACL,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,KAAK,cAAc,aACf,gEACA;GACN,CAAC,CAAC,KAAK,IAAI;EACb,CAAC;EACD,IAAI,SAAS,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B,wBAAwB;IACxB,sBAAsB;IACtB,GAAI,eAAe,GAAG,iBAAiB,aAAa,IAAI,CAAC;IACzD,GAAI,uBACA,GAAG,0BAA0B,qBAAqB,IAClD,CAAC;GACP;GACA;GACA,OAAO;GACP;EACF,GACA,QACA,EACE,YAAY,YAAY;GACtB,iBAAiB,MAAM,QAAQ;GAC/B,MAAM,cAAc;GACpB,MAAM,uBAAuB;GAC7B,MAAM,uBAAuB;EAC/B,EACF,CACF;CACF;AACF,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { E as extractZipMember, I as withInstallLock, T as extractTarGzMember } from "./service-backend-7SPDLUB9.js";
2
2
  import { t as PATHS } from "./paths-CpbTHKeP.js";
3
3
  import { i as parseBoolEnv, n as killChildProcessTree, o as resolveExecutable, s as runCommandCapture } from "./exec-MCU1H-KZ.js";
4
- import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, M as satisfiesMinVersion, O as toolbeltSkipSet, j as assetFor, k as vscodeRipgrepPath, un as collapsePathKeys } from "./peer-mcp-personas-CmR3f7nO.js";
4
+ import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, M as satisfiesMinVersion, O as toolbeltSkipSet, j as assetFor, k as vscodeRipgrepPath, un as collapsePathKeys } from "./peer-mcp-personas-Dt0VRKYz.js";
5
5
  import { a as sweepRegistry } from "./lifecycle-kpLzHUgD.js";
6
6
  import consola from "consola";
7
7
  import { existsSync } from "node:fs";
@@ -200,6 +200,9 @@ const STRIPPED_AUTH_ROUTING_ENV_KEYS = [
200
200
  "OPENAI_API_KEY",
201
201
  "OPENAI_BASE_URL",
202
202
  "CODEX_HOME",
203
+ "PI_CODING_AGENT_DIR",
204
+ "PI_CODING_AGENT_SESSION_DIR",
205
+ "OPENCODE_API_KEY",
203
206
  "AIORDIE_CLAUDE_BIND",
204
207
  "AIORDIE_TOKEN",
205
208
  "AIORDIE_INSECURE_TLS"
@@ -327,6 +330,12 @@ function buildLaunchCommand(target) {
327
330
  "claude",
328
331
  "--dangerously-skip-permissions",
329
332
  ...target.extraArgs
333
+ ] : target.kind === "pi" ? [
334
+ "pi",
335
+ "--provider",
336
+ "gh-router",
337
+ ...target.model ? ["--model", target.model] : [],
338
+ ...target.extraArgs
330
339
  ] : buildCodexCmd(target);
331
340
  const resolved = resolveExecutable(cmd[0], { env: process.env });
332
341
  if (resolved) cmd[0] = resolved;
@@ -684,4 +693,4 @@ async function exposedCommands(binDir) {
684
693
  //#endregion
685
694
  export { STRIPPED_AUTH_ROUTING_ENV_KEYS as a, launchChild as i, buildCodexProviderConfigFlags as n, getCodexVersion as r, provisionToolbelt as t };
686
695
 
687
- //# sourceMappingURL=provision-CxulCZpS.js.map
696
+ //# sourceMappingURL=provision-D_aHUCXt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provision-D_aHUCXt.js","names":[],"sources":["../src/lib/process-guard/index.ts","../src/lib/stripped-env-keys.ts","../src/lib/launch.ts","../src/lib/toolbelt/provision.ts"],"sourcesContent":["/**\n * Crash-safe process guard (POSIX only).\n *\n * If the proxy dies WITHOUT running its own shutdown handlers (hard crash,\n * SIGKILL, OOM), nothing in `cleanup()` runs to reap the launched CLI's\n * process tree. This guard is the last-resort net for that case.\n *\n * Platform split:\n * - **Windows: no guard needed.** Node assigns each child to a Job\n * Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, so when the proxy\n * dies (any cause) the OS tears down the whole descendant tree —\n * verified: force-killing a Node parent kills child AND grandchild.\n * `startProcessGuard` is a no-op on win32.\n * - **POSIX: a detached `node -e` reaper.** There is no job-object\n * equivalent (a killed parent's children reparent to init), so we\n * spawn a detached watchdog that learns of proxy death via an inherited\n * stdin PIPE EOF (the proxy holds the write end; the OS closes it on\n * proxy death) and reaps the CLI's process group.\n *\n * Never kill the WRONG process: if the child's PID/PGID was recycled after\n * the child exited, a blind `kill(-pid)` could hit an innocent group. The\n * reaper snapshots the child's process start-time at startup and, on proxy\n * death, kills ONLY if the live PID's start-time still matches. A mismatch\n * / unreadable probe → skip (fail-safe). We never trade an orphan-leak for\n * killing the user's work.\n *\n * The reaper is detached + unref'd so it survives the proxy's SIGKILL, and\n * self-exits once it has acted (or after a 24h cap) so it can never become\n * the orphan it exists to prevent. Opt out with\n * `GH_ROUTER_DISABLE_PROCESS_GUARD=1`.\n */\n\nimport { spawn, type ChildProcess } from \"node:child_process\"\nimport process from \"node:process\"\n\nimport { parseBoolEnv } from \"../exec\"\n\n/**\n * Live reaper children, held so the GC can't collect the `ChildProcess`\n * (and with it the stdin write-end that is the proxy-death signal) while\n * the proxy runs. Entries self-remove on the reaper's exit. We do NOT\n * proactively kill these on graceful shutdown: when the proxy exits the OS\n * closes the stdin pipe, the reaper hits EOF, re-verifies the child's\n * identity, and reaps any survivor that ignored the graceful SIGTERM —\n * exactly the backstop we want.\n */\nconst _activeReapers = new Set<ChildProcess>()\n\n/** Guard is on by default; `GH_ROUTER_DISABLE_PROCESS_GUARD=1` opts out. */\nexport function processGuardEnabled(): boolean {\n return parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROCESS_GUARD) !== true\n}\n\n/**\n * Build the start-time-verified node reaper script (POSIX). PURE — `pid`\n * is our own integer. `detachedGroup` selects `kill(-pid)` (process group,\n * the detached CLI) vs `kill(pid)` on POSIX.\n *\n * Kept dependency-free (require'd builtins only) so it runs under `node -e`\n * with no module resolution against the dist bundle.\n */\nexport function buildNodeReaperScript(\n pid: number,\n detachedGroup: boolean,\n): string {\n const target = detachedGroup ? \"-PID\" : \"PID\"\n return `\nconst cp = require(\"node:child_process\");\nconst fs = require(\"node:fs\");\nconst PID = ${pid >>> 0};\nfunction startTime() {\n try {\n if (process.platform === \"linux\") {\n const stat = fs.readFileSync(\"/proc/\" + PID + \"/stat\", \"utf8\");\n const post = stat.slice(stat.lastIndexOf(\")\") + 1).trim().split(/\\\\s+/);\n return post[19] || null; // field 22 (starttime) = index 19 after comm\n }\n const out = cp.execFileSync(\"ps\", [\"-o\",\"lstart=\",\"-p\",String(PID)],\n { stdio: [\"ignore\",\"pipe\",\"ignore\"], timeout: 2000 }).toString().trim();\n return out || null;\n } catch { return null; }\n}\nfunction alive() { try { process.kill(PID, 0); return true; } catch { return false; } }\nfunction treeKill() {\n try { process.kill(${target}, \"SIGTERM\"); } catch {}\n // NOT unref'd: this must keep the loop alive to deliver the escalated\n // SIGKILL (the onDeath exit timer below stays alive past 500ms too).\n setTimeout(() => { try { process.kill(${target}, \"SIGKILL\"); } catch {} }, 500);\n}\nconst snap = (() => {\n // The child is definitely ours and alive at startup, so a null here is a\n // transient probe failure (e.g. a momentary 'ps' hiccup), NOT a real\n // identity loss. Retry a few times so a one-off failure can't silently\n // disable the guard for the rest of the run.\n for (let i = 0; i < 3; i++) { const s = startTime(); if (s !== null) return s; }\n return null;\n})();\nlet done = false;\nfunction onDeath() {\n if (done) return; done = true;\n // Re-verify identity: kill ONLY if the live PID is still our child.\n if (snap !== null && alive() && startTime() === snap) treeKill();\n // REF'd (NOT unref'd): stdin has closed, so an unref'd timer would let\n // the loop empty and the process exit immediately — dropping the 500ms\n // SIGKILL escalation. Keep the loop alive to deliver it, then exit.\n setTimeout(() => process.exit(0), 1500);\n}\nprocess.stdin.resume();\nprocess.stdin.on(\"end\", onDeath);\nprocess.stdin.on(\"close\", onDeath);\nprocess.stdin.on(\"error\", onDeath);\nconst cap = setTimeout(() => process.exit(0), 24*3600*1000); if (cap.unref) cap.unref();\n`.trim()\n}\n\n/**\n * Spawn the detached node reaper holding the stdin death-pipe. Always\n * `detached` so it outlives a force-kill of the proxy, and `unref`'d so it\n * never holds the proxy's event loop open. Returns null on spawn failure.\n */\nfunction spawnNodeReaper(pid: number, detachedGroup: boolean): ChildProcess | null {\n try {\n const child = spawn(\n process.execPath,\n [\"-e\", buildNodeReaperScript(pid, detachedGroup)],\n {\n stdio: [\"pipe\", \"ignore\", \"ignore\"],\n detached: true,\n windowsHide: true,\n shell: false,\n },\n )\n child.on(\"error\", () => {})\n child.stdin?.on(\"error\", () => {})\n // Hold a reference so the GC can't drop the ChildProcess (and its stdin\n // write-end, the proxy-death signal) mid-run; drop it on reaper exit.\n _activeReapers.add(child)\n child.once(\"exit\", () => _activeReapers.delete(child))\n child.unref()\n return child\n } catch {\n return null\n }\n}\n\n/**\n * Start the crash-safe guard for a launched CLI child. No-op on Windows\n * (Node's Job Object already reaps the tree on proxy death) and when\n * disabled / unspawnable. Fire-and-forget; never throws.\n */\nexport function startProcessGuard(child: ChildProcess): void {\n if (!processGuardEnabled()) return\n const pid = child.pid\n if (!pid) return\n // Windows: the runtime's KILL_ON_JOB_CLOSE job object is the crash net.\n if (process.platform === \"win32\") return\n // POSIX: the CLI is spawned detached (own group), so reap the group.\n spawnNodeReaper(pid, true)\n}\n","/**\n * Auth / routing / remote / wire-fingerprint environment keys that must never\n * reach a github-router-spawned Claude or Codex child — through ANY channel.\n *\n * Two channels carry these keys to a spawned agent, and both must be defended:\n * 1. The PARENT PROCESS ENV — a user's shell exports. Stripped by\n * `sanitizeParentEnv` (`src/lib/launch.ts`) before the proxy's overrides.\n * 2. The serve mirror `settings.json` `env` BLOCK — a user's own\n * `~/.claude/settings.json`, snapshot-mirrored and applied to the\n * SDK-spawned claude via `settingSources`. Stripped by\n * `sanitizeServeSettingsEnv` (`src/lib/mcp-permissions-settings.ts`).\n *\n * If any of these survived, a Bedrock/Vertex/gateway user's config would\n * re-route the session OFF the github-router proxy, inject real auth that wins\n * over the synthetic `.credentials.json`, or activate Claude Code's\n * unimplemented Bridge/remote code path. `CLAUDE_CODE_COORDINATOR_MODE` (a\n * toolset-stripper) is NOT here — it's serve-specific, added to the serve list\n * directly. `ANTHROPIC_SMALL_FAST_MODEL` is deliberately NOT stripped (users\n * legitimately rely on it; `resolveModel` translates unrecognized values).\n */\nexport const STRIPPED_AUTH_ROUTING_ENV_KEYS = [\n // Claude Code auth surface\n \"ANTHROPIC_API_KEY\",\n \"ANTHROPIC_AUTH_TOKEN\",\n \"ANTHROPIC_BASE_URL\",\n \"ANTHROPIC_CUSTOM_HEADERS\",\n \"ANTHROPIC_MODEL\",\n \"CLAUDE_CODE_OAUTH_TOKEN\",\n // Alternate OAuth source (loads from an open file descriptor); stripping\n // prevents a third auth source alongside the synthetic .credentials.json.\n \"CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR\",\n \"CLAUDE_CODE_USE_BEDROCK\",\n \"CLAUDE_CODE_USE_VERTEX\",\n \"CLAUDE_CODE_USE_FOUNDRY\",\n // Defense-in-depth: a parent- or settings-set CLAUDE_CONFIG_DIR would\n // redirect the session's config dir away from the router-owned mirror.\n \"CLAUDE_CONFIG_DIR\",\n // Claude Code Bridge / IDE remote-session surface — activates a remote code\n // path (POST /v1/code/sessions, /v1/environments/bridge, …) the proxy does\n // not implement. Stripping forces a local-only session.\n \"CLAUDE_BRIDGE_OAUTH_TOKEN\",\n \"CLAUDE_BRIDGE_BASE_URL\",\n \"CLAUDE_BRIDGE_SESSION_INGRESS_URL\",\n \"SESSION_INGRESS_URL\",\n \"CLAUDE_CODE_REMOTE\",\n \"CLAUDE_CODE_CONTAINER_ID\",\n \"CLAUDE_CODE_REMOTE_SESSION_ID\",\n \"CLAUDE_CODE_SESSION_ID\",\n // Emits `x-anthropic-additional-protection` — pure wire-fingerprint noise\n // that breaks the VS Code stealth posture.\n \"CLAUDE_CODE_ADDITIONAL_PROTECTION\",\n // Optional Bluebird MCP bearer override. The router may consume it, but the\n // spawned CLI and its descendant tools/MCPs must never inherit it.\n \"BLUEBIRD_TOKEN\",\n // Codex CLI auth surface\n \"OPENAI_API_KEY\",\n \"OPENAI_BASE_URL\",\n \"CODEX_HOME\",\n // Pi coding-agent routing/auth surface. `PI_CODING_AGENT_DIR` would\n // redirect the session's agent dir away from the router-owned mirror;\n // provider keys would re-route Pi off the proxy or leak real auth.\n \"PI_CODING_AGENT_DIR\",\n \"PI_CODING_AGENT_SESSION_DIR\",\n \"OPENCODE_API_KEY\",\n // ai-or-die per-tab session-bind / artifact-review surface — must not leak\n // into a nested launch and hijack the parent tab's sidecar / bearer token.\n \"AIORDIE_CLAUDE_BIND\",\n \"AIORDIE_TOKEN\",\n \"AIORDIE_INSECURE_TLS\",\n] as const\n","import { execFileSync, spawn, type ChildProcess } from \"node:child_process\"\nimport { existsSync } from \"node:fs\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport type { Server } from \"srvx\"\n\nimport { resolveExecutable, killChildProcessTree } from \"./exec\"\nimport { DEFAULT_CODEX_MODEL } from \"./port\"\nimport { startProcessGuard } from \"./process-guard\"\nimport { STRIPPED_AUTH_ROUTING_ENV_KEYS } from \"./stripped-env-keys\"\nimport { collapsePathKeys } from \"./toolbelt/path-inject\"\nimport { sweepRegistry } from \"./worker-agent/lifecycle\"\n\n/**\n * Auth-related env keys we strip from the parent before spawning the child CLI.\n * The proxy provides its own values for everything we care about, so the child\n * behaves as if the user had no parent-env auth at all. The canonical list lives\n * in `./stripped-env-keys` (shared with serve's settings.json `env` strip).\n *\n * Why strip rather than override-with-empty-string: Claude Code emits \"Auth\n * conflict\" warnings whenever both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY\n * are present (any value); stripping suppresses it AND prevents an inherited\n * real key from leaking. Cloud-provider toggles + OAuth tokens are simpler\n * dropped than overridden — a missing var is unambiguously absent everywhere.\n */\nconst STRIPPED_PARENT_ENV_KEYS = STRIPPED_AUTH_ROUTING_ENV_KEYS\n\n/**\n * Strip auth-related keys from a parent-process env object. The result\n * is suitable to spread into a spawned child's env BEFORE the proxy's\n * explicit overrides, so the proxy is the only source of truth for\n * auth — and stale shell exports can't leak through.\n */\nexport function sanitizeParentEnv(\n parent: NodeJS.ProcessEnv,\n): NodeJS.ProcessEnv {\n const sanitized: NodeJS.ProcessEnv = { ...parent }\n for (const key of STRIPPED_PARENT_ENV_KEYS) {\n delete sanitized[key]\n }\n return sanitized\n}\n\nfunction commandExists(name: string): boolean {\n try {\n execFileSync(process.platform === \"win32\" ? \"where.exe\" : \"which\", [name], {\n stdio: \"ignore\",\n })\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Whether the launcher can execute `executable`.\n *\n * `buildLaunchCommand` resolves the CLI to an ABSOLUTE path (anti-shadow).\n * `where.exe` (and POSIX `which`) reject a full path argument — `where`\n * returns \"Could not find files for the given pattern(s)\" for an absolute\n * path even when the file exists — so the where/which probe is only valid\n * for bare command names. For an absolute path (already resolved against\n * PATH and existence-checked by `resolveExecutable`), check the\n * filesystem directly. Without this split, every launch where the CLI is\n * installed fails with a spurious \"not found on PATH\".\n */\nexport function isExecutableAvailable(executable: string): boolean {\n if (path.isAbsolute(executable)) return existsSync(executable)\n return commandExists(executable)\n}\n\n/**\n * Provider-config flags (`-c model_providers.github_router=...`) that\n * point Codex at our proxy. Extracted from `buildCodexCmd` so the new\n * `codex mcp-server` MCP-config builder can reuse the exact same\n * provider definition — drift between the two paths would silently\n * break the MCP wiring.\n */\nexport function buildCodexProviderConfigFlags(serverUrl: string): Array<string> {\n return [\n \"-c\",\n `model_providers.github_router={name=\"github-router\",base_url=\"${serverUrl}/v1\",wire_api=\"responses\",env_key=\"OPENAI_API_KEY\"}`,\n \"-c\",\n \"model_provider=github_router\",\n ]\n}\n\n/**\n * Inspect the installed `codex` binary. Used by the codex-MCP wiring\n * in `claude.ts` to gate `--codex-cli`. Codex 0.129.0 introduced the\n * `mcp-server` subcommand; older versions don't expose it, so we\n * downgrade to the HTTP backend with a warning.\n */\nexport function getCodexVersion(): { ok: boolean; version?: string } {\n if (!commandExists(\"codex\")) return { ok: false }\n let raw: string\n try {\n raw = execFileSync(\"codex\", [\"--version\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim()\n } catch {\n return { ok: false }\n }\n // Output examples: \"codex-cli 0.129.0\", \"codex 0.130.1-dev\"\n const m = /(\\d+)\\.(\\d+)\\.(\\d+)/.exec(raw)\n if (!m) return { ok: false, version: raw }\n const major = Number.parseInt(m[1], 10)\n const minor = Number.parseInt(m[2], 10)\n const version = `${m[1]}.${m[2]}.${m[3]}`\n // mcp-server requires codex >= 0.129.0\n const ok = major > 0 || (major === 0 && minor >= 129)\n return { ok, version }\n}\n\nexport interface LaunchTarget {\n kind: \"claude-code\" | \"codex\" | \"pi\"\n envVars: Record<string, string>\n extraArgs: string[]\n model?: string\n /**\n * Proxy URL the spawned child should target. Required for Codex 0.129+\n * which stopped honoring OPENAI_BASE_URL and now needs an explicit\n * `-c model_providers.<name>.base_url=...` argument. Set by the codex\n * subcommand from the same `serverUrl` it computed for env vars.\n */\n serverUrl?: string\n}\n\n/**\n * Codex 0.129.0 broke two things the launcher had been relying on:\n * (1) `--full-auto` was removed in favor of `--sandbox` + `--ask-for-approval`;\n * passing it now exits the child immediately with\n * `error: unexpected argument '--full-auto' found`.\n * (2) `OPENAI_BASE_URL` is silently ignored — Codex hardcodes\n * `https://api.openai.com/v1/responses` and 401s out without an\n * explicit `-c model_providers.<name>.base_url` override.\n *\n * `buildCodexCmd` builds the launch argv that works on Codex 0.129+ while\n * still being compatible with older versions that accept the same flags.\n */\nfunction buildCodexCmd(target: LaunchTarget): string[] {\n const cmd: string[] = [\"codex\"]\n if (target.serverUrl) {\n cmd.push(...buildCodexProviderConfigFlags(target.serverUrl))\n }\n cmd.push(\n \"--sandbox\",\n \"workspace-write\",\n \"--ask-for-approval\",\n \"on-request\",\n \"-m\",\n target.model ?? DEFAULT_CODEX_MODEL,\n ...target.extraArgs,\n )\n return cmd\n}\n\nexport function buildLaunchCommand(target: LaunchTarget): {\n cmd: string[]\n env: Record<string, string | undefined>\n} {\n // F10: don't force `--dangerously-skip-permissions` when the caller already\n // requested an explicit `--permission-mode` (e.g. ai-or-die's claude-bridge\n // appends one for a fleet create_session with permissionMode). The two flags\n // conflict — claude rejects them together — and the explicit mode must win.\n const wantsPermissionMode =\n target.kind === \"claude-code\" &&\n target.extraArgs.some((arg) => arg === \"--permission-mode\" || arg.startsWith(\"--permission-mode=\"))\n const cmd: string[] =\n target.kind === \"claude-code\"\n ? wantsPermissionMode\n ? [\"claude\", ...target.extraArgs]\n : [\"claude\", \"--dangerously-skip-permissions\", ...target.extraArgs]\n : target.kind === \"pi\"\n ? [\n \"pi\",\n \"--provider\",\n \"gh-router\",\n ...(target.model ? [\"--model\", target.model] : []),\n ...target.extraArgs,\n ]\n : buildCodexCmd(target)\n\n // Anti-shadow: resolve the top-level CLI to an ABSOLUTE path against\n // the clean parent PATH (excluding the cwd). The spawned child's env\n // prepends the toolbelt bin dir to PATH; without this, a stray\n // `claude.cmd`/`codex.cmd` in that dir — or in an untrusted repo's cwd\n // (Windows resolves cwd before PATH under shell:true) — could shadow\n // the real CLI. Resolving here means the toolbelt PATH only affects\n // the agent's OWN tool lookups, never which CLI we launch.\n const resolved = resolveExecutable(cmd[0], { env: process.env })\n if (resolved) cmd[0] = resolved\n\n const env = collapsePathKeys({\n ...sanitizeParentEnv(process.env),\n ...target.envVars,\n })\n return { cmd, env }\n}\n\n/**\n * Whether a resolved Windows executable must be launched through cmd.exe\n * (`shell:true`). Only batch shims (`.cmd`/`.bat`) need it — and even then\n * cmd.exe stays alive as the CLI's parent, so `taskkill /T` reaps the\n * whole tree. A real `.exe` (e.g. the native-installer `claude.exe`) is\n * spawned DIRECTLY so the CLI is the direct child, with no cmd.exe\n * intermediary to orphan its node/MCP grandchildren on a kill.\n */\nexport function windowsLaunchNeedsShell(executable: string): boolean {\n const ext = path.extname(executable).toLowerCase()\n return ext === \".cmd\" || ext === \".bat\"\n}\n\nexport function launchChild(\n target: LaunchTarget,\n server: Server,\n options: {\n onShutdown?: () => Promise<void> | void\n /**\n * Optional exit summary (e.g. the AIC session total). Called once from\n * `exit()`, after cleanup, on every shutdown path (natural child exit,\n * signal escalation, spawn error). Return undefined for no output.\n * Best-effort: throwing content is swallowed so shutdown never blocks.\n */\n onExitSummary?: () => string | undefined\n } = {},\n): void {\n const { cmd, env } = buildLaunchCommand(target)\n\n const executable = cmd[0]\n if (!isExecutableAvailable(executable)) {\n const msg = `\"${executable}\" not found on PATH. Install it first, then try again.`\n consola.error(msg)\n process.stderr.write(msg + \"\\n\")\n process.exit(1)\n }\n\n let child: ChildProcess\n try {\n if (process.platform === \"win32\") {\n if (windowsLaunchNeedsShell(cmd[0])) {\n // A batch shim genuinely needs cmd.exe. cmd.exe stays alive as the\n // CLI's parent for the shim's lifetime, so the tree-kill (taskkill\n // /T) and the crash guard both reap the whole tree through it. Use\n // the full command as a single string to avoid the DEP0190\n // deprecation warning about shell + args.\n const quoted = cmd.map((a) => (a.includes(\" \") ? `\"${a}\"` : a)).join(\" \")\n child = spawn(quoted, [], {\n env,\n stdio: \"inherit\",\n shell: true,\n })\n } else {\n // A real .exe (e.g. the native-installer claude.exe) needs no\n // shell. Spawning it directly makes the CLI the DIRECT child, so\n // child.kill()/taskkill and the crash guard target the real\n // process instead of a cmd.exe wrapper that would orphan its\n // node/MCP grandchildren.\n child = spawn(cmd[0], cmd.slice(1), {\n env,\n stdio: \"inherit\",\n })\n }\n } else {\n // detached:true → the CLI leads its OWN process group, so cleanup()\n // can kill(-pgid) the whole tree (grandchildren included). We still\n // await its exit, so we do NOT unref(). Terminal Ctrl-C no longer\n // reaches the child directly — the signal handlers below forward it.\n child = spawn(cmd[0], cmd.slice(1), {\n env,\n stdio: \"inherit\",\n detached: true,\n })\n }\n } catch (error) {\n const msg = `Failed to launch ${executable}: ${error instanceof Error ? error.message : String(error)}`\n consola.error(msg)\n process.stderr.write(msg + \"\\n\")\n server.close(true).catch(() => {})\n if (options.onShutdown) {\n void Promise.resolve(options.onShutdown()).catch(() => {})\n }\n process.exit(1)\n }\n\n // Crash-safe net: if the proxy dies WITHOUT running cleanup() (hard\n // crash, SIGKILL/taskkill, OOM). On Windows this is the OS's job —\n // Node's KILL_ON_JOB_CLOSE job object reaps the tree — so this is a\n // no-op there. On POSIX (no such mechanism) it spawns a detached reaper\n // that sees the proxy's stdin-pipe EOF, re-verifies the child's\n // identity, and reaps the group (also backstopping a graceful shutdown\n // where the child ignores SIGTERM and the proxy exits before the\n // escalation lands). Fire-and-forget; self-acts and self-exits.\n startProcessGuard(child)\n\n let cleaned = false\n let exiting = false\n async function cleanup(): Promise<void> {\n if (cleaned) return\n cleaned = true\n\n // Arm the hard fail-safe FIRST, before any (potentially blocking) kill\n // or async teardown, so a wedged taskkill / server.close can't hang\n // shutdown indefinitely.\n const timeout = setTimeout(() => process.exit(1), 5000)\n\n // Tree-kill the whole CLI subtree, not just the direct child. On\n // Windows taskkill /T reaps grandchildren; on POSIX kill(-pgid) reaps\n // the detached process group. (Replaces a plain child.kill() that\n // orphaned node/MCP grandchildren on Windows.) A SIGTERM-ignoring\n // survivor that outlives our exit is caught by the crash guard above.\n try {\n killChildProcessTree(child, {\n detachedGroup: process.platform !== \"win32\",\n })\n } catch {\n // Already exited / best-effort.\n }\n\n try {\n await server.close(true)\n } catch {\n // Server already closed\n }\n if (options.onShutdown) {\n try {\n await options.onShutdown()\n } catch {\n // Best-effort cleanup; shutdown must not be blocked by it.\n }\n }\n clearTimeout(timeout)\n }\n\n function exit(code: number): void {\n if (exiting) return\n exiting = true\n try {\n const summary = options.onExitSummary?.()\n if (summary) process.stderr.write(`\\n${summary}\\n`)\n } catch {\n // Best-effort summary; never block shutdown.\n }\n process.exit(code)\n }\n\n // On POSIX the CLI is in its own process group (detached), so terminal\n // Ctrl-C reaches only the proxy. Forward the signal to the child group\n // so the CLI's own interactive handler runs (e.g. Claude's \"press\n // Ctrl-C again to exit\"); let its natural exit drive shutdown and\n // escalate to a hard tree-kill only if it ignores us past a grace.\n let forwardGrace: NodeJS.Timeout | null = null\n const lastForwardAt: Record<\"SIGINT\" | \"SIGTERM\", number> = {\n SIGINT: 0,\n SIGTERM: 0,\n }\n const onSignal = (sig: \"SIGINT\" | \"SIGTERM\") => {\n if (process.platform !== \"win32\" && child.pid && !cleaned) {\n // Debounce PER SIGNAL a sub-second burst into ONE forward. The other\n // subsystem signal handlers (keep-awake/colbert/worker/browser)\n // re-raise the SAME signal to restore default-terminate, which\n // re-invokes us several times within milliseconds — without this the\n // child would receive a volley and Claude's \"press Ctrl-C again\"\n // guard would never see a single press. Per-signal so a SIGTERM right\n // after a SIGINT still forwards. A genuine second human Ctrl-C\n // (seconds later) falls outside the window and forwards again.\n const now = Date.now()\n if (now - lastForwardAt[sig] > 250) {\n lastForwardAt[sig] = now\n try {\n process.kill(-child.pid, sig)\n } catch {\n // group already gone — fall through to the grace escalation\n }\n }\n const graceMs = sig === \"SIGINT\" ? 10000 : 3000\n if (!forwardGrace) {\n forwardGrace = setTimeout(() => {\n cleanup().then(() => exit(130)).catch(() => exit(1))\n }, graceMs)\n forwardGrace.unref?.()\n }\n return\n }\n // Windows: the console already delivered Ctrl-C to the direct child;\n // cleanup()'s taskkill /T is the escalation hammer.\n cleanup().then(() => exit(130)).catch(() => exit(1))\n }\n process.on(\"SIGINT\", () => onSignal(\"SIGINT\"))\n process.on(\"SIGTERM\", () => onSignal(\"SIGTERM\"))\n\n child.on(\"exit\", (exitCode, signal) => {\n // When the spawned CLI exits we may be holding worker-agent\n // worktrees that the proxy will never get a chance to clean up\n // through the per-call finally (the proxy itself is about to\n // shut down). Drain them synchronously here — same sweep the\n // SIGINT/SIGTERM handlers use. No-op if no worker tools were\n // ever invoked (registry is null).\n try {\n sweepRegistry()\n } catch {\n // best-effort; don't let cleanup failures override the exit code\n }\n // When killed by a signal, exitCode is null — derive from signal number\n const code = exitCode ?? (signal ? 128 : 1)\n cleanup().then(() => exit(code)).catch(() => exit(1))\n })\n child.on(\"error\", () => {\n cleanup().then(() => exit(1)).catch(() => exit(1))\n })\n}\n","/**\n * Toolbelt provisioner: materialize curated CLI tools into the durable\n * router `bin/` dir so the spawned agent can call them on PATH.\n *\n * Properties (all load-bearing):\n * - **Best-effort.** Every tool is isolated in try/catch; a failure\n * skips that one tool and never throws to the launcher.\n * - **Gap-fill.** A tool already on the user's PATH is NOT\n * materialized (and a stale copy is removed) so we never shadow the\n * user's own `jq`/`yq`/etc.\n * - **Verified.** The downloaded archive's SHA256 must match the\n * hardcoded manifest digest BEFORE extraction.\n * - **Safe extraction.** Only the expected regular-file binary is\n * pulled out; symlink/hardlink/device entries are rejected.\n * - **Concurrency-safe.** A cross-process lock serializes writers;\n * unique temp names + atomic rename avoid half-written binaries.\n * - **Integrity-pruned.** Unexpected files in `bin/` are removed each\n * launch so a prompt-injected agent can't plant a `git.cmd` that\n * shadows real tools in future sessions.\n */\n\nimport { randomBytes, createHash } from \"node:crypto\"\nimport { existsSync } from \"node:fs\"\nimport {\n chmod,\n copyFile,\n link,\n mkdir,\n readdir,\n readFile,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { resolveExecutable, runCommandCapture } from \"../exec\"\nimport { PATHS } from \"../paths\"\nimport { withInstallLock } from \"../update-lock\"\n\nimport { extractTarGzMember, extractZipMember } from \"./extract\"\nimport { toolbeltEnabled, toolbeltSkipSet, vscodeRipgrepPath } from \"./index\"\nimport { assetFor, satisfiesMinVersion, TOOLBELT_TOOLS, type ToolAsset, type ToolSpec } from \"./manifest\"\n\n/** Per-download cap (bytes) — these binaries are a few MB at most. */\nconst MAX_DOWNLOAD_BYTES = 64 * 1024 * 1024\nconst DOWNLOAD_TIMEOUT_MS = 30_000\n\nconst EXE_EXT = process.platform === \"win32\" ? \".exe\" : \"\"\n\n/**\n * Materialize the toolbelt. Returns the list of command names exposed\n * in `bin/` after provisioning. Best-effort; never throws.\n */\nexport async function provisionToolbelt(): Promise<string[]> {\n if (!toolbeltEnabled()) return []\n const binDir = PATHS.TOOLBELT_BIN_DIR\n try {\n await mkdir(binDir, { recursive: true })\n } catch (err) {\n consola.debug(\"toolbelt: could not create bin dir:\", err)\n return []\n }\n\n const skip = toolbeltSkipSet()\n\n // Serialize across concurrent proxies. If another process holds the\n // lock it is provisioning; we skip and just report current state.\n await withInstallLock(\"toolbelt.lock\", async () => {\n await pruneUnexpected(binDir)\n await provisionRg(binDir, skip).catch((err) =>\n consola.debug(\"toolbelt: rg skipped:\", err),\n )\n await Promise.all(\n TOOLBELT_TOOLS.map((spec) =>\n provisionTool(spec, binDir, skip).catch((err) =>\n consola.debug(`toolbelt: ${spec.command} skipped:`, err),\n ),\n ),\n )\n })\n\n return exposedCommands(binDir)\n}\n\n/** Names allowed to live in `bin/` (managed binaries + their sidecars). */\nfunction expectedFileNames(): Set<string> {\n const names = new Set<string>()\n const add = (base: string) => {\n names.add(base + EXE_EXT)\n names.add(`${base}${EXE_EXT}.sha256`)\n }\n add(\"rg\")\n for (const spec of TOOLBELT_TOOLS) {\n add(spec.binBasename)\n for (const a of spec.aliases ?? []) add(a)\n }\n return names\n}\n\n/** Remove any file in `bin/` that isn't a managed binary or sidecar. */\nasync function pruneUnexpected(binDir: string): Promise<void> {\n const expected = expectedFileNames()\n let entries: string[]\n try {\n entries = await readdir(binDir)\n } catch {\n return\n }\n for (const name of entries) {\n if (name.endsWith(\".tmp\")) continue // in-flight temp from a peer\n if (!expected.has(name)) {\n await rm(path.join(binDir, name), { force: true }).catch(() => {})\n }\n }\n}\n\nasync function provisionRg(binDir: string, skip: Set<string>): Promise<void> {\n const dest = path.join(binDir, \"rg\" + EXE_EXT)\n if (skip.has(\"rg\") || resolveExecutable(\"rg\")) {\n // User has rg (or skipped) — don't shadow it. code_search uses its\n // own resolver regardless.\n await removeBin(dest)\n return\n }\n if (existsSync(dest)) return // already materialized\n const src = vscodeRipgrepPath()\n if (!src) return\n\n const tmp = tempName(dest)\n try {\n await link(src, tmp) // hardlink (same-volume fast path)\n } catch {\n await copyFile(src, tmp) // cross-volume (EXDEV) or other → copy\n }\n if (process.platform !== \"win32\") await chmod(tmp, 0o755).catch(() => {})\n await commit(tmp, dest)\n}\n\n/**\n * Does the user's own copy on PATH satisfy `spec.minVersion`?\n *\n * Returns true when there is nothing to check (no minVersion), and — this\n * is the load-bearing part — ALSO returns true when the probe fails or the\n * output cannot be parsed. Gap-fill exists so we never shadow a user's\n * pinned or wrapper install, and an unreadable `--version` is not evidence\n * that their tool is inadequate. We only step in front of it on positive\n * proof that it is too old.\n */\nasync function pathCopyIsAdequate(spec: ToolSpec, resolved: string): Promise<boolean> {\n if (!spec.minVersion) return true\n try {\n // `runCommandCapture`, NOT `runManagedExeCapture`: on Windows a tool\n // installed via npm resolves to a `.cmd` shim, which cannot be spawned\n // with `shell:false` (it throws EINVAL). That is exactly how the\n // ast-grep case presented — the probe threw, we treated the version as\n // unknown, and yielded to the outdated copy anyway. runCommandCapture\n // goes through buildExecInvocation, which routes shims via cmd.exe.\n const res = await runCommandCapture([resolved, \"--version\"], {\n timeoutMs: VERSION_PROBE_TIMEOUT_MS,\n })\n const verdict = satisfiesMinVersion(`${res.stdout} ${res.stderr}`, spec.minVersion)\n if (verdict === undefined) return true\n if (!verdict) {\n consola.debug(\n `[toolbelt] ${spec.command} on PATH is older than ${spec.minVersion}; using the router-pinned build instead`,\n )\n }\n return verdict\n } catch {\n return true\n }\n}\n\n/** A `--version` call should be instant; this only bounds a hung binary. */\nconst VERSION_PROBE_TIMEOUT_MS = 5_000\n\nasync function provisionTool(\n spec: ToolSpec,\n binDir: string,\n skip: Set<string>,\n): Promise<void> {\n const dest = path.join(binDir, spec.binBasename + EXE_EXT)\n const sidecar = `${dest}.sha256`\n const asset = assetFor(spec)\n\n if (skip.has(spec.command) || !asset) {\n await removeTool(spec, binDir)\n return\n }\n // Gap-fill: user already has it on PATH → remove ours, don't shadow.\n // Exception: a tool carrying `minVersion` is one this project's own code\n // depends on, so an older PATH copy is not \"good enough\" — it degrades\n // us silently. In that case we materialize ours anyway; the toolbelt bin\n // is prepended to the spawned agent's PATH and code_search checks the\n // router-owned paths first, so ours wins where it matters while the\n // user's shell keeps theirs.\n const onPath = resolveExecutable(spec.command)\n if (onPath && (await pathCopyIsAdequate(spec, onPath))) {\n await removeTool(spec, binDir)\n return\n }\n // Idempotent: present + sidecar matches → just ensure aliases exist.\n if (existsSync(dest) && (await sidecarMatches(sidecar, asset.sha256))) {\n await ensureAliases(spec, binDir, dest)\n return\n }\n\n const bytes = await downloadAndExtract(spec, asset)\n await atomicInstall(dest, bytes)\n await writeFile(sidecar, asset.sha256).catch(() => {})\n await ensureAliases(spec, binDir, dest)\n}\n\nasync function downloadAndExtract(\n spec: ToolSpec,\n asset: ToolAsset,\n): Promise<Buffer> {\n const data = await download(asset.url)\n const digest = createHash(\"sha256\").update(data).digest(\"hex\")\n if (digest !== asset.sha256) {\n throw new Error(\n `checksum mismatch for ${spec.command} (${asset.url}): expected ${asset.sha256}, got ${digest}`,\n )\n }\n if (asset.archive === \"raw\") return data\n const member =\n asset.archive === \"zip\"\n ? extractZipMember(data, spec.binBasename)\n : extractTarGzMember(data, spec.binBasename)\n if (!member) {\n throw new Error(`binary \"${spec.binBasename}\" not found in ${asset.url}`)\n }\n return member\n}\n\nasync function download(url: string): Promise<Buffer> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS)\n try {\n const res = await fetch(url, {\n signal: controller.signal,\n redirect: \"follow\",\n headers: { \"User-Agent\": \"github-router-toolbelt\" },\n })\n if (!res.ok) throw new Error(`download ${url}: HTTP ${res.status}`)\n const buf = Buffer.from(await res.arrayBuffer())\n if (buf.length > MAX_DOWNLOAD_BYTES) {\n throw new Error(`download ${url}: exceeds ${MAX_DOWNLOAD_BYTES} bytes`)\n }\n return buf\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** Write to a unique temp then atomically rename into place. */\nasync function atomicInstall(dest: string, bytes: Buffer): Promise<void> {\n const tmp = tempName(dest)\n await writeFile(tmp, bytes)\n if (process.platform !== \"win32\") await chmod(tmp, 0o755).catch(() => {})\n await commit(tmp, dest)\n}\n\n/** Rename tmp→dest, handling Windows replace-existing / in-use locks. */\nasync function commit(tmp: string, dest: string): Promise<void> {\n try {\n await rename(tmp, dest)\n } catch {\n // Windows: rename won't replace an existing/locked dest. Remove and\n // retry once; if that fails (in-use .exe), leave the existing copy.\n try {\n await rm(dest, { force: true })\n await rename(tmp, dest)\n } catch (err) {\n await rm(tmp, { force: true }).catch(() => {})\n throw err\n }\n }\n}\n\nasync function ensureAliases(\n spec: ToolSpec,\n binDir: string,\n dest: string,\n): Promise<void> {\n for (const alias of spec.aliases ?? []) {\n const ap = path.join(binDir, alias + EXE_EXT)\n if (existsSync(ap)) continue\n const tmp = tempName(ap)\n try {\n await copyFile(dest, tmp)\n if (process.platform !== \"win32\") await chmod(tmp, 0o755).catch(() => {})\n await commit(tmp, ap)\n } catch (err) {\n consola.debug(`toolbelt: alias ${alias} skipped:`, err)\n }\n }\n}\n\nasync function removeTool(spec: ToolSpec, binDir: string): Promise<void> {\n const dest = path.join(binDir, spec.binBasename + EXE_EXT)\n await removeBin(dest)\n for (const alias of spec.aliases ?? []) {\n await removeBin(path.join(binDir, alias + EXE_EXT))\n }\n}\n\nasync function removeBin(dest: string): Promise<void> {\n await rm(dest, { force: true }).catch(() => {})\n await rm(`${dest}.sha256`, { force: true }).catch(() => {})\n}\n\nasync function sidecarMatches(sidecar: string, sha256: string): Promise<boolean> {\n try {\n return (await readFile(sidecar, \"utf8\")).trim() === sha256\n } catch {\n return false\n }\n}\n\nfunction tempName(dest: string): string {\n return `${dest}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n}\n\n/** The command names currently exposed in `bin/`. */\nasync function exposedCommands(binDir: string): Promise<string[]> {\n let files: Set<string>\n try {\n files = new Set(await readdir(binDir))\n } catch {\n return []\n }\n const present = (base: string) => files.has(base + EXE_EXT)\n const out: string[] = []\n if (present(\"rg\")) out.push(\"rg\")\n for (const spec of TOOLBELT_TOOLS) {\n if (present(spec.binBasename)) out.push(spec.command)\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,iCAAiB,IAAI,IAAkB;;AAG7C,SAAgB,sBAA+B;CAC7C,OAAO,aAAa,QAAQ,IAAI,+BAA+B,MAAM;AACvE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AO,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;CAC9C,MAAM,GAAG,GAAG,KAAK,UAAU,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;AAC5D;AAEA,eAAe,eAAe,SAAiB,QAAkC;CAC/E,IAAI;EACF,QAAQ,MAAM,SAAS,SAAS,MAAM,EAAA,CAAG,KAAK,MAAM;CACtD,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,SAAS,MAAsB;CACtC,OAAO,GAAG,KAAK,GAAG,QAAQ,IAAI,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;AAClE;;AAGA,eAAe,gBAAgB,QAAmC;CAChE,IAAI;CACJ,IAAI;EACF,QAAQ,IAAI,IAAI,MAAM,QAAQ,MAAM,CAAC;CACvC,QAAQ;EACN,OAAO,CAAC;CACV;CACA,MAAM,WAAW,SAAiB,MAAM,IAAI,OAAO,OAAO;CAC1D,MAAM,MAAgB,CAAC;CACvB,IAAI,QAAQ,IAAI,GAAG,IAAI,KAAK,IAAI;CAChC,KAAK,MAAM,QAAQ,gBACjB,IAAI,QAAQ,KAAK,WAAW,GAAG,IAAI,KAAK,KAAK,OAAO;CAEtD,OAAO;AACT"}
@@ -4,14 +4,14 @@ import { r as ensureClaudeConfigMirror, s as removeOwnClaudeConfigMirror, t as P
4
4
  import { t as state } from "./state-CVp30CBF.js";
5
5
  import { d as resolveModel, m as getGitHubUser } from "./token-DATA_OQK.js";
6
6
  import { n as killChildProcessTree, o as resolveExecutable, s as runCommandCapture } from "./exec-MCU1H-KZ.js";
7
- import { R as runSelfUpdate, a as sharedServerArgs, c as stopKeepAwake, i as setupAndServe, j as resolveLaunchProfile, l as injectModelPickerSettingsFile, r as parseSharedArgs, s as startKeepAwake, t as getClaudeCodeEnvVars } from "./server-setup-Df9BxQ-V.js";
8
- import { At as nativeSubagentModel, Cn as resolveLeadSlugArg, D as toolbeltEnabled, Dt as geminiAvailable, E as buildToolbeltAwareness, Et as fleetToolsEnabled, Ft as scribeModel, It as standInToolEnabled, Lt as workerToolsEnabled, Mt as reviewerFastModel, Nt as reviewerModel, Ot as generalPurposeFastModel, Pt as scoutModel, Sn as pickClaudeDefault, T as availableToolCommands, an as provisionAndIndexColbert, at as agentToolsEnabled, c as enumerateInjectedMcpToolNames, dt as browserCompoundToolsEnabled, ft as browserToolsEnabled, jt as resolveGeminiReviewModel, kt as implementerFastModel, lt as brainstormModel, mn as DEFAULT_CLAUDE_MODEL_FALLBACKS, nn as provisionBrowserAssets, o as buildPeerAwarenessSnippet, ut as browseAgentEnabled, w as buildEnv } from "./peer-mcp-personas-CmR3f7nO.js";
7
+ import { M as resolveLaunchProfile, a as setupAndServe, c as startKeepAwake, i as parseSharedArgs, l as stopKeepAwake, o as sharedServerArgs, t as getClaudeCodeEnvVars, u as injectModelPickerSettingsFile, z as runSelfUpdate } from "./server-setup-UWugox0I.js";
8
+ import { At as nativeSubagentModel, Cn as resolveLeadSlugArg, D as toolbeltEnabled, Dt as geminiAvailable, E as buildToolbeltAwareness, Et as fleetToolsEnabled, Ft as scribeModel, It as standInToolEnabled, Lt as workerToolsEnabled, Mt as reviewerFastModel, Nt as reviewerModel, Ot as generalPurposeFastModel, Pt as scoutModel, Sn as pickClaudeDefault, T as availableToolCommands, an as provisionAndIndexColbert, at as agentToolsEnabled, c as enumerateInjectedMcpToolNames, dt as browserCompoundToolsEnabled, ft as browserToolsEnabled, jt as resolveGeminiReviewModel, kt as implementerFastModel, lt as brainstormModel, mn as DEFAULT_CLAUDE_MODEL_FALLBACKS, nn as provisionBrowserAssets, o as buildPeerAwarenessSnippet, ut as browseAgentEnabled, w as buildEnv } from "./peer-mcp-personas-Dt0VRKYz.js";
9
9
  import { n as hookLauncherDegradedWarning, r as resolveSelfInvocation } from "./self-invocation-DIUyoRgL.js";
10
- import { r as getCodexVersion, t as provisionToolbelt } from "./provision-CxulCZpS.js";
10
+ import { r as getCodexVersion, t as provisionToolbelt } from "./provision-D_aHUCXt.js";
11
11
  import { s as disposeBluebirdClients } from "./bluebird-client-DpYl1YmJ.js";
12
12
  import { s as injectStopHookIntoSettingsFile } from "./stop-gate-hook-DBcxPgkF.js";
13
13
  import { l as guardToolMatcher, n as activeDispatchModes, r as buildWorkerGuardHookCommand } from "./worker-dispatch-lRhno09M.js";
14
- import { C as writePeerMcpRuntimeFiles, S as workersKeyOf, _ as sanitizeServeSettingsEnv, a as appendPeerAwarenessToMirroredClaudeMd, b as resolveCodexCliBackend, c as buildOperatingDefaultsDirective, d as prependStyleDirectiveToMirroredClaudeMd, g as planModeAllowRules, h as injectAllowRules, i as writeInjectedSkill, m as configureServeDefaultPermissionMode, n as getInjectedSkills, o as appendToolbeltAwarenessToMirroredClaudeMd, p as SEAMLESS_BUILTIN_TOOLS, t as injectAttributionSuppressionIntoSettingsFile, u as prependOperatingDefaultsToMirroredClaudeMd, v as BUILTIN_SUBAGENT_DEFINITIONS, x as resolveGroupKeysFromMirror, y as injectPeerMcpIntoMirror } from "./attribution-settings-DpDZcVka.js";
14
+ import { C as writePeerMcpRuntimeFiles, S as workersKeyOf, _ as sanitizeServeSettingsEnv, a as appendPeerAwarenessToMirroredClaudeMd, b as resolveCodexCliBackend, c as buildOperatingDefaultsDirective, d as prependStyleDirectiveToMirroredClaudeMd, g as planModeAllowRules, h as injectAllowRules, i as writeInjectedSkill, m as configureServeDefaultPermissionMode, n as getInjectedSkills, o as appendToolbeltAwarenessToMirroredClaudeMd, p as SEAMLESS_BUILTIN_TOOLS, t as injectAttributionSuppressionIntoSettingsFile, u as prependOperatingDefaultsToMirroredClaudeMd, v as BUILTIN_SUBAGENT_DEFINITIONS, x as resolveGroupKeysFromMirror, y as injectPeerMcpIntoMirror } from "./attribution-settings-BTfKm-RU.js";
15
15
  import { i as planReviewEnabled, t as buildPlanReviewHookCommand } from "./plan-review-hook-BTvxvCCo.js";
16
16
  import { t as buildPromptSubmitHookCommand } from "./prompt-submit-hook-BeLUDy_m.js";
17
17
  import { defineCommand } from "citty";
@@ -1576,4 +1576,4 @@ const serve = defineCommand({
1576
1576
  //#endregion
1577
1577
  export { serve };
1578
1578
 
1579
- //# sourceMappingURL=serve-DVq-m7p5.js.map
1579
+ //# sourceMappingURL=serve-DWL5kmB_.js.map