github-router 0.3.341 → 0.3.343

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,7 +1,7 @@
1
1
  import { I as withInstallLock, N as warmTreeSitterPool } from "./service-backend-7SPDLUB9.js";
2
2
  import { t as state } from "./state-CVp30CBF.js";
3
3
  import { c as runCommandVoid, o as resolveExecutable, s as runCommandCapture } from "./exec-MCU1H-KZ.js";
4
- import { E as formatBalancedPrerequisiteFailure, I as validateCheapestProfilePrerequisites, M as resolveLaunchProfile, N as validateBalancedProfilePrerequisites, a as setupAndServe, c as startKeepAwake, f as enableFileLogging, i as parseSharedArgs, j as profileDescriptor, k as formatCheapestPrerequisiteFailure, l as stopKeepAwake, o as sharedServerArgs, r as getPiLaunchEnvVars, z as runSelfUpdate } from "./server-setup-LYpeaZ9B.js";
4
+ import { E as formatBalancedPrerequisiteFailure, I as validateCheapestProfilePrerequisites, M as resolveLaunchProfile, N as validateBalancedProfilePrerequisites, a as setupAndServe, c as startKeepAwake, f as enableFileLogging, i as parseSharedArgs, j as profileDescriptor, k as formatCheapestPrerequisiteFailure, l as stopKeepAwake, o as sharedServerArgs, r as getPiLaunchEnvVars, z as runSelfUpdate } from "./server-setup-CtzSW7Ms.js";
5
5
  import { a as BALANCED_PROFILE_NATIVE_EFFORTS, c as BALANCED_PROFILE_ORACLE_MODEL, r as BALANCED_PROFILE_MODELS, s as BALANCED_PROFILE_ORACLE_EFFORT } from "./balanced-profile-contract-C6AgFJNp.js";
6
6
  import { D as toolbeltEnabled, Gt as registerLaunch, In as CHEAPEST_PROFILE_NATIVE_EFFORTS, Kt as unregisterLaunch, Mn as CHEAPEST_PROFILE_ADVISOR_EFFORT, Nn as CHEAPEST_PROFILE_ADVISOR_MODEL, Pn as CHEAPEST_PROFILE_MODELS, Rn as CHEAPEST_PROFILE_ORACLE_EFFORT, an as provisionAndIndexColbert, ft as browserToolsEnabled, in as colbertDegradedWarning, nn as provisionBrowserAssets, zn as CHEAPEST_PROFILE_ORACLE_MODEL } from "./peer-mcp-personas-Dt0VRKYz.js";
7
7
  import { r as resolveSelfInvocation } from "./self-invocation-DIUyoRgL.js";
@@ -490,10 +490,12 @@ async function ensurePiAgentMirror() {
490
490
  } catch {
491
491
  return mirror;
492
492
  }
493
+ const keepUserExtensions = process.env.GH_ROUTER_PI_KEEP_USER_EXTENSIONS === "1";
493
494
  const SKIP = /* @__PURE__ */ new Set([
494
495
  "auth.json",
495
496
  "sessions",
496
- "models-store.json"
497
+ "models-store.json",
498
+ ...keepUserExtensions ? [] : ["extensions"]
497
499
  ]);
498
500
  await Promise.all(entries.filter((e) => !SKIP.has(e)).map(async (entry) => {
499
501
  try {
@@ -787,30 +789,87 @@ function buildPiSettingsJson(opts) {
787
789
  source: "npm:pi-subagents",
788
790
  skills: [],
789
791
  prompts: []
790
- }] : [], "local:gh-router-pi"]
792
+ }] : [], "local:gh-router-pi"],
793
+ ...peers ? { subagents: { agentOverrides: {
794
+ scout: { disabled: true },
795
+ worker: { disabled: true },
796
+ researcher: { disabled: true },
797
+ "evidence-auditor": { disabled: true }
798
+ } } } : {}
791
799
  };
792
800
  }
793
801
  function agentFileName(name) {
794
802
  return `${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}.md`;
795
803
  }
804
+ /**
805
+ * Deep-merge the `subagents` settings key across the snapshot/user and
806
+ * built layer. Only `agentOverrides` merges (per-agent, user wins);
807
+ * every other `subagents` sub-key follows the standard rule (built wins
808
+ * when present, else user survives). Non-object inputs are ignored so a
809
+ * corrupt user file degrades to built-only instead of crashing launch.
810
+ */
811
+ function mergeSubagentsSettings(userSubagents, builtSubagents) {
812
+ const user = userSubagents && typeof userSubagents === "object" && !Array.isArray(userSubagents) ? userSubagents : void 0;
813
+ const built = builtSubagents ?? void 0;
814
+ if (!user && !built) return void 0;
815
+ const userOverrides = user?.["agentOverrides"] && typeof user["agentOverrides"] === "object" && !Array.isArray(user["agentOverrides"]) ? user["agentOverrides"] : void 0;
816
+ const builtOverrides = built?.["agentOverrides"];
817
+ const mergedOverrides = userOverrides || builtOverrides ? {
818
+ ...builtOverrides,
819
+ ...userOverrides
820
+ } : void 0;
821
+ return {
822
+ ...user,
823
+ ...built,
824
+ ...mergedOverrides ? { agentOverrides: mergedOverrides } : {}
825
+ };
826
+ }
796
827
  function roleDescription(profileId, role) {
797
- const oracleNote = "For risky decisions, ask the oracle subagent for a second opinion before acting.";
798
- if (role.name === "Explore") return `Fast read-only recon: locate code, answer evidence questions, return compressed context. ${oracleNote}`;
828
+ const oracleNote = "May consult the oracle subagent when a decision feels risky.";
829
+ if (role.name === "Explore") return "Fast read-only recon: locate code, answer evidence questions, return compressed context.";
799
830
  if (role.name === "General-Purpose") return profileId === "balanced" ? `General implementation and follow-through on scoped tasks. May hand the result to reviewer only when the change alters behavior. ${oracleNote}` : `General implementation and follow-through on scoped tasks. May hand the result to reviewer for assessment. ${oracleNote}`;
800
831
  return profileId === "balanced" ? "Behavior-changing review only: assess a change, narrow scope with search first, delegate targeted discovery to Explore rather than sweeping the repo." : "Code review and assessment, including reproducing and root-causing a failure.";
801
832
  }
