github-router 0.3.371 → 0.3.372

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/ado-tools-CAtopk36.js +1 -0
  2. package/dist/{attribution-settings-Beer9wsJ.js → attribution-settings-HI_5bN_-.js} +6 -6
  3. package/dist/{attribution-settings-Beer9wsJ.js.map → attribution-settings-HI_5bN_-.js.map} +1 -1
  4. package/dist/browser-ext/manifest.json +1 -1
  5. package/dist/{claude-CAYTTiyt.js → claude-BBSsqwln.js} +10 -10
  6. package/dist/claude-BBSsqwln.js.map +1 -0
  7. package/dist/{claude-md-injection-D1aMjvb_.js → claude-md-injection-BMon6WUD.js} +19 -22
  8. package/dist/claude-md-injection-BMon6WUD.js.map +1 -0
  9. package/dist/{codex-CALX-qG4.js → codex-PRWoBiOH.js} +5 -5
  10. package/dist/{codex-CALX-qG4.js.map → codex-PRWoBiOH.js.map} +1 -1
  11. package/dist/engine-CDZdAx8N.js +1 -0
  12. package/dist/{gate-discovery-CITKjhsD.js → gate-discovery-BNy8GKsC.js} +2 -2
  13. package/dist/{gate-discovery-CITKjhsD.js.map → gate-discovery-BNy8GKsC.js.map} +1 -1
  14. package/dist/hooks.mjs +45 -10
  15. package/dist/hooks.sha256 +1 -1
  16. package/dist/{internal-prompt-submit-bi7F7pKk.js → internal-prompt-submit-BW5g3MjD.js} +2 -2
  17. package/dist/{internal-prompt-submit-bi7F7pKk.js.map → internal-prompt-submit-BW5g3MjD.js.map} +1 -1
  18. package/dist/{internal-prompt-submit-B-kKTl-8.js → internal-prompt-submit-C4uDwr7G.js} +2 -2
  19. package/dist/{internal-rebrief-B6ZJS6Mp.js → internal-rebrief-DvBS8myn.js} +3 -3
  20. package/dist/{internal-rebrief-B6ZJS6Mp.js.map → internal-rebrief-DvBS8myn.js.map} +1 -1
  21. package/dist/{internal-stop-hook-DT27bzH7.js → internal-stop-hook-CXlOsW63.js} +2 -2
  22. package/dist/{internal-stop-hook-DT27bzH7.js.map → internal-stop-hook-CXlOsW63.js.map} +1 -1
  23. package/dist/main.js +8 -8
  24. package/dist/{peer-mcp-personas-D7vaM-V5.js → peer-mcp-personas-Dxxw5X1g.js} +265 -242
  25. package/dist/peer-mcp-personas-Dxxw5X1g.js.map +1 -0
  26. package/dist/{pi-D4LrdubN.js → pi-IYAvKF50.js} +805 -68
  27. package/dist/pi-IYAvKF50.js.map +1 -0
  28. package/dist/{provision-DonGTIfK.js → provision-CIn6I4w_.js} +33 -2
  29. package/dist/provision-CIn6I4w_.js.map +1 -0
  30. package/dist/{serve-jzmQ8KEE.js → serve-CttHP8dJ.js} +7 -7
  31. package/dist/{serve-jzmQ8KEE.js.map → serve-CttHP8dJ.js.map} +1 -1
  32. package/dist/{server-setup-wWidNq5m.js → server-setup-D7XHUrhM.js} +20 -17
  33. package/dist/server-setup-D7XHUrhM.js.map +1 -0
  34. package/dist/{start-CTluQxu5.js → start-XU5HwLd9.js} +3 -3
  35. package/dist/{start-CTluQxu5.js.map → start-XU5HwLd9.js.map} +1 -1
  36. package/dist/{static-context-pack-DvwLWlbe.js → static-context-pack-CsOAC87F.js} +98 -18
  37. package/dist/static-context-pack-CsOAC87F.js.map +1 -0
  38. package/dist/{workiq-tools-CDLIrILp.js → workiq-tools-CMoDjrO0.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/ado-tools-512UGB6R.js +0 -1
  41. package/dist/claude-CAYTTiyt.js.map +0 -1
  42. package/dist/claude-md-injection-D1aMjvb_.js.map +0 -1
  43. package/dist/engine-CSAEqj2p.js +0 -1
  44. package/dist/peer-mcp-personas-D7vaM-V5.js.map +0 -1
  45. package/dist/pi-D4LrdubN.js.map +0 -1
  46. package/dist/provision-DonGTIfK.js.map +0 -1
  47. package/dist/server-setup-wWidNq5m.js.map +0 -1
  48. package/dist/static-context-pack-DvwLWlbe.js.map +0 -1
@@ -2,13 +2,13 @@ import { P as warmTreeSitterPool } from "./service-backend-B6D_DY1Z.js";
2
2
  import { t as getPackageVersion } from "./version-C8x2hQrZ.js";
3
3
  import { t as PATHS } from "./paths-C5477RGC.js";
4
4
  import { t as state } from "./state-DzsaGHr9.js";
5
- 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-wWidNq5m.js";
6
- import { Bn as colbertDegradedWarning, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, Dt as artifactToolsEnabled, Nt as browserToolsEnabled, Pn as provisionBrowserAssets, Qt as kustoToolsEnabled, Sn as unregisterLaunch, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, bn as registerLaunch, fn as configureLocalEgress, jt as browseAgentEnabled, pn as localBaseUrl, sn as workiqToolsEnabled } from "./peer-mcp-personas-D7vaM-V5.js";
7
- import { D as LOCAL_PROFILE_TIER_MODELS, S as localContractFor, _ as isCheapestFamily, f as balancedContractFor, g as isBalancedFamily, p as cheapestContractFor, v as isCheaplocalProfile, x as local2AdvisorContract, y as isLocalFamily } from "./static-context-pack-DvwLWlbe.js";
5
+ 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-D7XHUrhM.js";
6
+ import { Bn as colbertDegradedWarning, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, Dt as artifactToolsEnabled, Gn as LOCAL_CONSULT_REDACTION_NOTE, Mn as provisionBrowserAssets, Nt as browserToolsEnabled, Qt as kustoToolsEnabled, Sn as unregisterLaunch, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, Wn as LOCAL_CONSULT_REDACTION_LINE, bn as registerLaunch, fn as configureLocalEgress, jt as browseAgentEnabled, pn as localBaseUrl, sn as workiqToolsEnabled } from "./peer-mcp-personas-Dxxw5X1g.js";
7
+ import { C as localContractFor, O as LOCAL_PROFILE_TIER_MODELS, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, h as consultIsLocalTransport, p as cheapestContractFor, v as isCheapestFamily, y as isCheaplocalProfile } from "./static-context-pack-CsOAC87F.js";
8
8
  import { r as resolveSelfInvocation } from "./self-invocation-BtcGj-lY.js";
9
- import { i as launchChild, t as provisionToolbelt } from "./provision-DonGTIfK.js";
9
+ import { i as launchChild, t as provisionToolbelt } from "./provision-CIn6I4w_.js";
10
10
  import { d as removeAicLedgerFile, f as sweepStaleAicLedgerFiles, n as aicSnapshot, o as formatAicExitSummary, t as aicLedgerPath } from "./aic-ledger-Cp7Yk9-Q.js";
11
- import { t as FRESH_CONSULT_CONTRACT } from "./claude-md-injection-D1aMjvb_.js";
11
+ import { t as FRESH_CONSULT_CONTRACT } from "./claude-md-injection-BMon6WUD.js";
12
12
  import { i as buildAicStatusHookCommand, n as AIC_STATUSLINE_DISABLE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-B5EMMSFC.js";
13
13
  import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-T-cfWmc4.js";
14
14
  import { defineCommand } from "citty";
@@ -288,6 +288,51 @@ function buildPiStatusPayload(source, opts) {
288
288
  worktree: null
289
289
  };
290
290
  }
291
+ //#endregion
292
+ //#region src/lib/pi-package-cache.ts
293
+ /**
294
+ * Persistent npm-package cache for Pi launches.
295
+ *
296
+ * Pi installs the mirror's `packages[]` into `<agentDir>/npm` on every
297
+ * boot, and the agent dir is a fresh per-launch mirror
298
+ * (`pi-agent-<pid>-<rand>`) — so every launch pays a full registry
299
+ * install (~5s + `added N packages` noise that bypasses
300
+ * `npm_config_loglevel=error`). Pi skips the install when the package
301
+ * dir already exists and the installed version satisfies the configured
302
+ * range — and unpinned `npm:name` specs match ANY installed version —
303
+ * so pre-seeding `<mirror>/npm` from a durable cache makes repeat
304
+ * launches install nothing: faster AND silent.
305
+ *
306
+ * Keyed by the exact package set (sorted spec fingerprints), so flag
307
+ * combinations (`--helpers`/`--ui`/`--search`/`--browse`) each get
308
+ * their own entry and can never cross-contaminate. Entries older than
309
+ * the max age are treated as a miss so unpinned packages periodically
310
+ * refresh to upstream latest; the fresh install is then saved back over
311
+ * the entry. Opt out entirely with `GH_ROUTER_PI_NO_PACKAGE_CACHE=1`.
312
+ *
313
+ * Max age defaults to 24h, not the original 7d. Pi resolves an unpinned
314
+ * `npm:name` spec to whatever is already installed, so the max age IS the
315
+ * worst-case staleness of every extension the user runs — a week of it meant a
316
+ * fix published upstream on Monday was still missing the following Sunday.
317
+ * A day bounds the lag without making the cache pointless: the npm install it
318
+ * avoids takes ~5s, so one refresh per day is paid back by every other launch
319
+ * that day. Override with `GH_ROUTER_PI_PACKAGE_CACHE_HOURS`.
320
+ */
321
+ const PI_PACKAGE_CACHE_MAX_AGE_MS = 864e5;
322
+ /**
323
+ * Effective max age. Read per call rather than at module load so a test (or a
324
+ * long-lived process re-reading config) can change the env and observe it, and
325
+ * so a malformed value degrades to the default instead of `NaN` day math —
326
+ * `Date.now() - mtime > NaN` is always false, which would make every entry
327
+ * eternally fresh.
328
+ */
329
+ function piPackageCacheMaxAgeMs() {
330
+ const raw = (process.env["GH_ROUTER_PI_PACKAGE_CACHE_HOURS"] ?? "").trim();
331
+ if (!raw) return PI_PACKAGE_CACHE_MAX_AGE_MS;
332
+ const hours = Number(raw);
333
+ if (!Number.isFinite(hours) || hours <= 0) return PI_PACKAGE_CACHE_MAX_AGE_MS;
334
+ return hours * 3600 * 1e3;
335
+ }
291
336
  function cacheDisabled() {
292
337
  return process.env.GH_ROUTER_PI_NO_PACKAGE_CACHE === "1";
293
338
  }
@@ -333,8 +378,10 @@ async function seedPiPackageCache(mirrorDir, packages) {
333
378
  const cachedNpm = npmDirOf(piPackageCacheDir(key));
334
379
  const mtime = await mtimeMsOf(cachedNpm);
335
380
  if (mtime === null) return false;
336
- if (Date.now() - mtime > 6048e5) {
337
- consola.debug(`Pi package cache ${key} is stale; refreshing from registry.`);
381
+ const maxAge = piPackageCacheMaxAgeMs();
382
+ if (Date.now() - mtime > maxAge) {
383
+ const ageHours = Math.floor((Date.now() - mtime) / 36e5);
384
+ consola.debug(`Pi package cache ${key} is stale (${ageHours}h old, max ${Math.round(maxAge / 36e5)}h); refreshing from registry.`);
338
385
  return false;
339
386
  }
340
387
  try {
@@ -383,7 +430,7 @@ async function sweepStalePiPackageCaches() {
383
430
  const npmDir = npmDirOf(path.join(root, entry));
384
431
  try {
385
432
  const mtime = await mtimeMsOf(npmDir);
386
- if (mtime === null || Date.now() - mtime > 6048e5) await fs$1.rm(path.join(root, entry), {
433
+ if (mtime === null || Date.now() - mtime > piPackageCacheMaxAgeMs()) await fs$1.rm(path.join(root, entry), {
387
434
  recursive: true,
388
435
  force: true
389
436
  });
@@ -471,21 +518,32 @@ function piOracleToolReachable(profileId) {
471
518
  return allowlist === void 0 || allowlist.has("oracle");
472
519
  }
473
520
  /**
521
+ * Whether this profile has a consultant at all.
522
+ *
523
+ * Every Pi profile does. `local` used to be the exception on the reading that
524
+ * the Oracle is necessarily a Copilot call — it is not: the contract's
525
+ * `consultTransport` decides, and `local` declares `"local"`, so its Oracle is
526
+ * a consult of the same endpoint its lead already uses. The role therefore
527
+ * exists on every profile and `piOracleModel` never returns `undefined` for one
528
+ * of them; the transport, not the presence, is what differs.
529
+ */
530
+ function piOracleEnabled(_profileId) {
531
+ return true;
532
+ }
533
+ /**
474
534
  * Which model answers the `oracle` subagent.
475
535
  *
476
- * Every Copilot profile's oracle is a Copilot-served consultant pinned by its
477
- * family contract. `local` has no Copilot oracle at all, yet the subagent
478
- * still has to be emitted: omitting the file would un-shadow Pi's builtin
479
- * `oracle`, which also owns the `advisor` alias and is pinned to a model of
480
- * its own choosing. Pinning our file to the local lead tier keeps the role,
481
- * its nesting grant and the shadowing intact while running it on the one
482
- * endpoint the profile is allowed to use.
536
+ * Always a real id: a Copilot slug on every profile whose consult is billed,
537
+ * and the local lead tier (`opus`) on `local`, whose consult goes to the local
538
+ * endpoint like the rest of its turns. The transport is not this function's
539
+ * business — `piContractFor(profileId).consultTransport` is — so a caller that
540
+ * needs to know where the consult runs must ask the contract.
483
541
  */
484
542
  function piOracleModel(profileId) {
485
- return profileId === "local" ? piLeadModel(profileId) : piContractFor(profileId).oracleModel;
543
+ return piOracleEnabled(profileId) ? piContractFor(profileId).oracleModel : void 0;
486
544
  }
487
545
  function piOracleThinking(profileId) {
488
- return profileId === "local" ? piLeadThinking(profileId) : piContractFor(profileId).oracleEffort;
546
+ return piOracleEnabled(profileId) ? piContractFor(profileId).oracleEffort : void 0;
489
547
  }
490
548
  /**
491
549
  * Advisor row. Cheapest-family launches carry one; `balanced` is advisor-free
@@ -540,7 +598,8 @@ function piNativeRoles(profileId) {
540
598
  function piProfileModelIds(profileId, opts = {}) {
541
599
  const ids = /* @__PURE__ */ new Set([piLeadModel(profileId)]);
542
600
  if (opts.peers !== false) {
543
- ids.add(piOracleModel(profileId));
601
+ const oracle = piOracleModel(profileId);
602
+ if (oracle) ids.add(oracle);
544
603
  for (const r of piNativeRoles(profileId)) ids.add(r.model);
545
604
  const advisor = piAdvisorModel(profileId);
546
605
  if (advisor) ids.add(advisor.model);
@@ -773,6 +832,9 @@ const PI_COSMETIC_SETTING_KEYS = [
773
832
  "fullscreenCopyOnSelect",
774
833
  "fullscreenWheelScrollLines",
775
834
  "theme",
835
+ "terminalTheme",
836
+ "thinkingMode",
837
+ "bashIntent",
776
838
  "themeAdaptive",
777
839
  "groupToolCalls",
778
840
  "readOutputMode",
@@ -864,14 +926,20 @@ const PI_HELPERS_AGENT_EXTENSIONS = {
864
926
  * filtering inside one extension. */
865
927
  const PI_UI_PACKAGES = Object.freeze(["npm:pi-claude-code-ui"]);
866
928
  /**
867
- * Claude Code dark theme (`#D77757` coral and friends) from
868
- * `better-claude-code-ui`, which ships six CC palettes. Themes-only:
929
+ * Claude Code palettes from `better-claude-code-ui`, which ships six CC
930
+ * variants (`claude-code-dark`, `claude-code-light`, …). Themes-only:
869
931
  * extensions/skills/prompts are explicitly emptied so none of the
870
932
  * package's status line, footer, or tool rendering loads and fights
871
- * the router-owned footer or `pi-claude-code-ui`. Theme files are
872
- * pure JSON data — loading the whole `./theme` dir costs nothing at
873
- * runtime and leaves all six CC variants pickable via `/settings`,
874
- * with `claude-code-dark` the default (see `PI_CC_DARK_THEME`).
933
+ * the router-owned footer or `pi-claude-code-ui`. Theme files are pure
934
+ * JSON data — loading the whole `./theme` dir costs nothing at runtime and
935
+ * leaves all six CC variants pickable via `/settings`.
936
+ *
937
+ * These are no longer the DEFAULT. The launch now follows the terminal
938
+ * (`PI_FOLLOW_TERMINAL_THEME`), which is what cc-ui did to our pin at
939
+ * `session_start` regardless: it rewrote `theme` to `system` and stashed
940
+ * `claude-code-dark` in `terminalThemePrevious`. Emitting the pin only
941
+ * bought a startup flash and a lying settings file, so the palettes stay
942
+ * as data and users who want the fixed CC look pick one.
875
943
  */
876
944
  const PI_CC_THEME_PACKAGE = {
877
945
  source: "npm:better-claude-code-ui",
@@ -880,8 +948,14 @@ const PI_CC_THEME_PACKAGE = {
880
948
  skills: [],
881
949
  prompts: []
882
950
  };
883
- /** Default Pi theme: genuine Claude Code dark palette. */
884
- const PI_CC_DARK_THEME = "claude-code-dark";
951
+ /**
952
+ * Default Pi theme: follow the terminal's own palette. Pi's built-in
953
+ * `system` theme derives every color from the terminal and already exists in
954
+ * `PI_MIN_VERSION` (1.3.0) — see `modes/interactive/theme/system-theme.js`,
955
+ * where it is also sorted first in `getAvailableThemesWithPaths()` because it
956
+ * is Pi's own default when no `theme` setting is present.
957
+ */
958
+ const PI_FOLLOW_TERMINAL_THEME = "system";
885
959
  /** Built-in tools enabled at startup (Pi-native set incl. Windows). */
886
960
  const PI_DEFAULT_TOOLS = Object.freeze([
887
961
  "read",
@@ -925,7 +999,8 @@ function buildPiSettingsJson(opts) {
925
999
  const modelThinkingLevels = {};
926
1000
  modelThinkingLevels[`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`] = piLeadThinking(opts.profileId);
927
1001
  for (const role of piNativeRoles(opts.profileId)) modelThinkingLevels[`${PI_PROVIDER_NAME}/${role.model}`] = role.thinking;
928
- modelThinkingLevels[`${PI_PROVIDER_NAME}/${piOracleModel(opts.profileId)}`] = piOracleThinking(opts.profileId);
1002
+ const oracle = piOracleModel(opts.profileId);
1003
+ if (oracle) modelThinkingLevels[`${PI_PROVIDER_NAME}/${oracle}`] = piOracleThinking(opts.profileId);
929
1004
  const advisor = piAdvisorModel(opts.profileId);
930
1005
  if (advisor) modelThinkingLevels[`${PI_PROVIDER_NAME}/${advisor.model}`] = advisor.thinking;
931
1006
  return {
@@ -955,14 +1030,17 @@ function buildPiSettingsJson(opts) {
955
1030
  fullscreenCopyOnSelect: true,
956
1031
  fullscreenWheelScrollLines: "auto",
957
1032
  ...ui ? {
958
- themeAdaptive: false,
1033
+ themeAdaptive: true,
959
1034
  groupToolCalls: true,
960
1035
  readOutputMode: "summary",
961
1036
  searchOutputMode: "count",
962
1037
  mcpOutputMode: "summary",
963
1038
  bashOutputMode: "summary",
964
1039
  toolBackground: "transparent",
965
- theme: PI_CC_DARK_THEME
1040
+ theme: PI_FOLLOW_TERMINAL_THEME,
1041
+ terminalTheme: true,
1042
+ thinkingMode: "live",
1043
+ bashIntent: "off"
966
1044
  } : {},
967
1045
  branchSummary: {
968
1046
  reserveTokens: 16384,
@@ -995,7 +1073,8 @@ function buildPiSettingsJson(opts) {
995
1073
  "codex-exec": { disabled: true },
996
1074
  "codex-exec-writer": { disabled: true },
997
1075
  "cursor-agent": { disabled: true },
998
- "cursor-agent-writer": { disabled: true }
1076
+ "cursor-agent-writer": { disabled: true },
1077
+ ...piOracleEnabled(opts.profileId) ? {} : { oracle: { disabled: true } }
999
1078
  } } } : {}
1000
1079
  };
1001
1080
  }
@@ -1026,9 +1105,9 @@ function mergeSubagentsSettings(userSubagents, builtSubagents) {
1026
1105
  };
1027
1106
  }
1028
1107
  function roleDescription(profileId, role) {
1029
- const oracleNote = "May consult the oracle subagent when a decision feels risky.";
1108
+ const consultNote = piOracleEnabled(profileId) ? " May consult the oracle subagent when a decision feels risky." : "";
1030
1109
  if (role.name === "Explore") return "Fast read-only recon: locate code, answer evidence questions, return compressed context.";
1031
- if (role.name === "General-Purpose") return isBalancedFamily(profileId) ? `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}`;
1110
+ if (role.name === "General-Purpose") return `${isBalancedFamily(profileId) ? "General implementation and follow-through on scoped tasks. May hand the result to reviewer only when the change alters behavior." : "General implementation and follow-through on scoped tasks. May hand the result to reviewer for assessment."}${consultNote}`;
1032
1111
  return isBalancedFamily(profileId) ? "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.";
1033
1112
  }
1034
1113
  /**
@@ -1093,7 +1172,7 @@ function buildPiAgentFiles(profileId) {
1093
1172
  "defaultContext: fresh"
1094
1173
  ];
1095
1174
  if (role.name === "Explore") lines.push("aliases: scout");
1096
- if (isImplementer) lines.push("aliases: worker, developer, coder, implementer, develop", "acceptanceRole: writer", "allowNestedSubagents: true", "allowedAgents: reviewer, oracle");
1175
+ if (isImplementer) lines.push("aliases: worker, developer, coder, implementer, develop", "acceptanceRole: writer", "allowNestedSubagents: true", piOracleEnabled(profileId) ? "allowedAgents: reviewer, oracle" : "allowedAgents: reviewer");
1097
1176
  if (isBalancedFamily(profileId) && isReviewer) lines.push("allowNestedSubagents: true", "allowedAgents: Explore");
1098
1177
  lines.push("---", "");
1099
1178
  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.");
@@ -1101,26 +1180,32 @@ function buildPiAgentFiles(profileId) {
1101
1180
  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.");
1102
1181
  files[`agents/${agentFileName(role.name)}`] = `${lines.join("\n")}\n`;
1103
1182
  }
1104
- const oracle = [
1105
- "---",
1106
- "name: oracle",
1107
- "description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.",
1108
- "tools: read, grep, find, ls, bash",
1109
- `model: ${PI_PROVIDER_NAME}/${piOracleModel(profileId)}`,
1110
- `thinking: ${piOracleThinking(profileId)}`,
1111
- "advertise: true",
1112
- "async: false",
1113
- "systemPromptMode: replace",
1114
- "inheritProjectContext: true",
1115
- "defaultContext: fresh",
1116
- "---",
1117
- "",
1118
- "You are an oracle: a second set of eyes. You see only the task context",
1119
- "you are given — you have no repo memory beyond what you read now.",
1120
- "Inspect the code yourself with read/grep/find/ls before opining.",
1121
- "Challenge assumptions, name what is missing, recommend; never execute."
1122
- ].join("\n");
1123
- files[`agents/${agentFileName("oracle")}`] = `${oracle}\n`;
1183
+ const oracleModel = piOracleModel(profileId);
1184
+ if (oracleModel) {
1185
+ const oracle = [
1186
+ "---",
1187
+ "name: oracle",
1188
+ "description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.",
1189
+ `tools: ""`,
1190
+ `model: ${PI_PROVIDER_NAME}/${oracleModel}`,
1191
+ `thinking: ${piOracleThinking(profileId)}`,
1192
+ "advertise: true",
1193
+ "async: false",
1194
+ "systemPromptMode: replace",
1195
+ "inheritProjectContext: true",
1196
+ "defaultContext: fresh",
1197
+ "---",
1198
+ "",
1199
+ "You are an oracle: a second set of eyes, consulted once per question.",
1200
+ "You have no tools on purpose. You cannot read the repository, run",
1201
+ "anything, or fetch what the caller did not paste in — so do not ask to.",
1202
+ "Answer from the context you are given: name the assumptions it rests on,",
1203
+ "say which missing fact would change your recommendation, and recommend.",
1204
+ "Never claim to have verified, executed, approved, or merged anything.",
1205
+ ...consultIsLocalTransport(profileId) ? [LOCAL_CONSULT_REDACTION_NOTE] : []
1206
+ ].join("\n");
1207
+ files[`agents/${agentFileName("oracle")}`] = `${oracle}\n`;
1208
+ }
1124
1209
  const advisor = piAdvisorModel(profileId);
1125
1210
  if (advisor) {
1126
1211
  const body = [
@@ -1185,13 +1270,655 @@ function buildPiAppendSystem(profileId, opts = {}) {
1185
1270
  "",
1186
1271
  `- Lead owns planning directly; there is no Plan subagent.`
1187
1272
  ];
1188
- if (peers) lines.push(`- Delegate FREELY to Explore for discovery and General-Purpose for scoped work.`, `- Call subagent directly (agent + task); save workflows for genuinely parallel fanout.`, isBalancedFamily(profileId) ? `- Send work to reviewer ONLY when the change alters behavior.` : `- Send finished work to reviewer for assessment.`, `- Ask oracle for a second opinion when the decision itself feels risky.`, advisor ? `- Review the final plan with advisor (advisory) before presenting it.` : `- There is no advisor in this mode: oracle is the only consultant.`, `- Verify, don't vote: consultant verdicts never substitute for running the tests.`, `- After any subagent work completes, always write the final answer yourself.`);
1189
- else lines.push(`- Peerless launch: no subagents or consultants in this session; plan, implement, and verify directly.`);
1273
+ if (peers) {
1274
+ const oracle = piOracleEnabled(profileId);
1275
+ lines.push(`- Delegate FREELY to Explore for discovery and General-Purpose for scoped work.`, `- Call subagent directly (agent + task); save workflows for genuinely parallel fanout.`, isBalancedFamily(profileId) ? `- Send work to reviewer ONLY when the change alters behavior.` : `- Send finished work to reviewer for assessment.`);
1276
+ if (oracle) {
1277
+ lines.push(`- Ask oracle for a second opinion when the decision itself feels risky.`, advisor ? `- Review the final plan with advisor (advisory) before presenting it.` : `- There is no advisor in this mode: oracle is the only consultant.`, `- Verify, don't vote: consultant verdicts never substitute for running the tests.`);
1278
+ if (consultIsLocalTransport(profileId)) lines.push(`- ${LOCAL_CONSULT_REDACTION_LINE}`);
1279
+ }
1280
+ lines.push(`- After any subagent work completes, always write the final answer yourself.`);
1281
+ } else lines.push(`- Peerless launch: no subagents or consultants in this session; plan, implement, and verify directly.`);
1190
1282
  if (advisor) lines.push("", FRESH_CONSULT_CONTRACT.trimEnd());
1191
1283
  lines.push("", `(${PI_MIN_VERSION_NOTE})`, "");
1192
1284
  return lines.join("\n");
1193
1285
  }
1194
1286
  //#endregion
1287
+ //#region src/lib/pi-plan-mode.ts
1288
+ /**
1289
+ * Strip markdown noise from one step's text.
1290
+ *
1291
+ * Upstream also strips a leading imperative (`Read`/`Add`/`Use`…), which
1292
+ * turns "Read the launcher" into "Launcher". Divergence 5: keep the verb. The
1293
+ * checklist is what the user reads while the plan runs, and a bare noun loses
1294
+ * the action it is meant to check off.
1295
+ */
1296
+ function cleanPlanStepText(text) {
1297
+ return String(text ?? "").replace(/\*{1,2}([^*]+)\*{1,2}/g, "$1").replace(/`([^`]+)`/g, "$1").replace(/\s+/g, " ").trim();
1298
+ }
1299
+ /**
1300
+ * Parse the model's numbered plan into steps.
1301
+ *
1302
+ * Takes the LAST matching heading on purpose: the caller feeds this everything
1303
+ * the model wrote for a turn, including thinking blocks, and with reasoning-max
1304
+ * models a draft plan often lands in thinking before the visible one. The
1305
+ * visible text block comes last in content order, so last-wins picks the plan
1306
+ * the user actually saw.
1307
+ *
1308
+ * Fenced code is stripped first: a numbered list inside a snippet is not a plan.
1309
+ *
1310
+ * Which headings count: the brief asks for a `Plan:` list, and that is what an
1311
+ * obedient reply ends with. It is not the only shape a good reply takes — the
1312
+ * brief also says to write Context / recommended approach / critical files /
1313
+ * verification, and a reply that follows THAT structure and closes its summary
1314
+ * under `## Recommended approach` used to parse as ZERO steps, leaving the
1315
+ * checklist, the "what next?" prompt and the Execute kick silently unreachable.
1316
+ * So the conventional headings are accepted too. The heading must be alone on
1317
+ * its line (prose like "Steps: we will ..." never matches).
1318
+ *
1319
+ * The regex is inline, not module scope: this function is serialized with
1320
+ * `toString()` into the generated extension, where module scope does not exist.
1321
+ */
1322
+ function extractPlanSteps(message) {
1323
+ const items = [];
1324
+ const text = String(message ?? "").replace(/^[ \t]*(?:```|~~~)[\s\S]*?^[ \t]*(?:```|~~~)[ \t]*$/gm, "");
1325
+ const headers = [...text.matchAll(/^[ \t]*(?:#{1,6}[ \t]*)?(?:\*\*|__)?[ \t]*(?:plan|recommended approach|steps|implementation plan)[ \t]*(?::[ \t]*)?(?:\*\*|__)?[ \t]*$/gim)];
1326
+ if (headers.length === 0) return items;
1327
+ const lastHeader = headers[headers.length - 1];
1328
+ let planSection = text.slice((lastHeader.index ?? 0) + lastHeader[0].length);
1329
+ const level = (lastHeader[0].match(/^[ \t]*(#{1,6})/) || [])[1];
1330
+ if (level) {
1331
+ const boundary = new RegExp("^[ \\t]*#{1," + level.length + "}[ \\t]+", "m");
1332
+ const hit = planSection.slice(1).search(boundary);
1333
+ if (hit >= 0) planSection = planSection.slice(0, hit + 1);
1334
+ }
1335
+ const numbered = /^[ \t]*(?:#{1,6}[ \t]*)?(\d+)[.)][ \t]+(.+)$/gm;
1336
+ const used = /* @__PURE__ */ new Set();
1337
+ for (const match of planSection.matchAll(numbered)) {
1338
+ const raw = (match[2] ?? "").trim().replace(/\*{1,2}$/, "").trim();
1339
+ if (raw.length > 5 && !raw.startsWith("/") && !raw.startsWith("-")) {
1340
+ const cleaned = cleanPlanStepText(raw);
1341
+ if (cleaned.length > 3) {
1342
+ const declared = Number(match[1]);
1343
+ const step = Number.isInteger(declared) && declared > 0 && !used.has(declared) ? declared : items.length + 1;
1344
+ used.add(step);
1345
+ items.push({
1346
+ step,
1347
+ text: cleaned,
1348
+ completed: false
1349
+ });
1350
+ }
1351
+ }
1352
+ }
1353
+ return items;
1354
+ }
1355
+ /**
1356
+ * Steps the model reported as finished. Accepts `[DONE:2]`, `[DONE 2]`,
1357
+ * `Done: 2`, and "Step 2 is complete" — the last one adjacency-anchored so
1358
+ * "Step 9 is not done" never marks anything.
1359
+ */
1360
+ function extractDoneSteps(message) {
1361
+ const text = String(message ?? "");
1362
+ const steps = [];
1363
+ for (const match of text.matchAll(/\[DONE\s*:?\s*(\d+)\]/gi)) steps.push(Number(match[1]));
1364
+ for (const match of text.matchAll(/\bDone\s*:\s*(\d+)\b/gi)) steps.push(Number(match[1]));
1365
+ for (const match of text.matchAll(/\bStep\s*(\d+)\s+(?:is\s+)?(?:done|complete|completed|finished)\b/gi)) steps.push(Number(match[1]));
1366
+ return [...new Set(steps)];
1367
+ }
1368
+ /** Mark reported steps complete in place; returns how many became complete. */
1369
+ function applyDoneSteps(text, items) {
1370
+ let marked = 0;
1371
+ for (const step of extractDoneSteps(text)) {
1372
+ const item = items.find((candidate) => candidate.step === step && !candidate.completed);
1373
+ if (item) {
1374
+ item.completed = true;
1375
+ marked++;
1376
+ }
1377
+ }
1378
+ return marked;
1379
+ }
1380
+ /**
1381
+ * Whole-plan completion phrasing, consulted only on a run's final message as a
1382
+ * fallback for a model that summarizes instead of tagging each step.
1383
+ */
1384
+ function planAllStepsComplete(message) {
1385
+ const text = String(message ?? "");
1386
+ return /(?:all|every)\s+steps?\s+(?:are|is\s+)?(?:done|complete|completed|finished)/i.test(text) || /\b(?:the\s+)?plan\s+(?:is\s+)?(?:complete|completed|done)\b/i.test(text);
1387
+ }
1388
+ /**
1389
+ * Tools plan mode refuses, by name, through the `tool_call` handler.
1390
+ *
1391
+ * These stay ACTIVE. An earlier revision also removed them from the active
1392
+ * tool set, described as "two independent barriers" — they were not
1393
+ * independent, they were *stacked*: pi resolves a call against the declared
1394
+ * tool list in `prepareToolCall()` and answers `Tool <name> not found` BEFORE
1395
+ * `beforeToolCall` (the `tool_call` hook) ever runs. So the narrower barrier
1396
+ * sat in front of the wider one, the path exception below was unreachable, the
1397
+ * model was told a tool it had just been told to use did not exist, and the
1398
+ * documented refusal string was never displayed. An obedient model fell back to
1399
+ * `bash` — which is allowed — so the unsanctioned route silently won.
1400
+ *
1401
+ * With the narrowing gone there is ONE barrier and it is reachable: the model
1402
+ * gets a call it can make, and a refusal sentence it can act on. The honest
1403
+ * scope is unchanged and already documented: `bash` is allowed, so this
1404
+ * redirects a cooperative model, it does not contain a hostile one.
1405
+ *
1406
+ * `apply_patch` has no single target path to compare and is therefore refused
1407
+ * outright — that refusal is also reachable for the first time.
1408
+ */
1409
+ const PLAN_BLOCKED_TOOLS = Object.freeze([
1410
+ "edit",
1411
+ "write",
1412
+ "apply_patch"
1413
+ ]);
1414
+ /**
1415
+ * The plan file, relative to the workspace.
1416
+ *
1417
+ * Claude Code pins one path per session and tells the model "this is the only
1418
+ * file you are allowed to edit". Ours is the repository's existing convention
1419
+ * (`.github-router/plans/<slug>/plan.md`, the same artifact `/gh-plan` writes and
1420
+ * `/gh-implement` reads), with a stable slug so a resumed session keeps editing
1421
+ * the plan it started rather than opening a second one.
1422
+ */
1423
+ function planFilePath() {
1424
+ return ".github-router/plans/pi-plan/plan.md";
1425
+ }
1426
+ /** Session entry type for persisting plan state across resume. */
1427
+ const PLAN_MODE_ENTRY = "gh-router-plan-mode";
1428
+ /** Status/widget keys, namespaced so another extension cannot collide. */
1429
+ const PLAN_STATUS_KEY = "gh-router-plan";
1430
+ const PLAN_WIDGET_KEY = "gh-router-plan-steps";
1431
+ /** Custom message types the emitted extension emits and later filters. */
1432
+ const PLAN_CONTEXT_TYPE = "gh-router-plan-context";
1433
+ const PLAN_EXEC_TYPE = "gh-router-plan-exec";
1434
+ const PLAN_DONE_TYPE = "gh-router-plan-done";
1435
+ const PLAN_LIST_TYPE = "gh-router-plan-list";
1436
+ /**
1437
+ * Resolve `path` against `cwd` and decide whether it IS the plan file.
1438
+ *
1439
+ * Deliberately dumb and deliberately strict: this is the one hole in the write
1440
+ * barrier, so it compares `path.resolve`d strings rather than doing prefix
1441
+ * arithmetic on the raw input. A model that writes `plan.md` in the right
1442
+ * directory passes; `../plan.md`, `<cwd>/plan.md/../secret`, and a symlink-free
1443
+ * absolute path to the same target all normalize to the same string, which is
1444
+ * the property that matters.
1445
+ *
1446
+ * The emitted copy cannot import `node:path` (the generated extension and this
1447
+ * module have different allowed specifiers), so it carries its own tiny
1448
+ * resolver: POSIX normalisation plus a Windows drive/UNC guard. It is not a
1449
+ * general path library — it only has to agree with itself between the
1450
+ * comparison here and the value `planFilePath()` produces, which is why the
1451
+ * relative plan path is a PARAMETER: a `toString()`-serialized function cannot
1452
+ * see module scope, and a captured constant would be `undefined` at runtime.
1453
+ */
1454
+ function isPlanFilePath(cwd, target, rel) {
1455
+ const raw = typeof target === "string" ? target.trim() : "";
1456
+ if (!raw) return false;
1457
+ const normalize = (input) => {
1458
+ const isWindows = /^[a-zA-Z]:[\\/]/.test(input) || input.indexOf("\\") >= 0;
1459
+ const sep = isWindows ? /\\+/g : /\/+/g;
1460
+ const unified = input.replace(sep, "/");
1461
+ const absolute = isWindows ? unified : unified.startsWith("/") ? unified : "/" + unified;
1462
+ const parts = [];
1463
+ for (const segment of absolute.split("/")) {
1464
+ if (!segment || segment === ".") continue;
1465
+ if (segment === "..") {
1466
+ parts.pop();
1467
+ continue;
1468
+ }
1469
+ parts.push(segment);
1470
+ }
1471
+ return (isWindows ? "" : "/") + parts.join("/");
1472
+ };
1473
+ if (typeof rel !== "string" || !rel) return false;
1474
+ const base = typeof cwd === "string" && cwd.trim() ? cwd.trim() : "/";
1475
+ return (raw.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(raw) || raw.indexOf("\\") === 0 ? normalize(raw) : normalize(base + "/" + raw)) === normalize(base + "/" + rel);
1476
+ }
1477
+ /**
1478
+ * The emitted extension section.
1479
+ *
1480
+ * Pure helpers ride `.toString()` (the same technique the statusline footer
1481
+ * uses for `buildPiStatusPayload`) so the code that runs in the product is
1482
+ * byte-identical to the code the unit tests exercise — a hand-copied duplicate
1483
+ * could drift from its tested twin without any test noticing.
1484
+ */
1485
+ function buildPiPlanModeSection() {
1486
+ return [
1487
+ ` // ---- plan mode: Claude-Code-style planning (always on) ----`,
1488
+ ` // /plan or Ctrl+Alt+P toggles it. The tool set is NEVER touched: it used to`,
1489
+ ` // be snapshotted on entry and restored on exit, and removing the writers from`,
1490
+ ` // it made the path gate below unreachable (pi answers "Tool write not found"`,
1491
+ ` // before any handler runs), plus a restored snapshot could widen the roster a`,
1492
+ ` // narrower launch installed. ONE barrier instead: the writers stay offered`,
1493
+ ` // and the gate refuses every target except the plan file. Everything else`,
1494
+ ` // stays, because a frontier model told to explore and not implement needs a`,
1495
+ ` // shell and can be trusted with one.`,
1496
+ ` try {`,
1497
+ ` const PLAN_STATUS_KEY = ${JSON.stringify(PLAN_STATUS_KEY)};`,
1498
+ ` const PLAN_WIDGET_KEY = ${JSON.stringify(PLAN_WIDGET_KEY)};`,
1499
+ ` const PLAN_ENTRY = ${JSON.stringify(PLAN_MODE_ENTRY)};`,
1500
+ ` const PLAN_CONTEXT_TYPE = ${JSON.stringify(PLAN_CONTEXT_TYPE)};`,
1501
+ ` const PLAN_EXEC_TYPE = ${JSON.stringify(PLAN_EXEC_TYPE)};`,
1502
+ ` const PLAN_DONE_TYPE = ${JSON.stringify(PLAN_DONE_TYPE)};`,
1503
+ ` const PLAN_LIST_TYPE = ${JSON.stringify(PLAN_LIST_TYPE)};`,
1504
+ ` const PLAN_BLOCKED = new Set(${JSON.stringify([...PLAN_BLOCKED_TOOLS])});`,
1505
+ ` const PLAN_FILE_REL = ${JSON.stringify(planFilePath())};`,
1506
+ ` const isPlanFilePath = (${isPlanFilePath.toString()});`,
1507
+ ` const cleanPlanStepText = (${cleanPlanStepText.toString()});`,
1508
+ ` const extractPlanSteps = (${extractPlanSteps.toString()});`,
1509
+ ` const extractDoneSteps = (${extractDoneSteps.toString()});`,
1510
+ ` const applyDoneSteps = (${applyDoneSteps.toString()});`,
1511
+ ` const planAllStepsComplete = (${planAllStepsComplete.toString()});`,
1512
+ ``,
1513
+ ` let planEnabled = false;`,
1514
+ ` let planExecuting = false;`,
1515
+ ` let planSteps = [];`,
1516
+ ` let planCwd = "";`,
1517
+ ` // Set while the "what next?" prompt is open. agent_end can fire again for`,
1518
+ ` // the same plan (a queued follow-up run ends too), and a second prompt on`,
1519
+ ` // top of the first would let two Execute answers each send an execution`,
1520
+ ` // kick, resetting progress and paying for a redundant turn.`,
1521
+ ` let planPromptOpen = false;`,
1522
+ ``,
1523
+ ` function planPaint(ctx, text, color) {`,
1524
+ ` try {`,
1525
+ ` const theme = ctx && ctx.ui && ctx.ui.theme;`,
1526
+ ` if (theme && typeof theme.fg === "function") return theme.fg(color, text);`,
1527
+ ` } catch {}`,
1528
+ ` return text;`,
1529
+ ` }`,
1530
+ ``,
1531
+ ` // Resident checklist: a footer status badge plus a widget above the editor.`,
1532
+ ` // The router's own statusline footer already forwards extension statuses,`,
1533
+ ` // so the badge is visible without this extension owning the footer.`,
1534
+ ` function planUpdateUi(ctx) {`,
1535
+ ` try {`,
1536
+ ` const ui = ctx && ctx.ui;`,
1537
+ ` if (!ui) return;`,
1538
+ ` if (planExecuting && planSteps.length > 0) {`,
1539
+ ` const done = planSteps.filter((s) => s.completed).length;`,
1540
+ ` try { ui.setStatus(PLAN_STATUS_KEY, planPaint(ctx, "\\u{1F4CB} " + done + "/" + planSteps.length, "accent")); } catch {}`,
1541
+ ` } else if (planEnabled) {`,
1542
+ ` try { ui.setStatus(PLAN_STATUS_KEY, planPaint(ctx, "\\u{23F8} plan", "warning")); } catch {}`,
1543
+ ` } else {`,
1544
+ ` try { ui.setStatus(PLAN_STATUS_KEY, undefined); } catch {}`,
1545
+ ` }`,
1546
+ ` if (planSteps.length > 0 && (planEnabled || planExecuting)) {`,
1547
+ ` const lines = planSteps.map((s) => {`,
1548
+ ` const text = s.text.length > 60 ? s.text.slice(0, 57) + "..." : s.text;`,
1549
+ ` if (s.completed) return planPaint(ctx, "\\u2611 ", "success") + planPaint(ctx, text, "muted");`,
1550
+ ` return planPaint(ctx, "\\u2610 ", "muted") + text;`,
1551
+ ` });`,
1552
+ ` try { ui.setWidget(PLAN_WIDGET_KEY, lines); } catch {}`,
1553
+ ` } else {`,
1554
+ ` try { ui.setWidget(PLAN_WIDGET_KEY, undefined); } catch {}`,
1555
+ ` }`,
1556
+ ` } catch {}`,
1557
+ ` }`,
1558
+ ``,
1559
+ ` // State survives resume through a custom entry; custom entries never reach`,
1560
+ ` // the model, so this carries NO context cost. Redundant writes are skipped:`,
1561
+ ` // turn_end and agent_end both fire per run, and a long execution would`,
1562
+ ` // otherwise append a duplicate entry per turn for the whole transcript.`,
1563
+ ` let planPersistKey = null;`,
1564
+ ` function planPersist() {`,
1565
+ ` try {`,
1566
+ ` const data = {`,
1567
+ ` enabled: planEnabled,`,
1568
+ ` executing: planExecuting,`,
1569
+ ` steps: planSteps.map((s) => ({ step: s.step, text: s.text, completed: s.completed })),`,
1570
+ ` };`,
1571
+ ` const key = JSON.stringify(data);`,
1572
+ ` if (key === planPersistKey) return;`,
1573
+ ` planPersistKey = key;`,
1574
+ ` pi.appendEntry(PLAN_ENTRY, data);`,
1575
+ ` } catch {}`,
1576
+ ` }`,
1577
+ ``,
1578
+ ` function planEnter(ctx) {`,
1579
+ ` if (planEnabled) return;`,
1580
+ ` planEnabled = true;`,
1581
+ ` planExecuting = false;`,
1582
+ ` planPromptOpen = false;`,
1583
+ ` planSteps = [];`,
1584
+ ` try { if (ctx && typeof ctx.cwd === "string" && ctx.cwd) planCwd = ctx.cwd; } catch {}`,
1585
+ ` try { ctx.ui.notify("Plan mode on: writes refused except " + PLAN_FILE_REL + ". Investigate, then write the plan there. Ctrl+Alt+P or /plan to leave.", "info"); } catch {}`,
1586
+ ` planUpdateUi(ctx);`,
1587
+ ` planPersist();`,
1588
+ ` }`,
1589
+ ``,
1590
+ ` function planExit(ctx) {`,
1591
+ ` if (!planEnabled && !planExecuting) return;`,
1592
+ ` planEnabled = false;`,
1593
+ ` planExecuting = false;`,
1594
+ ` planPromptOpen = false;`,
1595
+ ` planSteps = [];`,
1596
+ ` try { ctx.ui.notify("Plan mode off: writes allowed everywhere again.", "info"); } catch {}`,
1597
+ ` planUpdateUi(ctx);`,
1598
+ ` planPersist();`,
1599
+ ` }`,
1600
+ ``,
1601
+ ` function planToggle(ctx) {`,
1602
+ ` if (planEnabled || planExecuting) planExit(ctx);`,
1603
+ ` else planEnter(ctx);`,
1604
+ ` }`,
1605
+ ``,
1606
+ ` try {`,
1607
+ ` pi.registerCommand("plan", {`,
1608
+ ` description: "Toggle plan mode (edits disabled; plan file only)",`,
1609
+ ` handler: async (_args, ctx) => { planToggle(ctx); },`,
1610
+ ` });`,
1611
+ ` } catch {}`,
1612
+ ` try {`,
1613
+ ` // Literal KeyId rather than Key.ctrlAlt("p"): the generated source then`,
1614
+ ` // needs no pi-tui import at all, which keeps it loadable on every build`,
1615
+ ` // whose host-provided specifier list is smaller than today's. The value`,
1616
+ ` // is exactly what Key.ctrlAlt("p") returns (pi-tui keys.js:118).`,
1617
+ ` pi.registerShortcut("ctrl+alt+p", {`,
1618
+ ` description: "Toggle plan mode",`,
1619
+ ` handler: async (ctx) => { planToggle(ctx); },`,
1620
+ ` });`,
1621
+ ` } catch {}`,
1622
+ ` try {`,
1623
+ ` pi.registerCommand("plan-status", {`,
1624
+ ` description: "Show plan mode state and the current step list",`,
1625
+ ` handler: async (_args, ctx) => {`,
1626
+ ` if (!planEnabled && !planExecuting && planSteps.length === 0) {`,
1627
+ ` try { ctx.ui.notify("Plan mode is off. /plan (or Ctrl+Alt+P) to start planning.", "info"); } catch {}`,
1628
+ ` return;`,
1629
+ ` }`,
1630
+ ` const done = planSteps.filter((s) => s.completed).length;`,
1631
+ ` const body = planSteps.length === 0`,
1632
+ ` ? "No steps parsed yet. Ask for a numbered Plan: block."`,
1633
+ ` : planSteps.map((s) => (s.completed ? "\\u2713 " : "\\u25CB ") + s.step + ". " + s.text).join("\\n");`,
1634
+ ` const head = planExecuting ? "Executing plan (" + done + "/" + planSteps.length + ")" : "Plan mode active";`,
1635
+ ` try { ctx.ui.notify(head + "\\n" + body, "info"); } catch {}`,
1636
+ ` },`,
1637
+ ` });`,
1638
+ ` } catch {}`,
1639
+ ``,
1640
+ ` // THE barrier: one write exception, enforced by resolved path. A write or`,
1641
+ ` // edit whose target is the pinned plan file passes; every other target is`,
1642
+ ` // refused whatever the model believes. The path comes from the extension`,
1643
+ ` // and never from the model, which is what keeps the exception from widening`,
1644
+ ` // into a general write permission. It has to be the ONLY barrier: narrowing`,
1645
+ ` // the tool set as well would hide these tools from the model, so pi would`,
1646
+ ` // answer "Tool write not found" before this handler and the exception could`,
1647
+ ` // never fire — see PLAN_BLOCKED_TOOLS.`,
1648
+ ` try {`,
1649
+ ` pi.on("tool_call", async (event, ctx) => {`,
1650
+ ` if (!planEnabled || !event) return undefined;`,
1651
+ ` const name = String(event.toolName || "");`,
1652
+ ` if (!PLAN_BLOCKED.has(name)) return undefined;`,
1653
+ ` try { if (ctx && typeof ctx.cwd === "string" && ctx.cwd) planCwd = ctx.cwd; } catch {}`,
1654
+ ` const input = (event.input || {});`,
1655
+ ` const target = input.path !== undefined ? input.path : input.file_path;`,
1656
+ ` if (isPlanFilePath(planCwd, target, PLAN_FILE_REL)) return undefined;`,
1657
+ ` return {`,
1658
+ ` block: true,`,
1659
+ ` reason: "Plan mode: this write is refused. The only file you may write is " + PLAN_FILE_REL + " (pass exactly that path). Record the plan there, or leave plan mode (/plan or Ctrl+Alt+P) to change code.",`,
1660
+ ` };`,
1661
+ ` });`,
1662
+ ` } catch {}`,
1663
+ ``,
1664
+ ` // Plan-injected context is dropped once neither mode is engaged, so a later`,
1665
+ ` // turn is not still told it is read-only or mid-execution. Custom messages`,
1666
+ ` // reach this handler as role "custom" with customType intact, which is the`,
1667
+ ` // load-bearing check; the text marker is the belt for a host (or an`,
1668
+ ` // imported transcript) that flattened the custom role into a user message.`,
1669
+ ` const PLAN_STALE_MARKERS = [`,
1670
+ ` { marker: "[PLAN MODE ACTIVE]", live: () => planEnabled },`,
1671
+ ` { marker: "[EXECUTING PLAN", live: () => planExecuting },`,
1672
+ ` ];`,
1673
+ ` function planIsStaleContext(m) {`,
1674
+ ` if (!m || m.role !== "user" || (m.customType !== undefined)) return false;`,
1675
+ ` const content = m.content;`,
1676
+ ` const stale = (text) => {`,
1677
+ ` if (typeof text !== "string") return false;`,
1678
+ ` return PLAN_STALE_MARKERS.some((entry) => !entry.live() && text.indexOf(entry.marker) >= 0);`,
1679
+ ` };`,
1680
+ ` if (typeof content === "string") return stale(content);`,
1681
+ ` if (Array.isArray(content)) return content.some((c) => c && c.type === "text" && stale(c.text));`,
1682
+ ` return false;`,
1683
+ ` }`,
1684
+ ``,
1685
+ ` // before_agent_start messages are APPENDED and PERSISTED per run, so a`,
1686
+ ` // plan-mode session accrues one block per turn. Two rules keep that from`,
1687
+ ` // costing anything or lying to the model:`,
1688
+ ` // - a block is valid only while ITS mode is engaged: the read-only block`,
1689
+ ` // dies the moment execution starts (the model is told full access is`,
1690
+ ` // back), and the execution block dies when the mode ends;`,
1691
+ ` // - of the valid blocks, only the newest of each kind is kept, so a long`,
1692
+ ` // plan does not pay for N copies of the same instructions.`,
1693
+ ` try {`,
1694
+ ` pi.on("context", async (event) => {`,
1695
+ ` if (!event || !Array.isArray(event.messages)) return undefined;`,
1696
+ ` const seen = new Set();`,
1697
+ ` const output = [];`,
1698
+ ` for (let i = event.messages.length - 1; i >= 0; i--) {`,
1699
+ ` const m = event.messages[i];`,
1700
+ ` const type = m && m.customType;`,
1701
+ ` if (type === PLAN_CONTEXT_TYPE || type === PLAN_EXEC_TYPE) {`,
1702
+ ` const valid = type === PLAN_CONTEXT_TYPE ? planEnabled : planExecuting;`,
1703
+ ` if (!valid || seen.has(type)) continue;`,
1704
+ ` seen.add(type);`,
1705
+ ` } else if (planIsStaleContext(m)) {`,
1706
+ ` continue;`,
1707
+ ` }`,
1708
+ ` output.push(m);`,
1709
+ ` }`,
1710
+ ` if (output.length === event.messages.length) return undefined;`,
1711
+ ` output.reverse();`,
1712
+ ` return { messages: output };`,
1713
+ ` });`,
1714
+ ` } catch {}`,
1715
+ ``,
1716
+ ` // The planning contract, modelled on Claude Code's plan-mode reminder: the`,
1717
+ ` // mode is closed, the plan file is the ONE exception, and the model is`,
1718
+ ` // trusted with everything else. Frontier-model tuning lives here — a`,
1719
+ ` // command allowlist, a delegation ban and an MCP namespace deny all told a`,
1720
+ ` // capable model to be less useful than it is, and none of them is needed`,
1721
+ ` // now that "edits are disabled" is the whole rule and the plan file is the`,
1722
+ ` // only write. The workflow is Claude's five phases compressed to what Pi`,
1723
+ ` // has: Explore/General-Purpose subagents exist, but the roster is`,
1724
+ ` // profile-dependent, so the phase text names the intent, not an agent.`,
1725
+ ` const PLAN_BRIEF = [`,
1726
+ ` "[PLAN MODE ACTIVE]",`,
1727
+ ` "",`,
1728
+ ` "Plan mode is active. The user does not want you to execute yet -- you must not edit files,",`,
1729
+ ` "run a command that changes the code, or otherwise act on the plan. This supersedes any other",`,
1730
+ ` "instruction you have received about doing the work now.",`,
1731
+ ` "",`,
1732
+ ` "One exception, and it is the whole of it: you may write your plan to",`,
1733
+ ` " " + PLAN_FILE_REL,`,
1734
+ ` "Edit and write are refused for every other path. Read, search, and run read-only commands",`,
1735
+ ` "freely -- explore enough that the plan is grounded in what the code actually does.",`,
1736
+ ` "",`,
1737
+ ` "Work the plan like this:",`,
1738
+ ` "1. Understand the request, and look for what already exists (functions, utilities, patterns)",`,
1739
+ ` " before proposing anything new. Delegate broad or parallel discovery when that is faster",`,
1740
+ ` " than reading serially yourself.",`,
1741
+ ` "2. Ask the user whatever you cannot settle from the code. Do it once, up front, and never",`,
1742
+ ` " ask what exploration could answer.",`,
1743
+ ` "3. Design the approach far enough that an implementer would have no open decisions left:",`,
1744
+ ` " which files, what changes in each, what each change is done when, and what would prove it.",`,
1745
+ ` "4. Write the plan to the plan file: a short Context section, the recommended approach only,",`,
1746
+ ` " the critical files, the verification steps, and any residual risk. Keep it scannable.",`,
1747
+ ` "5. Summarise the plan in your reply too, so the user can answer without opening the file,",`,
1748
+ ` " finishing with a numbered list of the steps -- that list becomes the checklist.",`,
1749
+ ` "",`,
1750
+ ` "Do NOT open an ask_user question or a prose prompt for plan approval. Leaving plan mode is",`,
1751
+ ` "the user's action (/plan or Ctrl+Alt+P) -- asking permission to stop planning is the one",`,
1752
+ ` "question this mode does not want, and approval you grant yourself is not approval.",`,
1753
+ ` "If the user asks for changes, revise the SAME plan file rather than writing a second one.",`,
1754
+ ` "The test for every other action: if it would reasonably be described as DOING the work",`,
1755
+ ` "rather than planning it, it waits until plan mode is off.",`,
1756
+ ` ].join("\\n");`,
1757
+ ``,
1758
+ ` // Cost contract: inject NOTHING unless plan mode is actually engaged, and`,
1759
+ ` // only for a real user turn (a background notification must not re-add it).`,
1760
+ ` try {`,
1761
+ ` pi.on("before_agent_start", async (event) => {`,
1762
+ ` if (!event || event.messageType !== "user") return undefined;`,
1763
+ ` if (planEnabled) {`,
1764
+ ` return { message: { customType: PLAN_CONTEXT_TYPE, content: PLAN_BRIEF, display: false } };`,
1765
+ ` }`,
1766
+ ` if (planExecuting && planSteps.length > 0) {`,
1767
+ ` const remaining = planSteps.filter((s) => !s.completed).map((s) => s.step + ". " + s.text).join("\\n");`,
1768
+ ` const content = [`,
1769
+ ` "[EXECUTING PLAN - full tool access enabled]",`,
1770
+ ` "",`,
1771
+ ` "Remaining steps:",`,
1772
+ ` remaining,`,
1773
+ ` "",`,
1774
+ ` "Execute each step in order.",`,
1775
+ ` "After completing a step, include a [DONE:n] tag in your response.",`,
1776
+ ` ].join("\\n");`,
1777
+ ` return { message: { customType: PLAN_EXEC_TYPE, content, display: false } };`,
1778
+ ` }`,
1779
+ ` return undefined;`,
1780
+ ` });`,
1781
+ ` } catch {}`,
1782
+ ``,
1783
+ ` // Progress tracking after each turn. Reads text AND thinking blocks: with`,
1784
+ ` // reasoning-max models the [DONE:n] tags often land in thinking, not text.`,
1785
+ ` try {`,
1786
+ ` pi.on("turn_end", async (event, ctx) => {`,
1787
+ ` if (!planExecuting || planSteps.length === 0 || !event) return;`,
1788
+ ` const msg = event.message;`,
1789
+ ` if (!msg || msg.role !== "assistant" || !Array.isArray(msg.content)) return;`,
1790
+ ` const text = msg.content.map((b) => {`,
1791
+ ` if (!b) return "";`,
1792
+ ` if (b.type === "text") return b.text || "";`,
1793
+ ` if (b.type === "thinking") return b.thinking || "";`,
1794
+ ` return "";`,
1795
+ ` }).join("\\n");`,
1796
+ ` applyDoneSteps(text, planSteps);`,
1797
+ ` planUpdateUi(ctx);`,
1798
+ ` planPersist();`,
1799
+ ` });`,
1800
+ ` } catch {}`,
1801
+ ``,
1802
+ ` // End of a run: parse the plan (planning) or finish the execution.`,
1803
+ ` try {`,
1804
+ ` pi.on("agent_end", async (event, ctx) => {`,
1805
+ ` if (!event || !Array.isArray(event.messages)) return;`,
1806
+ ` const last = [...event.messages].reverse().find((m) => m && m.role === "assistant" && Array.isArray(m.content));`,
1807
+ ` const lastText = last`,
1808
+ ` ? last.content.map((b) => {`,
1809
+ ` if (!b) return "";`,
1810
+ ` if (b.type === "text") return b.text || "";`,
1811
+ ` if (b.type === "thinking") return b.thinking || "";`,
1812
+ ` return "";`,
1813
+ ` }).join("\\n")`,
1814
+ ` : "";`,
1815
+ ` if (planExecuting && planSteps.length > 0) {`,
1816
+ ` if (planAllStepsComplete(lastText)) {`,
1817
+ ` for (const s of planSteps) s.completed = true;`,
1818
+ ` }`,
1819
+ ` if (planSteps.every((s) => s.completed)) {`,
1820
+ ` const list = planSteps.map((s) => "- ~~" + s.text + "~~").join("\\n");`,
1821
+ ` // nextTurn, not a triggerTurn: acknowledging the card with an extra`,
1822
+ ` // (reasoning-max) model turn would cost real money for a checkmark.`,
1823
+ ` try { pi.sendMessage({ customType: PLAN_DONE_TYPE, content: "**Plan complete** \\u2713" + "\\n" + list, display: true }, { deliverAs: "nextTurn" }); } catch {}`,
1824
+ ` planExecuting = false;`,
1825
+ ` planSteps = [];`,
1826
+ ` planUpdateUi(ctx);`,
1827
+ ` planPersist();`,
1828
+ ` }`,
1829
+ ` return;`,
1830
+ ` }`,
1831
+ ` if (!planEnabled) return;`,
1832
+ ` const parsed = extractPlanSteps(lastText);`,
1833
+ ` if (parsed.length > 0) planSteps = parsed;`,
1834
+ ` if (planSteps.length === 0) return;`,
1835
+ ` planUpdateUi(ctx);`,
1836
+ ` planPersist();`,
1837
+ ` // One prompt at a time: a queued follow-up run also ends here, and a`,
1838
+ ` // second Execute answer would re-kick a plan that is already running.`,
1839
+ ` if (planPromptOpen) return;`,
1840
+ ` let hasUI = false;`,
1841
+ ` try { hasUI = !!ctx.hasUI; } catch {}`,
1842
+ ` if (!hasUI || typeof ctx.ui.select !== "function") return;`,
1843
+ ` planPromptOpen = true;`,
1844
+ ` let choice = undefined;`,
1845
+ ` try {`,
1846
+ ` choice = await ctx.ui.select("Plan mode - what next?", [`,
1847
+ ` "Execute the plan (track progress)",`,
1848
+ ` "Stay in plan mode",`,
1849
+ ` "Refine the plan",`,
1850
+ ` ]);`,
1851
+ ` } catch { planPromptOpen = false; return; }`,
1852
+ ` planPromptOpen = false;`,
1853
+ ` if (!choice) return;`,
1854
+ ` // The user may have left plan mode while the prompt was open (slash`,
1855
+ ` // /plan, Ctrl+Alt+P, /new). Honouring Execute there would silently`,
1856
+ ` // re-enter a mode they just exited.`,
1857
+ ` if (!planEnabled) return;`,
1858
+ ` if (String(choice).indexOf("Execute") === 0) {`,
1859
+ ` planEnabled = false;`,
1860
+ ` planExecuting = true;`,
1861
+ ` planUpdateUi(ctx);`,
1862
+ ` planPersist();`,
1863
+ ` const list = planSteps.map((s) => s.step + ". " + s.text).join("\\n");`,
1864
+ ` const first = planSteps[0] ? planSteps[0].text : "";`,
1865
+ ` try {`,
1866
+ ` pi.sendMessage({ customType: PLAN_LIST_TYPE, content: "**Plan steps (" + planSteps.length + ")**" + "\\n" + list, display: true }, { deliverAs: "followUp" });`,
1867
+ ` pi.sendMessage({ customType: PLAN_EXEC_TYPE, content: "Execute the plan." + "\\n" + "Remaining steps:" + "\\n" + list + "\\n" + "Start with: " + first + "\\n" + "After completing a step, include a [DONE:n] tag." }, { triggerTurn: true, deliverAs: "followUp" });`,
1868
+ ` } catch {}`,
1869
+ ` } else if (choice === "Refine the plan" && typeof ctx.ui.editor === "function") {`,
1870
+ ` let refinement = undefined;`,
1871
+ ` try { refinement = await ctx.ui.editor("Refine the plan:", ""); } catch { return; }`,
1872
+ ` const trimmed = String(refinement || "").trim();`,
1873
+ ` if (!trimmed) return;`,
1874
+ ` try { pi.sendUserMessage(trimmed, { deliverAs: "followUp" }); } catch {}`,
1875
+ ` }`,
1876
+ ` });`,
1877
+ ` } catch {}`,
1878
+ ``,
1879
+ ` // Restore after resume: the ENTRY is the source of truth for the mode, the`,
1880
+ ` // step list and the badge — and nothing else. The gate below needs no`,
1881
+ ` // restore because it reads the live flag.`,
1882
+ ` // State is assigned UNCONDITIONALLY: a fresh session (/new, /fork into an`,
1883
+ ` // empty branch) has no entry, and leaving the previous session's flags in`,
1884
+ ` // place would keep a stale badge for a mode that is not gating anything.`,
1885
+ ` try {`,
1886
+ ` pi.on("session_start", async (_event, ctx) => {`,
1887
+ ` try {`,
1888
+ ` if (ctx && typeof ctx.cwd === "string" && ctx.cwd) planCwd = ctx.cwd;`,
1889
+ ` const entries = ctx.sessionManager && typeof ctx.sessionManager.getEntries === "function"`,
1890
+ ` ? ctx.sessionManager.getEntries()`,
1891
+ ` : [];`,
1892
+ ` let saved = undefined;`,
1893
+ ` for (const entry of entries) {`,
1894
+ ` if (entry && entry.type === "custom" && entry.customType === PLAN_ENTRY) saved = entry.data;`,
1895
+ ` }`,
1896
+ ` const nextEnabled = !!saved && saved.enabled === true;`,
1897
+ ` const nextExecuting = !!saved && saved.executing === true;`,
1898
+ ` // Nothing here touches the active tool set. Plan mode does not own`,
1899
+ ` // it: the only thing that ever changed the roster was the restriction`,
1900
+ ` // this design deleted, and a resumed snapshot must never widen the`,
1901
+ ` // roster a narrower current launch installed (that was a real bug:`,
1902
+ ` // resuming under --tools read,bash silently restored grep).`,
1903
+ ` planEnabled = nextEnabled;`,
1904
+ ` planExecuting = nextExecuting;`,
1905
+ ` planPromptOpen = false;`,
1906
+ ` planPersistKey = null;`,
1907
+ ` planSteps = saved && Array.isArray(saved.steps)`,
1908
+ ` ? saved.steps.map((s) => ({ step: Number(s.step) || 0, text: String(s.text || ""), completed: s.completed === true }))`,
1909
+ ` : [];`,
1910
+ ` // An execution with no steps is a dead end: the checklist is empty and`,
1911
+ ` // every execution branch bails on steps.length, so treat it as off.`,
1912
+ ` if (planExecuting && planSteps.length === 0) planExecuting = false;`,
1913
+ ` } catch {}`,
1914
+ ` planUpdateUi(ctx);`,
1915
+ ` });`,
1916
+ ` } catch {}`,
1917
+ ` } catch {}`,
1918
+ ``
1919
+ ];
1920
+ }
1921
+ //#endregion
1195
1922
  //#region src/lib/pi-extension.ts
1196
1923
  /**
1197
1924
  * The gh-router Pi extension source, generated per launch into the
@@ -1202,9 +1929,9 @@ function buildPiAppendSystem(profileId, opts = {}) {
1202
1929
  * server in the mirror's `mcp.json` (`src/lib/pi-mcp-config.ts`), which
1203
1930
  * brings `tool_search`, the `mcp_servers` roster and per-server `exposure`
1204
1931
  * that a hand-wrapped `registerTool` cannot. What stays is the work no MCP
1205
- * server can do: the statusline footer, the memory bridge, and (cheapest
1206
- * family only) the prompt-submit relay, which POSTs JSON-RPC `tools/call`
1207
- * to the running proxy with the per-launch nonce (the same
1932
+ * server can do: the statusline footer, plan mode, the memory bridge, and
1933
+ * (cheapest family only) the prompt-submit relay, which POSTs JSON-RPC
1934
+ * `tools/call` to the running proxy with the per-launch nonce (the same
1208
1935
  * `GH_ROUTER_HOOK_MCP_URL/NONCE` channel the Claude hooks use).
1209
1936
  *
1210
1937
  * No custom provider, no compaction replacement: `session_before_compact`
@@ -1217,6 +1944,13 @@ function buildPiAppendSystem(profileId, opts = {}) {
1217
1944
  * segments. There is deliberately no third-party statusline package and
1218
1945
  * no `statusLine` settings block (the community bridge only reads the
1219
1946
  * user's real global/project settings, never the launch mirror).
1947
+ *
1948
+ * Plan mode (always on): Claude Code ships plan mode as a mode; Pi ships it
1949
+ * only as an example extension a user has to install. `src/lib/pi-plan-mode.ts`
1950
+ * generates the equivalent into this same package — see
1951
+ * `buildPiPlanModeSection` for the single reachable write barrier (the path
1952
+ * gate; the tool roster is deliberately untouched) and the divergences from
1953
+ * upstream.
1220
1954
  */
1221
1955
  /**
1222
1956
  * Statusline footer section for the generated extension. Owns Pi's footer
@@ -1585,7 +2319,7 @@ function buildPiExtensionSource(opts) {
1585
2319
  ``
1586
2320
  ] : [], `export default function (pi) {`);
1587
2321
  if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
1588
- 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;`, ` }`, ` });`, ...promptBrief ? [
2322
+ 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 ? [
1589
2323
  ` // Cheapest-profile execution brief, injected ABOVE the model's turn.`,
1590
2324
  ` // Produced server-side; this only relays the prompt and re-emits the`,
1591
2325
  ` // result as a custom message. Additive: the user prompt stays the user`,
@@ -1650,7 +2384,7 @@ function buildPiExtensionSource(opts) {
1650
2384
  function buildPiSkills(opts) {
1651
2385
  const peers = opts.peers !== false;
1652
2386
  const skills = [];
1653
- if (peers) {
2387
+ if (peers && piOracleEnabled(opts.profileId)) {
1654
2388
  const oracleBody = piOracleToolReachable(opts.profileId) ? [
1655
2389
  "Call `mcp__gh-router-peers__oracle` (load it with `tool_search` if it is",
1656
2390
  "not in the tool list yet) with the decision, the options considered, and",
@@ -1662,9 +2396,9 @@ function buildPiSkills(opts) {
1662
2396
  ] : [
1663
2397
  "Delegate to the `oracle` subagent through the `subagent` tool with the",
1664
2398
  "decision, the options considered, and the missing-context gaps. The",
1665
- "oracle is cold-start: it sees only what you pass, plus whatever it reads",
1666
- "itself. Its verdict is advisory — verify with tests and code, never",
1667
- "substitute votes for verification."
2399
+ "oracle is cold-start and tool-less: it sees only what you pass, and it",
2400
+ "cannot read the repository on its own. Its verdict is advisory — verify",
2401
+ "with tests and code, never substitute votes for verification."
1668
2402
  ];
1669
2403
  skills.push({
1670
2404
  dir: "gh-oracle",
@@ -1698,7 +2432,10 @@ function buildPiSkills(opts) {
1698
2432
  ].join("\n")
1699
2433
  });
1700
2434
  if (opts.swe === true && peers) {
1701
- const consults = piAdvisorModel(opts.profileId) ? "`oracle`/`advisor` for consults" : "`oracle` for consults";
2435
+ const advisor = piAdvisorModel(opts.profileId);
2436
+ const oracle = piOracleEnabled(opts.profileId);
2437
+ const consults = advisor ? "`oracle`/`advisor` for consults" : oracle ? "`oracle` for consults" : void 0;
2438
+ const rosterLine = consults ? `for verification, ${consults} (builtin \`scout\` and` : "for verification. (Builtin `scout` and";
1702
2439
  skills.push({
1703
2440
  dir: "gh-delegate",
1704
2441
  content: [
@@ -1711,7 +2448,7 @@ function buildPiSkills(opts) {
1711
2448
  "",
1712
2449
  "You may delegate via the `subagent` tool to this roster only: `Explore`",
1713
2450
  "for discovery, `General-Purpose` for scoped implementation, `reviewer`",
1714
- `for verification, ${consults}. (Builtin \`scout\` and`,
2451
+ rosterLine,
1715
2452
  "`worker` are disabled in this session; their aliases resolve here.)",
1716
2453
  "Recommended loop: `Explore` to map the code, paste the brief excerpts",
1717
2454
  "into the `General-Purpose` brief to implement, `reviewer` to check,",
@@ -1725,7 +2462,7 @@ function buildPiSkills(opts) {
1725
2462
  isBalancedFamily(opts.profileId) ? "Send work to reviewer ONLY when the change alters behavior." : "Send finished work to reviewer for assessment."
1726
2463
  ].join("\n")
1727
2464
  });
1728
- if (peers && piAdvisorModel(opts.profileId)) skills.push({
2465
+ if (piAdvisorModel(opts.profileId)) skills.push({
1729
2466
  dir: "gh-advisor",
1730
2467
  content: [
1731
2468
  "---",
@@ -2513,7 +3250,7 @@ const pi = defineCommand({
2513
3250
  })}\n`);
2514
3251
  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");
2515
3252
  const { disposeBluebirdClients } = await import("./bluebird-client-CY6NBHQu.js");
2516
- const { disposeAdoClients } = await import("./ado-tools-512UGB6R.js");
3253
+ const { disposeAdoClients } = await import("./ado-tools-CAtopk36.js");
2517
3254
  launchChild({
2518
3255
  kind: "pi",
2519
3256
  envVars: {
@@ -2551,4 +3288,4 @@ const pi = defineCommand({
2551
3288
  //#endregion
2552
3289
  export { pi };
2553
3290
 
2554
- //# sourceMappingURL=pi-D4LrdubN.js.map
3291
+ //# sourceMappingURL=pi-IYAvKF50.js.map