github-router 0.3.371 → 0.3.373

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 (53) hide show
  1. package/dist/ado-tools-WDyisN8w.js +1 -0
  2. package/dist/{attribution-settings-Beer9wsJ.js → attribution-settings-DZ8fEfvP.js} +6 -6
  3. package/dist/{attribution-settings-Beer9wsJ.js.map → attribution-settings-DZ8fEfvP.js.map} +1 -1
  4. package/dist/browser-ext/manifest.json +1 -1
  5. package/dist/{claude-CAYTTiyt.js → claude-8ksmV0dC.js} +11 -11
  6. package/dist/claude-8ksmV0dC.js.map +1 -0
  7. package/dist/{claude-md-injection-D1aMjvb_.js → claude-md-injection-BnzVv_aB.js} +19 -22
  8. package/dist/claude-md-injection-BnzVv_aB.js.map +1 -0
  9. package/dist/{codex-CALX-qG4.js → codex-C89FoaaG.js} +6 -6
  10. package/dist/{codex-CALX-qG4.js.map → codex-C89FoaaG.js.map} +1 -1
  11. package/dist/engine-C207cikp.js +1 -0
  12. package/dist/{gate-discovery-CITKjhsD.js → gate-discovery-Bc9FdRwg.js} +2 -2
  13. package/dist/{gate-discovery-CITKjhsD.js.map → gate-discovery-Bc9FdRwg.js.map} +1 -1
  14. package/dist/hooks.mjs +45 -10
  15. package/dist/hooks.sha256 +1 -1
  16. package/dist/{index-cmd-CjRcmYk3.js → index-cmd-DOhwt92u.js} +2 -2
  17. package/dist/{index-cmd-CjRcmYk3.js.map → index-cmd-DOhwt92u.js.map} +1 -1
  18. package/dist/{internal-prompt-submit-bi7F7pKk.js → internal-prompt-submit-BW5g3MjD.js} +2 -2
  19. package/dist/{internal-prompt-submit-bi7F7pKk.js.map → internal-prompt-submit-BW5g3MjD.js.map} +1 -1
  20. package/dist/{internal-prompt-submit-B-kKTl-8.js → internal-prompt-submit-C4uDwr7G.js} +2 -2
  21. package/dist/{internal-rebrief-B6ZJS6Mp.js → internal-rebrief-DvBS8myn.js} +3 -3
  22. package/dist/{internal-rebrief-B6ZJS6Mp.js.map → internal-rebrief-DvBS8myn.js.map} +1 -1
  23. package/dist/{internal-stop-hook-DT27bzH7.js → internal-stop-hook-nS91Jkda.js} +2 -2
  24. package/dist/{internal-stop-hook-DT27bzH7.js.map → internal-stop-hook-nS91Jkda.js.map} +1 -1
  25. package/dist/main.js +9 -9
  26. package/dist/{peer-mcp-personas-D7vaM-V5.js → peer-mcp-personas-BSxDj9sJ.js} +266 -243
  27. package/dist/peer-mcp-personas-BSxDj9sJ.js.map +1 -0
  28. package/dist/{pi-D4LrdubN.js → pi-BglhJ6n_.js} +1031 -70
  29. package/dist/pi-BglhJ6n_.js.map +1 -0
  30. package/dist/{provision-DonGTIfK.js → provision-B0GNohdl.js} +34 -3
  31. package/dist/provision-B0GNohdl.js.map +1 -0
  32. package/dist/{serve-jzmQ8KEE.js → serve-BxZq9vNl.js} +8 -8
  33. package/dist/{serve-jzmQ8KEE.js.map → serve-BxZq9vNl.js.map} +1 -1
  34. package/dist/{server-setup-wWidNq5m.js → server-setup-BLdWCcby.js} +21 -18
  35. package/dist/server-setup-BLdWCcby.js.map +1 -0
  36. package/dist/{service-backend-B6D_DY1Z.js → service-backend-BV2hHjuB.js} +35 -17
  37. package/dist/service-backend-BV2hHjuB.js.map +1 -0
  38. package/dist/{start-CTluQxu5.js → start-C3Zb8XMT.js} +4 -4
  39. package/dist/{start-CTluQxu5.js.map → start-C3Zb8XMT.js.map} +1 -1
  40. package/dist/{static-context-pack-DvwLWlbe.js → static-context-pack-CsOAC87F.js} +98 -18
  41. package/dist/static-context-pack-CsOAC87F.js.map +1 -0
  42. package/dist/{workiq-tools-CDLIrILp.js → workiq-tools-C6LAF_vA.js} +1 -1
  43. package/package.json +2 -3
  44. package/dist/ado-tools-512UGB6R.js +0 -1
  45. package/dist/claude-CAYTTiyt.js.map +0 -1
  46. package/dist/claude-md-injection-D1aMjvb_.js.map +0 -1
  47. package/dist/engine-CSAEqj2p.js +0 -1
  48. package/dist/peer-mcp-personas-D7vaM-V5.js.map +0 -1
  49. package/dist/pi-D4LrdubN.js.map +0 -1
  50. package/dist/provision-DonGTIfK.js.map +0 -1
  51. package/dist/server-setup-wWidNq5m.js.map +0 -1
  52. package/dist/service-backend-B6D_DY1Z.js.map +0 -1
  53. package/dist/static-context-pack-DvwLWlbe.js.map +0 -1
@@ -1,14 +1,14 @@
1
- import { P as warmTreeSitterPool } from "./service-backend-B6D_DY1Z.js";
1
+ import { P as warmTreeSitterPool } from "./service-backend-BV2hHjuB.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-BLdWCcby.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-BSxDj9sJ.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-B0GNohdl.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-BnzVv_aB.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
  });