802
833
  /**
803
834
  * Build `.md` agent definitions for the mode's native roster, in the
804
835
  * OpenCode/pi-subagents-lite frontmatter format Pi delegation tools
805
- * consume (`name/description/tools/model/thinking/max_turns`, plus
806
- * `allowedAgents` where the delegation graph has an edge). Bodies are
836
+ * consume (`name/description/tools/model/thinking`, plus `allowedAgents`
837
+ * where the delegation graph has an edge). Bodies are
807
838
  * short execution contracts; workflow prose lives in skills so agent
808
839
  * files stay small enough to inline cheaply.
840
+ *
841
+ * Load-bearing semantics (verified against pi-subagents docs + source):
842
+ * - `reviewer`/`oracle` intentionally SHADOW the same-named builtins
843
+ * wholesale (user scope wins; omitted fields are NOT inherited). That
844
+ * is how the roster pins gh-router models/thinking for cost control.
845
+ * The shadowed `advisor` alias dies with the builtin oracle definition,
846
+ * which is why `advisor` ships as its own file on cheapest.
847
+ * - `allowedAgents` only narrows an existing nesting grant, so every
848
+ * delegating agent also sets `allowNestedSubagents: true` and lists
849
+ * `subagent` in `tools`. Depth reaches 3 on balanced
850
+ * (lead → General-Purpose → reviewer → Explore), covered by
851
+ * `PI_SUBAGENT_MAX_DEPTH=3` in the launch env (default guard is 2).
852
+ * - Deliberately NO `output:`/`defaultReads`/`defaultProgress` file
853
+ * bindings: single-shot launches resolve relative outputs under
854
+ * per-run artifact dirs while `defaultReads` resolves against the
855
+ * child cwd and skips missing files silently — a lead-mediated
856
+ * Explore→General-Purpose file handoff never fires. Handoff is inline
857
+ * prose via the delegating brief instead. `defaultProgress` is doubly
858
+ * out: its default dir is the repo cwd (untracked litter, no cleanup).
859
+ * - `advertise: true` puts custom agents in the parent prompt catalog
860
+ * (default false); `aliases` catch habitual builtin invocations
861
+ * (`scout`, `worker`, …) deterministically since those builtins are
862
+ * disabled in settings.
863
+ * - `inheritProjectContext: true` keeps bridged repo rules (AGENTS.md)
864
+ * visible to children; `defaultContext: fresh` pins the cold-start
865
+ * contract explicitly instead of relying on implicit fallback.
809
866
  */
