github-router 0.3.378 → 0.3.379

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.
@@ -1,4 +1,4 @@
1
- import { S as enableFileLogging, Z as runSelfUpdate, a as setupAndServe, i as parseSharedArgs, n as getCodexEnvVars, o as sharedServerArgs, v as startKeepAwake, x as listModelsForEndpoint, y as stopKeepAwake } from "./server-setup-CptI7SUT.js";
1
+ import { S as enableFileLogging, Z as runSelfUpdate, a as setupAndServe, i as parseSharedArgs, n as getCodexEnvVars, o as sharedServerArgs, v as startKeepAwake, x as listModelsForEndpoint, y as stopKeepAwake } from "./server-setup-ClZdV33Q.js";
2
2
  import { i as launchChild, t as provisionToolbelt } from "./provision-DPL8aGe2.js";
3
3
  import { Bn as colbertDegradedWarning, D as toolbeltEnabled, Mn as provisionBrowserAssets, Nn as hasSupportedBrowserInstalled, Qn as DEFAULT_CODEX_MODEL_FALLBACKS, Vn as provisionAndIndexColbert, Zn as DEFAULT_CODEX_MODEL } from "./peer-mcp-personas-OWsSm6To.js";
4
4
  import { t as state } from "./state-CCGDJ43X.js";
@@ -91,4 +91,4 @@ const codex = defineCommand({
91
91
  });
92
92
  export { codex };
93
93
 