@@ -424,6 +471,28 @@ function piThinkingLevelMapFor(efforts) {
424
471
  /** Provider key used in models.json and agent `provider/model` references. */
425
472
  const PI_PROVIDER_NAME = "gh-router";
426
473
  const PI_MIN_VERSION_NOTE = `Requires Pi >= ${PI_MIN_VERSION} and Node >= 22.19.`;
474
+ /**
475
+ * The tool-preference steer the digest carries.
476
+ *
477
+ * Pi's own per-tool guidelines cover `read`/`write`/`edit` but leave `grep`,
478
+ * `find` and `ls` with empty arrays (`dist/core/tools/*.js`), and its "use bash
479
+ * for ls, rg, find" rule fires only when those dedicated tools are ABSENT
480
+ * (`dist/core/system-prompt.js:46`). A launch with all eight active is told
481
+ * nothing, so the digest has to say it.
482
+ *
483
+ * Both halves are load-bearing. The first half stops the model shelling out to
484
+ * `sed`/`cat`/`python` for work the dedicated tools do better and with the
485
+ * harness's own approval and diff handling. The second half exists because the
486
+ * first is not true without it: a `jq` pipeline over a JSON blob, an `ast-grep`
487
+ * structural query, `git log -S`, or a build/test command all belong in bash,
488
+ * and a blanket "never shell out" would make the agent worse at exactly the
489
+ * tasks where the shell is the right instrument. Naming the tools is the point
490
+ * — "use the best tool" alone gives no signal.
491
+ *
492
+ * Single constant so the test suite pins one sentence rather than scraping the
493
+ * digest for keywords.
494
+ */
495
+ const PI_TOOL_PREFERENCE_LINE = "- Use the dedicated tools where they fit — read/write/edit for files and grep/find/ls for search — instead of shelling out to cat, sed, or python; but reach for rg, jq, ast-grep, git, and the build/test commands whenever those are the better tool for the job.";
427
496
  function piCopilotContractFor(profileId) {
428
497
  return isCheapestFamily(profileId) ? cheapestContractFor(profileId) : balancedContractFor(profileId);
429
498
  }
@@ -471,21 +540,32 @@ function piOracleToolReachable(profileId) {
471
540
  return allowlist === void 0 || allowlist.has("oracle");
472
541
  }
473
542
  /**
543
+ * Whether this profile has a consultant at all.
544
+ *
545
+ * Every Pi profile does. `local` used to be the exception on the reading that
546
+ * the Oracle is necessarily a Copilot call — it is not: the contract's
547
+ * `consultTransport` decides, and `local` declares `"local"`, so its Oracle is
548
+ * a consult of the same endpoint its lead already uses. The role therefore
549
+ * exists on every profile and `piOracleModel` never returns `undefined` for one
550
+ * of them; the transport, not the presence, is what differs.
551
+ */
552
+ function piOracleEnabled(_profileId) {
553
+ return true;
554
+ }
555
+ /**
474
556
  * Which model answers the `oracle` subagent.
475
557
  *
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.
558
+ * Always a real id: a Copilot slug on every profile whose consult is billed,
559
+ * and the local lead tier (`opus`) on `local`, whose consult goes to the local
560
+ * endpoint like the rest of its turns. The transport is not this function's
561
+ * business — `piContractFor(profileId).consultTransport` is — so a caller that
562
+ * needs to know where the consult runs must ask the contract.
483
563
  */
484
564
  function piOracleModel(profileId) {
485
- return profileId === "local" ? piLeadModel(profileId) : piContractFor(profileId).oracleModel;
565
+ return piOracleEnabled(profileId) ? piContractFor(profileId).oracleModel : void 0;
486
566
  }
487
567
  function piOracleThinking(profileId) {
488
- return profileId === "local" ? piLeadThinking(profileId) : piContractFor(profileId).oracleEffort;
568
+ return piOracleEnabled(profileId) ? piContractFor(profileId).oracleEffort : void 0;
489
569
  }
490
570
  /**
491
571
  * Advisor row. Cheapest-family launches carry one; `balanced` is advisor-free
@@ -540,7 +620,8 @@ function piNativeRoles(profileId) {
540
620
  function piProfileModelIds(profileId, opts = {}) {
541
621
  const ids = /* @__PURE__ */ new Set([piLeadModel(profileId)]);
542
622
  if (opts.peers !== false) {
543
- ids.add(piOracleModel(profileId));
623
+ const oracle = piOracleModel(profileId);
624
+ if (oracle) ids.add(oracle);
544
625
  for (const r of piNativeRoles(profileId)) ids.add(r.model);
545
626
  const advisor = piAdvisorModel(profileId);
546
627
  if (advisor) ids.add(advisor.model);
@@ -773,6 +854,9 @@ const PI_COSMETIC_SETTING_KEYS = [
773
854
  "fullscreenCopyOnSelect",
774
855
  "fullscreenWheelScrollLines",
775
856
  "theme",
857
+ "terminalTheme",
858
+ "thinkingMode",
859
+ "bashIntent",
776
860
  "themeAdaptive",
777
861
  "groupToolCalls",
778
862
  "readOutputMode",
@@ -864,14 +948,20 @@ const PI_HELPERS_AGENT_EXTENSIONS = {
864
948
  * filtering inside one extension. */
865
949
  const PI_UI_PACKAGES = Object.freeze(["npm:pi-claude-code-ui"]);
866
950
  /**
867
- * Claude Code dark theme (`#D77757` coral and friends) from
868
- * `better-claude-code-ui`, which ships six CC palettes. Themes-only:
951
+ * Claude Code palettes from `better-claude-code-ui`, which ships six CC
952
+ * variants (`claude-code-dark`, `claude-code-light`, …). Themes-only:
869
953
  * extensions/skills/prompts are explicitly emptied so none of the
870
954
  * 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`).
955
+ * the router-owned footer or `pi-claude-code-ui`. Theme files are pure
956
+ * JSON data — loading the whole `./theme` dir costs nothing at runtime and
957
+ * leaves all six CC variants pickable via `/settings`.
958
+ *
959
+ * These are no longer the DEFAULT. The launch now follows the terminal
960
+ * (`PI_FOLLOW_TERMINAL_THEME`), which is what cc-ui did to our pin at
961
+ * `session_start` regardless: it rewrote `theme` to `system` and stashed
962
+ * `claude-code-dark` in `terminalThemePrevious`. Emitting the pin only
963
+ * bought a startup flash and a lying settings file, so the palettes stay
964
+ * as data and users who want the fixed CC look pick one.
875
965
  */
876
966
  const PI_CC_THEME_PACKAGE = {
877
967
  source: "npm:better-claude-code-ui",
@@ -880,8 +970,14 @@ const PI_CC_THEME_PACKAGE = {
880
970
  skills: [],
881
971
  prompts: []
882
972
  };
883
- /** Default Pi theme: genuine Claude Code dark palette. */
884
- const PI_CC_DARK_THEME = "claude-code-dark";
973
+ /**
974
+ * Default Pi theme: follow the terminal's own palette. Pi's built-in
975
+ * `system` theme derives every color from the terminal and already exists in
976
+ * `PI_MIN_VERSION` (1.3.0) — see `modes/interactive/theme/system-theme.js`,
977
+ * where it is also sorted first in `getAvailableThemesWithPaths()` because it
978
+ * is Pi's own default when no `theme` setting is present.
979
+ */
980
+ const PI_FOLLOW_TERMINAL_THEME = "system";
885
981
  /** Built-in tools enabled at startup (Pi-native set incl. Windows). */
886
982
  const PI_DEFAULT_TOOLS = Object.freeze([
887
983
  "read",
@@ -894,6 +990,70 @@ const PI_DEFAULT_TOOLS = Object.freeze([
894
990
  "ls"
895
991
  ]);
896
992
  /**
993
+ * The pi keybinding action that owns `shift+tab` by default.
994
+ *
995
+ * Named rather than spelled inline so the keybindings writer and the test that
996
+ * pins it cannot drift: `dist/core/keybindings.js:13` declares this action with
997
+ * `defaultKeys: "shift+tab"`, and `RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS`
998
+ * in `dist/core/extensions/runner.js:9-26` lists it, which is what makes an
999
+ * extension's `shift+tab` registration die with "conflicts with built-in
1000
+ * shortcut. Skipping."
1001
+ */
1002
+ const PI_THINKING_CYCLE_ACTION = "app.thinking.cycle";
1003
+ /** The key `shift+tab` moves to when plan mode claims it. */
1004
+ const PI_THINKING_CYCLE_REBIND = "ctrl+shift+t";
1005
+ /**
1006
+ * Build the per-launch `keybindings.json` that frees `shift+tab` for plan mode.
1007
+ *
1008
+ * Claude Code binds `shift+tab` to its permission-mode ring, and the whole point
1009
+ * of this file is that a user arriving from Claude Code presses the same key
1010
+ * here. Pi routes the key to `app.thinking.cycle` and *reserves* it against
1011
+ * extension overrides, so an extension cannot claim it — but
1012
+ * `buildBuiltinKeybindings` skips every action whose configured value is an
1013
+ * empty list (`runner.js:31-49`), which leaves the key unbound and free for an
1014
+ * extension registration to take.
1015
+ *
1016
+ * The action is MOVED rather than emptied. Emptying was the first cut and it
1017
+ * costs a working pi binding for a plan-mode toggle that `/plan` already
1018
+ * provides; moving it keeps thinking-level cycling reachable. `ctrl+shift+t`
1019
+ * is free in pi's own table (`keybindings.js`) and among every shortcut the
1020
+ * bundled packages register (verified: ctrl+shift+o/e/r, ctrl+., alt+t).
1021
+ *
1022
+ * Only this one action is touched. Every other pi default is left to pi, so
1023
+ * this file cannot silently re-map a binding the user relies on. A user's own
1024
+ * `keybindings.json` is merged UNDER it, matching how `settings.json` is
1025
+ * layered — with one refinement in `mergePiKeybindingsSettings`: a user who
1026
+ * already moved thinking-cycle off `shift+tab` keeps their key, because the
1027
+ * invariant this file enforces is "shift+tab is unbound", not "our value wins".
1028
+ */
1029
+ function buildPiKeybindingsJson() {
1030
+ return { [PI_THINKING_CYCLE_ACTION]: [PI_THINKING_CYCLE_REBIND] };
1031
+ }
1032
+ /** Does this configured binding still claim `shift+tab`? */
1033
+ function boundToShiftTab(value) {
1034
+ return (Array.isArray(value) ? value : [value]).some((k) => typeof k === "string" && k.trim().toLowerCase() === "shift+tab");
1035
+ }
1036
+ /**
1037
+ * Lay our freed key over a snapshotted user `keybindings.json`.
1038
+ *
1039
+ * The invariant is "`shift+tab` is unbound", not "our value wins". So the
1040
+ * built value is applied only when the user's file still routes `shift+tab`
1041
+ * through `app.thinking.cycle` (absent counts as still-bound: that is the pi
1042
+ * default). A user who already moved it elsewhere — `F2`, `ctrl+shift+t`,
1043
+ * anything without `shift+tab` — keeps their binding, and the key is free
1044
+ * either way. Forcing our value there would silently undo a preference with no
1045
+ * gain to plan mode.
1046
+ *
1047
+ * Every other user binding survives untouched. Non-object input (corrupt JSON
1048
+ * parsed to a string, or an array) is discarded rather than spread, so a broken
1049
+ * file cannot plant junk keys in the launch mirror.
1050
+ */
1051
+ function mergePiKeybindingsSettings(userKeybindings, built) {
1052
+ const merged = { ...userKeybindings && typeof userKeybindings === "object" && !Array.isArray(userKeybindings) ? userKeybindings : {} };
1053
+ for (const [action, keys] of Object.entries(built)) if (!(action in merged) || boundToShiftTab(merged[action])) merged[action] = keys;
1054
+ return merged;
1055
+ }
1056
+ /**
897
1057
  * Build the per-launch `settings.json`. Additive over the snapshotted
898
1058
  * user settings (the launcher merges lists it owns): narrow model
899
1059
  * scope, fixed thinking, limited toolset, derived compaction, and the
@@ -925,7 +1085,8 @@ function buildPiSettingsJson(opts) {
925
1085
  const modelThinkingLevels = {};
926
1086
  modelThinkingLevels[`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`] = piLeadThinking(opts.profileId);
927
1087
  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);
1088
+ const oracle = piOracleModel(opts.profileId);
1089
+ if (oracle) modelThinkingLevels[`${PI_PROVIDER_NAME}/${oracle}`] = piOracleThinking(opts.profileId);
929
1090
  const advisor = piAdvisorModel(opts.profileId);
930
1091
  if (advisor) modelThinkingLevels[`${PI_PROVIDER_NAME}/${advisor.model}`] = advisor.thinking;
931
1092
  return {
@@ -955,14 +1116,17 @@ function buildPiSettingsJson(opts) {
955
1116
  fullscreenCopyOnSelect: true,
956
1117
  fullscreenWheelScrollLines: "auto",
957
1118
  ...ui ? {
958
- themeAdaptive: false,
1119
+ themeAdaptive: true,
959
1120
  groupToolCalls: true,
960
1121
  readOutputMode: "summary",
961
1122
  searchOutputMode: "count",
962
1123
  mcpOutputMode: "summary",
963
1124
  bashOutputMode: "summary",
964
1125
  toolBackground: "transparent",
965
- theme: PI_CC_DARK_THEME
1126
+ theme: PI_FOLLOW_TERMINAL_THEME,
1127
+ terminalTheme: true,
1128
+ thinkingMode: "live",
1129
+ bashIntent: "off"
966
1130
  } : {},
967
1131
  branchSummary: {
968
1132
  reserveTokens: 16384,
@@ -995,7 +1159,8 @@ function buildPiSettingsJson(opts) {
995
1159
  "codex-exec": { disabled: true },
996
1160
  "codex-exec-writer": { disabled: true },
997
1161
  "cursor-agent": { disabled: true },
998
- "cursor-agent-writer": { disabled: true }
1162
+ "cursor-agent-writer": { disabled: true },
1163
+ ...piOracleEnabled(opts.profileId) ? {} : { oracle: { disabled: true } }
999
1164
  } } } : {}
1000
1165
  };
1001
1166
  }
@@ -1026,9 +1191,9 @@ function mergeSubagentsSettings(userSubagents, builtSubagents) {
1026
1191
  };
1027
1192
  }
1028
1193
  function roleDescription(profileId, role) {
1029
- const oracleNote = "May consult the oracle subagent when a decision feels risky.";
1194
+ const consultNote = piOracleEnabled(profileId) ? " May consult the oracle subagent when a decision feels risky." : "";
1030
1195
  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}`;
1196
+ 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
1197
  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
1198
  }
1034
1199
  /**
@@ -1093,7 +1258,7 @@ function buildPiAgentFiles(profileId) {
1093
1258
  "defaultContext: fresh"
1094
1259
  ];
1095
1260
  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");
1261
+ if (isImplementer) lines.push("aliases: worker, developer, coder, implementer, develop", "acceptanceRole: writer", "allowNestedSubagents: true", piOracleEnabled(profileId) ? "allowedAgents: reviewer, oracle" : "allowedAgents: reviewer");
1097
1262
  if (isBalancedFamily(profileId) && isReviewer) lines.push("allowNestedSubagents: true", "allowedAgents: Explore");
1098
1263
  lines.push("---", "");
1099
1264
  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 +1266,32 @@ function buildPiAgentFiles(profileId) {
1101
1266
  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
1267
  files[`agents/${agentFileName(role.name)}`] = `${lines.join("\n")}\n`;
1103
1268
  }
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`;
1269
+ const oracleModel = piOracleModel(profileId);
1270
+ if (oracleModel) {
1271
+ const oracle = [
1272
+ "---",
1273
+ "name: oracle",
1274
+ "description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.",
1275
+ `tools: ""`,
1276
+ `model: ${PI_PROVIDER_NAME}/${oracleModel}`,
1277
+ `thinking: ${piOracleThinking(profileId)}`,
1278
+ "advertise: true",
1279
+ "async: false",
1280
+ "systemPromptMode: replace",
1281
+ "inheritProjectContext: true",
1282
+ "defaultContext: fresh",
1283
+ "---",
1284
+ "",
1285
+ "You are an oracle: a second set of eyes, consulted once per question.",
1286
+ "You have no tools on purpose. You cannot read the repository, run",
1287
+ "anything, or fetch what the caller did not paste in — so do not ask to.",
1288
+ "Answer from the context you are given: name the assumptions it rests on,",
1289
+ "say which missing fact would change your recommendation, and recommend.",
1290
+ "Never claim to have verified, executed, approved, or merged anything.",
1291
+ ...consultIsLocalTransport(profileId) ? [LOCAL_CONSULT_REDACTION_NOTE] : []
1292
+ ].join("\n");
1293
+ files[`agents/${agentFileName("oracle")}`] = `${oracle}\n`;
1294
+ }
1124
1295
  const advisor = piAdvisorModel(profileId);
1125
1296
  if (advisor) {
1126
1297
  const body = [
@@ -1183,15 +1354,785 @@ function buildPiAppendSystem(profileId, opts = {}) {
1183
1354
  const lines = [
1184
1355
  `# gh-router ${profileId} mode`,
1185
1356
  "",
1186
- `- Lead owns planning directly; there is no Plan subagent.`
1357
+ `- Lead owns planning directly; there is no Plan subagent.`,
1358
+ PI_TOOL_PREFERENCE_LINE
1187
1359
  ];
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.`);
1360
+ if (peers) {
1361
+ const oracle = piOracleEnabled(profileId);
1362
+ 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.`);
1363
+ if (oracle) {
1364
+ 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.`);
1365
+ if (consultIsLocalTransport(profileId)) lines.push(`- ${LOCAL_CONSULT_REDACTION_LINE}`);
1366
+ }
1367
+ lines.push(`- After any subagent work completes, always write the final answer yourself.`);
1368
+ } else lines.push(`- Peerless launch: no subagents or consultants in this session; plan, implement, and verify directly.`);
1190
1369
  if (advisor) lines.push("", FRESH_CONSULT_CONTRACT.trimEnd());
1191
1370
  lines.push("", `(${PI_MIN_VERSION_NOTE})`, "");
1192
1371
  return lines.join("\n");
1193
1372
  }
1194
1373
  //#endregion
1374
+ //#region src/lib/pi-plan-mode.ts
1375
+ /**
1376
+ * Strip markdown noise from one step's text.
1377
+ *
1378
+ * Upstream also strips a leading imperative (`Read`/`Add`/`Use`…), which
1379
+ * turns "Read the launcher" into "Launcher". Divergence 5: keep the verb. The
1380
+ * checklist is what the user reads while the plan runs, and a bare noun loses
1381
+ * the action it is meant to check off.
1382
+ */
1383
+ function cleanPlanStepText(text) {
1384
+ return String(text ?? "").replace(/\*{1,2}([^*]+)\*{1,2}/g, "$1").replace(/`([^`]+)`/g, "$1").replace(/\s+/g, " ").trim();
1385
+ }
1386
+ /**
1387
+ * Parse the model's numbered plan into steps.
1388
+ *
1389
+ * Takes the LAST matching heading on purpose: the caller feeds this everything
1390
+ * the model wrote for a turn, including thinking blocks, and with reasoning-max
1391
+ * models a draft plan often lands in thinking before the visible one. The
1392
+ * visible text block comes last in content order, so last-wins picks the plan
1393
+ * the user actually saw.
1394
+ *
1395
+ * Fenced code is stripped first: a numbered list inside a snippet is not a plan.
1396
+ *
1397
+ * Which headings count: the brief asks for a `Plan:` list, and that is what an
1398
+ * obedient reply ends with. It is not the only shape a good reply takes — the
1399
+ * brief also says to write Context / recommended approach / critical files /
1400
+ * verification, and a reply that follows THAT structure and closes its summary
1401
+ * under `## Recommended approach` used to parse as ZERO steps, leaving the
1402
+ * checklist, the "what next?" prompt and the Execute kick silently unreachable.
1403
+ * So the conventional headings are accepted too. The heading must be alone on
1404
+ * its line (prose like "Steps: we will ..." never matches).
1405
+ *
1406
+ * The regex is inline, not module scope: this function is serialized with
1407
+ * `toString()` into the generated extension, where module scope does not exist.
1408
+ */
1409
+ function extractPlanSteps(message) {
1410
+ const items = [];
1411
+ const text = String(message ?? "").replace(/^[ \t]*(?:```|~~~)[\s\S]*?^[ \t]*(?:```|~~~)[ \t]*$/gm, "");
1412
+ const headers = [...text.matchAll(/^[ \t]*(?:#{1,6}[ \t]*)?(?:\*\*|__)?[ \t]*(?:plan|recommended approach|steps|implementation plan)[ \t]*(?::[ \t]*)?(?:\*\*|__)?[ \t]*$/gim)];
1413
+ if (headers.length === 0) return items;
1414
+ const lastHeader = headers[headers.length - 1];
1415
+ let planSection = text.slice((lastHeader.index ?? 0) + lastHeader[0].length);
1416
+ const level = (lastHeader[0].match(/^[ \t]*(#{1,6})/) || [])[1];
1417
+ if (level) {
1418
+ const boundary = new RegExp("^[ \\t]*#{1," + level.length + "}[ \\t]+", "m");
1419
+ const hit = planSection.slice(1).search(boundary);
1420
+ if (hit >= 0) planSection = planSection.slice(0, hit + 1);
1421
+ }
1422
+ const numbered = /^[ \t]*(?:#{1,6}[ \t]*)?(\d+)[.)][ \t]+(.+)$/gm;
1423
+ const used = /* @__PURE__ */ new Set();
1424
+ for (const match of planSection.matchAll(numbered)) {
1425
+ const raw = (match[2] ?? "").trim().replace(/\*{1,2}$/, "").trim();
1426
+ if (raw.length > 5 && !raw.startsWith("/") && !raw.startsWith("-")) {
1427
+ const cleaned = cleanPlanStepText(raw);
1428
+ if (cleaned.length > 3) {
1429
+ const declared = Number(match[1]);
1430
+ const step = Number.isInteger(declared) && declared > 0 && !used.has(declared) ? declared : items.length + 1;
1431
+ used.add(step);
1432
+ items.push({
1433
+ step,
1434
+ text: cleaned,
1435
+ completed: false
1436
+ });
1437
+ }
1438
+ }
1439
+ }
1440
+ return items;
1441
+ }
1442
+ /**
1443
+ * Steps the model reported as finished. Accepts `[DONE:2]`, `[DONE 2]`,
1444
+ * `Done: 2`, and "Step 2 is complete" — the last one adjacency-anchored so
1445
+ * "Step 9 is not done" never marks anything.
1446
+ */
1447
+ function extractDoneSteps(message) {
1448
+ const text = String(message ?? "");
1449
+ const steps = [];
1450
+ for (const match of text.matchAll(/\[DONE\s*:?\s*(\d+)\]/gi)) steps.push(Number(match[1]));
1451
+ for (const match of text.matchAll(/\bDone\s*:\s*(\d+)\b/gi)) steps.push(Number(match[1]));
1452
+ for (const match of text.matchAll(/\bStep\s*(\d+)\s+(?:is\s+)?(?:done|complete|completed|finished)\b/gi)) steps.push(Number(match[1]));
1453
+ return [...new Set(steps)];
1454
+ }
1455
+ /** Mark reported steps complete in place; returns how many became complete. */
1456
+ function applyDoneSteps(text, items) {
1457
+ let marked = 0;
1458
+ for (const step of extractDoneSteps(text)) {
1459
+ const item = items.find((candidate) => candidate.step === step && !candidate.completed);
1460
+ if (item) {
1461
+ item.completed = true;
1462
+ marked++;
1463
+ }
1464
+ }
1465
+ return marked;
1466
+ }
1467
+ /**
1468
+ * Whole-plan completion phrasing, consulted only on a run's final message as a
1469
+ * fallback for a model that summarizes instead of tagging each step.
1470
+ */
1471
+ function planAllStepsComplete(message) {
1472
+ const text = String(message ?? "");
1473
+ 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);
1474
+ }
1475
+ /**
1476
+ * Tools plan mode refuses, by name, through the `tool_call` handler.
1477
+ *
1478
+ * These stay ACTIVE. An earlier revision also removed them from the active
1479
+ * tool set, described as "two independent barriers" — they were not
1480
+ * independent, they were *stacked*: pi resolves a call against the declared
1481
+ * tool list in `prepareToolCall()` and answers `Tool <name> not found` BEFORE
1482
+ * `beforeToolCall` (the `tool_call` hook) ever runs. So the narrower barrier
1483
+ * sat in front of the wider one, the path exception below was unreachable, the
1484
+ * model was told a tool it had just been told to use did not exist, and the
1485
+ * documented refusal string was never displayed. An obedient model fell back to
1486
+ * `bash` — which is allowed — so the unsanctioned route silently won.
1487
+ *
1488
+ * With the narrowing gone there is ONE barrier and it is reachable: the model
1489
+ * gets a call it can make, and a refusal sentence it can act on. The honest
1490
+ * scope is unchanged and already documented: `bash` is allowed, so this
1491
+ * redirects a cooperative model, it does not contain a hostile one.
1492
+ *
1493
+ * `apply_patch` has no single target path to compare and is therefore refused
1494
+ * outright — that refusal is also reachable for the first time.
1495
+ */
1496
+ const PLAN_BLOCKED_TOOLS = Object.freeze([
1497
+ "edit",
1498
+ "write",
1499
+ "apply_patch"
1500
+ ]);
1501
+ /**
1502
+ * The plan file for ONE session, relative to the workspace.
1503
+ *
1504
+ * A fixed path was the original design and it does not survive parallel use.
1505
+ * Two sessions in the same repo both passed the path gate — the gate compares a
1506
+ * resolved path against this value and has no notion of ownership — so the
1507
+ * second plan silently replaced the first, and an `edit` written against the
1508
+ * old text failed with a message about fuzzy matching instead of naming the
1509
+ * collision. The rest of plan mode was already per-session: the mode flag, the
1510
+ * steps and the execution flag live in a `PLAN_MODE_ENTRY` in each session's
1511
+ * own transcript. The file was the last piece of shared mutable state.
1512
+ *
1513
+ * The Claude front-end already does this — its artifact hook reads
1514
+ * `tool_input.planFilePath` "per-session; never the globally-newest file in the
1515
+ * shared plans dir" (`src/internal-artifact-open.ts`). This is the same
1516
+ * contract, with the name derived rather than model-chosen:
1517
+ *
1518
+ * - **Derived, not chosen.** A generated three-word name would have to survive
1519
+ * the model restating it, and a resumed session that picked a different name
1520
+ * would fork the plan. A session id is unforgeable and resume-stable for
1521
+ * free, and it keeps the gate an exact-path comparison.
1522
+ * - **Full id, not a hash or a prefix.** The id already appears in the
1523
+ * transcript filename, so a plan directory traces back to the session that
1524
+ * wrote it. UUIDv7 is time-ordered at the front, so a prefix would collide
1525
+ * for launches in the same millisecond.
1526
+ * - **One `<slug>` segment**, so the repository's existing convention
1527
+ * (`.github-router/plans/<slug>/plan.md`, what `/gh-plan` writes and
1528
+ * `/gh-implement` reads, `.complete` beside it) still describes the shape.
1529
+ *
1530
+ * Sanitized to `[A-Za-z0-9._-]` as belt-and-braces: the id is host-generated,
1531
+ * but sanitizing also makes traversal structurally impossible — path separators
1532
+ * cannot survive, and a segment that is entirely dots is unreachable anyway
1533
+ * because every one of these starts with `pi-plan-`.
1534
+ *
1535
+ * Sanitizing is LOSSY, and lossy is a collision. pi's own id validator
1536
+ * (`assertValidSessionId`) admits `.`, so `a.b` and `a-b` are both legal ids,
1537
+ * and `--session-id` lets an operator pick either; mapping one onto the other
1538
+ * would reinstate, for that pair, the very bug this function exists to prevent.
1539
+ * Dots are therefore KEPT (they are inert inside a prefixed segment). Anything
1540
+ * that still had to be ALTERED — a character dropped, or the length cap hit —
1541
+ * carries a digest of its original bytes instead of silently merging with its
1542
+ * neighbours. Generated UUIDv7 ids are `[0-9a-f-]` and are untouched, so the
1543
+ * readable form that traces to the transcript filename stays the common case.
1544
+ * FNV-1a rather than a cryptographic digest because this has to survive being
1545
+ * inlined into the emitted extension (a `toString()` copy cannot import
1546
+ * `node:crypto`), and telling two host-generated ids apart does not need
1547
+ * resistance to an attacker who could pick the path outright.
1548
+ *
1549
+ * Emitted via `.toString()`, so this body carries no module-scope references —
1550
+ * the layout strings are inline for that reason, not by preference, and the
1551
+ * digest is hand-rolled because `node:crypto` is not importable there.
1552
+ */
1553
+ function planFilePathForSession(sessionId) {
1554
+ const raw = typeof sessionId === "string" ? sessionId.trim() : "";
1555
+ let slug = "";
1556
+ let altered = false;
1557
+ for (const ch of raw) if (/[A-Za-z0-9._-]/.test(ch)) slug += ch;
1558
+ else {
1559
+ altered = true;
1560
+ if (slug.length > 0 && !slug.endsWith("-")) slug += "-";
1561
+ }
1562
+ slug = slug.replace(/^[.-]+|[.-]+$/g, "");
1563
+ if (slug.length > 96) {
1564
+ slug = slug.slice(0, 96).replace(/[.-]+$/g, "");
1565
+ altered = true;
1566
+ }
1567
+ if (slug !== raw) altered = true;
1568
+ if (!slug) return ".github-router/plans/pi-plan/plan.md";
1569
+ if (altered) {
1570
+ let hash = 2166136261;
1571
+ for (let i = 0; i < raw.length; i++) {
1572
+ hash ^= raw.charCodeAt(i);
1573
+ hash = Math.imul(hash, 16777619) >>> 0;
1574
+ }
1575
+ slug += "-" + hash.toString(16).padStart(8, "0");
1576
+ }
1577
+ return ".github-router/plans/pi-plan-" + slug + "/plan.md";
1578
+ }
1579
+ /** Session entry type for persisting plan state across resume. */
1580
+ const PLAN_MODE_ENTRY = "gh-router-plan-mode";
1581
+ /** Status/widget keys, namespaced so another extension cannot collide. */
1582
+ const PLAN_STATUS_KEY = "gh-router-plan";
1583
+ const PLAN_WIDGET_KEY = "gh-router-plan-steps";
1584
+ /** Custom message types the emitted extension emits and later filters. */
1585
+ const PLAN_CONTEXT_TYPE = "gh-router-plan-context";
1586
+ const PLAN_EXEC_TYPE = "gh-router-plan-exec";
1587
+ const PLAN_DONE_TYPE = "gh-router-plan-done";
1588
+ const PLAN_LIST_TYPE = "gh-router-plan-list";
1589
+ /**
1590
+ * Resolve `path` against `cwd` and decide whether it IS the plan file.
1591
+ *
1592
+ * Deliberately dumb and deliberately strict: this is the one hole in the write
1593
+ * barrier, so it compares `path.resolve`d strings rather than doing prefix
1594
+ * arithmetic on the raw input. A model that writes `plan.md` in the right
1595
+ * directory passes; `../plan.md`, `<cwd>/plan.md/../secret`, and a symlink-free
1596
+ * absolute path to the same target all normalize to the same string, which is
1597
+ * the property that matters.
1598
+ *
1599
+ * The emitted copy cannot import `node:path` (the generated extension and this
1600
+ * module have different allowed specifiers), so it carries its own tiny
1601
+ * resolver: POSIX normalisation plus a Windows drive/UNC guard. It is not a
1602
+ * general path library — it only has to agree with itself between the
1603
+ * comparison here and the value `planFilePathForSession()` produces, which is
1604
+ * why the relative plan path is a PARAMETER: a `toString()`-serialized function
1605
+ * cannot see module scope, and a captured constant would be `undefined` at
1606
+ * runtime.
1607
+ */
1608
+ function isPlanFilePath(cwd, target, rel) {
1609
+ const raw = typeof target === "string" ? target.trim() : "";
1610
+ if (!raw) return false;
1611
+ const normalize = (input) => {
1612
+ const isWindows = /^[a-zA-Z]:[\\/]/.test(input) || input.indexOf("\\") >= 0;
1613
+ const sep = isWindows ? /\\+/g : /\/+/g;
1614
+ const unified = input.replace(sep, "/");
1615
+ const absolute = isWindows ? unified : unified.startsWith("/") ? unified : "/" + unified;
1616
+ const parts = [];
1617
+ for (const segment of absolute.split("/")) {
1618
+ if (!segment || segment === ".") continue;
1619
+ if (segment === "..") {
1620
+ parts.pop();
1621
+ continue;
1622
+ }
1623
+ parts.push(segment);
1624
+ }
1625
+ return (isWindows ? "" : "/") + parts.join("/");
1626
+ };
1627
+ if (typeof rel !== "string" || !rel) return false;
1628
+ const base = typeof cwd === "string" && cwd.trim() ? cwd.trim() : "/";
1629
+ return (raw.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(raw) || raw.indexOf("\\") === 0 ? normalize(raw) : normalize(base + "/" + raw)) === normalize(base + "/" + rel);
1630
+ }
1631
+ /**
1632
+ * The emitted extension section.
1633
+ *
1634
+ * Pure helpers ride `.toString()` (the same technique the statusline footer
1635
+ * uses for `buildPiStatusPayload`) so the code that runs in the product is
1636
+ * byte-identical to the code the unit tests exercise — a hand-copied duplicate
1637
+ * could drift from its tested twin without any test noticing.
1638
+ */
1639
+ function buildPiPlanModeSection() {
1640
+ return [
1641
+ ` // ---- plan mode: Claude-Code-style planning (always on) ----`,
1642
+ ` // /plan, Shift+Tab (freed: the mirror's keybindings.json moves thinking-`,
1643
+ ` // level cycling to Ctrl+Shift+T) or Ctrl+Alt+P (the fallback on a host`,
1644
+ ` // without that file) toggles it. The tool set is NEVER touched: it used to`,
1645
+ ` // be snapshotted on entry and restored on exit, and removing the writers from`,
1646
+ ` // it made the path gate below unreachable (pi answers "Tool write not found"`,
1647
+ ` // before any handler runs), plus a restored snapshot could widen the roster a`,
1648
+ ` // narrower launch installed. ONE barrier instead: the writers stay offered`,
1649
+ ` // and the gate refuses every target except the plan file. Everything else`,
1650
+ ` // stays, because a frontier model told to explore and not implement needs a`,
1651
+ ` // shell and can be trusted with one.`,
1652
+ ` try {`,
1653
+ ` const PLAN_STATUS_KEY = ${JSON.stringify(PLAN_STATUS_KEY)};`,
1654
+ ` const PLAN_WIDGET_KEY = ${JSON.stringify(PLAN_WIDGET_KEY)};`,
1655
+ ` const PLAN_ENTRY = ${JSON.stringify(PLAN_MODE_ENTRY)};`,
1656
+ ` const PLAN_CONTEXT_TYPE = ${JSON.stringify(PLAN_CONTEXT_TYPE)};`,
1657
+ ` const PLAN_EXEC_TYPE = ${JSON.stringify(PLAN_EXEC_TYPE)};`,
1658
+ ` const PLAN_DONE_TYPE = ${JSON.stringify(PLAN_DONE_TYPE)};`,
1659
+ ` const PLAN_LIST_TYPE = ${JSON.stringify(PLAN_LIST_TYPE)};`,
1660
+ ` const PLAN_BLOCKED = new Set(${JSON.stringify([...PLAN_BLOCKED_TOOLS])});`,
1661
+ ` const planFilePathForSession = (${planFilePathForSession.toString()});`,
1662
+ ` const isPlanFilePath = (${isPlanFilePath.toString()});`,
1663
+ ` const cleanPlanStepText = (${cleanPlanStepText.toString()});`,
1664
+ ` const extractPlanSteps = (${extractPlanSteps.toString()});`,
1665
+ ` const extractDoneSteps = (${extractDoneSteps.toString()});`,
1666
+ ` const applyDoneSteps = (${applyDoneSteps.toString()});`,
1667
+ ` const planAllStepsComplete = (${planAllStepsComplete.toString()});`,
1668
+ ``,
1669
+ ` let planEnabled = false;`,
1670
+ ` let planExecuting = false;`,
1671
+ ` let planSteps = [];`,
1672
+ ` let planCwd = "";`,
1673
+ ` // The plan file, resolved from THIS session's id and cached for the run.`,
1674
+ ` // A fixed path was the original design and it does not survive parallel`,
1675
+ ` // use: two sessions in one repo both cleared the gate, so the second plan`,
1676
+ ` // silently replaced the first. Resolving from the session id gives each`,
1677
+ ` // session its own file with no lock and no coordination, and because the`,
1678
+ ` // id is stable across resume the same session keeps editing the same file.`,
1679
+ ` // Cached, then re-resolved on every session_start: the derive is cheap but`,
1680
+ ` // it must run once per (possibly changing) session, not once per gate hit.`,
1681
+ ` let planRel = "";`,
1682
+ ` // Set while the "what next?" prompt is open. agent_end can fire again for`,
1683
+ ` // the same plan (a queued follow-up run ends too), and a second prompt on`,
1684
+ ` // top of the first would let two Execute answers each send an execution`,
1685
+ ` // kick, resetting progress and paying for a redundant turn.`,
1686
+ ` let planPromptOpen = false;`,
1687
+ ``,
1688
+ ` // Resolve (once per session) the ONE file this session may write. Every`,
1689
+ ` // read site goes through here so the notify, the status line, the brief`,
1690
+ ` // and the gate can never disagree about the path.`,
1691
+ ` function planRelFor(ctx) {`,
1692
+ ` if (planRel) return planRel;`,
1693
+ ` let id = "";`,
1694
+ ` try {`,
1695
+ ` const sm = ctx && ctx.sessionManager;`,
1696
+ ` if (sm && typeof sm.getSessionId === "function") id = sm.getSessionId();`,
1697
+ ` } catch {}`,
1698
+ ` // No second fallback here: planFilePathForSession ALWAYS returns a usable`,
1699
+ ` // path (an unusable id becomes the shared fallback inside it), so a`,
1700
+ ` // "|| fallback" would be dead code that reads like a live guard.`,
1701
+ ` planRel = planFilePathForSession(id);`,
1702
+ ` return planRel;`,
1703
+ ` }`,
1704
+ ``,
1705
+ ` function planPaint(ctx, text, color) {`,
1706
+ ` try {`,
1707
+ ` const theme = ctx && ctx.ui && ctx.ui.theme;`,
1708
+ ` if (theme && typeof theme.fg === "function") return theme.fg(color, text);`,
1709
+ ` } catch {}`,
1710
+ ` return text;`,
1711
+ ` }`,
1712
+ ``,
1713
+ ` // Resident checklist: a footer status badge plus a widget above the editor.`,
1714
+ ` // The router's own statusline footer already forwards extension statuses,`,
1715
+ ` // so the badge is visible without this extension owning the footer.`,
1716
+ ` function planUpdateUi(ctx) {`,
1717
+ ` try {`,
1718
+ ` const ui = ctx && ctx.ui;`,
1719
+ ` if (!ui) return;`,
1720
+ ` if (planExecuting && planSteps.length > 0) {`,
1721
+ ` const done = planSteps.filter((s) => s.completed).length;`,
1722
+ ` try { ui.setStatus(PLAN_STATUS_KEY, planPaint(ctx, "\\u{1F4CB} " + done + "/" + planSteps.length, "accent")); } catch {}`,
1723
+ ` } else if (planEnabled) {`,
1724
+ ` try { ui.setStatus(PLAN_STATUS_KEY, planPaint(ctx, "\\u{23F8} plan", "warning")); } catch {}`,
1725
+ ` } else {`,
1726
+ ` try { ui.setStatus(PLAN_STATUS_KEY, undefined); } catch {}`,
1727
+ ` }`,
1728
+ ` if (planSteps.length > 0 && (planEnabled || planExecuting)) {`,
1729
+ ` const lines = planSteps.map((s) => {`,
1730
+ ` const text = s.text.length > 60 ? s.text.slice(0, 57) + "..." : s.text;`,
1731
+ ` if (s.completed) return planPaint(ctx, "\\u2611 ", "success") + planPaint(ctx, text, "muted");`,
1732
+ ` return planPaint(ctx, "\\u2610 ", "muted") + text;`,
1733
+ ` });`,
1734
+ ` try { ui.setWidget(PLAN_WIDGET_KEY, lines); } catch {}`,
1735
+ ` } else {`,
1736
+ ` try { ui.setWidget(PLAN_WIDGET_KEY, undefined); } catch {}`,
1737
+ ` }`,
1738
+ ` } catch {}`,
1739
+ ` }`,
1740
+ ``,
1741
+ ` // State survives resume through a custom entry; custom entries never reach`,
1742
+ ` // the model, so this carries NO context cost. Redundant writes are skipped:`,
1743
+ ` // turn_end and agent_end both fire per run, and a long execution would`,
1744
+ ` // otherwise append a duplicate entry per turn for the whole transcript.`,
1745
+ ` let planPersistKey = null;`,
1746
+ ` function planPersist() {`,
1747
+ ` try {`,
1748
+ ` const data = {`,
1749
+ ` enabled: planEnabled,`,
1750
+ ` executing: planExecuting,`,
1751
+ ` steps: planSteps.map((s) => ({ step: s.step, text: s.text, completed: s.completed })),`,
1752
+ ` };`,
1753
+ ` const key = JSON.stringify(data);`,
1754
+ ` if (key === planPersistKey) return;`,
1755
+ ` planPersistKey = key;`,
1756
+ ` pi.appendEntry(PLAN_ENTRY, data);`,
1757
+ ` } catch {}`,
1758
+ ` }`,
1759
+ ``,
1760
+ ` function planEnter(ctx) {`,
1761
+ ` if (planEnabled) return;`,
1762
+ ` planEnabled = true;`,
1763
+ ` planExecuting = false;`,
1764
+ ` planPromptOpen = false;`,
1765
+ ` planSteps = [];`,
1766
+ ` try { if (ctx && typeof ctx.cwd === "string" && ctx.cwd) planCwd = ctx.cwd; } catch {}`,
1767
+ ` try { ctx.ui.notify("Plan mode on: writes refused except " + planRelFor(ctx) + ". Investigate, then write the plan there. Shift+Tab (or /plan) to leave.", "info"); } catch {}`,
1768
+ ` planUpdateUi(ctx);`,
1769
+ ` planPersist();`,
1770
+ ` }`,
1771
+ ``,
1772
+ ` function planExit(ctx) {`,
1773
+ ` if (!planEnabled && !planExecuting) return;`,
1774
+ ` planEnabled = false;`,
1775
+ ` planExecuting = false;`,
1776
+ ` planPromptOpen = false;`,
1777
+ ` planSteps = [];`,
1778
+ ` try { ctx.ui.notify("Plan mode off: writes allowed everywhere again.", "info"); } catch {}`,
1779
+ ` planUpdateUi(ctx);`,
1780
+ ` planPersist();`,
1781
+ ` }`,
1782
+ ``,
1783
+ ` function planToggle(ctx) {`,
1784
+ ` if (planEnabled || planExecuting) planExit(ctx);`,
1785
+ ` else planEnter(ctx);`,
1786
+ ` }`,
1787
+ ``,
1788
+ ` try {`,
1789
+ ` pi.registerCommand("plan", {`,
1790
+ ` description: "Toggle plan mode (edits disabled; plan file only)",`,
1791
+ ` handler: async (_args, ctx) => { planToggle(ctx); },`,
1792
+ ` });`,
1793
+ ` } catch {}`,
1794
+ ` try {`,
1795
+ ` // Claude Code's plan-mode key. Pi binds app.thinking.cycle to shift+tab`,
1796
+ ` // and reserves it against extension overrides, so the launcher moves that`,
1797
+ ` // action off shift+tab in the mirror's keybindings.json — this`,
1798
+ ` // registration takes the freed key. Registering anyway is safe when the`,
1799
+ ` // key is still bound: pi drops the extension shortcut with a diagnostic`,
1800
+ ` // instead of throwing, which is the honest failure mode.`,
1801
+ ` pi.registerShortcut("shift+tab", {`,
1802
+ ` description: "Toggle plan mode",`,
1803
+ ` handler: async (ctx) => { planToggle(ctx); },`,
1804
+ ` });`,
1805
+ ` } catch {}`,
1806
+ ` try {`,
1807
+ ` // Literal KeyId rather than Key.ctrlAlt("p"): the generated source then`,
1808
+ ` // needs no pi-tui import at all, which keeps it loadable on every build`,
1809
+ ` // whose host-provided specifier list is smaller than today's. The value`,
1810
+ ` // is exactly what Key.ctrlAlt("p") returns (pi-tui keys.js:118).`,
1811
+ ` // Kept as the fallback for a host whose keybindings.json we did not`,
1812
+ ` // write (older launcher, hand-run pi against this extension).`,
1813
+ ` pi.registerShortcut("ctrl+alt+p", {`,
1814
+ ` description: "Toggle plan mode (alternate)",`,
1815
+ ` handler: async (ctx) => { planToggle(ctx); },`,
1816
+ ` });`,
1817
+ ` } catch {}`,
1818
+ ` try {`,
1819
+ ` pi.registerCommand("plan-status", {`,
1820
+ ` description: "Show plan mode state and the current step list",`,
1821
+ ` handler: async (_args, ctx) => {`,
1822
+ ` if (!planEnabled && !planExecuting && planSteps.length === 0) {`,
1823
+ ` try { ctx.ui.notify("Plan mode is off. /plan (or Shift+Tab) to start planning.", "info"); } catch {}`,
1824
+ ` return;`,
1825
+ ` }`,
1826
+ ` const done = planSteps.filter((s) => s.completed).length;`,
1827
+ ` const body = planSteps.length === 0`,
1828
+ ` ? "No steps parsed yet. Ask for a numbered Plan: block."`,
1829
+ ` : planSteps.map((s) => (s.completed ? "\\u2713 " : "\\u25CB ") + s.step + ". " + s.text).join("\\n");`,
1830
+ ` const head = planExecuting ? "Executing plan (" + done + "/" + planSteps.length + ")" : "Plan mode active";`,
1831
+ ` // Name THIS session's file: with a per-session path, "the plan file"`,
1832
+ ` // is no longer a single answer, and the human needs the real one.`,
1833
+ ` try { ctx.ui.notify(head + "\\n" + planRelFor(ctx) + "\\n" + body, "info"); } catch {}`,
1834
+ ` },`,
1835
+ ` });`,
1836
+ ` } catch {}`,
1837
+ ``,
1838
+ ` // THE barrier: one write exception, enforced by resolved path. A write or`,
1839
+ ` // edit whose target is the pinned plan file passes; every other target is`,
1840
+ ` // refused whatever the model believes. The path comes from the extension`,
1841
+ ` // and never from the model, which is what keeps the exception from widening`,
1842
+ ` // into a general write permission. It has to be the ONLY barrier: narrowing`,
1843
+ ` // the tool set as well would hide these tools from the model, so pi would`,
1844
+ ` // answer "Tool write not found" before this handler and the exception could`,
1845
+ ` // never fire — see PLAN_BLOCKED_TOOLS.`,
1846
+ ` try {`,
1847
+ ` pi.on("tool_call", async (event, ctx) => {`,
1848
+ ` if (!planEnabled || !event) return undefined;`,
1849
+ ` const name = String(event.toolName || "");`,
1850
+ ` if (!PLAN_BLOCKED.has(name)) return undefined;`,
1851
+ ` try { if (ctx && typeof ctx.cwd === "string" && ctx.cwd) planCwd = ctx.cwd; } catch {}`,
1852
+ ` const input = (event.input || {});`,
1853
+ ` const target = input.path !== undefined ? input.path : input.file_path;`,
1854
+ ` const planFileRel = planRelFor(ctx);`,
1855
+ ` if (isPlanFilePath(planCwd, target, planFileRel)) return undefined;`,
1856
+ ` return {`,
1857
+ ` block: true,`,
1858
+ ` reason: "Plan mode: this write is refused. The only file you may write is " + planFileRel + " (pass exactly that path). Record the plan there, or leave plan mode (/plan or Shift+Tab) to change code.",`,
1859
+ ` };`,
1860
+ ` });`,
1861
+ ` } catch {}`,
1862
+ ``,
1863
+ ` // Plan-injected context is dropped once neither mode is engaged, so a later`,
1864
+ ` // turn is not still told it is read-only or mid-execution. Custom messages`,
1865
+ ` // reach this handler as role "custom" with customType intact, which is the`,
1866
+ ` // load-bearing check; the text marker is the belt for a host (or an`,
1867
+ ` // imported transcript) that flattened the custom role into a user message.`,
1868
+ ` const PLAN_STALE_MARKERS = [`,
1869
+ ` { marker: "[PLAN MODE ACTIVE]", live: () => planEnabled },`,
1870
+ ` { marker: "[EXECUTING PLAN", live: () => planExecuting },`,
1871
+ ` ];`,
1872
+ ` function planIsStaleContext(m) {`,
1873
+ ` if (!m || m.role !== "user" || (m.customType !== undefined)) return false;`,
1874
+ ` const content = m.content;`,
1875
+ ` const stale = (text) => {`,
1876
+ ` if (typeof text !== "string") return false;`,
1877
+ ` return PLAN_STALE_MARKERS.some((entry) => !entry.live() && text.indexOf(entry.marker) >= 0);`,
1878
+ ` };`,
1879
+ ` if (typeof content === "string") return stale(content);`,
1880
+ ` if (Array.isArray(content)) return content.some((c) => c && c.type === "text" && stale(c.text));`,
1881
+ ` return false;`,
1882
+ ` }`,
1883
+ ``,
1884
+ ` // before_agent_start messages are APPENDED and PERSISTED per run, so a`,
1885
+ ` // plan-mode session accrues one block per turn. Two rules keep that from`,
1886
+ ` // costing anything or lying to the model:`,
1887
+ ` // - a block is valid only while ITS mode is engaged: the read-only block`,
1888
+ ` // dies the moment execution starts (the model is told full access is`,
1889
+ ` // back), and the execution block dies when the mode ends;`,
1890
+ ` // - of the valid blocks, only the newest of each kind is kept, so a long`,
1891
+ ` // plan does not pay for N copies of the same instructions.`,
1892
+ ` try {`,
1893
+ ` pi.on("context", async (event) => {`,
1894
+ ` if (!event || !Array.isArray(event.messages)) return undefined;`,
1895
+ ` const seen = new Set();`,
1896
+ ` const output = [];`,
1897
+ ` for (let i = event.messages.length - 1; i >= 0; i--) {`,
1898
+ ` const m = event.messages[i];`,
1899
+ ` const type = m && m.customType;`,
1900
+ ` if (type === PLAN_CONTEXT_TYPE || type === PLAN_EXEC_TYPE) {`,
1901
+ ` const valid = type === PLAN_CONTEXT_TYPE ? planEnabled : planExecuting;`,
1902
+ ` if (!valid || seen.has(type)) continue;`,
1903
+ ` seen.add(type);`,
1904
+ ` } else if (planIsStaleContext(m)) {`,
1905
+ ` continue;`,
1906
+ ` }`,
1907
+ ` output.push(m);`,
1908
+ ` }`,
1909
+ ` if (output.length === event.messages.length) return undefined;`,
1910
+ ` output.reverse();`,
1911
+ ` return { messages: output };`,
1912
+ ` });`,
1913
+ ` } catch {}`,
1914
+ ``,
1915
+ ` // The planning contract, modelled on Claude Code's plan-mode reminder: the`,
1916
+ ` // mode is closed, the plan file is the ONE exception, and the model is`,
1917
+ ` // trusted with everything else. Frontier-model tuning lives here — a`,
1918
+ ` // command allowlist, a delegation ban and an MCP namespace deny all told a`,
1919
+ ` // capable model to be less useful than it is, and none of them is needed`,
1920
+ ` // now that "edits are disabled" is the whole rule and the plan file is the`,
1921
+ ` // only write. The workflow is Claude's five phases compressed to what Pi`,
1922
+ ` // has: Explore/General-Purpose subagents exist, but the roster is`,
1923
+ ` // profile-dependent, so the phase text names the intent, not an agent.`,
1924
+ ` // Built per resolved path rather than as a module constant: the plan file`,
1925
+ ` // is per-session now, so a constant would name the wrong file for every`,
1926
+ ` // session but one. Called once per session (the result is cached on the`,
1927
+ ` // resolved path), not once per turn.`,
1928
+ ` let planBriefCache = { rel: "", text: "" };`,
1929
+ ` function planBriefFor(rel) {`,
1930
+ ` if (planBriefCache.rel === rel) return planBriefCache.text;`,
1931
+ ` const planBriefLines = [`,
1932
+ ` "[PLAN MODE ACTIVE]",`,
1933
+ ` "",`,
1934
+ ` "Plan mode is active. The user does not want you to execute yet -- you must not edit files,",`,
1935
+ ` "run a command that changes the code, or otherwise act on the plan. This supersedes any other",`,
1936
+ ` "instruction you have received about doing the work now.",`,
1937
+ ` "",`,
1938
+ ` "One exception, and it is the whole of it: you may write your plan to",`,
1939
+ ` " " + rel,`,
1940
+ ` "Edit and write are refused for every other path. Read, search, and run read-only commands",`,
1941
+ ` "freely -- explore enough that the plan is grounded in what the code actually does.",`,
1942
+ ` "",`,
1943
+ ` "Work the plan like this:",`,
1944
+ ` "1. Understand the request, and look for what already exists (functions, utilities, patterns)",`,
1945
+ ` " before proposing anything new. Delegate broad or parallel discovery when that is faster",`,
1946
+ ` " than reading serially yourself.",`,
1947
+ ` "2. Ask the user whatever you cannot settle from the code. Do it once, up front, and never",`,
1948
+ ` " ask what exploration could answer.",`,
1949
+ ` "3. Design the approach far enough that an implementer would have no open decisions left:",`,
1950
+ ` " which files, what changes in each, what each change is done when, and what would prove it.",`,
1951
+ ` "4. Write the plan to the plan file: a short Context section, the recommended approach only,",`,
1952
+ ` " the critical files, the verification steps, and any residual risk. Keep it scannable.",`,
1953
+ ` "5. Summarise the plan in your reply too, so the user can answer without opening the file,",`,
1954
+ ` " finishing with a numbered list of the steps -- that list becomes the checklist.",`,
1955
+ ` "",`,
1956
+ ` "Do NOT open an ask_user question or a prose prompt for plan approval. Leaving plan mode is",`,
1957
+ ` "the user's action (/plan or Shift+Tab) -- asking permission to stop planning is the one",`,
1958
+ ` "question this mode does not want, and approval you grant yourself is not approval.",`,
1959
+ ` "If the user asks for changes, revise this one plan file in place rather than writing a second plan.",`,
1960
+ ` "The test for every other action: if it would reasonably be described as DOING the work",`,
1961
+ ` "rather than planning it, it waits until plan mode is off.",`,
1962
+ ` ].join("\\n");`,
1963
+ ` planBriefCache = { rel: rel, text: planBriefLines };`,
1964
+ ` return planBriefLines;`,
1965
+ ` }`,
1966
+ ``,
1967
+ ` // Cost contract: inject NOTHING unless plan mode is actually engaged, and`,
1968
+ ` // only for a real user turn (a background notification must not re-add it).`,
1969
+ ` try {`,
1970
+ ` pi.on("before_agent_start", async (event, ctx) => {`,
1971
+ ` if (!event || event.messageType !== "user") return undefined;`,
1972
+ ` if (planEnabled) {`,
1973
+ ` return { message: { customType: PLAN_CONTEXT_TYPE, content: planBriefFor(planRelFor(ctx)), display: false } };`,
1974
+ ` }`,
1975
+ ` if (planExecuting && planSteps.length > 0) {`,
1976
+ ` const remaining = planSteps.filter((s) => !s.completed).map((s) => s.step + ". " + s.text).join("\\n");`,
1977
+ ` const content = [`,
1978
+ ` "[EXECUTING PLAN - full tool access enabled]",`,
1979
+ ` "",`,
1980
+ ` "Remaining steps:",`,
1981
+ ` remaining,`,
1982
+ ` "",`,
1983
+ ` "Execute each step in order.",`,
1984
+ ` "After completing a step, include a [DONE:n] tag in your response.",`,
1985
+ ` ].join("\\n");`,
1986
+ ` return { message: { customType: PLAN_EXEC_TYPE, content, display: false } };`,
1987
+ ` }`,
1988
+ ` return undefined;`,
1989
+ ` });`,
1990
+ ` } catch {}`,
1991
+ ``,
1992
+ ` // Progress tracking after each turn. Reads text AND thinking blocks: with`,
1993
+ ` // reasoning-max models the [DONE:n] tags often land in thinking, not text.`,
1994
+ ` try {`,
1995
+ ` pi.on("turn_end", async (event, ctx) => {`,
1996
+ ` if (!planExecuting || planSteps.length === 0 || !event) return;`,
1997
+ ` const msg = event.message;`,
1998
+ ` if (!msg || msg.role !== "assistant" || !Array.isArray(msg.content)) return;`,
1999
+ ` const text = msg.content.map((b) => {`,
2000
+ ` if (!b) return "";`,
2001
+ ` if (b.type === "text") return b.text || "";`,
2002
+ ` if (b.type === "thinking") return b.thinking || "";`,
2003
+ ` return "";`,
2004
+ ` }).join("\\n");`,
2005
+ ` applyDoneSteps(text, planSteps);`,
2006
+ ` planUpdateUi(ctx);`,
2007
+ ` planPersist();`,
2008
+ ` });`,
2009
+ ` } catch {}`,
2010
+ ``,
2011
+ ` // End of a run: parse the plan (planning) or finish the execution.`,
2012
+ ` try {`,
2013
+ ` pi.on("agent_end", async (event, ctx) => {`,
2014
+ ` if (!event || !Array.isArray(event.messages)) return;`,
2015
+ ` const last = [...event.messages].reverse().find((m) => m && m.role === "assistant" && Array.isArray(m.content));`,
2016
+ ` const lastText = last`,
2017
+ ` ? last.content.map((b) => {`,
2018
+ ` if (!b) return "";`,
2019
+ ` if (b.type === "text") return b.text || "";`,
2020
+ ` if (b.type === "thinking") return b.thinking || "";`,
2021
+ ` return "";`,
2022
+ ` }).join("\\n")`,
2023
+ ` : "";`,
2024
+ ` if (planExecuting && planSteps.length > 0) {`,
2025
+ ` if (planAllStepsComplete(lastText)) {`,
2026
+ ` for (const s of planSteps) s.completed = true;`,
2027
+ ` }`,
2028
+ ` if (planSteps.every((s) => s.completed)) {`,
2029
+ ` const list = planSteps.map((s) => "- ~~" + s.text + "~~").join("\\n");`,
2030
+ ` // nextTurn, not a triggerTurn: acknowledging the card with an extra`,
2031
+ ` // (reasoning-max) model turn would cost real money for a checkmark.`,
2032
+ ` try { pi.sendMessage({ customType: PLAN_DONE_TYPE, content: "**Plan complete** \\u2713" + "\\n" + list, display: true }, { deliverAs: "nextTurn" }); } catch {}`,
2033
+ ` planExecuting = false;`,
2034
+ ` planSteps = [];`,
2035
+ ` planUpdateUi(ctx);`,
2036
+ ` planPersist();`,
2037
+ ` }`,
2038
+ ` return;`,
2039
+ ` }`,
2040
+ ` if (!planEnabled) return;`,
2041
+ ` const parsed = extractPlanSteps(lastText);`,
2042
+ ` if (parsed.length > 0) planSteps = parsed;`,
2043
+ ` if (planSteps.length === 0) return;`,
2044
+ ` planUpdateUi(ctx);`,
2045
+ ` planPersist();`,
2046
+ ` // One prompt at a time: a queued follow-up run also ends here, and a`,
2047
+ ` // second Execute answer would re-kick a plan that is already running.`,
2048
+ ` if (planPromptOpen) return;`,
2049
+ ` let hasUI = false;`,
2050
+ ` try { hasUI = !!ctx.hasUI; } catch {}`,
2051
+ ` if (!hasUI || typeof ctx.ui.select !== "function") return;`,
2052
+ ` planPromptOpen = true;`,
2053
+ ` let choice = undefined;`,
2054
+ ` try {`,
2055
+ ` choice = await ctx.ui.select("Plan mode - what next?", [`,
2056
+ ` "Execute the plan (track progress)",`,
2057
+ ` "Stay in plan mode",`,
2058
+ ` "Refine the plan",`,
2059
+ ` ]);`,
2060
+ ` } catch { planPromptOpen = false; return; }`,
2061
+ ` planPromptOpen = false;`,
2062
+ ` if (!choice) return;`,
2063
+ ` // The user may have left plan mode while the prompt was open (slash`,
2064
+ ` // /plan, Shift+Tab, /new). Honouring Execute there would silently`,
2065
+ ` // re-enter a mode they just exited.`,
2066
+ ` if (!planEnabled) return;`,
2067
+ ` if (String(choice).indexOf("Execute") === 0) {`,
2068
+ ` planEnabled = false;`,
2069
+ ` planExecuting = true;`,
2070
+ ` planUpdateUi(ctx);`,
2071
+ ` planPersist();`,
2072
+ ` const list = planSteps.map((s) => s.step + ". " + s.text).join("\\n");`,
2073
+ ` const first = planSteps[0] ? planSteps[0].text : "";`,
2074
+ ` try {`,
2075
+ ` pi.sendMessage({ customType: PLAN_LIST_TYPE, content: "**Plan steps (" + planSteps.length + ")**" + "\\n" + list, display: true }, { deliverAs: "followUp" });`,
2076
+ ` 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" });`,
2077
+ ` } catch {}`,
2078
+ ` } else if (choice === "Refine the plan" && typeof ctx.ui.editor === "function") {`,
2079
+ ` let refinement = undefined;`,
2080
+ ` try { refinement = await ctx.ui.editor("Refine the plan:", ""); } catch { return; }`,
2081
+ ` const trimmed = String(refinement || "").trim();`,
2082
+ ` if (!trimmed) return;`,
2083
+ ` try { pi.sendUserMessage(trimmed, { deliverAs: "followUp" }); } catch {}`,
2084
+ ` }`,
2085
+ ` });`,
2086
+ ` } catch {}`,
2087
+ ``,
2088
+ ` // Restore after resume: the ENTRY is the source of truth for the mode, the`,
2089
+ ` // step list and the badge — and nothing else. The gate below needs no`,
2090
+ ` // restore because it reads the live flag.`,
2091
+ ` // State is assigned UNCONDITIONALLY: a fresh session (/new, /fork into an`,
2092
+ ` // empty branch) has no entry, and leaving the previous session's flags in`,
2093
+ ` // place would keep a stale badge for a mode that is not gating anything.`,
2094
+ ` try {`,
2095
+ ` pi.on("session_start", async (_event, ctx) => {`,
2096
+ ` try {`,
2097
+ ` if (ctx && typeof ctx.cwd === "string" && ctx.cwd) planCwd = ctx.cwd;`,
2098
+ ` // Re-resolve the plan file for THIS session. The id is stable across`,
2099
+ ` // resume, so a resumed session lands back on the file it started; a`,
2100
+ ` // fork or a new session gets its own, which is the whole point.`,
2101
+ ` planRel = "";`,
2102
+ ` planRelFor(ctx);`,
2103
+ ` const entries = ctx.sessionManager && typeof ctx.sessionManager.getEntries === "function"`,
2104
+ ` ? ctx.sessionManager.getEntries()`,
2105
+ ` : [];`,
2106
+ ` let saved = undefined;`,
2107
+ ` for (const entry of entries) {`,
2108
+ ` if (entry && entry.type === "custom" && entry.customType === PLAN_ENTRY) saved = entry.data;`,
2109
+ ` }`,
2110
+ ` const nextEnabled = !!saved && saved.enabled === true;`,
2111
+ ` const nextExecuting = !!saved && saved.executing === true;`,
2112
+ ` // Nothing here touches the active tool set. Plan mode does not own`,
2113
+ ` // it: the only thing that ever changed the roster was the restriction`,
2114
+ ` // this design deleted, and a resumed snapshot must never widen the`,
2115
+ ` // roster a narrower current launch installed (that was a real bug:`,
2116
+ ` // resuming under --tools read,bash silently restored grep).`,
2117
+ ` planEnabled = nextEnabled;`,
2118
+ ` planExecuting = nextExecuting;`,
2119
+ ` planPromptOpen = false;`,
2120
+ ` planPersistKey = null;`,
2121
+ ` planSteps = saved && Array.isArray(saved.steps)`,
2122
+ ` ? saved.steps.map((s) => ({ step: Number(s.step) || 0, text: String(s.text || ""), completed: s.completed === true }))`,
2123
+ ` : [];`,
2124
+ ` // An execution with no steps is a dead end: the checklist is empty and`,
2125
+ ` // every execution branch bails on steps.length, so treat it as off.`,
2126
+ ` if (planExecuting && planSteps.length === 0) planExecuting = false;`,
2127
+ ` } catch {}`,
2128
+ ` planUpdateUi(ctx);`,
2129
+ ` });`,
2130
+ ` } catch {}`,
2131
+ ` } catch {}`,
2132
+ ``
2133
+ ];
2134
+ }
2135
+ //#endregion
1195
2136
  //#region src/lib/pi-extension.ts
1196
2137
  /**
1197
2138
  * The gh-router Pi extension source, generated per launch into the
@@ -1202,9 +2143,9 @@ function buildPiAppendSystem(profileId, opts = {}) {
1202
2143
  * server in the mirror's `mcp.json` (`src/lib/pi-mcp-config.ts`), which
1203
2144
  * brings `tool_search`, the `mcp_servers` roster and per-server `exposure`
1204
2145
  * 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
2146
+ * server can do: the statusline footer, plan mode, the memory bridge, and
2147
+ * (cheapest family only) the prompt-submit relay, which POSTs JSON-RPC
2148
+ * `tools/call` to the running proxy with the per-launch nonce (the same
1208
2149
  * `GH_ROUTER_HOOK_MCP_URL/NONCE` channel the Claude hooks use).
1209
2150
  *
1210
2151
  * No custom provider, no compaction replacement: `session_before_compact`
@@ -1217,6 +2158,13 @@ function buildPiAppendSystem(profileId, opts = {}) {
1217
2158
  * segments. There is deliberately no third-party statusline package and
1218
2159
  * no `statusLine` settings block (the community bridge only reads the
1219
2160
  * user's real global/project settings, never the launch mirror).
2161
+ *
2162
+ * Plan mode (always on): Claude Code ships plan mode as a mode; Pi ships it
2163
+ * only as an example extension a user has to install. `src/lib/pi-plan-mode.ts`
2164
+ * generates the equivalent into this same package — see
2165
+ * `buildPiPlanModeSection` for the single reachable write barrier (the path
2166
+ * gate; the tool roster is deliberately untouched) and the divergences from
2167
+ * upstream.
1220
2168
  */
1221
2169
  /**
1222
2170
  * Statusline footer section for the generated extension. Owns Pi's footer
@@ -1585,7 +2533,7 @@ function buildPiExtensionSource(opts) {
1585
2533
  ``
1586
2534
  ] : [], `export default function (pi) {`);
1587
2535
  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 ? [
2536
+ 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
2537
  ` // Cheapest-profile execution brief, injected ABOVE the model's turn.`,
1590
2538
  ` // Produced server-side; this only relays the prompt and re-emits the`,
1591
2539
  ` // result as a custom message. Additive: the user prompt stays the user`,
@@ -1650,7 +2598,7 @@ function buildPiExtensionSource(opts) {
1650
2598
  function buildPiSkills(opts) {
1651
2599
  const peers = opts.peers !== false;
1652
2600
  const skills = [];
1653
- if (peers) {
2601
+ if (peers && piOracleEnabled(opts.profileId)) {
1654
2602
  const oracleBody = piOracleToolReachable(opts.profileId) ? [
1655
2603
  "Call `mcp__gh-router-peers__oracle` (load it with `tool_search` if it is",
1656
2604
  "not in the tool list yet) with the decision, the options considered, and",
@@ -1662,9 +2610,9 @@ function buildPiSkills(opts) {
1662
2610
  ] : [
1663
2611
  "Delegate to the `oracle` subagent through the `subagent` tool with the",
1664
2612
  "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."
2613
+ "oracle is cold-start and tool-less: it sees only what you pass, and it",
2614
+ "cannot read the repository on its own. Its verdict is advisory — verify",
2615
+ "with tests and code, never substitute votes for verification."
1668
2616
  ];
1669
2617
  skills.push({
1670
2618
  dir: "gh-oracle",
@@ -1698,7 +2646,10 @@ function buildPiSkills(opts) {
1698
2646
  ].join("\n")
1699
2647
  });
1700
2648
  if (opts.swe === true && peers) {
1701
- const consults = piAdvisorModel(opts.profileId) ? "`oracle`/`advisor` for consults" : "`oracle` for consults";
2649
+ const advisor = piAdvisorModel(opts.profileId);
2650
+ const oracle = piOracleEnabled(opts.profileId);
2651
+ const consults = advisor ? "`oracle`/`advisor` for consults" : oracle ? "`oracle` for consults" : void 0;
2652
+ const rosterLine = consults ? `for verification, ${consults} (builtin \`scout\` and` : "for verification. (Builtin `scout` and";
1702
2653
  skills.push({
1703
2654
  dir: "gh-delegate",
1704
2655
  content: [
@@ -1711,7 +2662,7 @@ function buildPiSkills(opts) {
1711
2662
  "",
1712
2663
  "You may delegate via the `subagent` tool to this roster only: `Explore`",
1713
2664
  "for discovery, `General-Purpose` for scoped implementation, `reviewer`",
1714
- `for verification, ${consults}. (Builtin \`scout\` and`,
2665
+ rosterLine,
1715
2666
  "`worker` are disabled in this session; their aliases resolve here.)",
1716
2667
  "Recommended loop: `Explore` to map the code, paste the brief excerpts",
1717
2668
  "into the `General-Purpose` brief to implement, `reviewer` to check,",
@@ -1725,7 +2676,7 @@ function buildPiSkills(opts) {
1725
2676
  isBalancedFamily(opts.profileId) ? "Send work to reviewer ONLY when the change alters behavior." : "Send finished work to reviewer for assessment."
1726
2677
  ].join("\n")
1727
2678
  });
1728
- if (peers && piAdvisorModel(opts.profileId)) skills.push({
2679
+ if (piAdvisorModel(opts.profileId)) skills.push({
1729
2680
  dir: "gh-advisor",
1730
2681
  content: [
1731
2682
  "---",
@@ -2372,6 +3323,16 @@ const pi = defineCommand({
2372
3323
  ...cosmeticOverrides,
2373
3324
  ...mergedSubagents ? { subagents: mergedSubagents } : {}
2374
3325
  });
3326
+ const keybindingsPath = path.join(mirror, "keybindings.json");
3327
+ let userKeybindings = {};
3328
+ try {
3329
+ const raw = await fs$1.readFile(keybindingsPath, "utf8");
3330
+ const parsedKeybindings = JSON.parse(raw);
3331
+ if (parsedKeybindings && typeof parsedKeybindings === "object") userKeybindings = parsedKeybindings;
3332
+ } catch {
3333
+ userKeybindings = {};
3334
+ }
3335
+ await writeJsonFile(keybindingsPath, { ...mergePiKeybindingsSettings(userKeybindings, buildPiKeybindingsJson()) });
2375
3336
  packagesForCache = [...builtSettings.packages];
2376
3337
  if (await seedPiPackageCache(mirror, packagesForCache)) consola.debug("Pi package cache hit: mirror pre-seeded, skipping registry install.");
2377
3338
  const bridgeDisabled = args["memory-bridge"] === false || process$1.env.GH_ROUTER_PI_BRIDGE === "0" || process$1.env.GH_ROUTER_DISABLE_PI_BRIDGE === "1";
@@ -2513,7 +3474,7 @@ const pi = defineCommand({
2513
3474
  })}\n`);
2514
3475
  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
3476
  const { disposeBluebirdClients } = await import("./bluebird-client-CY6NBHQu.js");
2516
- const { disposeAdoClients } = await import("./ado-tools-512UGB6R.js");
3477
+ const { disposeAdoClients } = await import("./ado-tools-WDyisN8w.js");
2517
3478
  launchChild({
2518
3479
  kind: "pi",
2519
3480
  envVars: {
@@ -2551,4 +3512,4 @@ const pi = defineCommand({
2551
3512
  //#endregion
2552
3513
  export { pi };
2553
3514
 
2554
- //# sourceMappingURL=pi-D4LrdubN.js.map
3515
+ //# sourceMappingURL=pi-BglhJ6n_.js.map