810
867
  function buildPiAgentFiles(profileId) {
811
868
  const files = {};
812
869
  for (const role of piNativeRoles(profileId)) {
813
- const tools = role.name === "General-Purpose" ? "[read, bash, edit, write, grep, find, ls]" : "[read, grep, find, ls]";
870
+ const isImplementer = role.name === "General-Purpose";
871
+ const isReviewer = role.name === "reviewer";
872
+ const tools = isImplementer ? "[read, grep, find, ls, bash, edit, write, subagent, contact_supervisor]" : isReviewer ? profileId === "balanced" ? "[read, grep, find, ls, watchdog_diff, contact_supervisor, subagent]" : "[read, grep, find, ls, watchdog_diff, contact_supervisor]" : "[read, grep, find, ls, bash]";
814
873
  const lines = [
815
874
  "---",
816
875
  `name: ${role.name}`,
@@ -818,28 +877,36 @@ function buildPiAgentFiles(profileId) {
818
877
  `tools: ${tools}`,
819
878
  `model: ${PI_PROVIDER_NAME}/${role.model}`,
820
879
  `thinking: ${role.thinking}`,
821
- "max_turns: 80"
880
+ "advertise: true",
881
+ "systemPromptMode: replace",
882
+ "inheritProjectContext: true",
883
+ "defaultContext: fresh"
822
884
  ];
823
- if (profileId === "balanced" && role.name === "reviewer") lines.push("allowedAgents: [Explore]");
824
- if (role.name === "General-Purpose") lines.push("allowedAgents: [reviewer]");
885
+ if (role.name === "Explore") lines.push("aliases: scout");
886
+ if (isImplementer) lines.push("aliases: worker, developer, coder, implementer, develop", "acceptanceRole: writer", "allowNestedSubagents: true", "allowedAgents: reviewer, oracle");
887
+ if (profileId === "balanced" && isReviewer) lines.push("allowNestedSubagents: true", "allowedAgents: Explore");
825
888
  lines.push("---", "");
826
- if (role.name === "Explore") lines.push("You are a read-only scout. Never modify files. Search first, read second,", "return the smallest sufficient evidence: file paths, line spans, and short quotes.");
827
- else if (role.name === "reviewer") lines.push("You review a change that already exists. Reproduce failures before diagnosing.", "Report findings with file:line references; do not rewrite code outside small,", "clearly-marked suggestions.");
828
- else lines.push("You implement the scoped task and verify it (run the relevant tests).", "Hand behavior-changing results to reviewer when asked; otherwise summarize", "the diff and how it was verified.");
889
+ if (role.name === "Explore") lines.push("You are a read-only scout. Never modify files.", "Use bash only for non-interactive inspection.", "Search first, read second: return the smallest sufficient evidence — entry points,", "key types and functions, data flow, files likely to need changes, constraints and", "open questions — with exact file paths and line ranges.");
890
+ else if (isReviewer) lines.push("You are a disciplined review subagent. Inspect the actual change; verify from code,", "tests, and docs — never guess. Cover intent match, correctness and edge cases,", "test coverage, side effects, and minimality.", "Report findings with file:line evidence ranked P0 (blocker) / P1 (should fix) / P2 (nit),", "ending with one of: Merge verdict: BLOCK, Merge verdict: OK, Merge verdict: OK with notes.", "You have no shell: cite the test commands for the lead to run rather than executing them.", "Do not rewrite code outside small, clearly-marked suggestions.");
891
+ else lines.push("You are the single writer thread. Execute the assigned task with narrow, coherent edits;", "the lead remains the decision authority. Work from the brief's pasted context,", "then implement minimally and verify by running the relevant tests.", "If the work reveals an unapproved decision you cannot safely resolve, stop and escalate", "instead of guessing; never leave placeholders or TODOs.", "Hand behavior-changing results to reviewer when asked; otherwise summarize the diff,", "validation, risks, and next step.");
829
892
  files[`agents/${agentFileName(role.name)}`] = `${lines.join("\n")}\n`;
830
893
  }
831
894
  const oracle = [
832
895
  "---",
833
896
  "name: oracle",
834
- `description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.`,
835
- "tools: [read, grep, find, ls]",
897
+ "description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.",
898
+ "tools: [read, grep, find, ls, bash]",
836
899
  `model: ${PI_PROVIDER_NAME}/${piOracleModel(profileId)}`,
837
900
  `thinking: ${piOracleThinking(profileId)}`,
838
- "max_turns: 40",
901
+ "advertise: true",
902
+ "systemPromptMode: replace",
903
+ "inheritProjectContext: true",
904
+ "defaultContext: fresh",
839
905
  "---",
840
906
  "",
841
907
  "You are an oracle: a second set of eyes. You see only the task context",
842
908
  "you are given — you have no repo memory beyond what you read now.",
909
+ "Inspect the code yourself with read/grep/find/ls before opining.",
843
910
  "Challenge assumptions, name what is missing, recommend; never execute."
844
911
  ].join("\n");
845
912
  files[`agents/${agentFileName("oracle")}`] = `${oracle}\n`;
@@ -848,11 +915,14 @@ function buildPiAgentFiles(profileId) {
848
915
  const body = [
849
916
  "---",
850
917
  "name: advisor",
851
- `description: Advisory plan review for the lead: review the final plan before it is presented. Never executes.`,
918
+ "description: Advisory plan review for the lead: review the final plan before it is presented. Never executes.",
852
919
  "tools: [read, grep, find, ls]",
853
920
  `model: ${PI_PROVIDER_NAME}/${advisor.model}`,
854
921
  `thinking: ${advisor.thinking}`,
855
- "max_turns: 40",
922
+ "advertise: true",
923
+ "systemPromptMode: replace",
924
+ "inheritProjectContext: true",
925
+ "defaultContext: fresh",
856
926
  "---",
857
927
  "",
858
928
  "You review the lead's final plan and give advisory feedback only.",
@@ -1125,11 +1195,125 @@ function buildPiStatuslineFooterSection() {
1125
1195
  ` }`
1126
1196
  ];
1127
1197
  }
1198
+ /**
1199
+ * Memory-bridge section for the generated extension: path-scoped rules
1200
+ * lazy-attach on `read/edit/write` tool results (once per rule per
1201
+ * session, mirroring `pi-code/claude-rules.ts`), plus `/memory` (bridge
1202
+ * inventory + auto-memory locations, on-demand only) and `/context`
1203
+ * (what bridged vs skipped). Fail-open: every handler is try/catch and
1204
+ * returns undefined on any error so Pi native behavior is preserved.
1205
+ */
1206
+ function buildPiMemoryBridgeSection(bridge) {
1207
+ const cappedRules = bridge.scopedRules.map((r) => ({
1208
+ file: r.file.replaceAll("\0", ""),
1209
+ body: (r.body.length > 8e3 ? `${r.body.slice(0, 8e3)}\n…[truncated by gh-router memory bridge]` : r.body).replaceAll("\0", ""),
1210
+ globs: r.globs,
1211
+ source: r.source
1212
+ }));
1213
+ return [
1214
+ ` // Memory bridge: lazy path-scoped rules + /memory + /context (on-demand only).`,
1215
+ ` {`,
1216
+ ` let BRIDGE = null;`,
1217
+ ` try { BRIDGE = ${JSON.stringify({
1218
+ stats: bridge.stats,
1219
+ scopedRules: cappedRules
1220
+ })}; } catch { BRIDGE = null; }`,
1221
+ ` const attached = new Set();`,
1222
+ ` function globToRegExp(glob) {`,
1223
+ ` let g = String(glob || "").trim().replace(/^\\.\\//, "").replace(/^\\/+/, "");`,
1224
+ ` let re = "";`,
1225
+ ` for (let k = 0; k < g.length;) {`,
1226
+ ` const c = g[k];`,
1227
+ ` if (c === "*") {`,
1228
+ ` if (g[k + 1] === "*") {`,
1229
+ ` if (g[k + 2] === "/") { re += "(?:.*/)?"; k += 3; }`,
1230
+ ` else { re += ".*"; k += 2; }`,
1231
+ ` } else { re += "[^/]*"; k += 1; }`,
1232
+ ` continue;`,
1233
+ ` }`,
1234
+ ` if (c === "?") { re += "[^/]"; k += 1; continue; }`,
1235
+ ` if ("+()|^$.{}[]\\\\".includes(c)) re += "\\\\" + c; else re += c;`,
1236
+ ` k += 1;`,
1237
+ ` }`,
1238
+ ` if (!g.includes("/")) re = "(?:.*/)?" + re;`,
1239
+ ` try { return new RegExp("^" + re + "$"); } catch { return null; }`,
1240
+ ` }`,
1241
+ ` function ruleMatches(rule, touchedPath, cwd) {`,
1242
+ ` try {`,
1243
+ ` const cands = [touchedPath];`,
1244
+ ` const base = String(touchedPath || "").split("/").pop() || "";`,
1245
+ ` if (base) cands.push(base);`,
1246
+ ` let rel = touchedPath || "";`,
1247
+ ` try {`,
1248
+ ` if (cwd && String(touchedPath).startsWith(String(cwd))) rel = String(touchedPath).slice(String(cwd).length).replace(/^\\/+/, "");`,
1249
+ ` } catch {}`,
1250
+ ` if (rel) cands.push(rel);`,
1251
+ ` for (const g of (rule.globs || [])) {`,
1252
+ ` const re = globToRegExp(g);`,
1253
+ ` if (!re) continue;`,
1254
+ ` for (const c of cands) { try { if (re.test(c)) return true; } catch {} }`,
1255
+ ` }`,
1256
+ ` } catch {}`,
1257
+ ` return false;`,
1258
+ ` }`,
1259
+ ` try {`,
1260
+ ` pi.on("tool_result", async (event, ctx) => {`,
1261
+ ` try {`,
1262
+ ` if (!BRIDGE || !Array.isArray(BRIDGE.scopedRules) || BRIDGE.scopedRules.length === 0) return undefined;`,
1263
+ ` if (event.isError) return undefined;`,
1264
+ ` if (event.toolName !== "read" && event.toolName !== "edit" && event.toolName !== "write") return undefined;`,
1265
+ ` const rel = event.input && event.input.path;`,
1266
+ ` if (typeof rel !== "string" || !rel) return undefined;`,
1267
+ ` let abs = rel;`,
1268
+ ` try { const cwd = ctx.cwd || ""; abs = rel.startsWith("/") ? rel : (cwd ? cwd + "/" + rel : rel); } catch {}`,
1269
+ ` const bodies = [];`,
1270
+ ` for (const rule of BRIDGE.scopedRules) {`,
1271
+ ` try {`,
1272
+ ` if (attached.has(rule.file)) continue;`,
1273
+ ` if (!ruleMatches(rule, abs, ctx.cwd || "")) continue;`,
1274
+ ` attached.add(rule.file);`,
1275
+ ` bodies.push(rule.body);`,
1276
+ ` } catch {}`,
1277
+ ` }`,
1278
+ ` if (bodies.length === 0) return undefined;`,
1279
+ ` return { content: [...(event.content || []), ...bodies.map((text) => ({ type: "text", text }))] };`,
1280
+ ` } catch { return undefined; }`,
1281
+ ` });`,
1282
+ ` } catch {}`,
1283
+ ` try {`,
1284
+ ` pi.registerCommand("memory", {`,
1285
+ ` description: "Show bridged memory inventory and auto-memory locations (on-demand; nothing auto-injected)",`,
1286
+ ` handler: async (_args, ctx) => {`,
1287
+ ` try {`,
1288
+ ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,
1289
+ ` const lines = ["Memory bridge (gh-router)", " Static files: " + s.staticFiles, " Scoped rules (lazy): " + s.scopedRules, " Imports: " + s.imports, " Skipped: " + s.skipped, " Auto-memory: ~/.claude/projects/<slug>/memory/MEMORY.md (on-demand read only)", " Pi memory: ~/.pi/agent/memory/ (your own pi-memory install, snapshotted)"];`,
1290
+ ` try {`,
1291
+ ` const files = (BRIDGE.scopedRules || []).map((r) => r.file);`,
1292
+ ` if (files.length > 0) lines.push(" Scoped files:", ...files.slice(0, 20).map((f) => " - " + f));`,
1293
+ ` } catch {}`,
1294
+ ` lines.push("cwd: " + (ctx.cwd || ""));`,
1295
+ ` ctx.ui.notify(lines.join("\\n"), "info");`,
1296
+ ` } catch {}`,
1297
+ ` },`,
1298
+ ` });`,
1299
+ ` } catch {}`,
1300
+ ` try {`,
1301
+ ` pi.registerCommand("context", {`,
1302
+ ` description: "Show what the gh-router memory bridge loaded",`,
1303
+ ` handler: async (_args, ctx) => {`,
1304
+ ` try {`,
1305
+ ` const s = (BRIDGE && BRIDGE.stats) || { staticFiles: 0, scopedRules: 0, imports: 0, skipped: 0 };`,
1306
+ ` ctx.ui.notify("Bridge context: " + s.staticFiles + " static, " + s.scopedRules + " scoped (attached " + attached.size + "), " + s.imports + " imports, " + s.skipped + " skipped. Native AGENTS.md/CLAUDE.md still load via Pi.", "info");`,
1307
+ ` } catch {}`,
1308
+ ` },`,
1309
+ ` });`,
1310
+ ` } catch {}`,
1311
+ ` }`
1312
+ ];
1313
+ }
1128
1314
  function buildPiExtensionSource(opts) {
1129
1315
  const peers = opts.peers !== false;
1130
1316
  const advisor = peers ? piAdvisorModel(opts.profileId) : void 0;
1131
- const oracleModel = piOracleModel(opts.profileId);
1132
- const oracleThinking = piOracleThinking(opts.profileId);
1133
1317
  const lines = [];
1134
1318
  lines.push(`// gh-router-pi extension (${opts.profileId} mode). Generated per launch; do not edit.`, `// Executable seams only. Workflow guidance lives in skills/, not here.`, `import { Type } from "typebox";`, `import { spawn } from "node:child_process";`, ``, ...peers ? [
1135
1319
  `const OracleParams = Type.Object({`,
@@ -1142,20 +1326,66 @@ function buildPiExtensionSource(opts) {
1142
1326
  ` plan: Type.String({ description: "The final plan to review (advisory)" }),`,
1143
1327
  ` context: Type.Optional(Type.String({ description: "Background context" })),`,
1144
1328
  `});`
1145
- ] : [], `const CodeSearchParams = Type.Object({`, ` query: Type.String({ description: "What to find" }),`, ` mode: Type.Optional(Type.String({ description: "semantic (default), lexical, exact, regex, or ast" })),`, ` limit: Type.Optional(Type.Number({ description: "Max results" })),`, `});`, `const BrowserParams = Type.Object({`, ` url: Type.Optional(Type.String({ description: "URL to act on" })),`, ` intent: Type.Optional(Type.String({ description: "What to do on the page" })),`, `});`, `async function toolText(promise) {`, ` const text = await promise;`, ` return { content: [{ type: "text", text }], details: undefined };`, `}`, `const MCP_URL = (process.env.GH_ROUTER_HOOK_MCP_URL ?? "").replace(/\\/+$/, "");`, `const MCP_NONCE = process.env.GH_ROUTER_HOOK_NONCE ?? "";`, ...peers ? [`const ORACLE_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${oracleModel}`)};`, `const ORACLE_THINKING = ${JSON.stringify(oracleThinking)};`] : [], ...advisor ? [`const ADVISOR_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${advisor.model}`)};`, `const ADVISOR_THINKING = ${JSON.stringify(advisor.thinking)};`] : [], `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`, `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`, ``, `async function callMcp(group, tool, args, signal) {`, ` const res = await fetch(MCP_URL + "/mcp/" + group, {`, ` method: "POST",`, ` headers: { "content-type": "application/json", accept: "application/json", authorization: "Bearer " + MCP_NONCE },`, ` body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } }),`, ` signal,`, ` });`, ` if (!res.ok) throw new Error("mcp " + group + "/" + tool + " -> HTTP " + res.status);`, ` const body = await res.json();`, ` if (body.error) return "Error: " + body.error.message;`, ` const content = body.result && body.result.content;`, ` if (!Array.isArray(content)) return "";`, ` return content.map((c) => c.text || "").join("\\n");`, `}`, ``, `export default function (pi) {`, ...peers ? [
1329
+ ] : [], ...opts.searchEnabled ? [
1330
+ `const CodeSearchParams = Type.Object({`,
1331
+ ` query: Type.String({ description: "What to find" }),`,
1332
+ ` mode: Type.Optional(Type.String({ description: "semantic (default), lexical, exact, regex, or ast" })),`,
1333
+ ` limit: Type.Optional(Type.Number({ description: "Max results" })),`,
1334
+ ` workspace: Type.Optional(Type.String({ description: "Absolute path to the project root to search. Defaults to the launch workspace." })),`,
1335
+ ` file_glob: Type.Optional(Type.String({ description: "Optional ripgrep glob filter (e.g. src/**/*.ts)" })),`,
1336
+ `});`
1337
+ ] : [], ...opts.browseEnabled ? [
1338
+ `const OpenTabParams = Type.Object({`,
1339
+ ` url: Type.String({ description: "URL to load" }),`,
1340
+ ` reuseActive: Type.Optional(Type.Boolean({ description: "Navigate the active tab instead of opening a new one" })),`,
1341
+ `});`,
1342
+ `const NavigateParams = Type.Object({`,
1343
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1344
+ ` action: Type.String({ description: "goto, back, forward, or reload" }),`,
1345
+ ` url: Type.Optional(Type.String({ description: "URL for action=goto" })),`,
1346
+ ` hard: Type.Optional(Type.Boolean({ description: "Reload only: bypass cache" })),`,
1347
+ `});`,
1348
+ `const ScreenshotParams = Type.Object({`,
1349
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1350
+ ` format: Type.Optional(Type.String({ description: "png or jpeg" })),`,
1351
+ ` quality: Type.Optional(Type.Number({ description: "JPEG quality 1-100" })),`,
1352
+ `});`,
1353
+ `const ActParams = Type.Object({`,
1354
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1355
+ ` intent: Type.Optional(Type.String({ description: "Natural-language action (INTENT mode)" })),`,
1356
+ ` ref: Type.Optional(Type.String({ description: "Element ref for REF mode" })),`,
1357
+ ` action: Type.Optional(Type.String({ description: "REF mode action" })),`,
1358
+ ` value: Type.Optional(Type.String({ description: "Value for fill/type/select" })),`,
1359
+ `});`,
1360
+ `const ObserveParams = Type.Object({`,
1361
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1362
+ ` intent: Type.Optional(Type.String({ description: "Focus for the summary" })),`,
1363
+ `});`,
1364
+ `const ExtractParams = Type.Object({`,
1365
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1366
+ ` schema: Type.Any({ description: "JSON schema for the desired output shape" }),`,
1367
+ ` instruction: Type.String({ description: "What to extract" }),`,
1368
+ `});`
1369
+ ] : [], `function stripNul(s) { return String(s ?? "").replace(/\\0/g, ""); }`, `async function toolText(promise) {`, ` const text = await promise;`, ` return { content: [{ type: "text", text: stripNul(text) }], details: undefined };`, `}`, `function toolErrorText(text) {`, ` return { content: [{ type: "text", text }], details: undefined };`, `}`, `const MCP_URL = (process.env.GH_ROUTER_HOOK_MCP_URL ?? "").replace(/\\/+$/, "");`, `const MCP_NONCE = process.env.GH_ROUTER_HOOK_NONCE ?? "";`, `const PI_WORKSPACE = (process.env.GH_ROUTER_WORKSPACE ?? "").trim();`, `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`, `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`, `void LEAD_MODEL; void LEAD_THINKING;`, ``, `async function callMcp(group, tool, args, signal) {`, ` const headers = { "content-type": "application/json", accept: "application/json", authorization: "Bearer " + MCP_NONCE };`, ` if (PI_WORKSPACE && (group === "search" || group === "workers" || group === "orchestrate")) { headers["X-GH-Workspace"] = PI_WORKSPACE; }`, ` const res = await fetch(MCP_URL + "/mcp/" + group, {`, ` method: "POST",`, ` headers,`, ` body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } }),`, ` signal,`, ` });`, ` if (!res.ok) throw new Error("mcp " + group + "/" + tool + " -> HTTP " + res.status);`, ` const body = await res.json();`, ` if (body.error) return "Error: " + body.error.message;`, ` const content = body.result && body.result.content;`, ` if (!Array.isArray(content)) return "";`, ` return content.map((c) => c.text || "").join("\\n");`, `}`, ``, `export default function (pi) {`, ...peers ? [
1146
1370
  ` pi.registerTool({`,
1147
1371
  ` name: "oracle",`,
1148
1372
  ` label: "Oracle",`,
1149
1373
  ` description: "Second opinion before acting on a risky decision. Advisory only: challenges assumptions, never edits. Pass decision, options, and context.",`,
1150
1374
  ` parameters: OracleParams,`,
1151
1375
  ` async execute(_toolCallId, params, signal) {`,
1152
- ` return await toolText(callMcp("peers", "oracle", { decision: params.decision, options: params.options || "", context: params.context, model: ORACLE_MODEL, thinking: ORACLE_THINKING }, signal));`,
1376
+ ` const query = stripNul(params.decision || "").trim();`,
1377
+ ` const opts = stripNul(params.options || "").trim();`,
1378
+ ` const ctx = stripNul(params.context || "").trim();`,
1379
+ ` const context = (opts ? "Options considered:\\n" + opts + "\\n\\n" : "") + ctx;`,
1380
+ ` if (!query || !context.trim()) return toolErrorText("oracle: decision and context are required (non-empty strings)");`,
1381
+ ` return await toolText(callMcp("peers", "oracle", { query, context }, signal));`,
1153
1382
  ` },`,
1154
1383
  ` });`
1155
1384
  ] : []);
1156
- if (advisor) lines.push(` pi.registerTool({`, ` name: "advisor",`, ` label: "Advisor",`, ` description: "Advisory plan review for the lead: review the final plan before presenting it. Never executes.",`, ` parameters: AdvisorParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("peers", "oracle", { decision: "Review this plan (advisory)", options: params.plan, context: params.context || "", model: ADVISOR_MODEL, thinking: ADVISOR_THINKING }, signal));`, ` },`, ` });`);
1157
- if (opts.searchEnabled) lines.push(` pi.registerTool({`, ` name: "code_search",`, ` label: "Code search",`, ` description: "Semantic-first code search over the workspace index (falls back to lexical with a label). Use for finding code by meaning.",`, ` parameters: CodeSearchParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("search", "code", { query: params.query, mode: params.mode || "semantic", limit: params.limit || 15 }, signal));`, ` },`, ` });`);
1158
- if (opts.browseEnabled) lines.push(` const BROWSER_TOOLS = ["browser_open_tab", "browser_navigate", "browser_screenshot", "browser_act", "browser_observe", "browser_extract"];`, ` for (const wireName of BROWSER_TOOLS) {`, ` pi.registerTool({`, ` name: wireName,`, ` description: "Browser control (" + wireName + "). Returns install_required with setup steps when the extension is not loaded.",`, ` parameters: BrowserParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("browser", wireName, { url: params.url || "", intent: params.intent || "" }, signal));`, ` },`, ` });`, ` }`);
1385
+ if (advisor) lines.push(` pi.registerTool({`, ` name: "advisor",`, ` label: "Advisor",`, ` description: "Advisory plan review for the lead: review the final plan before presenting it. Never executes.",`, ` parameters: AdvisorParams,`, ` async execute(_toolCallId, params, signal) {`, ` const plan = stripNul(params.plan || "").trim();`, ` const ctx = stripNul(params.context || "").trim();`, ` const context = (plan ? "Plan under review:\\n" + plan : "") + (ctx ? "\\n\\nBackground:\\n" + ctx : "");`, ` if (!plan || !context.trim()) return toolErrorText("advisor: plan and context are required (non-empty strings)");`, ` return await toolText(callMcp("peers", "oracle", { query: "Review this plan (advisory)", context }, signal));`, ` },`, ` });`);
1386
+ if (opts.searchEnabled) lines.push(` pi.registerTool({`, ` name: "code_search",`, ` label: "Code search",`, ` description: "Semantic-first code search over the workspace index (falls back to lexical with a label). Use for finding code by meaning.",`, ` parameters: CodeSearchParams,`, ` async execute(_toolCallId, params, signal) {`, ` const query = stripNul(params.query || "").trim();`, ` if (!query) return toolErrorText("code_search: query is required (non-empty string)");`, ` const workspace = (typeof params.workspace === "string" && params.workspace.trim()) ? params.workspace.trim() : PI_WORKSPACE;`, ` if (!workspace) return toolErrorText("code_search: a workspace is required. Pass the absolute project path as workspace.");`, ` const args = { query, mode: params.mode || "semantic", limit: params.limit || 15, workspace };`, ` if (typeof params.file_glob === "string" && params.file_glob) args.file_glob = params.file_glob;`, ` return await toolText(callMcp("search", "code", args, signal));`, ` },`, ` });`);
1387
+ if (opts.browseEnabled) lines.push(` pi.registerTool({`, ` name: "open_tab",`, ` label: "Browser open tab",`, ` description: "Open a URL in a new browser tab (MCP browser/open_tab). Returns install_required with setup steps when the extension is not loaded.",`, ` parameters: OpenTabParams,`, ` async execute(_toolCallId, params, signal) {`, ` const url = stripNul(params.url || "").trim();`, ` if (!url) return toolErrorText("open_tab: url is required");`, ` const args = { url };`, ` if (typeof params.reuseActive === "boolean") args.reuseActive = params.reuseActive;`, ` return await toolText(callMcp("browser", "open_tab", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "navigate",`, ` label: "Browser navigate",`, ` description: "Navigate an existing tab (MCP browser/navigate). Requires tabId + action; url only for action=goto.",`, ` parameters: NavigateParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("navigate: tabId is required (number from open_tab)");`, ` if (!params.action) return toolErrorText("navigate: action is required (goto, back, forward, reload)");`, ` const args = { tabId: params.tabId, action: params.action };`, ` if (typeof params.url === "string" && params.url) args.url = params.url;`, ` if (typeof params.hard === "boolean") args.hard = params.hard;`, ` return await toolText(callMcp("browser", "navigate", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "screenshot",`, ` label: "Browser screenshot",`, ` description: "Screenshot a tab (MCP browser/screenshot). Requires tabId.",`, ` parameters: ScreenshotParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("screenshot: tabId is required (number from open_tab)");`, ` const args = { tabId: params.tabId };`, ` if (typeof params.format === "string" && params.format) args.format = params.format;`, ` if (typeof params.quality === "number") args.quality = params.quality;`, ` return await toolText(callMcp("browser", "screenshot", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "act",`, ` label: "Browser act",`, ` description: "Interact with a tab (MCP browser/act). Requires tabId plus intent or ref.",`, ` parameters: ActParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("act: tabId is required (number from open_tab)");`, ` if (!params.intent && !params.ref) return toolErrorText("act: intent or ref is required");`, ` const args = { tabId: params.tabId };`, ` if (typeof params.intent === "string" && params.intent) args.intent = params.intent;`, ` if (typeof params.ref === "string" && params.ref) args.ref = params.ref;`, ` if (typeof params.action === "string" && params.action) args.action = params.action;`, ` if (typeof params.value === "string") args.value = params.value;`, ` return await toolText(callMcp("browser", "act", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "observe",`, ` label: "Browser observe",`, ` description: "Summarize a tab (MCP browser/observe). Requires tabId.",`, ` parameters: ObserveParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("observe: tabId is required (number from open_tab)");`, ` const args = { tabId: params.tabId };`, ` if (typeof params.intent === "string" && params.intent) args.intent = params.intent;`, ` return await toolText(callMcp("browser", "observe", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "extract",`, ` label: "Browser extract",`, ` description: "Extract structured data from a tab (MCP browser/extract). Requires tabId, schema, instruction.",`, ` parameters: ExtractParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("extract: tabId is required (number from open_tab)");`, ` if (!params.instruction) return toolErrorText("extract: instruction is required");`, ` if (params.schema === undefined) return toolErrorText("extract: schema is required");`, ` return await toolText(callMcp("browser", "extract", { tabId: params.tabId, schema: params.schema, instruction: params.instruction }, signal));`, ` },`, ` });`);
1388
+ if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
1159
1389
  lines.push(...buildPiStatuslineFooterSection(), ` // 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;`, ` }`, ` });`, `}`, ``);
1160
1390
  return `${lines.join("\n")}\n`;
1161
1391
  }
@@ -1163,8 +1393,9 @@ function buildPiExtensionSource(opts) {
1163
1393
  * Workflow guidance as skills (progressive disclosure, not tools).
1164
1394
  * Ownership mirrors the Claude launcher: peer consult prose rides
1165
1395
  * `--peers`, semantic-search prose rides `--search`, and the
1166
- * delegation/review pipeline rides `--swe`. A bare launch emits NO
1167
- * skills at all.
1396
+ * delegation/review pipeline rides `--swe` AND `--peers` — without
1397
+ * agents + the subagent provider its prose dangles, so peerless+swe
1398
+ * emits none. A bare launch emits NO skills at all.
1168
1399
  */
1169
1400
  function buildPiSkills(opts) {
1170
1401
  const peers = opts.peers !== false;
@@ -1182,7 +1413,9 @@ function buildPiSkills(opts) {
1182
1413
  "Call the `oracle` tool with the decision, the options considered, and the",
1183
1414
  "missing-context gaps. The oracle is cold-start: it sees only what you pass.",
1184
1415
  "Its verdict is advisory — verify with tests and code, never substitute votes",
1185
- "for verification."
1416
+ "for verification. (The `oracle` tool is the one-shot consult; the `oracle`",
1417
+ "subagent is the same role for interactive follow-ups — same name, different",
1418
+ "invocation. Prefer the tool for a single verdict.)"
1186
1419
  ].join("\n")
1187
1420
  });
1188
1421
  if (opts.search === true) skills.push({
@@ -1201,7 +1434,8 @@ function buildPiSkills(opts) {
1201
1434
  "assuming full coverage."
1202
1435
  ].join("\n")
1203
1436
  });
1204
- if (opts.swe === true) {
1437
+ if (opts.swe === true && peers) {
1438
+ const consults = opts.profileId === "balanced" ? "`oracle` for consults" : "`oracle`/`advisor` for consults";
1205
1439
  skills.push({
1206
1440
  dir: "gh-delegate",
1207
1441
  content: [
@@ -1212,9 +1446,14 @@ function buildPiSkills(opts) {
1212
1446
  "",
1213
1447
  "# Delegate",
1214
1448
  "",
1215
- "Recommended loop: scout (Explore) before you understand the code, worker",
1216
- "(General-Purpose) to implement, fresh reviewers to check, worker to apply",
1217
- "feedback. Keep delegated tasks scoped with file:line evidence on return.",
1449
+ "You may delegate via the `subagent` tool to this roster only: `Explore`",
1450
+ "for discovery, `General-Purpose` for scoped implementation, `reviewer`",
1451
+ `for verification, ${consults}. (Builtin \`scout\` and`,
1452
+ "`worker` are disabled in this session; their aliases resolve here.)",
1453
+ "Recommended loop: `Explore` to map the code, paste the brief excerpts",
1454
+ "into the `General-Purpose` brief to implement, `reviewer` to check,",
1455
+ "`General-Purpose` to apply feedback. Keep delegated tasks",
1456
+ "scoped with file:line evidence on return.",
1218
1457
  opts.profileId === "balanced" ? "Send work to reviewer ONLY when the change alters behavior." : "Send finished work to reviewer for assessment."
1219
1458
  ].join("\n")
1220
1459
  });
@@ -1238,11 +1477,17 @@ function buildPiSkills(opts) {
1238
1477
  }
1239
1478
  /**
1240
1479
  * Saved workflow shortcuts as prompt templates (`/name`). The review
1241
- * pipeline is SWE-pipeline surface: only `--swe` emits prompts, so a
1242
- * bare launch advertises none.
1480
+ * pipeline is SWE-pipeline surface: only `--swe` AND `--peers` emit
1481
+ * prompts (peerless launches have no agents behind them), so a bare
1482
+ * launch advertises none.
1483
+ *
1484
+ * `/parallel-review` intentionally shadows the packaged pi-subagents
1485
+ * prompt of the same name (package prompts are filtered to `[]` in
1486
+ * settings): ours routes to our pinned-model `reviewer`, not the
1487
+ * default-model builtin. `/review` is novel — no packaged collision.
1243
1488
  */
1244
1489
  function buildPiPrompts(opts) {
1245
- if (opts.swe !== true) return [];
1490
+ if (opts.swe !== true || opts.peers === false) return [];
1246
1491
  const prompts = [{
1247
1492
  name: "review",
1248
1493
  content: [
@@ -1302,6 +1547,11 @@ const piArgs = {
1302
1547
  type: "boolean",
1303
1548
  default: true,
1304
1549
  description: "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."
1550
+ },
1551
+ "memory-bridge": {
1552
+ type: "boolean",
1553
+ default: true,
1554
+ 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."
1305
1555
  }
1306
1556
  };
1307
1557
  /**
@@ -1467,21 +1717,48 @@ const pi = defineCommand({
1467
1717
  } catch {
1468
1718
  userSettings = {};
1469
1719
  }
1720
+ const builtSettings = buildPiSettingsJson({
1721
+ profileId,
1722
+ searchEnabled,
1723
+ browseEnabled,
1724
+ catalog,
1725
+ peers: peersEnabled
1726
+ });
1727
+ const mergedSubagents = mergeSubagentsSettings(userSettings["subagents"], builtSettings.subagents);
1470
1728
  await writeJsonFile(settingsPath, {
1471
1729
  ...userSettings,
1472
- ...buildPiSettingsJson({
1473
- profileId,
1474
- searchEnabled,
1475
- browseEnabled,
1476
- catalog,
1477
- peers: peersEnabled
1478
- })
1730
+ ...builtSettings,
1731
+ ...mergedSubagents ? { subagents: mergedSubagents } : {}
1479
1732
  });
1733
+ const bridgeDisabled = args["memory-bridge"] === false || process$1.env.GH_ROUTER_PI_BRIDGE === "0" || process$1.env.GH_ROUTER_DISABLE_PI_BRIDGE === "1";
1734
+ let bridgeStats;
1735
+ let bridgeScoped = [];
1736
+ if (!bridgeDisabled) {
1737
+ const passthrough = collectPiPassthroughArgs(rawArgs, piArgs);
1738
+ if (!(passthrough.includes("--no-context-files") || passthrough.includes("-nc"))) try {
1739
+ const { collectBridgeInputs } = await import("./pi-memory-bridge-DEU1SUDz.js");
1740
+ const collected = await collectBridgeInputs(process$1.cwd());
1741
+ bridgeStats = {
1742
+ staticFiles: collected.copilotInstructions.length + collected.unscopedRules.length + collected.userGlobal.length,
1743
+ scopedRules: collected.scopedRules.length,
1744
+ imports: collected.imports.length,
1745
+ skipped: collected.skipped.length
1746
+ };
1747
+ bridgeScoped = collected.scopedRules;
1748
+ globalThis.__ghRouterBridgeCollected = collected;
1749
+ } catch (err) {
1750
+ consola.debug("Pi memory bridge collection skipped:", err);
1751
+ }
1752
+ }
1480
1753
  await writeTextFile(path.join(mirror, "extensions", "gh-router-pi", "index.ts"), buildPiExtensionSource({
1481
1754
  profileId,
1482
1755
  searchEnabled,
1483
1756
  browseEnabled,
1484
- peers: peersEnabled
1757
+ peers: peersEnabled,
1758
+ bridge: bridgeStats ? {
1759
+ stats: bridgeStats,
1760
+ scopedRules: bridgeScoped
1761
+ } : void 0
1485
1762
  }));
1486
1763
  if (peersEnabled) {
1487
1764
  const agentFiles = buildPiAgentFiles(profileId);
@@ -1495,9 +1772,35 @@ const pi = defineCommand({
1495
1772
  })) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
1496
1773
  for (const prompt of buildPiPrompts({
1497
1774
  profileId,
1498
- swe: sweEnabled
1775
+ swe: sweEnabled,
1776
+ peers: peersEnabled
1499
1777
  })) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
1500
1778
  await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, { peers: peersEnabled }));
1779
+ try {
1780
+ const collected = globalThis.__ghRouterBridgeCollected;
1781
+ if (collected) {
1782
+ const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-DEU1SUDz.js");
1783
+ const { section } = buildMirrorBridgeSection(collected, { repoRoot: process$1.cwd() });
1784
+ const agentsPath = path.join(mirror, "AGENTS.md");
1785
+ let existing;
1786
+ try {
1787
+ existing = await fs.readFile(agentsPath, "utf8");
1788
+ } catch {
1789
+ existing = void 0;
1790
+ }
1791
+ await writeTextFile(agentsPath, mergeBridgeIntoAgentsMd(existing, section));
1792
+ await writeJsonFile(path.join(mirror, ".gh-router-bridge.json"), {
1793
+ stats: bridgeStats ?? null,
1794
+ scopedRuleFiles: bridgeScoped.map((r) => r.file)
1795
+ });
1796
+ }
1797
+ } catch (err) {
1798
+ consola.debug("Pi memory bridge synthesis skipped:", err);
1799
+ } finally {
1800
+ try {
1801
+ delete globalThis.__ghRouterBridgeCollected;
1802
+ } catch {}
1803
+ }
1501
1804
  } catch (err) {
1502
1805
  consola.error(`Failed to write Pi launch files: ${err instanceof Error ? err.message : String(err)}.`);
1503
1806
  process$1.exit(1);
@@ -1541,6 +1844,7 @@ const pi = defineCommand({
1541
1844
  const modelIds = piProfileModelIds(profileId, { peers: peersEnabled });
1542
1845
  const surface = [`peers=${peersEnabled ? "on" : "off"}`, `swe=${sweEnabled ? "on" : "off"}`].join(" ");
1543
1846
  process$1.stderr.write(`Server ready on ${serverUrl}, launching Pi (${profileId} lead ${lead}, models ${modelIds.length}, ${surface})...\n`);
1847
+ 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");
1544
1848
  const { disposeBluebirdClients } = await import("./bluebird-client-bn9Yv6Cb.js");
1545
1849
  launchChild({
1546
1850
  kind: "pi",
@@ -1548,6 +1852,8 @@ const pi = defineCommand({
1548
1852
  ...getPiLaunchEnvVars(mirror),
1549
1853
  GH_ROUTER_HOOK_MCP_URL: serverUrl,
1550
1854
  GH_ROUTER_HOOK_NONCE: nonce,
1855
+ GH_ROUTER_WORKSPACE: process$1.cwd(),
1856
+ PI_SUBAGENT_MAX_DEPTH: "3",
1551
1857
  ...aicLedgerEnv ? { [AIC_LEDGER_ENV]: aicLedgerEnv } : {},
1552
1858
  ...aicStatusCommandEnv ? { [PI_STATUS_COMMAND_ENV]: aicStatusCommandEnv } : {}
1553
1859
  },
@@ -1565,4 +1871,4 @@ const pi = defineCommand({
1565
1871
  //#endregion
1566
1872
  export { pi };
1567
1873
 
1568
- //# sourceMappingURL=pi-BNvhtN7g.js.map
1874
+ //# sourceMappingURL=pi-CnsdJGF0.js.map