94
- //# sourceMappingURL=codex-DHRMLpSo.js.map
94
+ //# sourceMappingURL=codex-BG0pfud9.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"codex-DHRMLpSo.js","names":[],"sources":["../src/codex.ts"],"sourcesContent":["import process from \"node:process\"\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { enableFileLogging } from \"./lib/file-log-reporter\"\nimport { launchChild } from \"./lib/launch\"\nimport { listModelsForEndpoint } from \"./lib/model-validation\"\nimport {\n DEFAULT_CODEX_MODEL,\n DEFAULT_CODEX_MODEL_FALLBACKS,\n} from \"./lib/port\"\nimport {\n getCodexEnvVars,\n parseSharedArgs,\n setupAndServe,\n sharedServerArgs,\n} from \"./lib/server-setup\"\nimport { runSelfUpdate } from \"./lib/self-update\"\nimport { state } from \"./lib/state\"\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 { hasSupportedBrowserInstalled } from \"./lib/browser-mcp/browser-detect\"\nimport { disposeBluebirdClients } from \"./lib/bluebird-client\"\nimport { resolveCodexModel, resolveModel } from \"./lib/utils\"\n\nexport const codex = defineCommand({\n meta: {\n name: \"codex\",\n description: \"Start the proxy server and launch Codex CLI\",\n },\n args: {\n ...sharedServerArgs,\n model: {\n alias: \"m\",\n type: \"string\",\n description: \"Override the default model for Codex CLI\",\n },\n },\n async run({ args }) {\n if (!process.stdout.isTTY) {\n consola.error(\"The codex subcommand requires a TTY (interactive terminal).\")\n process.exit(1)\n }\n\n const parsed = parseSharedArgs(args as unknown as Record<string, unknown>)\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, // undefined = random 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 // Best-effort self-update (detached, applies next launch).\n void runSelfUpdate({ selfUpdate: args[\"self-update\"] !== false })\n\n // Materialize the LLM toolbelt in the background (PATH prepend is in\n // getCodexEnvVars). Best-effort; never blocks launch.\n if (toolbeltEnabled()) {\n void provisionToolbelt().catch(() => {})\n }\n\n // Best-effort ColBERT semantic-search provision + background index of\n // the launch cwd. Opt-IN via --search (no-op otherwise); never blocks\n // launch, never throws.\n void provisionAndIndexColbert()\n\n // Surface a terminally-failed semantic index to the HUMAN (see the note\n // in claude.ts). Fire-and-forget; lexical search still works.\n void colbertDegradedWarning(undefined, { logsToFile: true })\n .then((warning) => {\n if (warning) process.stderr.write(`${warning}\\n`)\n })\n .catch(() => {})\n\n // Best-effort, bounded launch warm-up: ready one tree-sitter worker.\n // Opt out with GH_ROUTER_DISABLE_TS_POOL_WARMUP=1.\n void warmTreeSitterPool()\n\n // Best-effort: keep the machine awake while the proxy/Codex session\n // runs (win32 default-on; opt out GH_ROUTER_DISABLE_KEEP_AWAKE=1).\n // Self-registered SIGINT/SIGTERM/exit reaper releases the assertion.\n startKeepAwake()\n\n // Best-effort: materialize the browser extension + bridge into the\n // stable app-dir and stamp the running version. Gated inline (browse\n // opt-in + a supported browser) rather than via browserToolsEnabled()\n // so the codex command path doesn't eagerly pull the compressor /\n // worker-agent graph. Never blocks launch, never throws.\n const browseOptIn =\n state.browseEnabled || process.env.GH_ROUTER_ENABLE_BROWSE === \"1\"\n if (browseOptIn && hasSupportedBrowserInstalled()) {\n void provisionBrowserAssets().catch((err) =>\n consola.debug(\"Browser extension provisioning failed:\", err),\n )\n }\n\n const usingDefault = !args.model\n const requestedModel = args.model ?? DEFAULT_CODEX_MODEL\n\n // Resolve model before printing success message (so we show the actual model)\n // but enable file logging first so resolution warnings go to file, not terminal\n enableFileLogging()\n\n let codexModel = resolveCodexModel(requestedModel)\n if (codexModel !== requestedModel) {\n consola.info(`Model \"${requestedModel}\" resolved to \"${codexModel}\"`)\n }\n\n // For the implicit-default path only: honor the explicit fallback order\n // (DEFAULT_CODEX_MODEL, then DEFAULT_CODEX_MODEL_FALLBACKS led by gpt-5.5)\n // by cache presence BEFORE resolveCodexModel's codex-slug-preferring\n // \"best /responses model\" safety net. `resolveModel` (NOT resolveCodexModel)\n // walks the chain, so the codex-slug preference can't shadow an\n // earlier-in-chain named fallback (e.g. gpt-5.5) that IS present. The\n // resolveCodexModel result above stays as the FINAL safety net, used only\n // when none of the named chain entries is in the catalog.\n if (usingDefault && state.models) {\n const inCache = (id: string) =>\n state.models?.data.some((m) => m.id === id) ?? false\n const firstPresent = [DEFAULT_CODEX_MODEL, ...DEFAULT_CODEX_MODEL_FALLBACKS]\n .map((id) => resolveModel(id))\n .find((id) => inCache(id))\n if (firstPresent) {\n if (firstPresent !== codexModel) {\n consola.info(\n `Default model \"${DEFAULT_CODEX_MODEL}\" not in your Copilot model list; falling back to \"${firstPresent}\".`,\n )\n }\n codexModel = firstPresent\n }\n }\n\n // Validate model exists in Copilot model list\n const modelEntry = state.models?.data.find((m) => m.id === codexModel)\n if (!modelEntry) {\n const available = listModelsForEndpoint(\"/responses\")\n consola.warn(\n `Model \"${codexModel}\" not found. Available codex models: ${available.join(\", \")}`,\n )\n } else {\n const ctx = modelEntry.capabilities?.limits?.max_context_window_tokens\n if (ctx) consola.info(`Model context window: ${ctx.toLocaleString()} tokens`)\n }\n\n // Print to stderr directly — consola's terminal reporter is already gone\n process.stderr.write(`Server ready on ${serverUrl}, launching Codex CLI (${codexModel})...\\n`)\n\n const envVars = getCodexEnvVars(serverUrl)\n const extraArgs = ((args as unknown as Record<string, unknown>)._ as string[]) ?? []\n\n launchChild(\n {\n kind: \"codex\",\n envVars,\n extraArgs,\n model: codexModel,\n serverUrl,\n },\n server,\n {\n onShutdown: async () => {\n await stopKeepAwake()\n // Dynamic, like `claude.ts` and `pi.ts` do for the same call: a\n // static import of `ado-tools` would pull the whole non-persona MCP\n // registry (and the worker/orchestration modules behind it) into the\n // Codex CLI's import graph for one shutdown-time call. The client\n // module has a second, static importer in `serve.ts`, which already\n // loads that registry — this import is the one that would be pure\n // weight.\n const { disposeAdoClients } = await import(\"./lib/ado-tools\")\n await disposeBluebirdClients()\n await disposeAdoClients()\n },\n },\n )\n },\n})\n"],"mappings":";;;;;;;;;;;AA8BA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,GAAG;EACH,OAAO;GACL,OAAO;GACP,MAAM;GACN,aAAa;EACf;CACF;CACA,MAAM,IAAI,EAAE,QAAQ;EAClB,IAAI,CAAC,QAAQ,OAAO,OAAO;GACzB,QAAQ,MAAM,6DAA6D;GAC3E,QAAQ,KAAK,CAAC;EAChB;EAEA,MAAM,SAAS,gBAAgB,IAA0C;EAEzE,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,MAAM,SAAS,MAAM,cAAc;IACjC,GAAG;IACH,MAAM,OAAO;IACb,QAAQ;GACV,CAAC;GACD,SAAS,OAAO;GAChB,YAAY,OAAO;EACrB,SAAS,OAAO;GACd,QAAQ,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,KAAK;GACvF,QAAQ,KAAK,CAAC;EAChB;EAGK,cAAc,EAAE,YAAY,KAAK,mBAAmB,MAAM,CAAC;EAIhE,IAAI,gBAAgB,GACb,kBAAkB,CAAC,CAAC,YAAY,CAAC,CAAC;EAMpC,yBAAyB;EAIzB,uBAAuB,KAAA,GAAW,EAAE,YAAY,KAAK,CAAC,CAAC,CACzD,MAAM,YAAY;GACjB,IAAI,SAAS,QAAQ,OAAO,MAAM,GAAG,QAAQ,GAAG;EAClD,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;EAIZ,mBAAmB;EAKxB,eAAe;EASf,KADE,MAAM,iBAAiB,QAAQ,IAAI,4BAA4B,QAC9C,6BAA6B,GACzC,uBAAuB,CAAC,CAAC,OAAO,QACnC,QAAQ,MAAM,0CAA0C,GAAG,CAC7D;EAGF,MAAM,eAAe,CAAC,KAAK;EAC3B,MAAM,iBAAiB,KAAK,SAAA;EAI5B,kBAAkB;EAElB,IAAI,aAAa,kBAAkB,cAAc;EACjD,IAAI,eAAe,gBACjB,QAAQ,KAAK,UAAU,eAAe,iBAAiB,WAAW,EAAE;EAWtE,IAAI,gBAAgB,MAAM,QAAQ;GAChC,MAAM,WAAW,OACf,MAAM,QAAQ,KAAK,MAAM,MAAM,EAAE,OAAO,EAAE,KAAK;GACjD,MAAM,eAAe,CAAC,qBAAqB,GAAG,6BAA6B,CAAC,CACzE,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,CAC7B,MAAM,OAAO,QAAQ,EAAE,CAAC;GAC3B,IAAI,cAAc;IAChB,IAAI,iBAAiB,YACnB,QAAQ,KACN,kBAAkB,oBAAoB,qDAAqD,aAAa,GAC1G;IAEF,aAAa;GACf;EACF;EAGA,MAAM,aAAa,MAAM,QAAQ,KAAK,MAAM,MAAM,EAAE,OAAO,UAAU;EACrE,IAAI,CAAC,YAAY;GACf,MAAM,YAAY,sBAAsB,YAAY;GACpD,QAAQ,KACN,UAAU,WAAW,uCAAuC,UAAU,KAAK,IAAI,GACjF;EACF,OAAO;GACL,MAAM,MAAM,WAAW,cAAc,QAAQ;GAC7C,IAAI,KAAK,QAAQ,KAAK,yBAAyB,IAAI,eAAe,EAAE,QAAQ;EAC9E;EAGA,QAAQ,OAAO,MAAM,mBAAmB,UAAU,yBAAyB,WAAW,OAAO;EAE7F,MAAM,UAAU,gBAAgB,SAAS;EACzC,MAAM,YAAc,KAA4C,KAAkB,CAAC;EAEnF,YACE;GACE,MAAM;GACN;GACA;GACA,OAAO;GACP;EACF,GACA,QACA,EACE,YAAY,YAAY;GACtB,MAAM,cAAc;GAQpB,MAAM,EAAE,sBAAsB,MAAM,OAAO;GAC3C,MAAM,uBAAuB;GAC7B,MAAM,kBAAkB;EAC1B,EACF,CACF;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"codex-BG0pfud9.js","names":[],"sources":["../src/codex.ts"],"sourcesContent":["import process from \"node:process\"\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { enableFileLogging } from \"./lib/file-log-reporter\"\nimport { launchChild } from \"./lib/launch\"\nimport { listModelsForEndpoint } from \"./lib/model-validation\"\nimport {\n DEFAULT_CODEX_MODEL,\n DEFAULT_CODEX_MODEL_FALLBACKS,\n} from \"./lib/port\"\nimport {\n getCodexEnvVars,\n parseSharedArgs,\n setupAndServe,\n sharedServerArgs,\n} from \"./lib/server-setup\"\nimport { runSelfUpdate } from \"./lib/self-update\"\nimport { state } from \"./lib/state\"\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 { hasSupportedBrowserInstalled } from \"./lib/browser-mcp/browser-detect\"\nimport { disposeBluebirdClients } from \"./lib/bluebird-client\"\nimport { resolveCodexModel, resolveModel } from \"./lib/utils\"\n\nexport const codex = defineCommand({\n meta: {\n name: \"codex\",\n description: \"Start the proxy server and launch Codex CLI\",\n },\n args: {\n ...sharedServerArgs,\n model: {\n alias: \"m\",\n type: \"string\",\n description: \"Override the default model for Codex CLI\",\n },\n },\n async run({ args }) {\n if (!process.stdout.isTTY) {\n consola.error(\"The codex subcommand requires a TTY (interactive terminal).\")\n process.exit(1)\n }\n\n const parsed = parseSharedArgs(args as unknown as Record<string, unknown>)\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, // undefined = random 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 // Best-effort self-update (detached, applies next launch).\n void runSelfUpdate({ selfUpdate: args[\"self-update\"] !== false })\n\n // Materialize the LLM toolbelt in the background (PATH prepend is in\n // getCodexEnvVars). Best-effort; never blocks launch.\n if (toolbeltEnabled()) {\n void provisionToolbelt().catch(() => {})\n }\n\n // Best-effort ColBERT semantic-search provision + background index of\n // the launch cwd. Opt-IN via --search (no-op otherwise); never blocks\n // launch, never throws.\n void provisionAndIndexColbert()\n\n // Surface a terminally-failed semantic index to the HUMAN (see the note\n // in claude.ts). Fire-and-forget; lexical search still works.\n void colbertDegradedWarning(undefined, { logsToFile: true })\n .then((warning) => {\n if (warning) process.stderr.write(`${warning}\\n`)\n })\n .catch(() => {})\n\n // Best-effort, bounded launch warm-up: ready one tree-sitter worker.\n // Opt out with GH_ROUTER_DISABLE_TS_POOL_WARMUP=1.\n void warmTreeSitterPool()\n\n // Best-effort: keep the machine awake while the proxy/Codex session\n // runs (win32 default-on; opt out GH_ROUTER_DISABLE_KEEP_AWAKE=1).\n // Self-registered SIGINT/SIGTERM/exit reaper releases the assertion.\n startKeepAwake()\n\n // Best-effort: materialize the browser extension + bridge into the\n // stable app-dir and stamp the running version. Gated inline (browse\n // opt-in + a supported browser) rather than via browserToolsEnabled()\n // so the codex command path doesn't eagerly pull the compressor /\n // worker-agent graph. Never blocks launch, never throws.\n const browseOptIn =\n state.browseEnabled || process.env.GH_ROUTER_ENABLE_BROWSE === \"1\"\n if (browseOptIn && hasSupportedBrowserInstalled()) {\n void provisionBrowserAssets().catch((err) =>\n consola.debug(\"Browser extension provisioning failed:\", err),\n )\n }\n\n const usingDefault = !args.model\n const requestedModel = args.model ?? DEFAULT_CODEX_MODEL\n\n // Resolve model before printing success message (so we show the actual model)\n // but enable file logging first so resolution warnings go to file, not terminal\n enableFileLogging()\n\n let codexModel = resolveCodexModel(requestedModel)\n if (codexModel !== requestedModel) {\n consola.info(`Model \"${requestedModel}\" resolved to \"${codexModel}\"`)\n }\n\n // For the implicit-default path only: honor the explicit fallback order\n // (DEFAULT_CODEX_MODEL, then DEFAULT_CODEX_MODEL_FALLBACKS led by gpt-5.5)\n // by cache presence BEFORE resolveCodexModel's codex-slug-preferring\n // \"best /responses model\" safety net. `resolveModel` (NOT resolveCodexModel)\n // walks the chain, so the codex-slug preference can't shadow an\n // earlier-in-chain named fallback (e.g. gpt-5.5) that IS present. The\n // resolveCodexModel result above stays as the FINAL safety net, used only\n // when none of the named chain entries is in the catalog.\n if (usingDefault && state.models) {\n const inCache = (id: string) =>\n state.models?.data.some((m) => m.id === id) ?? false\n const firstPresent = [DEFAULT_CODEX_MODEL, ...DEFAULT_CODEX_MODEL_FALLBACKS]\n .map((id) => resolveModel(id))\n .find((id) => inCache(id))\n if (firstPresent) {\n if (firstPresent !== codexModel) {\n consola.info(\n `Default model \"${DEFAULT_CODEX_MODEL}\" not in your Copilot model list; falling back to \"${firstPresent}\".`,\n )\n }\n codexModel = firstPresent\n }\n }\n\n // Validate model exists in Copilot model list\n const modelEntry = state.models?.data.find((m) => m.id === codexModel)\n if (!modelEntry) {\n const available = listModelsForEndpoint(\"/responses\")\n consola.warn(\n `Model \"${codexModel}\" not found. Available codex models: ${available.join(\", \")}`,\n )\n } else {\n const ctx = modelEntry.capabilities?.limits?.max_context_window_tokens\n if (ctx) consola.info(`Model context window: ${ctx.toLocaleString()} tokens`)\n }\n\n // Print to stderr directly — consola's terminal reporter is already gone\n process.stderr.write(`Server ready on ${serverUrl}, launching Codex CLI (${codexModel})...\\n`)\n\n const envVars = getCodexEnvVars(serverUrl)\n const extraArgs = ((args as unknown as Record<string, unknown>)._ as string[]) ?? []\n\n launchChild(\n {\n kind: \"codex\",\n envVars,\n extraArgs,\n model: codexModel,\n serverUrl,\n },\n server,\n {\n onShutdown: async () => {\n await stopKeepAwake()\n // Dynamic, like `claude.ts` and `pi.ts` do for the same call: a\n // static import of `ado-tools` would pull the whole non-persona MCP\n // registry (and the worker/orchestration modules behind it) into the\n // Codex CLI's import graph for one shutdown-time call. The client\n // module has a second, static importer in `serve.ts`, which already\n // loads that registry — this import is the one that would be pure\n // weight.\n const { disposeAdoClients } = await import(\"./lib/ado-tools\")\n await disposeBluebirdClients()\n await disposeAdoClients()\n },\n },\n )\n },\n})\n"],"mappings":";;;;;;;;;;;AA8BA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,GAAG;EACH,OAAO;GACL,OAAO;GACP,MAAM;GACN,aAAa;EACf;CACF;CACA,MAAM,IAAI,EAAE,QAAQ;EAClB,IAAI,CAAC,QAAQ,OAAO,OAAO;GACzB,QAAQ,MAAM,6DAA6D;GAC3E,QAAQ,KAAK,CAAC;EAChB;EAEA,MAAM,SAAS,gBAAgB,IAA0C;EAEzE,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,MAAM,SAAS,MAAM,cAAc;IACjC,GAAG;IACH,MAAM,OAAO;IACb,QAAQ;GACV,CAAC;GACD,SAAS,OAAO;GAChB,YAAY,OAAO;EACrB,SAAS,OAAO;GACd,QAAQ,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,KAAK;GACvF,QAAQ,KAAK,CAAC;EAChB;EAGK,cAAc,EAAE,YAAY,KAAK,mBAAmB,MAAM,CAAC;EAIhE,IAAI,gBAAgB,GACb,kBAAkB,CAAC,CAAC,YAAY,CAAC,CAAC;EAMpC,yBAAyB;EAIzB,uBAAuB,KAAA,GAAW,EAAE,YAAY,KAAK,CAAC,CAAC,CACzD,MAAM,YAAY;GACjB,IAAI,SAAS,QAAQ,OAAO,MAAM,GAAG,QAAQ,GAAG;EAClD,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;EAIZ,mBAAmB;EAKxB,eAAe;EASf,KADE,MAAM,iBAAiB,QAAQ,IAAI,4BAA4B,QAC9C,6BAA6B,GACzC,uBAAuB,CAAC,CAAC,OAAO,QACnC,QAAQ,MAAM,0CAA0C,GAAG,CAC7D;EAGF,MAAM,eAAe,CAAC,KAAK;EAC3B,MAAM,iBAAiB,KAAK,SAAA;EAI5B,kBAAkB;EAElB,IAAI,aAAa,kBAAkB,cAAc;EACjD,IAAI,eAAe,gBACjB,QAAQ,KAAK,UAAU,eAAe,iBAAiB,WAAW,EAAE;EAWtE,IAAI,gBAAgB,MAAM,QAAQ;GAChC,MAAM,WAAW,OACf,MAAM,QAAQ,KAAK,MAAM,MAAM,EAAE,OAAO,EAAE,KAAK;GACjD,MAAM,eAAe,CAAC,qBAAqB,GAAG,6BAA6B,CAAC,CACzE,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,CAC7B,MAAM,OAAO,QAAQ,EAAE,CAAC;GAC3B,IAAI,cAAc;IAChB,IAAI,iBAAiB,YACnB,QAAQ,KACN,kBAAkB,oBAAoB,qDAAqD,aAAa,GAC1G;IAEF,aAAa;GACf;EACF;EAGA,MAAM,aAAa,MAAM,QAAQ,KAAK,MAAM,MAAM,EAAE,OAAO,UAAU;EACrE,IAAI,CAAC,YAAY;GACf,MAAM,YAAY,sBAAsB,YAAY;GACpD,QAAQ,KACN,UAAU,WAAW,uCAAuC,UAAU,KAAK,IAAI,GACjF;EACF,OAAO;GACL,MAAM,MAAM,WAAW,cAAc,QAAQ;GAC7C,IAAI,KAAK,QAAQ,KAAK,yBAAyB,IAAI,eAAe,EAAE,QAAQ;EAC9E;EAGA,QAAQ,OAAO,MAAM,mBAAmB,UAAU,yBAAyB,WAAW,OAAO;EAE7F,MAAM,UAAU,gBAAgB,SAAS;EACzC,MAAM,YAAc,KAA4C,KAAkB,CAAC;EAEnF,YACE;GACE,MAAM;GACN;GACA;GACA,OAAO;GACP;EACF,GACA,QACA,EACE,YAAY,YAAY;GACtB,MAAM,cAAc;GAQpB,MAAM,EAAE,sBAAsB,MAAM,OAAO;GAC3C,MAAM,uBAAuB;GAC7B,MAAM,kBAAkB;EAC1B,EACF,CACF;CACF;AACF,CAAC"}
package/dist/main.js CHANGED
@@ -47,12 +47,12 @@ const main = defineCommand({
47
47
  },
48
48
  subCommands: {
49
49
  auth: () => import("./auth-BZHpTtfF.js").then((m) => m.auth),
50
- start: () => import("./start-DioCGjM8.js").then((m) => m.start),
51
- claude: () => import("./claude--4O3wHRq.js").then((m) => m.claude),
52
- codex: () => import("./codex-DHRMLpSo.js").then((m) => m.codex),
53
- pi: () => import("./pi-B0EFY6l7.js").then((m) => m.pi),
50
+ start: () => import("./start-mnedD5cH.js").then((m) => m.start),
51
+ claude: () => import("./claude-CSuIdaLV.js").then((m) => m.claude),
52
+ codex: () => import("./codex-BG0pfud9.js").then((m) => m.codex),
53
+ pi: () => import("./pi-DmeBxzIo.js").then((m) => m.pi),
54
54
  workiq: () => import("./workiq-CQauEAMc.js").then((m) => m.workiq),
55
- serve: () => import("./serve-C13q-9w0.js").then((m) => m.serve),
55
+ serve: () => import("./serve-zbQKfx1E.js").then((m) => m.serve),
56
56
  models: () => import("./models-B6nH1sS6.js").then((m) => m.models),
57
57
  "check-usage": () => import("./check-usage-BlIWDuV2.js").then((m) => m.checkUsage),
58
58
  index: () => import("./index-cmd-sKwchRJz.js").then((m) => m.indexCmd),
@@ -1,4 +1,4 @@
1
- import { H as profileDescriptor, I as formatBalancedPrerequisiteFailure, S as enableFileLogging, U as resolveLaunchProfile, V as formatLocalPrerequisiteFailure, W as validateBalancedProfilePrerequisites, Y as validateLocalProfilePrerequisites, Z as runSelfUpdate, _ as sweepStalePiAgentMirrors, a as setupAndServe, c as PI_MIN_VERSION, d as meetsPiMinVersion, f as refreshPiInBackground, g as removeOwnPiAgentMirror, h as ensurePiAgentMirror, i as parseSharedArgs, l as ensurePiInstalled, m as updatePi, o as sharedServerArgs, p as resolvePiRegistry, q as validateCheapestProfilePrerequisites, r as getPiLaunchEnvVars, s as LAUNCH_SECRET_HEADER, u as getInstalledPiVersion, v as startKeepAwake, y as stopKeepAwake, z as formatCheapestPrerequisiteFailure } from "./server-setup-CptI7SUT.js";
1
+ import { H as profileDescriptor, I as formatBalancedPrerequisiteFailure, S as enableFileLogging, U as resolveLaunchProfile, V as formatLocalPrerequisiteFailure, W as validateBalancedProfilePrerequisites, Y as validateLocalProfilePrerequisites, Z as runSelfUpdate, _ as sweepStalePiAgentMirrors, a as setupAndServe, c as PI_MIN_VERSION, d as meetsPiMinVersion, f as refreshPiInBackground, g as removeOwnPiAgentMirror, h as ensurePiAgentMirror, i as parseSharedArgs, l as ensurePiInstalled, m as updatePi, o as sharedServerArgs, p as resolvePiRegistry, q as validateCheapestProfilePrerequisites, r as getPiLaunchEnvVars, s as LAUNCH_SECRET_HEADER, u as getInstalledPiVersion, v as startKeepAwake, y as stopKeepAwake, z as formatCheapestPrerequisiteFailure } from "./server-setup-ClZdV33Q.js";
2
2
  import { i as buildAicStatusHookCommand, n as AIC_STATUSLINE_DISABLE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-BKveu679.js";
3
3
  import { d as removeAicLedgerFile, f as sweepStaleAicLedgerFiles, n as aicSnapshot, o as formatAicExitSummary, t as aicLedgerPath } from "./aic-ledger-CeSXqTEE.js";
4
4
  import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-UXC6NQbN.js";
@@ -468,6 +468,31 @@ function piThinkingLevelMapFor(efforts) {
468
468
  for (const level of PI_THINKING_LEVELS) map[level] = set.has(level) ? level : null;
469
469
  return map;
470
470
  }
471
+ /**
472
+ * Pi's own window for the LOCAL family (`-m local`, `-m local2`).
473
+ *
474
+ * 272K, not 200K, and deliberately NOT `LOCAL_PROFILE_LEAD_CONTEXT_TOKENS`:
475
+ * that constant is the *Claude Code client's* window, pinned at 200K by the
476
+ * seeded `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`, and nothing in this module can
477
+ * move it. Two clients, two windows, both true.
478
+ *
479
+ * The choice is policy, not measurement. Measured on the live endpoint this
480
+ * session: 105K–720K input is accepted verbatim, 730K+ is
481
+ * `400 prompt is too long`, so the real ceiling is ~720K and 272K sits at a
482
+ * 2.6× margin. 272K is also the Copilot Default-tier boundary the roster
483
+ * already uses (`PI_TIER_THRESHOLDS`), so every Pi profile in this repo now
484
+ * budgets against the same number instead of two conventions.
485
+ *
486
+ * Raising the window alone would make compaction WORSE, not better. Pi's
487
+ * clamp is `room = window − input − max(4096, 15% of input)`, and the
488
+ * summarization call's input is `trigger − keepRecentTokens`, not the trigger.
489
+ * Measured through Pi's own `clampMaxTokensToContext`, a 272K window only
490
+ * hands that call the full 65 536 once the trigger is at or under ~198.6K
491
+ * (reserve >= ~73.4K); at a 217 600 trigger it gets 43 736, and at 232 000 it
492
+ * gets 31 744 — today's truncating ceiling. The three constants move together
493
+ * or not at all.
494
+ */
495
+ const PI_LOCAL_CONTEXT_TOKENS = 272e3;
471
496
  /** Provider key used in models.json and agent `provider/model` references. */
472
497
  const PI_PROVIDER_NAME = "gh-router";
473
498
  const PI_MIN_VERSION_NOTE = `Requires Pi >= ${PI_MIN_VERSION} and Node >= 22.19.`;
@@ -798,7 +823,7 @@ function buildPiModelsJson(opts) {
798
823
  name: id,
799
824
  reasoning: true,
800
825
  input: entry?.vision === false ? ["text"] : ["text", "image"],
801
- contextWindow: piContextWindowFor(id, entry?.maxContextTokens),
826
+ contextWindow: local && isLocalTier ? PI_LOCAL_CONTEXT_TOKENS : piContextWindowFor(id, entry?.maxContextTokens),
802
827
  maxTokens,
803
828
  ...entry?.cost ? { cost: entry.cost } : {},
804
829
  ...isLocalTier && localHeaders ? { headers: localHeaders } : {},
@@ -811,7 +836,7 @@ function buildPiModelsJson(opts) {
811
836
  } } };
812
837
  }
813
838
  /**
814
- * Local-family compaction reserve: 80% of the 200K window.
839
+ * Local-family compaction reserve: a flat 81 600 tokens for the 272K window.
815
840
  *
816
841
  * The Copilot derivation below optimises for a price cliff; the local
817
842
  * endpoint has none, so the binding constraint there is the summarization
@@ -823,13 +848,38 @@ function buildPiModelsJson(opts) {
823
848
  * `getSummarizationFailure` refuses the truncated summary
824
849
  * (`generation hit the token cap and the summary is incomplete`).
825
850
  *
826
- * Triggering at 160K instead of Pi's 183K default leaves the clamp enough
827
- * room that the 32768 budget below is reachable: at a 160K estimate
828
- * `clampMaxTokensToContext` yields 32768, so the provider sends
829
- * `budget = min(32768, 32768 − 1024)`. Raised reserves alone are not enough
830
- * (the budget, not the trigger, is the ceiling) — both halves ship together.
831
- */
832
- const PI_LOCAL_COMPACTION_RESERVE_TOKENS = 4e4;
851
+ * The reserve is **flat**, not a ratio, so it is the half of this pairing
852
+ * that has to be recomputed whenever the window moves. 272 000 − 81 600 =
853
+ * 190 400 is the trigger (70% of the window, vs the 160K/80% it replaces —
854
+ * the absolute amount of conversation before compaction goes UP).
855
+ *
856
+ * The number is derived, not chosen. Pi clamps the summarization request to
857
+ * `room = window − input − max(4096, 15% · input)` and the summarizer sees
858
+ * `trigger − keepRecentTokens` (20 000). For the 65 536 budget below to
859
+ * survive that clamp, that input must stay at or under 178 642
860
+ * (`(272000 − 65536 − 1024) / 1.15` rounds down one token short). Read back
861
+ * as a reserve:
862
+ *
863
+ * | reserve | trigger | summarizer input | `budget_tokens` |
864
+ * |---------|---------|------------------|-----------------|
865
+ * | 40 000 | 232 000 | 212 000 | 31 744 |
866
+ * | 54 400 | 217 600 | 197 600 | 43 736 |
867
+ * | 73 357 | 198 643 | 178 643 | 65 535 |
868
+ * | 81 600 | 190 400 | 170 400 | 65 536 |
869
+ *
870
+ * 73 357 is the exact boundary and has zero slack: one token past it and the
871
+ * budget starts eroding, and a history that overshoots the trigger by 5%
872
+ * would get 55 264. 81 600 keeps ~8K of headroom, so that same 5% overshoot
873
+ * still receives 65 218. Ship the number with the slack, not the boundary.
874
+ *
875
+ * Both halves ship together: the budget is what the endpoint serves as
876
+ * `budget_tokens`, and the reserve is what keeps the clamp from eating it.
877
+ * The two rows above 40 000 are the ones that matter — a raised window with
878
+ * the OLD reserve leaves the summarizer at 31 744, and even the plan's
879
+ * original 54 400 caps it at 43 736, i.e. still short of the budget it asks
880
+ * for, from a launch that claims to have doubled its headroom.
881
+ */
882
+ const PI_LOCAL_COMPACTION_RESERVE_TOKENS = 81600;
833
883
  /**
834
884
  * Thinking budgets for LOCAL launches only.
835
885
  *
@@ -838,13 +888,23 @@ const PI_LOCAL_COMPACTION_RESERVE_TOKENS = 4e4;
838
888
  * carry no `thinkingLevelMap`, so `clampReasoning` walks `max`/`xhigh` down
839
889
  * to `high`). 16384 is the ceiling that truncates real summaries — 5 of the
840
890
  * 19 compactions in the reference session reported output above it, up to
841
- * 21643. 32768 roughly doubles the summarization headroom and costs nothing
842
- * on local inference.
891
+ * 21643. 65536 quadruples the summarization headroom and costs nothing on
892
+ * local inference.
893
+ *
894
+ * The doubling from 32768 is not a reflex: the endpoint serves the request as
895
+ * `budget_tokens`, and at the 190 400-token trigger the summarizer sees
896
+ * 170 400 (`trigger − keepRecentTokens`), where the clamp still affords the
897
+ * full 65 536 (measured: +5% historical overshoot → 65 218). A 32 768 budget
898
+ * would be the tight half of what the window now allows, and at the old
899
+ * 40 000 reserve the second clamp pinned the request back to 31 744 — the
900
+ * truncating ceiling this constant exists to remove. Both numbers are
901
+ * measured against Pi's own `clampMaxTokensToContext` in
902
+ * `tests/pi-models-settings.test.ts` rather than asserted here.
843
903
  *
844
904
  * Deliberately NOT emitted for Copilot profiles: there the thinking budget
845
905
  * is billed reasoning tokens on every turn, not a free local decode.
846
906
  */
847
- const PI_LOCAL_THINKING_BUDGETS = Object.freeze({ high: 32768 });
907
+ const PI_LOCAL_THINKING_BUDGETS = Object.freeze({ high: 65536 });
848
908
  /**
849
909
  * Derive Pi compaction budgets from live catalog `max_prompt_tokens`
850
910
  * ceilings AND each model's cheap-tier window — the Pi-native analogue
@@ -862,8 +922,8 @@ const PI_LOCAL_THINKING_BUDGETS = Object.freeze({ high: 32768 });
862
922
  * `PI_LOCAL_COMPACTION_RESERVE_TOKENS`): the local catalog carries no
863
923
  * `max_prompt_tokens`, so the price-cliff derivation has nothing to read,
864
924
  * and the constraint that matters is the endpoint's thinking-budget
865
- * ceiling. Every local row is the same 200K window, so one flat reserve
866
- * covers the whole roster.
925
+ * ceiling. Every local row is the same 272K window (see
926
+ * `PI_LOCAL_CONTEXT_TOKENS`), so one flat reserve covers the whole roster.
867
927
  */
868
928
  function derivePiCompactionSettings(catalog, modelIds, profileId) {
869
929
  const FALLBACK = {
@@ -1426,11 +1486,21 @@ function buildPiLaunchCard(opts) {
1426
1486
  opts.copilotVersion ? `copilot chat ${opts.copilotVersion}` : void 0,
1427
1487
  opts.vsCodeVersion ? `vscode ${opts.vsCodeVersion}` : void 0
1428
1488
  ].filter((part) => typeof part === "string" && part.length > 0);
1429
- return [
1489
+ const lines = [
1430
1490
  `github-router v${opts.version} · pi (${opts.profileId})`,
1431
1491
  ` ${identity.join(" · ")}`,
1432
1492
  ` lead ${opts.lead} · ${opts.modelCount} models · ${surface.join(" ")} · ${opts.serverUrl}`
1433
- ].join("\n");
1493
+ ];
1494
+ const foreign = opts.foreign;
1495
+ if (foreign) {
1496
+ const parts = [`${foreign.agents} foreign agents (lazy)`];
1497
+ if (foreign.prompts > 0) parts.push(`${foreign.prompts} prompts`);
1498
+ if (foreign.skills > 0) parts.push(`${foreign.skills} skills`);
1499
+ lines.push(` foreign: ${parts.join(" · ")}`);
1500
+ if (foreign.renamed.length > 0) lines.push(` renamed ${foreign.renamed.map((r) => `${r.from} → ${r.to}`).join(", ")}`);
1501
+ if (foreign.skipped.length > 0) lines.push(` skipped ${foreign.skipped.map((s) => s.name).join(", ")} (name taken by gh-router)`);
1502
+ } else if (opts.foreignAvailable !== void 0 && opts.foreignAvailable > 0) lines.push(` foreign: ${opts.foreignAvailable} agent definition(s) found, not bridged · add --foreign`);
1503
+ return lines.join("\n");
1434
1504
  }
1435
1505
  /**
1436
1506
  * Short operating digest appended to APPEND_SYSTEM.md (prompt-cache-stable).
@@ -2478,6 +2548,159 @@ function buildPiStatuslineFooterSection() {
2478
2548
  ];
2479
2549
  }
2480
2550
  /**
2551
+ * Pinned pi-subagents event contract. The router cannot import the package, so
2552
+ * the event NAME and the request shape are literals here, exactly as the
2553
+ * upstream module defines them (`runtime-agent-events.js`:
2554
+ * `RUNTIME_AGENT_REGISTER_EVENT`, version 1). A version bump upstream leaves
2555
+ * this registration unanswered and the extension reports it — never a crash.
2556
+ */
2557
+ const PI_SUBAGENTS_REGISTER_EVENT = "pi-subagents:runtime-agent-register:v1";
2558
+ const PI_SUBAGENTS_REGISTER_VERSION = 1;
2559
+ /**
2560
+ * Foreign Claude/Copilot agents: one registry entry each, announced in a
2561
+ * compact prompt section, loaded on demand.
2562
+ *
2563
+ * Three seams, and the reasons each is the shape it is:
2564
+ *
2565
+ * 1. **Registration goes through the documented event**, not through pi's
2566
+ * `registerAgent` (there is none) and not through agent FILES. A file in
2567
+ * `<mirror>/agents/` would be a configured agent — a second identity that
2568
+ * `mergeRuntimeAgents` validates on EVERY discovery, so one collision breaks
2569
+ * every `subagent` call in the process. A runtime registration fails only
2570
+ * its own call, and can be removed at runtime.
2571
+ * 2. **The index is a prompt SECTION**, not a chat message. A custom message
2572
+ * is re-emitted on every run and reaches the model as a user turn; sections
2573
+ * are diff-patched by Pi (`diffSystemPromptSections`), so the index is sent
2574
+ * once and stays cache-stable.
2575
+ * 3. **The `tool_result` net is the backstop for what reservation cannot see**
2576
+ * (a user adding a colliding agent mid-session). It disposes exactly the
2577
+ * offender named in the registry's own error and lets the model retry;
2578
+ * every other error is passed through untouched.
2579
+ *
2580
+ * Fail-open everywhere: a Pi build without these events, a pi-subagents that
2581
+ * is not installed, or a rejected registration all degrade to "the foreign
2582
+ * agents are not available", never to a broken session.
2583
+ */
2584
+ function buildPiForeignAgentsSection(foreign) {
2585
+ return [
2586
+ ` // ---- foreign agents: Claude/Copilot, lazy, collision-reserved ----`,
2587
+ ` // No files: each spec is a RUNTIME agent in pi-subagents, so it participates`,
2588
+ ` // in discovery without becoming a configured identity every subagent call`,
2589
+ ` // re-validates. The index below is the only always-on context.`,
2590
+ ` {`,
2591
+ ` let FOREIGN = [];`,
2592
+ ` try { FOREIGN = ${JSON.stringify(foreign.agents.map((a) => ({
2593
+ name: a.name,
2594
+ description: a.description,
2595
+ body: a.body
2596
+ })))}; } catch { FOREIGN = []; }`,
2597
+ ` const FOREIGN_INDEX = ${JSON.stringify(foreign.index)};`,
2598
+ ` const FOREIGN_EVENT = ${JSON.stringify(PI_SUBAGENTS_REGISTER_EVENT)};`,
2599
+ ` const FOREIGN_VERSION = ${PI_SUBAGENTS_REGISTER_VERSION};`,
2600
+ ` const registrations = new Map();`,
2601
+ ` const failures = [];`,
2602
+ ` // Name of the offending runtime agent, from the registry's own throw text.`,
2603
+ ` // Deliberately parsed rather than inferred: the net must never dispose a`,
2604
+ ` // registration that is not the one the registry just named.`,
2605
+ ` const COLLISION_RE = /^Runtime agent '([^']+)' collides with configured agent/;`,
2606
+ ` function registerAll(ctx) {`,
2607
+ ` for (const spec of FOREIGN) {`,
2608
+ ` try {`,
2609
+ ` // Re-registering the same name throws ('collides with runtime agent'),`,
2610
+ ` // so a prior handle for this name is disposed first. Load-bearing on`,
2611
+ ` // /reload: the extension instance is recreated but the pi-subagents`,
2612
+ ` // registry it talks to is not necessarily torn down first.`,
2613
+ ` const prior = registrations.get(spec.name);`,
2614
+ ` if (prior) { try { prior.dispose(); } catch {} registrations.delete(spec.name); }`,
2615
+ ` const request: any = { version: FOREIGN_VERSION, name: spec.name, definition: {`,
2616
+ ` description: spec.description,`,
2617
+ ` systemPrompt: spec.body,`,
2618
+ ` systemPromptMode: "replace",`,
2619
+ ` inheritProjectContext: true,`,
2620
+ ` } };`,
2621
+ ` try { pi.events.emit(FOREIGN_EVENT, request); } catch {}`,
2622
+ ` const result = request.result;`,
2623
+ ` if (result && result.ok === true && result.registration && typeof result.registration.dispose === "function") {`,
2624
+ ` registrations.set(spec.name, result.registration);`,
2625
+ ` continue;`,
2626
+ ` }`,
2627
+ ` const reason = result && result.ok === false && result.error`,
2628
+ ` ? String(result.error.message || result.error)`,
2629
+ ` : "pi-subagents did not answer";`,
2630
+ ` failures.push(spec.name + ": " + reason);`,
2631
+ ` } catch (error) {`,
2632
+ ` failures.push(spec.name + ": " + String(error && error.message ? error.message : error));`,
2633
+ ` }`,
2634
+ ` }`,
2635
+ ` if (failures.length > 0 && ctx && ctx.ui && typeof ctx.ui.notify === "function") {`,
2636
+ ` try { ctx.ui.notify("gh-router: " + failures.length + " foreign agent(s) not bridged (" + failures.slice(0, 3).join("; ") + ")", "warning"); } catch {}`,
2637
+ ` }`,
2638
+ ` }`,
2639
+ ` pi.on("session_start", async (event, ctx) => {`,
2640
+ ` // Children must not pay for the roster: every subagent process loads`,
2641
+ ` // this extension too (background runners mark themselves, foreground`,
2642
+ ` // children load no ambient extensions). Registration there would also`,
2643
+ ` // fight the parent's names in a second registry.`,
2644
+ ` if (process.env.PI_SUBAGENT_CHILD === "1") return;`,
2645
+ ` registerAll(ctx);`,
2646
+ ` });`,
2647
+ ` pi.on("session_shutdown", async () => {`,
2648
+ ` // Load-bearing, not hygiene: a stale registration outliving this`,
2649
+ ` // instance makes the next session's registration of the same name`,
2650
+ ` // throw 'collides with runtime agent'.`,
2651
+ ` for (const registration of registrations.values()) {`,
2652
+ ` try { registration.dispose(); } catch {}`,
2653
+ ` }`,
2654
+ ` registrations.clear();`,
2655
+ ` });`,
2656
+ ` // Self-healing net: a colliding foreign agent fails EVERY subagent call in`,
2657
+ ` // the process, so leaving it registered until the user quits is not an`,
2658
+ ` // option. Only a registration this extension created is ever disposed,`,
2659
+ ` // keyed by the name the registry itself reported.`,
2660
+ ` pi.on("tool_result", async (event) => {`,
2661
+ ` try {`,
2662
+ ` if (!event || event.toolName !== "subagent" || event.isError !== true) return undefined;`,
2663
+ ` const text = Array.isArray(event.content)`,
2664
+ ` ? event.content.map((c) => (c && typeof c.text === "string" ? c.text : "")).join("\\n")`,
2665
+ ` : "";`,
2666
+ ` const match = COLLISION_RE.exec(text);`,
2667
+ ` if (!match) return undefined;`,
2668
+ ` const offender = match[1];`,
2669
+ ` // Reset lastIndex for the shared regex: a stale index would make the`,
2670
+ ` // next match start mid-string and silently miss.`,
2671
+ ` COLLISION_RE.lastIndex = 0;`,
2672
+ ` const registration = registrations.get(offender);`,
2673
+ ` if (!registration) return undefined;`,
2674
+ ` try { registration.dispose(); } catch {}`,
2675
+ ` registrations.delete(offender);`,
2676
+ ` return {`,
2677
+ ` content: [{ type: "text", text: "Foreign agent '" + offender + "' collided with an agent configured in this session and was unregistered. Retry the call, or use a roster agent." }],`,
2678
+ ` isError: false,`,
2679
+ ` };`,
2680
+ ` } catch {`,
2681
+ ` return undefined;`,
2682
+ ` }`,
2683
+ ` });`,
2684
+ ` // The compact index, as a system-prompt section. Skipped in children`,
2685
+ ` // (they never see the roster) and when nothing was bridged.`,
2686
+ ` if (FOREIGN_INDEX) {`,
2687
+ ` pi.on("before_agent_start", async (event) => {`,
2688
+ ` try {`,
2689
+ ` if (process.env.PI_SUBAGENT_CHILD === "1") return undefined;`,
2690
+ ` const options = event && event.systemPromptOptions;`,
2691
+ ` if (!options || typeof options !== "object") return undefined;`,
2692
+ ` if (!options.sections || typeof options.sections !== "object") options.sections = {};`,
2693
+ ` options.sections.foreign_agents = FOREIGN_INDEX;`,
2694
+ ` return undefined;`,
2695
+ ` } catch {`,
2696
+ ` return undefined;`,
2697
+ ` }`,
2698
+ ` });`,
2699
+ ` }`,
2700
+ ` }`
2701
+ ];
2702
+ }
2703
+ /**
2481
2704
  * Memory-bridge section for the generated extension: path-scoped rules
2482
2705
  * lazy-attach on `read/edit/write` tool results (once per rule per
2483
2706
  * session, mirroring `pi-code/claude-rules.ts`), plus `/memory` (bridge
@@ -2621,6 +2844,7 @@ function buildPiExtensionSource(opts) {
2621
2844
  ``
2622
2845
  ] : [], `export default function (pi) {`);
2623
2846
  if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
2847
+ if (opts.foreign && opts.foreign.agents.length + opts.foreign.index.length > 0) lines.push(...buildPiForeignAgentsSection(opts.foreign));
2624
2848
  lines.push(...buildPiStatuslineFooterSection(), ...buildPiPlanModeSection(), ` // Route compaction summaries to the mode's cheap capable model;`, ` // ALWAYS fall back to Pi native (return undefined) on any failure.`, ` pi.on("session_before_compact", async (event) => {`, ` try {`, ` const preparation = event.preparation;`, ` if (!preparation || !Array.isArray(preparation.messagesToSummarize)) return undefined;`, ` return undefined; // v1: observe only; native pipeline stays authoritative.`, ` } catch {`, ` return undefined;`, ` }`, ` });`, ...promptBrief ? [
2625
2849
  ` // Cheapest-profile execution brief, injected ABOVE the model's turn.`,
2626
2850
  ` // Produced server-side; this only relays the prompt and re-emits the`,
@@ -3168,6 +3392,11 @@ const piArgs = {
3168
3392
  type: "boolean",
3169
3393
  default: true,
3170
3394
  description: "Bridge Copilot (.github/copilot-instructions.md, .github/instructions/*.instructions.md) and Claude (.claude/rules/, .claude/CLAUDE.md, ~/.claude/CLAUDE.md) memory into Pi. Static repo-wide slice synthesizes into the mirror AGENTS.md; path-scoped rules lazy-attach. Set to false (--no-memory-bridge) for Pi-native discovery only."
3395
+ },
3396
+ foreign: {
3397
+ type: "boolean",
3398
+ default: false,
3399
+ description: "Bridge the project's and your Claude Code and Copilot artifacts: .claude/skills + .github/skills + .copilot/skills as Pi skills, .claude/commands + .github/prompts as prompt shortcuts, and .claude/agents + .github/agents as Pi subagents announced in one compact index and loaded on demand. Authored names are kept; a name already taken by the router, a pi-subagents builtin or your own agent/skill/command is renamed (skills, prompts) or reported (agents) rather than overwritten. Foreign `model:` is ignored — every bridged agent runs on the lead model. Off by default."
3171
3400
  }
3172
3401
  };
3173
3402
  /**
@@ -3325,6 +3554,7 @@ const pi = defineCommand({
3325
3554
  }
3326
3555
  const peersEnabled = args["peers"] !== false;
3327
3556
  const sweEnabled = args["swe"] === true;
3557
+ const foreignEnabled = args["foreign"] === true;
3328
3558
  const helpersEnabled = args["helpers"] !== false;
3329
3559
  const uiEnabled = args["ui"] !== false;
3330
3560
  const searchEnabled = parsed.searchEnabled || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
@@ -3360,6 +3590,8 @@ const pi = defineCommand({
3360
3590
  }
3361
3591
  enableFileLogging();
3362
3592
  let packagesForCache = [];
3593
+ let foreignAvailable;
3594
+ let foreignStats;
3363
3595
  const launchSecret = randomBytes(32).toString("hex");
3364
3596
  try {
3365
3597
  const catalog = state.models?.data.map((m) => {
@@ -3428,7 +3660,7 @@ const pi = defineCommand({
3428
3660
  if (!bridgeDisabled) {
3429
3661
  const passthrough = collectPiPassthroughArgs(rawArgs, piArgs);
3430
3662
  if (!(passthrough.includes("--no-context-files") || passthrough.includes("-nc"))) try {
3431
- const { collectBridgeInputs } = await import("./pi-memory-bridge-Dvj1T3e3.js");
3663
+ const { collectBridgeInputs } = await import("./pi-memory-bridge-Bp9AnYw9.js");
3432
3664
  const collected = await collectBridgeInputs(process$1.cwd());
3433
3665
  bridgeStats = {
3434
3666
  staticFiles: collected.copilotInstructions.length + collected.unscopedRules.length + collected.userGlobal.length,
@@ -3442,12 +3674,95 @@ const pi = defineCommand({
3442
3674
  consola.debug("Pi memory bridge collection skipped:", err);
3443
3675
  }
3444
3676
  }
3677
+ const routerAgentFiles = peersEnabled ? buildPiAgentFiles(profileId) : {};
3678
+ const routerSkills = buildPiSkills({
3679
+ profileId,
3680
+ peers: peersEnabled,
3681
+ swe: sweEnabled,
3682
+ search: searchEnabled
3683
+ });
3684
+ const routerPrompts = buildPiPrompts({
3685
+ profileId,
3686
+ swe: sweEnabled,
3687
+ peers: peersEnabled
3688
+ });
3689
+ for (const [rel, content] of Object.entries(routerAgentFiles)) await writeTextFile(path.join(mirror, rel), content);
3690
+ for (const skill of routerSkills) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
3691
+ for (const prompt of routerPrompts) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
3692
+ await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, {
3693
+ peers: peersEnabled,
3694
+ codeSearch: surfaces.codeSearch
3695
+ }));
3696
+ let foreign;
3697
+ if (foreignEnabled) try {
3698
+ const { buildForeignAgentIndex, buildReservedNames, piForeignHomeDir, piForeignRepoRoot, planForeignArtifacts, writeForeignArtifacts } = await import("./pi-foreign-artifacts-DZ4tioyO.js");
3699
+ const repoRoot = await piForeignRepoRoot(process$1.cwd());
3700
+ const homeDir = piForeignHomeDir();
3701
+ const reservedNames = await buildReservedNames({
3702
+ mirrorDir: mirror,
3703
+ repoRoot,
3704
+ homeDir,
3705
+ emittedAgents: Object.keys(routerAgentFiles).map((rel) => path.basename(rel, ".md")),
3706
+ emittedSkills: routerSkills.map((skill) => skill.dir),
3707
+ emittedPrompts: routerPrompts.map((prompt) => prompt.name)
3708
+ });
3709
+ const plan = await planForeignArtifacts({
3710
+ repoRoot,
3711
+ homeDir,
3712
+ mirrorDir: mirror,
3713
+ reservedNames
3714
+ });
3715
+ const written = await writeForeignArtifacts(mirror, plan);
3716
+ if (written.overwritten > 0) consola.warn(`Pi foreign bridge: ${written.overwritten} existing file(s) were replaced. That is a bug in the name reservation, not expected behavior.`);
3717
+ foreign = {
3718
+ agents: plan.agents.map(({ name, description, body }) => ({
3719
+ name,
3720
+ description,
3721
+ body
3722
+ })),
3723
+ index: buildForeignAgentIndex(plan.agents)
3724
+ };
3725
+ foreignStats = {
3726
+ agents: plan.agents.length,
3727
+ renamed: [
3728
+ ...plan.agents.filter((agent) => agent.renamedFrom).map((agent) => ({
3729
+ from: String(agent.renamedFrom),
3730
+ to: agent.name
3731
+ })),
3732
+ ...plan.skills.filter((skill) => skill.renamedFrom).map((skill) => ({
3733
+ from: String(skill.renamedFrom),
3734
+ to: skill.name
3735
+ })),
3736
+ ...plan.prompts.filter((prompt) => prompt.renamedFrom).map((prompt) => ({
3737
+ from: String(prompt.renamedFrom),
3738
+ to: prompt.name
3739
+ }))
3740
+ ],
3741
+ skipped: plan.skipped.map(({ name, reason }) => ({
3742
+ name,
3743
+ reason
3744
+ })),
3745
+ written
3746
+ };
3747
+ } catch (err) {
3748
+ consola.debug("Pi foreign bridge skipped:", err);
3749
+ }
3750
+ else try {
3751
+ const { countForeignAgentFiles, piForeignHomeDir, piForeignRepoRoot } = await import("./pi-foreign-artifacts-DZ4tioyO.js");
3752
+ foreignAvailable = await countForeignAgentFiles({
3753
+ repoRoot: await piForeignRepoRoot(process$1.cwd()),
3754
+ homeDir: piForeignHomeDir()
3755
+ });
3756
+ } catch (err) {
3757
+ consola.debug("Pi foreign artifact probe skipped:", err);
3758
+ }
3445
3759
  await writeTextFile(path.join(mirror, "extensions", "gh-router-pi", "index.ts"), buildPiExtensionSource({
3446
3760
  profileId,
3447
3761
  bridge: bridgeStats ? {
3448
3762
  stats: bridgeStats,
3449
3763
  scopedRules: bridgeScoped
3450
- } : void 0
3764
+ } : void 0,
3765
+ foreign
3451
3766
  }));
3452
3767
  if (surfaces.groups.length > 0) {
3453
3768
  const written = await writePiMcpJson({
@@ -3460,29 +3775,10 @@ const pi = defineCommand({
3460
3775
  if (written.skippedReason) consola.warn(`Pi MCP: left ${written.path} alone (${written.skippedReason}); the scoped groups are not exposed to Pi this launch.`);
3461
3776
  else for (const { key, file } of written.shadowed) consola.warn(`Pi MCP: ${file} declares "${key}" and outranks the mirror copy, so the router's version is not the one Pi will run. Rename that entry to keep both.`);
3462
3777
  }
3463
- if (peersEnabled) {
3464
- const agentFiles = buildPiAgentFiles(profileId);
3465
- for (const [rel, content] of Object.entries(agentFiles)) await writeTextFile(path.join(mirror, rel), content);
3466
- }
3467
- for (const skill of buildPiSkills({
3468
- profileId,
3469
- peers: peersEnabled,
3470
- swe: sweEnabled,
3471
- search: searchEnabled
3472
- })) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
3473
- for (const prompt of buildPiPrompts({
3474
- profileId,
3475
- swe: sweEnabled,
3476
- peers: peersEnabled
3477
- })) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
3478
- await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, {
3479
- peers: peersEnabled,
3480
- codeSearch: surfaces.codeSearch
3481
- }));
3482
3778
  try {
3483
3779
  const collected = globalThis.__ghRouterBridgeCollected;
3484
3780
  if (collected) {
3485
- const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-Dvj1T3e3.js");
3781
+ const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-Bp9AnYw9.js");
3486
3782
  const { section } = buildMirrorBridgeSection(collected, { repoRoot: process$1.cwd() });
3487
3783
  const agentsPath = path.join(mirror, "AGENTS.md");
3488
3784
  let existing;
@@ -3560,6 +3856,14 @@ const pi = defineCommand({
3560
3856
  search: searchEnabled,
3561
3857
  browse: browseEnabled,
3562
3858
  mcpGroups: surfaces.groups.map((g) => g.group),
3859
+ foreign: foreignStats ? {
3860
+ agents: foreignStats.agents,
3861
+ skills: foreignStats.written.skills,
3862
+ prompts: foreignStats.written.prompts,
3863
+ renamed: foreignStats.renamed,
3864
+ skipped: foreignStats.skipped
3865
+ } : void 0,
3866
+ foreignAvailable,
3563
3867
  serverUrl
3564
3868
  })}\n`);
3565
3869
  if (sweEnabled && !peersEnabled) process$1.stderr.write("Note: --swe without --peers emits no delegate/review skills or prompts (no agents behind them in a peerless launch).\n");
@@ -3601,4 +3905,4 @@ const pi = defineCommand({
3601
3905
  });
3602
3906
  export { pi };
3603
3907
 
3604
- //# sourceMappingURL=pi-B0EFY6l7.js.map
3908
+ //# sourceMappingURL=pi-DmeBxzIo.js.map