github-router 0.3.342 → 0.3.344

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 (43) hide show
  1. package/README.md +13 -8
  2. package/dist/{attribution-settings-DA3wkQHE.js → attribution-settings-BkhBJn_K.js} +4 -4
  3. package/dist/{attribution-settings-DA3wkQHE.js.map → attribution-settings-BkhBJn_K.js.map} +1 -1
  4. package/dist/{auth-DjKEIiqG.js → auth-Cgsy2T0s.js} +2 -2
  5. package/dist/{auth-DjKEIiqG.js.map → auth-Cgsy2T0s.js.map} +1 -1
  6. package/dist/browser-ext/manifest.json +1 -1
  7. package/dist/{check-usage-B7UrDwD8.js → check-usage-26G2hw_F.js} +3 -3
  8. package/dist/{check-usage-B7UrDwD8.js.map → check-usage-26G2hw_F.js.map} +1 -1
  9. package/dist/{claude-CMuHUWWy.js → claude-CarqHLsD.js} +7 -7
  10. package/dist/{claude-CMuHUWWy.js.map → claude-CarqHLsD.js.map} +1 -1
  11. package/dist/{codex-B__qfHCC.js → codex-AdG6FZIV.js} +5 -5
  12. package/dist/{codex-B__qfHCC.js.map → codex-AdG6FZIV.js.map} +1 -1
  13. package/dist/engine-gOzWnh6S.js +2 -0
  14. package/dist/{gate-discovery-BIBgN6mA.js → gate-discovery-ByujYipc.js} +2 -2
  15. package/dist/{gate-discovery-BIBgN6mA.js.map → gate-discovery-ByujYipc.js.map} +1 -1
  16. package/dist/{get-copilot-usage-CGaV01dC.js → get-copilot-usage-C_6ast5h.js} +2 -2
  17. package/dist/{get-copilot-usage-CGaV01dC.js.map → get-copilot-usage-C_6ast5h.js.map} +1 -1
  18. package/dist/{internal-stop-hook-Dyn0fRpZ.js → internal-stop-hook-DEMbF-hU.js} +2 -2
  19. package/dist/{internal-stop-hook-Dyn0fRpZ.js.map → internal-stop-hook-DEMbF-hU.js.map} +1 -1
  20. package/dist/main.js +9 -9
  21. package/dist/{models-68HDOEPK.js → models-BGCeGVXl.js} +2 -2
  22. package/dist/{models-68HDOEPK.js.map → models-BGCeGVXl.js.map} +1 -1
  23. package/dist/{peer-mcp-personas-Dt0VRKYz.js → peer-mcp-personas-CvqVopTx.js} +2 -2
  24. package/dist/{peer-mcp-personas-Dt0VRKYz.js.map → peer-mcp-personas-CvqVopTx.js.map} +1 -1
  25. package/dist/{pi-WT6IahMr.js → pi-C8jxbK_2.js} +689 -130
  26. package/dist/pi-C8jxbK_2.js.map +1 -0
  27. package/dist/{pi-memory-bridge-BWZJnjpz.js → pi-memory-bridge-DEU1SUDz.js} +5 -5
  28. package/dist/{pi-memory-bridge-BWZJnjpz.js.map → pi-memory-bridge-DEU1SUDz.js.map} +1 -1
  29. package/dist/{provision-D_aHUCXt.js → provision-CJ3Zzs_Q.js} +2 -2
  30. package/dist/{provision-D_aHUCXt.js.map → provision-CJ3Zzs_Q.js.map} +1 -1
  31. package/dist/{serve-BaLMvHSp.js → serve-DQhAmfp2.js} +6 -6
  32. package/dist/{serve-BaLMvHSp.js.map → serve-DQhAmfp2.js.map} +1 -1
  33. package/dist/{server-setup-B7Usfq5v.js → server-setup-BBbpJRWv.js} +25 -10
  34. package/dist/server-setup-BBbpJRWv.js.map +1 -0
  35. package/dist/{start-C-13_1Ld.js → start-C34seGtb.js} +3 -3
  36. package/dist/{start-C-13_1Ld.js.map → start-C34seGtb.js.map} +1 -1
  37. package/dist/state-CVp30CBF.js.map +1 -1
  38. package/dist/{token-DATA_OQK.js → token-s5Wd-Kwr.js} +2 -1
  39. package/dist/{token-DATA_OQK.js.map → token-s5Wd-Kwr.js.map} +1 -1
  40. package/package.json +2 -2
  41. package/dist/engine-DvGukHty.js +0 -2
  42. package/dist/pi-WT6IahMr.js.map +0 -1
  43. package/dist/server-setup-B7Usfq5v.js.map +0 -1
@@ -1,24 +1,27 @@
1
1
  import { I as withInstallLock, N as warmTreeSitterPool } from "./service-backend-7SPDLUB9.js";
2
+ import { t as getPackageVersion } from "./version-C8x2hQrZ.js";
3
+ import { t as PATHS } from "./paths-CpbTHKeP.js";
2
4
  import { t as state } from "./state-CVp30CBF.js";
3
5
  import { c as runCommandVoid, o as resolveExecutable, s as runCommandCapture } from "./exec-MCU1H-KZ.js";
4
- import { E as formatBalancedPrerequisiteFailure, I as validateCheapestProfilePrerequisites, M as resolveLaunchProfile, N as validateBalancedProfilePrerequisites, a as setupAndServe, c as startKeepAwake, f as enableFileLogging, i as parseSharedArgs, j as profileDescriptor, k as formatCheapestPrerequisiteFailure, l as stopKeepAwake, o as sharedServerArgs, r as getPiLaunchEnvVars, z as runSelfUpdate } from "./server-setup-B7Usfq5v.js";
6
+ import { B as runSelfUpdate, E as formatBalancedPrerequisiteFailure, I as validateCheapestProfilePrerequisites, M as resolveLaunchProfile, N as validateBalancedProfilePrerequisites, a as setupAndServe, c as startKeepAwake, f as enableFileLogging, i as parseSharedArgs, j as profileDescriptor, k as formatCheapestPrerequisiteFailure, l as stopKeepAwake, o as sharedServerArgs, r as getPiLaunchEnvVars, z as queueDetachedGlobalInstall } from "./server-setup-BBbpJRWv.js";
5
7
  import { a as BALANCED_PROFILE_NATIVE_EFFORTS, c as BALANCED_PROFILE_ORACLE_MODEL, r as BALANCED_PROFILE_MODELS, s as BALANCED_PROFILE_ORACLE_EFFORT } from "./balanced-profile-contract-C6AgFJNp.js";
6
- import { D as toolbeltEnabled, Gt as registerLaunch, In as CHEAPEST_PROFILE_NATIVE_EFFORTS, Kt as unregisterLaunch, Mn as CHEAPEST_PROFILE_ADVISOR_EFFORT, Nn as CHEAPEST_PROFILE_ADVISOR_MODEL, Pn as CHEAPEST_PROFILE_MODELS, Rn as CHEAPEST_PROFILE_ORACLE_EFFORT, an as provisionAndIndexColbert, ft as browserToolsEnabled, in as colbertDegradedWarning, nn as provisionBrowserAssets, zn as CHEAPEST_PROFILE_ORACLE_MODEL } from "./peer-mcp-personas-Dt0VRKYz.js";
8
+ import { D as toolbeltEnabled, Gt as registerLaunch, In as CHEAPEST_PROFILE_NATIVE_EFFORTS, Kt as unregisterLaunch, Mn as CHEAPEST_PROFILE_ADVISOR_EFFORT, Nn as CHEAPEST_PROFILE_ADVISOR_MODEL, Pn as CHEAPEST_PROFILE_MODELS, Rn as CHEAPEST_PROFILE_ORACLE_EFFORT, an as provisionAndIndexColbert, ft as browserToolsEnabled, in as colbertDegradedWarning, nn as provisionBrowserAssets, zn as CHEAPEST_PROFILE_ORACLE_MODEL } from "./peer-mcp-personas-CvqVopTx.js";
7
9
  import { r as resolveSelfInvocation } from "./self-invocation-DIUyoRgL.js";
8
- import { i as launchChild, t as provisionToolbelt } from "./provision-D_aHUCXt.js";
10
+ import { i as launchChild, t as provisionToolbelt } from "./provision-CJ3Zzs_Q.js";
9
11
  import { d as sweepStaleAicLedgerFiles, t as aicLedgerPath } from "./aic-ledger-D4fmThbS.js";
10
12
  import { i as buildAicStatusHookCommand, n as AIC_STATUSLINE_DISABLE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-YoDG20pq.js";
11
13
  import { defineCommand } from "citty";
12
14
  import consola from "consola";
15
+ import { existsSync } from "node:fs";
13
16
  import path from "node:path";
14
17
  import { randomBytes } from "node:crypto";
15
- import fs from "node:fs/promises";
18
+ import fs$1 from "node:fs/promises";
16
19
  import os from "node:os";
17
20
  import process$1 from "node:process";
18
21
  //#region src/lib/pi-version-check.ts
19
22
  const PI_NPM_PACKAGE = "@earendil-works/pi-coding-agent";
20
23
  /** Minimum Pi version the `pi` launcher supports. */
21
- const PI_MIN_VERSION = "0.80.10";
24
+ const PI_MIN_VERSION = "0.87.1";
22
25
  const THROTTLE_HOURS = 1;
23
26
  const NPM_VIEW_TIMEOUT_MS = 5e3;
24
27
  const PI_VERSION_TIMEOUT_MS = 3e3;
@@ -29,7 +32,7 @@ function cacheFilePath() {
29
32
  }
30
33
  async function readCache() {
31
34
  try {
32
- const raw = await fs.readFile(cacheFilePath(), "utf8");
35
+ const raw = await fs$1.readFile(cacheFilePath(), "utf8");
33
36
  const parsed = JSON.parse(raw);
34
37
  if (typeof parsed.checkedAt !== "string" || parsed.installedVersion !== null && typeof parsed.installedVersion !== "string" || parsed.latestVersion !== null && typeof parsed.latestVersion !== "string") return null;
35
38
  return parsed;
@@ -39,8 +42,8 @@ async function readCache() {
39
42
  }
40
43
  async function writeCache(cache) {
41
44
  try {
42
- await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true });
43
- await fs.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 384 });
45
+ await fs$1.mkdir(path.dirname(cacheFilePath()), { recursive: true });
46
+ await fs$1.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 384 });
44
47
  } catch (err) {
45
48
  consola.debug("Failed to write pi version-check cache:", err);
46
49
  }
@@ -171,20 +174,77 @@ async function checkPiVersion(opts = {}) {
171
174
  }
172
175
  /**
173
176
  * Install (or upgrade) Pi from npm under the cross-process install lock.
174
- * Best-effort: throws on failure; callers fall back to the installed
175
- * version with a visible warning rather than stranding the launch.
177
+ * Returns `true` when this call performed the install, `false` when
178
+ * another process holds the lock (caller skips — its install will land
179
+ * for a later launch). Best-effort: throws on failure; callers fall
180
+ * back to the installed version with a visible warning rather than
181
+ * stranding the launch.
176
182
  */
177
- async function updatePi(version) {
183
+ function updatePi(version, opts = {}) {
178
184
  const npmPath = resolveExecutable("npm");
179
185
  if (!npmPath) throw new Error("npm not found on PATH; cannot install Pi automatically");
180
- await withInstallLock("pi-install.lock", async () => {
186
+ return withInstallLock("pi-install.lock", async () => {
181
187
  consola.info(`Installing ${PI_NPM_PACKAGE}@${version}...`);
182
188
  await runCommandVoid([
183
189
  npmPath,
184
190
  "install",
185
191
  "-g",
186
192
  `${PI_NPM_PACKAGE}@${version}`
187
- ], { timeoutMs: NPM_INSTALL_TIMEOUT_MS });
193
+ ], {
194
+ timeoutMs: NPM_INSTALL_TIMEOUT_MS,
195
+ signal: opts.signal
196
+ });
197
+ });
198
+ }
199
+ /**
200
+ * Blocking fresh install for when Pi is absent entirely. Installs
201
+ * `@latest`, then force re-checks; throws when Pi still is not on PATH
202
+ * (caller exits with the install command). Only used when there is no
203
+ * usable Pi at all — the healthy path never blocks on npm.
204
+ */
205
+ async function ensurePiInstalled(opts = {}) {
206
+ const acquired = await updatePi("latest", opts);
207
+ const retry = await checkPiVersion({ force: true });
208
+ if (retry.installed && retry.installedVersion) return retry.installedVersion;
209
+ throw new Error(acquired ? "install did not place pi on PATH" : "another Pi install is already running; retry in a moment");
210
+ }
211
+ /**
212
+ * Fire-and-forget freshness refresh for a healthy Pi install. Never
213
+ * blocks launch and never throws: on the throttled schedule it probes
214
+ * npm for a newer Pi and, when one exists, queues a DETACHED post-exit
215
+ * install (same pattern as the proxy self-update) so neither startup
216
+ * nor the running session nor shutdown ever waits on npm. The
217
+ * cross-process install lock serializes against concurrent launches;
218
+ * every failure degrades to a debug log.
219
+ *
220
+ * Deliberately never touches a below-floor install: the floor is
221
+ * enforced foreground by the launcher (fail-closed), and a background
222
+ * task must not change what the running session validated.
223
+ */
224
+ function refreshPiInBackground(opts) {
225
+ if (!opts.autoUpdate) return;
226
+ (async () => {
227
+ try {
228
+ if (!shouldCheckNow(await readCache())) return;
229
+ const installedVersion = await getInstalledPiVersion();
230
+ if (!meetsPiMinVersion(installedVersion)) return;
231
+ const npmPath = resolveExecutable("npm");
232
+ const latestVersion = await getLatestPiVersion();
233
+ await writeCache({
234
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
235
+ installedVersion,
236
+ latestVersion
237
+ });
238
+ if (!npmPath) return;
239
+ if (!latestVersion || !isPiNewer(installedVersion, latestVersion)) return;
240
+ if (await withInstallLock("pi-install.lock", async () => {
241
+ queueDetachedGlobalInstall(npmPath, `@earendil-works/pi-coding-agent@${latestVersion}`);
242
+ })) consola.info(`Pi ${installedVersion} → ${latestVersion} update queued; it takes effect on the next launch.`);
243
+ } catch (err) {
244
+ consola.debug("Background Pi refresh failed:", err);
245
+ }
246
+ })().catch((err) => {
247
+ consola.debug("Background Pi refresh failed:", err);
188
248
  });
189
249
  }
190
250
  //#endregion
@@ -482,22 +542,24 @@ function piMirrorDir() {
482
542
  */
483
543
  async function ensurePiAgentMirror() {
484
544
  const mirror = piMirrorDir();
485
- await fs.mkdir(mirror, { recursive: true });
545
+ await fs$1.mkdir(mirror, { recursive: true });
486
546
  const source = userPiAgentDir();
487
547
  let entries;
488
548
  try {
489
- entries = await fs.readdir(source);
549
+ entries = await fs$1.readdir(source);
490
550
  } catch {
491
551
  return mirror;
492
552
  }
553
+ const keepUserExtensions = process.env.GH_ROUTER_PI_KEEP_USER_EXTENSIONS === "1";
493
554
  const SKIP = /* @__PURE__ */ new Set([
494
555
  "auth.json",
495
556
  "sessions",
496
- "models-store.json"
557
+ "models-store.json",
558
+ ...keepUserExtensions ? [] : ["extensions"]
497
559
  ]);
498
560
  await Promise.all(entries.filter((e) => !SKIP.has(e)).map(async (entry) => {
499
561
  try {
500
- await fs.cp(path.join(source, entry), path.join(mirror, entry), { recursive: true });
562
+ await fs$1.cp(path.join(source, entry), path.join(mirror, entry), { recursive: true });
501
563
  } catch (err) {
502
564
  consola.debug(`Pi mirror: skipping ${entry}:`, err);
503
565
  }
@@ -507,7 +569,7 @@ async function ensurePiAgentMirror() {
507
569
  /** Remove THIS launch's Pi mirror on shutdown. Best-effort, never throws. */
508
570
  async function removeOwnPiAgentMirror() {
509
571
  try {
510
- await fs.rm(piMirrorDir(), {
572
+ await fs$1.rm(piMirrorDir(), {
511
573
  recursive: true,
512
574
  force: true
513
575
  });
@@ -523,14 +585,14 @@ async function sweepStalePiAgentMirrors() {
523
585
  const root = path.join(appDir(), "pi-mirrors");
524
586
  let entries;
525
587
  try {
526
- entries = await fs.readdir(root);
588
+ entries = await fs$1.readdir(root);
527
589
  } catch {
528
590
  return;
529
591
  }
530
592
  await Promise.all(entries.map(async (entry) => {
531
593
  const dir = path.join(root, entry);
532
594
  try {
533
- const stat = await fs.stat(dir);
595
+ const stat = await fs$1.stat(dir);
534
596
  const ageMs = Date.now() - stat.mtimeMs;
535
597
  const pidMatch = /^pi-agent-(\d+)-[0-9a-f]+$/.exec(entry);
536
598
  let dead = ageMs > 864e5;
@@ -542,7 +604,7 @@ async function sweepStalePiAgentMirrors() {
542
604
  dead = true;
543
605
  }
544
606
  }
545
- if (dead) await fs.rm(dir, {
607
+ if (dead) await fs$1.rm(dir, {
546
608
  recursive: true,
547
609
  force: true
548
610
  });
@@ -553,9 +615,36 @@ async function sweepStalePiAgentMirrors() {
553
615
  }
554
616
  //#endregion
555
617
  //#region src/lib/pi-models-settings.ts
618
+ /**
619
+ * Pi thinking levels that can appear in `thinkingLevelMap`. `off` is
620
+ * omitted: it means "no reasoning" and is never mapped to a provider
621
+ * value.
622
+ */
623
+ const PI_THINKING_LEVELS = [
624
+ "minimal",
625
+ "low",
626
+ "medium",
627
+ "high",
628
+ "xhigh",
629
+ "max"
630
+ ];
631
+ /**
632
+ * Build a Pi `thinkingLevelMap` from a catalog `reasoning_effort`
633
+ * allowlist: supported levels map to themselves, unsupported to `null`
634
+ * (Pi hides them in `/thinking`). Returns `undefined` when the catalog
635
+ * carries no effort signal so Pi falls back to its own defaults rather
636
+ * than a guessed map.
637
+ */
638
+ function piThinkingLevelMapFor(efforts) {
639
+ if (!efforts || efforts.length === 0) return void 0;
640
+ const set = new Set(efforts);
641
+ const map = {};
642
+ for (const level of PI_THINKING_LEVELS) map[level] = set.has(level) ? level : null;
643
+ return map;
644
+ }
556
645
  /** Provider key used in models.json and agent `provider/model` references. */
557
646
  const PI_PROVIDER_NAME = "gh-router";
558
- const PI_MIN_VERSION_NOTE = "Requires Pi >= 0.80.10 and Node >= 22.19.";
647
+ const PI_MIN_VERSION_NOTE = "Requires Pi >= 0.87.1 and Node >= 22.19.";
559
648
  function piLeadModel(profileId) {
560
649
  return profileId === "cheapest" ? CHEAPEST_PROFILE_MODELS.lead : BALANCED_PROFILE_MODELS.lead;
561
650
  }
@@ -634,6 +723,51 @@ function piProfileModelIds(profileId, opts = {}) {
634
723
  return [...ids];
635
724
  }
636
725
  /**
726
+ * Conservative per-model image resize Pi applies before sending.
727
+ * Docs-example values: 1568px, 512KiB encoded payload, JPEG quality 75.
728
+ * Well under Copilot's 3MiB decoded limit and ample for UI screenshots
729
+ * (measured ~35KB PNG), so sends stay fast and cheap. A model publishing
730
+ * a smaller `max_prompt_image_size` clamps `maxBytes` further via
731
+ * `piImageResizeFor` (encoded budget scaled from the decoded limit).
732
+ */
733
+ const PI_IMAGE_RESIZE_MAX_WIDTH = 1568;
734
+ const PI_IMAGE_RESIZE_MAX_HEIGHT = 1568;
735
+ const PI_IMAGE_RESIZE_MAX_BYTES = 524288;
736
+ /**
737
+ * Derive the `inputLimits.images.resize` budget for a model row.
738
+ * Returns `undefined` for text-only models (explicit `vision === false`).
739
+ * Otherwise the conservative defaults, with `maxBytes` clamped to the
740
+ * decoded catalog limit scaled to encoded units when that limit is
741
+ * smaller than the default budget.
742
+ */
743
+ function piImageResizeFor(vision, maxImageBytes) {
744
+ if (vision === false) return void 0;
745
+ let maxBytes = PI_IMAGE_RESIZE_MAX_BYTES;
746
+ if (typeof maxImageBytes === "number" && Number.isFinite(maxImageBytes) && maxImageBytes > 0) {
747
+ const scaled = Math.floor(maxImageBytes * 4 / 3);
748
+ if (scaled < maxBytes) maxBytes = Math.max(scaled, 1);
749
+ }
750
+ return { images: { resize: {
751
+ maxWidth: PI_IMAGE_RESIZE_MAX_WIDTH,
752
+ maxHeight: PI_IMAGE_RESIZE_MAX_HEIGHT,
753
+ maxBytes,
754
+ jpegQuality: 75
755
+ } } };
756
+ }
757
+ /**
758
+ * Derive a per-model Responses/Completions API from catalog endpoints.
759
+ * Returns `undefined` when the catalog carries no endpoint signal so the
760
+ * caller falls back to the provider default. A Responses-capable model
761
+ * stays on the provider default; a chat-only model overrides to
762
+ * completions.
763
+ */
764
+ function piApiForEndpoints(endpoints) {
765
+ if (!endpoints || endpoints.length === 0) return void 0;
766
+ const lower = endpoints.map((e) => e.toLowerCase());
767
+ if (lower.some((e) => e.includes("responses"))) return "openai-responses";
768
+ if (lower.some((e) => e.includes("chat") || e.includes("completion"))) return "openai-completions";
769
+ }
770
+ /**
637
771
  * Fallback per-request output cap when the catalog carries no
638
772
  * max_output_tokens. Matches the documented Luna/Grok 128K ceiling;
639
773
  * the live catalog always wins. Never below the proxy's 16-token floor.
@@ -672,11 +806,23 @@ function piUsdCostFor(prices) {
672
806
  * Responses-only on Copilot, and Pi POSTs `{baseUrl}/responses` for
673
807
  * that API — i.e. our `/v1/responses`, the Codex-proven path. Sending
674
808
  * these models to `/v1/chat/completions` is a Copilot 400 (observed).
809
+ * A model whose catalog endpoints lack Responses (future chat-served
810
+ * model) overrides per-model via `piApiForEndpoints`.
675
811
  *
676
812
  * Every row is BARE (no `[1m]`) with its cheap-tier window from
677
813
  * `piContextWindowFor` (272K Luna/Sol, 200K Grok/unknown): Pi budgets
678
814
  * `contextWindow` per model, so each role gets its cheapest tier and
679
815
  * Long-tier (2x) pricing is structurally unreachable.
816
+ *
817
+ * Vision is fail-open: only an explicit catalog `vision === false`
818
+ * advertises `["text"]`; unknown models advertise `["text","image"]`
819
+ * so Pi's native image paths (@path/--file/paste/read) stay available
820
+ * and the proxy vision preflight (drop-with-note + learned upstream
821
+ * ceilings) remains the backstop. Vision rows also carry
822
+ * `inputLimits.images.resize` so Pi resizes before sending instead of
823
+ * paying a send-then-drop round trip, and `thinkingLevelMap` from the
824
+ * catalog `reasoning_effort` allowlist so Pi never offers an effort
825
+ * tier Copilot would 400.
680
826
  */
681
827
  function buildPiModelsJson(opts) {
682
828
  const baseUrl = `${opts.serverUrl.replace(/\/+$/, "")}/v1`;
@@ -690,15 +836,20 @@ function buildPiModelsJson(opts) {
690
836
  const entry = opts.catalog?.find((m) => m.id === id);
691
837
  const out = entry?.maxOutputTokens;
692
838
  const maxTokens = typeof out === "number" && Number.isFinite(out) && out >= 16 ? Math.floor(out) : PI_MAX_TOKENS_FALLBACK;
693
- const override = opts.apiOverrides?.[id];
839
+ const endpointApi = piApiForEndpoints(entry?.endpoints);
840
+ const override = opts.apiOverrides?.[id] ?? endpointApi;
841
+ const thinkingLevelMap = piThinkingLevelMapFor(entry?.efforts);
842
+ const inputLimits = piImageResizeFor(entry?.vision, entry?.maxImageBytes);
694
843
  return {
695
844
  id,
696
845
  name: id,
697
846
  reasoning: true,
698
- input: ["text"],
847
+ input: entry?.vision === false ? ["text"] : ["text", "image"],
699
848
  contextWindow: piContextWindowFor(id, entry?.maxContextTokens),
700
849
  maxTokens,
701
850
  ...entry?.cost ? { cost: entry.cost } : {},
851
+ ...thinkingLevelMap ? { thinkingLevelMap } : {},
852
+ ...inputLimits ? { inputLimits } : {},
702
853
  ...override && override !== providerApi ? { api: override } : {}
703
854
  };
704
855
  })
@@ -748,6 +899,138 @@ function derivePiCompactionSettings(catalog, modelIds) {
748
899
  };
749
900
  }
750
901
  /**
902
+ * Presentational settings keys that stay user-customizable. When the
903
+ * snapshotted user settings already define one of these, the user's
904
+ * value wins over the built default at launch-merge time (see
905
+ * `applyCosmeticUserOverrides`). Everything else the builder emits —
906
+ * models, tools, thinking levels, compaction, retry, packages — stays
907
+ * built-wins: those are the cost contract, not a preference.
908
+ */
909
+ const PI_COSMETIC_SETTING_KEYS = [
910
+ "hideThinkingBlock",
911
+ "theme",
912
+ "themeAdaptive",
913
+ "groupToolCalls",
914
+ "readOutputMode",
915
+ "searchOutputMode",
916
+ "mcpOutputMode",
917
+ "bashOutputMode",
918
+ "toolBackground",
919
+ "terminal",
920
+ "images",
921
+ "markdown",
922
+ "collapseChangelog"
923
+ ];
924
+ /**
925
+ * Overlay user-defined presentational values onto built settings.
926
+ * Only keys listed in `PI_COSMETIC_SETTING_KEYS` that are actually
927
+ * present (not `undefined`) in `userSettings` override — so a user
928
+ * `~/.pi/agent/settings.json` with e.g. `"hideThinkingBlock": false`
929
+ * or `"readOutputMode": "preview"` keeps their look, while everyone
930
+ * else gets the Claude-Code-like defaults. Returns the picked
931
+ * overrides (empty object when the user customized nothing).
932
+ */
933
+ function applyCosmeticUserOverrides(userSettings, builtSettings) {
934
+ const overrides = {};
935
+ if (!userSettings) return overrides;
936
+ const built = builtSettings;
937
+ for (const key of PI_COSMETIC_SETTING_KEYS) {
938
+ if (!(key in userSettings)) continue;
939
+ const value = userSettings[key];
940
+ if (value === void 0) continue;
941
+ if (!(key in built)) continue;
942
+ overrides[key] = value;
943
+ }
944
+ return overrides;
945
+ }
946
+ /**
947
+ * Helpful third-party bundle, wired extensions-only (skills/prompts/
948
+ * themes filtered out so third-party prose never reaches Ctrl+O — same
949
+ * policy as `pi-subagents`). Router-owned surfaces stay excluded:
950
+ * no statusline/footer package (built into `local:gh-router-pi`), no
951
+ * compaction replacers, no provider/model overriders.
952
+ *
953
+ * - `pi-mcp-adapter`: MCP servers as one proxy tool instead of hundreds
954
+ * of definitions (context/cost win).
955
+ * - `pi-web-access`: search/fetch/PDF-extract fallback. Only wired when
956
+ * the launch has neither `--search` nor `--browse`, otherwise it
957
+ * double-pays our ColBERT/browser surfaces.
958
+ * - `pi-agent-extensions`: allowlisted stable extensions only
959
+ * (sessions, structured questions, todos, handoff, context/files
960
+ * dashboards, notifications, analytics). `review`/`loop`/`workflow`/
961
+ * `control` overlap our delegate/review pipeline and `powerline-footer`
962
+ * would fight the router-owned AIC footer, so all are excluded.
963
+ */
964
+ const PI_HELPERS_MCP_ADAPTER = {
965
+ source: "npm:pi-mcp-adapter",
966
+ skills: [],
967
+ prompts: []
968
+ };
969
+ const PI_HELPERS_WEB_ACCESS = {
970
+ source: "npm:pi-web-access",
971
+ skills: [],
972
+ prompts: []
973
+ };
974
+ /** Verified manifest paths (pi-agent-extensions 0.5.x). Bare relative
975
+ * form, NO `./` prefix: Pi matches package-filter patterns with
976
+ * minimatch against root-relative paths, and a `./` prefix matches
977
+ * nothing (observed live: zero extensions loaded, silent). */
978
+ const PI_HELPERS_AGENT_EXTENSIONS = {
979
+ source: "npm:pi-agent-extensions",
980
+ extensions: [
981
+ "extensions/sessions/index.ts",
982
+ "extensions/ask-user/index.ts",
983
+ "extensions/handoff/index.ts",
984
+ "extensions/notify/index.ts",
985
+ "extensions/context/index.ts",
986
+ "extensions/files/index.ts",
987
+ "extensions/todos/index.ts",
988
+ "extensions/answer/index.ts",
989
+ "extensions/cwd-history/index.ts",
990
+ "extensions/session-breakdown/index.ts"
991
+ ],
992
+ skills: [],
993
+ prompts: [],
994
+ themes: []
995
+ };
996
+ /** Claude-look UI bundle: transcript grouping, Shiki diffs, Ctrl+O
997
+ * previews. Default-on (purely presentational — zero model cost);
998
+ * opt out with `--no-ui`. `pi-code` behaviors stay a docs recipe:
999
+ * its `/memory` + `/context` commands would collide with the
1000
+ * router-owned pair in `gh-router-pi`, and Pi offers no per-command
1001
+ * filtering inside one extension. */
1002
+ const PI_UI_PACKAGES = Object.freeze(["npm:pi-claude-code-ui"]);
1003
+ /**
1004
+ * Claude Code dark theme (`#D77757` coral and friends) from
1005
+ * `better-claude-code-ui`, which ships six CC palettes. Themes-only:
1006
+ * extensions/skills/prompts are explicitly emptied so none of the
1007
+ * package's status line, footer, or tool rendering loads and fights
1008
+ * the router-owned footer or `pi-claude-code-ui`. Theme files are
1009
+ * pure JSON data — loading the whole `./theme` dir costs nothing at
1010
+ * runtime and leaves all six CC variants pickable via `/settings`,
1011
+ * with `claude-code-dark` the default (see `PI_CC_DARK_THEME`).
1012
+ */
1013
+ const PI_CC_THEME_PACKAGE = {
1014
+ source: "npm:better-claude-code-ui",
1015
+ themes: ["theme/*.json"],
1016
+ extensions: [],
1017
+ skills: [],
1018
+ prompts: []
1019
+ };
1020
+ /** Default Pi theme: genuine Claude Code dark palette. */
1021
+ const PI_CC_DARK_THEME = "claude-code-dark";
1022
+ /** Built-in tools enabled at startup (Pi-native set incl. Windows). */
1023
+ const PI_DEFAULT_TOOLS = Object.freeze([
1024
+ "read",
1025
+ "bash",
1026
+ "powershell",
1027
+ "edit",
1028
+ "write",
1029
+ "grep",
1030
+ "find",
1031
+ "ls"
1032
+ ]);
1033
+ /**
751
1034
  * Build the per-launch `settings.json`. Additive over the snapshotted
752
1035
  * user settings (the launcher merges lists it owns): narrow model
753
1036
  * scope, fixed thinking, limited toolset, derived compaction, and the
@@ -756,6 +1039,11 @@ function derivePiCompactionSettings(catalog, modelIds) {
756
1039
  * `pi-subagents` rides `peersEnabled` and loads extensions ONLY
757
1040
  * (skills/prompts filtered out — the mode's own skills/prompts cover
758
1041
  * the roster, so the third-party sets never reach Ctrl+O).
1042
+ * The helpful bundle rides `helpers` (default on, peers-gated):
1043
+ * `pi-mcp-adapter` + allowlisted `pi-agent-extensions` always, plus
1044
+ * `pi-web-access` only when neither search nor browse is on (otherwise
1045
+ * it double-pays our ColBERT/browser surfaces). The `--ui` bundle
1046
+ * (`pi-code`, `pi-claude-code-ui`) is opt-in.
759
1047
  * The statusline footer is built into `local:gh-router-pi` (no
760
1048
  * third-party statusline package: the community bridge reads only the
761
1049
  * user's real global/project settings and never sees the launch mirror,
@@ -763,54 +1051,161 @@ function derivePiCompactionSettings(catalog, modelIds) {
763
1051
  */
764
1052
  function buildPiSettingsJson(opts) {
765
1053
  const peers = opts.peers !== false;
1054
+ const helpers = opts.helpers !== false && peers;
1055
+ const webAccess = helpers && !opts.searchEnabled && !opts.browseEnabled;
1056
+ const ui = opts.ui !== false;
766
1057
  const modelIds = piProfileModelIds(opts.profileId, { peers });
1058
+ const modelThinkingLevels = {};
1059
+ modelThinkingLevels[`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`] = piLeadThinking(opts.profileId);
1060
+ for (const role of piNativeRoles(opts.profileId)) modelThinkingLevels[`${PI_PROVIDER_NAME}/${role.model}`] = role.thinking;
1061
+ modelThinkingLevels[`${PI_PROVIDER_NAME}/${piOracleModel(opts.profileId)}`] = piOracleThinking(opts.profileId);
1062
+ const advisor = piAdvisorModel(opts.profileId);
1063
+ if (advisor) modelThinkingLevels[`${PI_PROVIDER_NAME}/${advisor.model}`] = advisor.thinking;
767
1064
  return {
768
1065
  defaultProvider: PI_PROVIDER_NAME,
769
1066
  defaultModel: piLeadModel(opts.profileId),
770
1067
  defaultThinkingLevel: piLeadThinking(opts.profileId),
771
1068
  enabledModels: modelIds.map((id) => `${PI_PROVIDER_NAME}/${id}`),
772
- defaultTools: [
773
- "read",
774
- "bash",
775
- "edit",
776
- "write",
777
- "grep",
778
- "find",
779
- "ls"
780
- ],
1069
+ defaultTools: [...PI_DEFAULT_TOOLS],
1070
+ modelThinkingLevels,
1071
+ terminal: {
1072
+ showImages: true,
1073
+ imageWidthCells: 60,
1074
+ showTerminalProgress: true
1075
+ },
1076
+ markdown: { mermaid: "streaming" },
1077
+ collapseChangelog: true,
1078
+ images: {
1079
+ autoResize: true,
1080
+ blockImages: false
1081
+ },
1082
+ transport: "auto",
1083
+ hideThinkingBlock: true,
1084
+ ...ui ? {
1085
+ themeAdaptive: false,
1086
+ groupToolCalls: true,
1087
+ readOutputMode: "summary",
1088
+ searchOutputMode: "count",
1089
+ mcpOutputMode: "summary",
1090
+ bashOutputMode: "summary",
1091
+ toolBackground: "transparent",
1092
+ theme: PI_CC_DARK_THEME
1093
+ } : {},
1094
+ branchSummary: {
1095
+ reserveTokens: 16384,
1096
+ skipPrompt: false
1097
+ },
781
1098
  compaction: derivePiCompactionSettings(opts.catalog, modelIds),
782
1099
  retry: {
783
1100
  enabled: true,
784
- maxRetries: 3
1101
+ maxRetries: 3,
1102
+ provider: { maxRetries: 0 }
785
1103
  },
786
- packages: [...peers ? [{
787
- source: "npm:pi-subagents",
788
- skills: [],
789
- prompts: []
790
- }] : [], "local:gh-router-pi"]
1104
+ packages: [
1105
+ ...peers ? [{
1106
+ source: "npm:pi-subagents",
1107
+ skills: [],
1108
+ prompts: []
1109
+ }] : [],
1110
+ ...helpers ? [PI_HELPERS_MCP_ADAPTER, PI_HELPERS_AGENT_EXTENSIONS] : [],
1111
+ ...webAccess ? [PI_HELPERS_WEB_ACCESS] : [],
1112
+ ...ui ? [...PI_UI_PACKAGES, PI_CC_THEME_PACKAGE] : [],
1113
+ "local:gh-router-pi"
1114
+ ],
1115
+ ...peers ? { subagents: { agentOverrides: {
1116
+ scout: { disabled: true },
1117
+ worker: { disabled: true },
1118
+ researcher: { disabled: true },
1119
+ "evidence-auditor": { disabled: true },
1120
+ "claude-code": { disabled: true },
1121
+ "claude-code-writer": { disabled: true },
1122
+ "codex-exec": { disabled: true },
1123
+ "codex-exec-writer": { disabled: true },
1124
+ "cursor-agent": { disabled: true },
1125
+ "cursor-agent-writer": { disabled: true }
1126
+ } } } : {}
791
1127
  };
792
1128
  }
793
1129
  function agentFileName(name) {
794
1130
  return `${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}.md`;
795
1131
  }
1132
+ /**
1133
+ * Deep-merge the `subagents` settings key across the snapshot/user and
1134
+ * built layer. Only `agentOverrides` merges (per-agent, user wins);
1135
+ * every other `subagents` sub-key follows the standard rule (built wins
1136
+ * when present, else user survives). Non-object inputs are ignored so a
1137
+ * corrupt user file degrades to built-only instead of crashing launch.
1138
+ */
1139
+ function mergeSubagentsSettings(userSubagents, builtSubagents) {
1140
+ const user = userSubagents && typeof userSubagents === "object" && !Array.isArray(userSubagents) ? userSubagents : void 0;
1141
+ const built = builtSubagents ?? void 0;
1142
+ if (!user && !built) return void 0;
1143
+ const userOverrides = user?.["agentOverrides"] && typeof user["agentOverrides"] === "object" && !Array.isArray(user["agentOverrides"]) ? user["agentOverrides"] : void 0;
1144
+ const builtOverrides = built?.["agentOverrides"];
1145
+ const mergedOverrides = userOverrides || builtOverrides ? {
1146
+ ...builtOverrides,
1147
+ ...userOverrides
1148
+ } : void 0;
1149
+ return {
1150
+ ...user,
1151
+ ...built,
1152
+ ...mergedOverrides ? { agentOverrides: mergedOverrides } : {}
1153
+ };
1154
+ }
796
1155
  function roleDescription(profileId, role) {
797
- const oracleNote = "For risky decisions, ask the oracle subagent for a second opinion before acting.";
798
- if (role.name === "Explore") return `Fast read-only recon: locate code, answer evidence questions, return compressed context. ${oracleNote}`;
1156
+ const oracleNote = "May consult the oracle subagent when a decision feels risky.";
1157
+ if (role.name === "Explore") return "Fast read-only recon: locate code, answer evidence questions, return compressed context.";
799
1158
  if (role.name === "General-Purpose") return profileId === "balanced" ? `General implementation and follow-through on scoped tasks. May hand the result to reviewer only when the change alters behavior. ${oracleNote}` : `General implementation and follow-through on scoped tasks. May hand the result to reviewer for assessment. ${oracleNote}`;
800
1159
  return profileId === "balanced" ? "Behavior-changing review only: assess a change, narrow scope with search first, delegate targeted discovery to Explore rather than sweeping the repo." : "Code review and assessment, including reproducing and root-causing a failure.";
801
1160
  }
802
1161
  /**
803
1162
  * Build `.md` agent definitions for the mode's native roster, in the
804
1163
  * OpenCode/pi-subagents-lite frontmatter format Pi delegation tools
805
- * consume (`name/description/tools/model/thinking/max_turns`, plus
806
- * `allowedAgents` where the delegation graph has an edge). Bodies are
1164
+ * consume (`name/description/tools/model/thinking`, plus `allowedAgents`
1165
+ * where the delegation graph has an edge). Bodies are
807
1166
  * short execution contracts; workflow prose lives in skills so agent
808
1167
  * files stay small enough to inline cheaply.
1168
+ *
1169
+ * Load-bearing semantics (verified against pi-subagents docs + source):
1170
+ * - `reviewer`/`oracle` intentionally SHADOW the same-named builtins
1171
+ * wholesale (user scope wins; omitted fields are NOT inherited). That
1172
+ * is how the roster pins gh-router models/thinking for cost control.
1173
+ * The shadowed `advisor` alias dies with the builtin oracle definition,
1174
+ * which is why `advisor` ships as its own file on cheapest.
1175
+ * Shadowing deliberately does NOT inherit `contact_supervisor` on
1176
+ * reviewer (leaf) or `defaultContext: fork` on oracle (fresh keeps
1177
+ * the cold-start consultant contract).
1178
+ * - `allowedAgents` only narrows an existing nesting grant, so every
1179
+ * delegating agent also sets `allowNestedSubagents: true` and lists
1180
+ * `subagent` in `tools`. Depth reaches 3 on balanced
1181
+ * (lead → General-Purpose → reviewer → Explore), covered by
1182
+ * `PI_SUBAGENT_MAX_DEPTH=3` in the launch env (default guard is 2).
1183
+ * - `async: false` on every file: foreground children run in-process
1184
+ * with the parent's full tool registry. The detached background
1185
+ * runner demonstrably drops read/bash from its registry (observed
1186
+ * live as "requested unavailable child tools: [read, bash]"),
1187
+ * failing every strict-allowlist child it touches.
1188
+ * - Deliberately NO `output:`/`defaultReads`/`defaultProgress` file
1189
+ * bindings: single-shot launches resolve relative outputs under
1190
+ * per-run artifact dirs while `defaultReads` resolves against the
1191
+ * child cwd and skips missing files silently — a lead-mediated
1192
+ * Explore→General-Purpose file handoff never fires. Handoff is inline
1193
+ * prose via the delegating brief instead. `defaultProgress` is doubly
1194
+ * out: its default dir is the repo cwd (untracked litter, no cleanup).
1195
+ * - `advertise: true` puts custom agents in the parent prompt catalog
1196
+ * (default false); `aliases` catch habitual builtin invocations
1197
+ * (`scout`, `worker`, …) deterministically since those builtins are
1198
+ * disabled in settings.
1199
+ * - `inheritProjectContext: true` keeps bridged repo rules (AGENTS.md)
1200
+ * visible to children; `defaultContext: fresh` pins the cold-start
1201
+ * contract explicitly instead of relying on implicit fallback.
809
1202
  */
810
1203
  function buildPiAgentFiles(profileId) {
811
1204
  const files = {};
812
1205
  for (const role of piNativeRoles(profileId)) {
813
- const tools = role.name === "General-Purpose" ? "[read, bash, edit, write, grep, find, ls]" : "[read, grep, find, ls]";
1206
+ const isImplementer = role.name === "General-Purpose";
1207
+ const isReviewer = role.name === "reviewer";
1208
+ const tools = isImplementer ? "read, grep, find, ls, bash, edit, write, subagent, contact_supervisor" : isReviewer ? profileId === "balanced" ? "read, grep, find, ls, watchdog_diff, subagent" : "read, grep, find, ls, watchdog_diff" : "read, grep, find, ls, bash";
814
1209
  const lines = [
815
1210
  "---",
816
1211
  `name: ${role.name}`,
@@ -818,28 +1213,38 @@ function buildPiAgentFiles(profileId) {
818
1213
  `tools: ${tools}`,
819
1214
  `model: ${PI_PROVIDER_NAME}/${role.model}`,
820
1215
  `thinking: ${role.thinking}`,
821
- "max_turns: 80"
1216
+ "advertise: true",
1217
+ "async: false",
1218
+ "systemPromptMode: replace",
1219
+ "inheritProjectContext: true",
1220
+ "defaultContext: fresh"
822
1221
  ];
823
- if (profileId === "balanced" && role.name === "reviewer") lines.push("allowedAgents: [Explore]");
824
- if (role.name === "General-Purpose") lines.push("allowedAgents: [reviewer]");
1222
+ if (role.name === "Explore") lines.push("aliases: scout");
1223
+ if (isImplementer) lines.push("aliases: worker, developer, coder, implementer, develop", "acceptanceRole: writer", "allowNestedSubagents: true", "allowedAgents: reviewer, oracle");
1224
+ if (profileId === "balanced" && isReviewer) lines.push("allowNestedSubagents: true", "allowedAgents: Explore");
825
1225
  lines.push("---", "");
826
- if (role.name === "Explore") lines.push("You are a read-only scout. Never modify files. Search first, read second,", "return the smallest sufficient evidence: file paths, line spans, and short quotes.");
827
- else if (role.name === "reviewer") lines.push("You review a change that already exists. Reproduce failures before diagnosing.", "Report findings with file:line references; do not rewrite code outside small,", "clearly-marked suggestions.");
828
- else lines.push("You implement the scoped task and verify it (run the relevant tests).", "Hand behavior-changing results to reviewer when asked; otherwise summarize", "the diff and how it was verified.");
1226
+ 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.");
1227
+ else if (isReviewer) lines.push("You are a disciplined review subagent. Inspect the actual change; verify from code,", "tests, and docs — never guess. Cover intent match, correctness and edge cases,", "test coverage, side effects, and minimality.", "Report findings with file:line evidence ranked P0 (blocker) / P1 (should fix) / P2 (nit),", "ending with one of: Merge verdict: BLOCK, Merge verdict: OK, Merge verdict: OK with notes.", "You have no shell: cite the test commands for the lead to run rather than executing them.", "Do not rewrite code outside small, clearly-marked suggestions.");
1228
+ else lines.push("You are the single writer thread. Execute the assigned task with narrow, coherent edits;", "the lead remains the decision authority. Work from the brief's pasted context,", "then implement minimally and verify by running the relevant tests.", "If the work reveals an unapproved decision you cannot safely resolve, stop and escalate", "instead of guessing; never leave placeholders or TODOs.", "Hand behavior-changing results to reviewer when asked; otherwise summarize the diff,", "validation, risks, and next step.");
829
1229
  files[`agents/${agentFileName(role.name)}`] = `${lines.join("\n")}\n`;
830
1230
  }
831
1231
  const oracle = [
832
1232
  "---",
833
1233
  "name: oracle",
834
- `description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.`,
835
- "tools: [read, grep, find, ls]",
1234
+ "description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.",
1235
+ "tools: read, grep, find, ls, bash",
836
1236
  `model: ${PI_PROVIDER_NAME}/${piOracleModel(profileId)}`,
837
1237
  `thinking: ${piOracleThinking(profileId)}`,
838
- "max_turns: 40",
1238
+ "advertise: true",
1239
+ "async: false",
1240
+ "systemPromptMode: replace",
1241
+ "inheritProjectContext: true",
1242
+ "defaultContext: fresh",
839
1243
  "---",
840
1244
  "",
841
1245
  "You are an oracle: a second set of eyes. You see only the task context",
842
1246
  "you are given — you have no repo memory beyond what you read now.",
1247
+ "Inspect the code yourself with read/grep/find/ls before opining.",
843
1248
  "Challenge assumptions, name what is missing, recommend; never execute."
844
1249
  ].join("\n");
845
1250
  files[`agents/${agentFileName("oracle")}`] = `${oracle}\n`;
@@ -848,11 +1253,15 @@ function buildPiAgentFiles(profileId) {
848
1253
  const body = [
849
1254
  "---",
850
1255
  "name: advisor",
851
- `description: Advisory plan review for the lead: review the final plan before it is presented. Never executes.`,
852
- "tools: [read, grep, find, ls]",
1256
+ "description: Advisory plan review for the lead: review the final plan before it is presented. Never executes.",
1257
+ "tools: read, grep, find, ls",
853
1258
  `model: ${PI_PROVIDER_NAME}/${advisor.model}`,
854
1259
  `thinking: ${advisor.thinking}`,
855
- "max_turns: 40",
1260
+ "advertise: true",
1261
+ "async: false",
1262
+ "systemPromptMode: replace",
1263
+ "inheritProjectContext: true",
1264
+ "defaultContext: fresh",
856
1265
  "---",
857
1266
  "",
858
1267
  "You review the lead's final plan and give advisory feedback only.",
@@ -864,6 +1273,32 @@ function buildPiAgentFiles(profileId) {
864
1273
  return files;
865
1274
  }
866
1275
  /**
1276
+ * One elegant three-line launch summary for the `pi` preamble,
1277
+ * written directly to stderr (no reporter icons or timestamps).
1278
+ * Missing facts are omitted, never printed as blanks — a first run
1279
+ * that never resolved versions still renders cleanly.
1280
+ */
1281
+ function buildPiLaunchCard(opts) {
1282
+ const surface = [];
1283
+ surface.push(opts.peers ? "peers" : "peerless");
1284
+ if (opts.peers && opts.helpers) surface.push("helpers");
1285
+ if (opts.ui) surface.push("ui");
1286
+ if (opts.swe) surface.push("swe");
1287
+ if (opts.search) surface.push("search");
1288
+ if (opts.browse) surface.push("browse");
1289
+ const identity = [
1290
+ opts.accountType,
1291
+ opts.login,
1292
+ opts.copilotVersion ? `copilot chat ${opts.copilotVersion}` : void 0,
1293
+ opts.vsCodeVersion ? `vscode ${opts.vsCodeVersion}` : void 0
1294
+ ].filter((part) => typeof part === "string" && part.length > 0);
1295
+ return [
1296
+ `github-router v${opts.version} · pi (${opts.profileId})`,
1297
+ ` ${identity.join(" · ")}`,
1298
+ ` lead ${opts.lead} · ${opts.modelCount} models · ${surface.join(" ")} · ${opts.serverUrl}`
1299
+ ].join("\n");
1300
+ }
1301
+ /**
867
1302
  * Short operating digest appended to APPEND_SYSTEM.md (prompt-cache-stable).
868
1303
  * Mode identity — always injected. Peer consult sentences drop out under
869
1304
  * `peers: false` so the digest never names tools that don't exist.
@@ -876,7 +1311,7 @@ function buildPiAppendSystem(profileId, opts = {}) {
876
1311
  "",
877
1312
  `- Lead owns planning directly; there is no Plan subagent.`
878
1313
  ];
879
- if (peers) lines.push(`- Delegate FREELY to Explore for discovery and General-Purpose for scoped work.`, profileId === "balanced" ? `- 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.`);
1314
+ 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.`, profileId === "balanced" ? `- 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.`);
880
1315
  else lines.push(`- Peerless launch: no subagents or consultants in this session; plan, implement, and verify directly.`);
881
1316
  lines.push("", `(${PI_MIN_VERSION_NOTE})`, "");
882
1317
  return lines.join("\n");
@@ -1135,8 +1570,8 @@ function buildPiStatuslineFooterSection() {
1135
1570
  */
1136
1571
  function buildPiMemoryBridgeSection(bridge) {
1137
1572
  const cappedRules = bridge.scopedRules.map((r) => ({
1138
- file: r.file,
1139
- body: r.body.length > 8e3 ? `${r.body.slice(0, 8e3)}\n…[truncated by gh-router memory bridge]` : r.body,
1573
+ file: r.file.replaceAll("\0", ""),
1574
+ body: (r.body.length > 8e3 ? `${r.body.slice(0, 8e3)}\n…[truncated by gh-router memory bridge]` : r.body).replaceAll("\0", ""),
1140
1575
  globs: r.globs,
1141
1576
  source: r.source
1142
1577
  }));
@@ -1244,8 +1679,6 @@ function buildPiMemoryBridgeSection(bridge) {
1244
1679
  function buildPiExtensionSource(opts) {
1245
1680
  const peers = opts.peers !== false;
1246
1681
  const advisor = peers ? piAdvisorModel(opts.profileId) : void 0;
1247
- const oracleModel = piOracleModel(opts.profileId);
1248
- const oracleThinking = piOracleThinking(opts.profileId);
1249
1682
  const lines = [];
1250
1683
  lines.push(`// gh-router-pi extension (${opts.profileId} mode). Generated per launch; do not edit.`, `// Executable seams only. Workflow guidance lives in skills/, not here.`, `import { Type } from "typebox";`, `import { spawn } from "node:child_process";`, ``, ...peers ? [
1251
1684
  `const OracleParams = Type.Object({`,
@@ -1258,20 +1691,65 @@ function buildPiExtensionSource(opts) {
1258
1691
  ` plan: Type.String({ description: "The final plan to review (advisory)" }),`,
1259
1692
  ` context: Type.Optional(Type.String({ description: "Background context" })),`,
1260
1693
  `});`
1261
- ] : [], `const CodeSearchParams = Type.Object({`, ` query: Type.String({ description: "What to find" }),`, ` mode: Type.Optional(Type.String({ description: "semantic (default), lexical, exact, regex, or ast" })),`, ` limit: Type.Optional(Type.Number({ description: "Max results" })),`, `});`, `const BrowserParams = Type.Object({`, ` url: Type.Optional(Type.String({ description: "URL to act on" })),`, ` intent: Type.Optional(Type.String({ description: "What to do on the page" })),`, `});`, `async function toolText(promise) {`, ` const text = await promise;`, ` return { content: [{ type: "text", text }], details: undefined };`, `}`, `const MCP_URL = (process.env.GH_ROUTER_HOOK_MCP_URL ?? "").replace(/\\/+$/, "");`, `const MCP_NONCE = process.env.GH_ROUTER_HOOK_NONCE ?? "";`, ...peers ? [`const ORACLE_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${oracleModel}`)};`, `const ORACLE_THINKING = ${JSON.stringify(oracleThinking)};`] : [], ...advisor ? [`const ADVISOR_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${advisor.model}`)};`, `const ADVISOR_THINKING = ${JSON.stringify(advisor.thinking)};`] : [], `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`, `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`, ``, `async function callMcp(group, tool, args, signal) {`, ` const res = await fetch(MCP_URL + "/mcp/" + group, {`, ` method: "POST",`, ` headers: { "content-type": "application/json", accept: "application/json", authorization: "Bearer " + MCP_NONCE },`, ` body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } }),`, ` signal,`, ` });`, ` if (!res.ok) throw new Error("mcp " + group + "/" + tool + " -> HTTP " + res.status);`, ` const body = await res.json();`, ` if (body.error) return "Error: " + body.error.message;`, ` const content = body.result && body.result.content;`, ` if (!Array.isArray(content)) return "";`, ` return content.map((c) => c.text || "").join("\\n");`, `}`, ``, `export default function (pi) {`, ...peers ? [
1694
+ ] : [], ...opts.searchEnabled ? [
1695
+ `const CodeSearchParams = Type.Object({`,
1696
+ ` query: Type.String({ description: "What to find" }),`,
1697
+ ` mode: Type.Optional(Type.String({ description: "semantic (default), lexical, exact, regex, or ast" })),`,
1698
+ ` limit: Type.Optional(Type.Number({ description: "Max results" })),`,
1699
+ ` workspace: Type.Optional(Type.String({ description: "Absolute path to the project root to search. Defaults to the launch workspace." })),`,
1700
+ ` file_glob: Type.Optional(Type.String({ description: "Optional ripgrep glob filter (e.g. src/**/*.ts)" })),`,
1701
+ `});`
1702
+ ] : [], ...opts.browseEnabled ? [
1703
+ `const OpenTabParams = Type.Object({`,
1704
+ ` url: Type.String({ description: "URL to load" }),`,
1705
+ ` reuseActive: Type.Optional(Type.Boolean({ description: "Navigate the active tab instead of opening a new one" })),`,
1706
+ `});`,
1707
+ `const NavigateParams = Type.Object({`,
1708
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1709
+ ` action: Type.String({ description: "goto, back, forward, or reload" }),`,
1710
+ ` url: Type.Optional(Type.String({ description: "URL for action=goto" })),`,
1711
+ ` hard: Type.Optional(Type.Boolean({ description: "Reload only: bypass cache" })),`,
1712
+ `});`,
1713
+ `const ScreenshotParams = Type.Object({`,
1714
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1715
+ ` format: Type.Optional(Type.String({ description: "png or jpeg" })),`,
1716
+ ` quality: Type.Optional(Type.Number({ description: "JPEG quality 1-100" })),`,
1717
+ `});`,
1718
+ `const ActParams = Type.Object({`,
1719
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1720
+ ` intent: Type.Optional(Type.String({ description: "Natural-language action (INTENT mode)" })),`,
1721
+ ` ref: Type.Optional(Type.String({ description: "Element ref for REF mode" })),`,
1722
+ ` action: Type.Optional(Type.String({ description: "REF mode action" })),`,
1723
+ ` value: Type.Optional(Type.String({ description: "Value for fill/type/select" })),`,
1724
+ `});`,
1725
+ `const ObserveParams = Type.Object({`,
1726
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1727
+ ` intent: Type.Optional(Type.String({ description: "Focus for the summary" })),`,
1728
+ `});`,
1729
+ `const ExtractParams = Type.Object({`,
1730
+ ` tabId: Type.Number({ description: "Tab id from open_tab" }),`,
1731
+ ` schema: Type.Any({ description: "JSON schema for the desired output shape" }),`,
1732
+ ` instruction: Type.String({ description: "What to extract" }),`,
1733
+ `});`
1734
+ ] : [], `function stripNul(s) { return String(s ?? "").replace(/\\0/g, ""); }`, `async function toolText(promise) {`, ` const text = await promise;`, ` return { content: [{ type: "text", text: stripNul(text) }], details: undefined };`, `}`, `function toolErrorText(text) {`, ` return { content: [{ type: "text", text }], details: undefined };`, `}`, `const MCP_URL = (process.env.GH_ROUTER_HOOK_MCP_URL ?? "").replace(/\\/+$/, "");`, `const MCP_NONCE = process.env.GH_ROUTER_HOOK_NONCE ?? "";`, `const PI_WORKSPACE = (process.env.GH_ROUTER_WORKSPACE ?? "").trim();`, `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`, `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`, `void LEAD_MODEL; void LEAD_THINKING;`, ``, `async function callMcp(group, tool, args, signal) {`, ` const headers = { "content-type": "application/json", accept: "application/json", authorization: "Bearer " + MCP_NONCE };`, ` if (PI_WORKSPACE && (group === "search" || group === "workers" || group === "orchestrate")) { headers["X-GH-Workspace"] = PI_WORKSPACE; }`, ` const res = await fetch(MCP_URL + "/mcp/" + group, {`, ` method: "POST",`, ` headers,`, ` body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } }),`, ` signal,`, ` });`, ` if (!res.ok) throw new Error("mcp " + group + "/" + tool + " -> HTTP " + res.status);`, ` const body = await res.json();`, ` if (body.error) return "Error: " + body.error.message;`, ` const content = body.result && body.result.content;`, ` if (!Array.isArray(content)) return "";`, ` return content.map((c) => c.text || "").join("\\n");`, `}`, ``, `export default function (pi) {`, ...peers ? [
1262
1735
  ` pi.registerTool({`,
1263
1736
  ` name: "oracle",`,
1264
1737
  ` label: "Oracle",`,
1265
1738
  ` description: "Second opinion before acting on a risky decision. Advisory only: challenges assumptions, never edits. Pass decision, options, and context.",`,
1266
1739
  ` parameters: OracleParams,`,
1267
1740
  ` async execute(_toolCallId, params, signal) {`,
1268
- ` return await toolText(callMcp("peers", "oracle", { decision: params.decision, options: params.options || "", context: params.context, model: ORACLE_MODEL, thinking: ORACLE_THINKING }, signal));`,
1741
+ ` const query = stripNul(params.decision || "").trim();`,
1742
+ ` const opts = stripNul(params.options || "").trim();`,
1743
+ ` const ctx = stripNul(params.context || "").trim();`,
1744
+ ` const context = (opts ? "Options considered:\\n" + opts + "\\n\\n" : "") + ctx;`,
1745
+ ` if (!query || !context.trim()) return toolErrorText("oracle: decision and context are required (non-empty strings)");`,
1746
+ ` return await toolText(callMcp("peers", "oracle", { query, context }, signal));`,
1269
1747
  ` },`,
1270
1748
  ` });`
1271
1749
  ] : []);
1272
- if (advisor) lines.push(` pi.registerTool({`, ` name: "advisor",`, ` label: "Advisor",`, ` description: "Advisory plan review for the lead: review the final plan before presenting it. Never executes.",`, ` parameters: AdvisorParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("peers", "oracle", { decision: "Review this plan (advisory)", options: params.plan, context: params.context || "", model: ADVISOR_MODEL, thinking: ADVISOR_THINKING }, signal));`, ` },`, ` });`);
1273
- if (opts.searchEnabled) lines.push(` pi.registerTool({`, ` name: "code_search",`, ` label: "Code search",`, ` description: "Semantic-first code search over the workspace index (falls back to lexical with a label). Use for finding code by meaning.",`, ` parameters: CodeSearchParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("search", "code", { query: params.query, mode: params.mode || "semantic", limit: params.limit || 15 }, signal));`, ` },`, ` });`);
1274
- if (opts.browseEnabled) lines.push(` const BROWSER_TOOLS = ["browser_open_tab", "browser_navigate", "browser_screenshot", "browser_act", "browser_observe", "browser_extract"];`, ` for (const wireName of BROWSER_TOOLS) {`, ` pi.registerTool({`, ` name: wireName,`, ` description: "Browser control (" + wireName + "). Returns install_required with setup steps when the extension is not loaded.",`, ` parameters: BrowserParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("browser", wireName, { url: params.url || "", intent: params.intent || "" }, signal));`, ` },`, ` });`, ` }`);
1750
+ if (advisor) lines.push(` pi.registerTool({`, ` name: "advisor",`, ` label: "Advisor",`, ` description: "Advisory plan review for the lead: review the final plan before presenting it. Never executes.",`, ` parameters: AdvisorParams,`, ` async execute(_toolCallId, params, signal) {`, ` const plan = stripNul(params.plan || "").trim();`, ` const ctx = stripNul(params.context || "").trim();`, ` const context = (plan ? "Plan under review:\\n" + plan : "") + (ctx ? "\\n\\nBackground:\\n" + ctx : "");`, ` if (!plan || !context.trim()) return toolErrorText("advisor: plan and context are required (non-empty strings)");`, ` return await toolText(callMcp("peers", "oracle", { query: "Review this plan (advisory)", context }, signal));`, ` },`, ` });`);
1751
+ if (opts.searchEnabled) lines.push(` pi.registerTool({`, ` name: "code_search",`, ` label: "Code search",`, ` description: "Semantic-first code search over the workspace index (falls back to lexical with a label). Use for finding code by meaning.",`, ` parameters: CodeSearchParams,`, ` async execute(_toolCallId, params, signal) {`, ` const query = stripNul(params.query || "").trim();`, ` if (!query) return toolErrorText("code_search: query is required (non-empty string)");`, ` const workspace = (typeof params.workspace === "string" && params.workspace.trim()) ? params.workspace.trim() : PI_WORKSPACE;`, ` if (!workspace) return toolErrorText("code_search: a workspace is required. Pass the absolute project path as workspace.");`, ` const args = { query, mode: params.mode || "semantic", limit: params.limit || 15, workspace };`, ` if (typeof params.file_glob === "string" && params.file_glob) args.file_glob = params.file_glob;`, ` return await toolText(callMcp("search", "code", args, signal));`, ` },`, ` });`);
1752
+ if (opts.browseEnabled) lines.push(` pi.registerTool({`, ` name: "open_tab",`, ` label: "Browser open tab",`, ` description: "Open a URL in a new browser tab (MCP browser/open_tab). Returns install_required with setup steps when the extension is not loaded.",`, ` parameters: OpenTabParams,`, ` async execute(_toolCallId, params, signal) {`, ` const url = stripNul(params.url || "").trim();`, ` if (!url) return toolErrorText("open_tab: url is required");`, ` const args = { url };`, ` if (typeof params.reuseActive === "boolean") args.reuseActive = params.reuseActive;`, ` return await toolText(callMcp("browser", "open_tab", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "navigate",`, ` label: "Browser navigate",`, ` description: "Navigate an existing tab (MCP browser/navigate). Requires tabId + action; url only for action=goto.",`, ` parameters: NavigateParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("navigate: tabId is required (number from open_tab)");`, ` if (!params.action) return toolErrorText("navigate: action is required (goto, back, forward, reload)");`, ` const args = { tabId: params.tabId, action: params.action };`, ` if (typeof params.url === "string" && params.url) args.url = params.url;`, ` if (typeof params.hard === "boolean") args.hard = params.hard;`, ` return await toolText(callMcp("browser", "navigate", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "screenshot",`, ` label: "Browser screenshot",`, ` description: "Screenshot a tab (MCP browser/screenshot). Requires tabId.",`, ` parameters: ScreenshotParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("screenshot: tabId is required (number from open_tab)");`, ` const args = { tabId: params.tabId };`, ` if (typeof params.format === "string" && params.format) args.format = params.format;`, ` if (typeof params.quality === "number") args.quality = params.quality;`, ` return await toolText(callMcp("browser", "screenshot", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "act",`, ` label: "Browser act",`, ` description: "Interact with a tab (MCP browser/act). Requires tabId plus intent or ref.",`, ` parameters: ActParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("act: tabId is required (number from open_tab)");`, ` if (!params.intent && !params.ref) return toolErrorText("act: intent or ref is required");`, ` const args = { tabId: params.tabId };`, ` if (typeof params.intent === "string" && params.intent) args.intent = params.intent;`, ` if (typeof params.ref === "string" && params.ref) args.ref = params.ref;`, ` if (typeof params.action === "string" && params.action) args.action = params.action;`, ` if (typeof params.value === "string") args.value = params.value;`, ` return await toolText(callMcp("browser", "act", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "observe",`, ` label: "Browser observe",`, ` description: "Summarize a tab (MCP browser/observe). Requires tabId.",`, ` parameters: ObserveParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("observe: tabId is required (number from open_tab)");`, ` const args = { tabId: params.tabId };`, ` if (typeof params.intent === "string" && params.intent) args.intent = params.intent;`, ` return await toolText(callMcp("browser", "observe", args, signal));`, ` },`, ` });`, ` pi.registerTool({`, ` name: "extract",`, ` label: "Browser extract",`, ` description: "Extract structured data from a tab (MCP browser/extract). Requires tabId, schema, instruction.",`, ` parameters: ExtractParams,`, ` async execute(_toolCallId, params, signal) {`, ` if (typeof params.tabId !== "number") return toolErrorText("extract: tabId is required (number from open_tab)");`, ` if (!params.instruction) return toolErrorText("extract: instruction is required");`, ` if (params.schema === undefined) return toolErrorText("extract: schema is required");`, ` return await toolText(callMcp("browser", "extract", { tabId: params.tabId, schema: params.schema, instruction: params.instruction }, signal));`, ` },`, ` });`);
1275
1753
  if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
1276
1754
  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;`, ` }`, ` });`, `}`, ``);
1277
1755
  return `${lines.join("\n")}\n`;
@@ -1280,8 +1758,9 @@ function buildPiExtensionSource(opts) {
1280
1758
  * Workflow guidance as skills (progressive disclosure, not tools).
1281
1759
  * Ownership mirrors the Claude launcher: peer consult prose rides
1282
1760
  * `--peers`, semantic-search prose rides `--search`, and the
1283
- * delegation/review pipeline rides `--swe`. A bare launch emits NO
1284
- * skills at all.
1761
+ * delegation/review pipeline rides `--swe` AND `--peers` — without
1762
+ * agents + the subagent provider its prose dangles, so peerless+swe
1763
+ * emits none. A bare launch emits NO skills at all.
1285
1764
  */
1286
1765
  function buildPiSkills(opts) {
1287
1766
  const peers = opts.peers !== false;
@@ -1299,7 +1778,9 @@ function buildPiSkills(opts) {
1299
1778
  "Call the `oracle` tool with the decision, the options considered, and the",
1300
1779
  "missing-context gaps. The oracle is cold-start: it sees only what you pass.",
1301
1780
  "Its verdict is advisory — verify with tests and code, never substitute votes",
1302
- "for verification."
1781
+ "for verification. (The `oracle` tool is the one-shot consult; the `oracle`",
1782
+ "subagent is the same role for interactive follow-ups — same name, different",
1783
+ "invocation. Prefer the tool for a single verdict.)"
1303
1784
  ].join("\n")
1304
1785
  });
1305
1786
  if (opts.search === true) skills.push({
@@ -1318,7 +1799,8 @@ function buildPiSkills(opts) {
1318
1799
  "assuming full coverage."
1319
1800
  ].join("\n")
1320
1801
  });
1321
- if (opts.swe === true) {
1802
+ if (opts.swe === true && peers) {
1803
+ const consults = opts.profileId === "balanced" ? "`oracle` for consults" : "`oracle`/`advisor` for consults";
1322
1804
  skills.push({
1323
1805
  dir: "gh-delegate",
1324
1806
  content: [
@@ -1329,9 +1811,19 @@ function buildPiSkills(opts) {
1329
1811
  "",
1330
1812
  "# Delegate",
1331
1813
  "",
1332
- "Recommended loop: scout (Explore) before you understand the code, worker",
1333
- "(General-Purpose) to implement, fresh reviewers to check, worker to apply",
1334
- "feedback. Keep delegated tasks scoped with file:line evidence on return.",
1814
+ "You may delegate via the `subagent` tool to this roster only: `Explore`",
1815
+ "for discovery, `General-Purpose` for scoped implementation, `reviewer`",
1816
+ `for verification, ${consults}. (Builtin \`scout\` and`,
1817
+ "`worker` are disabled in this session; their aliases resolve here.)",
1818
+ "Recommended loop: `Explore` to map the code, paste the brief excerpts",
1819
+ "into the `General-Purpose` brief to implement, `reviewer` to check,",
1820
+ "`General-Purpose` to apply feedback. Keep delegated tasks",
1821
+ "scoped with file:line evidence on return.",
1822
+ "Call `subagent` directly (agent + task). Reserve `workflowScript`",
1823
+ "workflows for genuinely parallel or scripted multi-step fanout —",
1824
+ "our agents run foreground and background runs add spawn overhead.",
1825
+ "After any subagent work completes, always write the final answer",
1826
+ "yourself; never end on tool output or completion notices alone.",
1335
1827
  opts.profileId === "balanced" ? "Send work to reviewer ONLY when the change alters behavior." : "Send finished work to reviewer for assessment."
1336
1828
  ].join("\n")
1337
1829
  });
@@ -1355,11 +1847,17 @@ function buildPiSkills(opts) {
1355
1847
  }
1356
1848
  /**
1357
1849
  * Saved workflow shortcuts as prompt templates (`/name`). The review
1358
- * pipeline is SWE-pipeline surface: only `--swe` emits prompts, so a
1359
- * bare launch advertises none.
1850
+ * pipeline is SWE-pipeline surface: only `--swe` AND `--peers` emit
1851
+ * prompts (peerless launches have no agents behind them), so a bare
1852
+ * launch advertises none.
1853
+ *
1854
+ * `/parallel-review` intentionally shadows the packaged pi-subagents
1855
+ * prompt of the same name (package prompts are filtered to `[]` in
1856
+ * settings): ours routes to our pinned-model `reviewer`, not the
1857
+ * default-model builtin. `/review` is novel — no packaged collision.
1360
1858
  */
1361
1859
  function buildPiPrompts(opts) {
1362
- if (opts.swe !== true) return [];
1860
+ if (opts.swe !== true || opts.peers === false) return [];
1363
1861
  const prompts = [{
1364
1862
  name: "review",
1365
1863
  content: [
@@ -1403,12 +1901,12 @@ const piArgs = {
1403
1901
  "update-check": {
1404
1902
  type: "boolean",
1405
1903
  default: true,
1406
- description: "Check the npm registry for a newer Pi release on launch (throttled hourly). Set to false (--no-update-check) to skip (offline/CI)."
1904
+ description: "Verify Pi is installed and above the supported floor on launch (fast local probe), and refresh it in the background (throttled hourly). Set to false (--no-update-check) to skip both (offline/CI)."
1407
1905
  },
1408
1906
  "auto-update": {
1409
1907
  type: "boolean",
1410
1908
  default: true,
1411
- description: "Install the latest Pi on launch when stale (default). Set to false (--no-auto-update) to warn only."
1909
+ description: "Refresh Pi in the background (throttled hourly): probe npm and queue a post-exit install when newer, without delaying launch. Set to false (--no-auto-update) to disable background updates (the install floor is still enforced)."
1412
1910
  },
1413
1911
  swe: {
1414
1912
  type: "boolean",
@@ -1420,6 +1918,16 @@ const piArgs = {
1420
1918
  default: true,
1421
1919
  description: "Wire the peer/subagent floor: native agent files, the oracle tool (plus cheapest-only advisor), the gh-oracle skill, and the pi-subagents package. Set to false (--no-peers) for a lead-only session; prereqs then validate the lead model only."
1422
1920
  },
1921
+ helpers: {
1922
+ type: "boolean",
1923
+ default: true,
1924
+ description: "Wire the helpful bundle: pi-mcp-adapter, allowlisted pi-agent-extensions (sessions, ask_user, todos, handoff, context, files, analytics — no review/loop/footer), and pi-web-access when neither --search nor --browse is on. Set to false (--no-helpers) for pi-subagents + gh-router-pi only."
1925
+ },
1926
+ ui: {
1927
+ type: "boolean",
1928
+ default: true,
1929
+ description: "Load the Claude-look transcript UI (pi-claude-code-ui: grouped rows, Shiki diffs, Ctrl+O previews). Presentational only, zero model cost. Set to false (--no-ui) for stock Pi rendering."
1930
+ },
1423
1931
  "memory-bridge": {
1424
1932
  type: "boolean",
1425
1933
  default: true,
@@ -1470,12 +1978,12 @@ function collectPiPassthroughArgs(rawArgs, argsDef) {
1470
1978
  return forwarded;
1471
1979
  }
1472
1980
  async function writeJsonFile(file, value) {
1473
- await fs.mkdir(path.dirname(file), { recursive: true });
1474
- await fs.writeFile(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
1981
+ await fs$1.mkdir(path.dirname(file), { recursive: true });
1982
+ await fs$1.writeFile(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
1475
1983
  }
1476
1984
  async function writeTextFile(file, content) {
1477
- await fs.mkdir(path.dirname(file), { recursive: true });
1478
- await fs.writeFile(file, content, { mode: 384 });
1985
+ await fs$1.mkdir(path.dirname(file), { recursive: true });
1986
+ await fs$1.writeFile(file, content, { mode: 384 });
1479
1987
  }
1480
1988
  const pi = defineCommand({
1481
1989
  meta: {
@@ -1498,51 +2006,76 @@ const pi = defineCommand({
1498
2006
  const profileId = launchProfileId;
1499
2007
  let server;
1500
2008
  let serverUrl;
2009
+ const updateCheck = args["update-check"] !== false;
2010
+ const autoUpdate = args["auto-update"] !== false;
2011
+ let installedVersion = null;
2012
+ const pendingInstall = {
2013
+ promise: null,
2014
+ abort: null
2015
+ };
2016
+ if (updateCheck) {
2017
+ try {
2018
+ installedVersion = await getInstalledPiVersion();
2019
+ } catch (err) {
2020
+ consola.debug("Pi presence probe failed:", err);
2021
+ }
2022
+ if (installedVersion === null) {
2023
+ const controller = new AbortController();
2024
+ pendingInstall.abort = () => controller.abort();
2025
+ pendingInstall.promise = ensurePiInstalled({ signal: controller.signal });
2026
+ pendingInstall.promise.catch(() => {});
2027
+ }
2028
+ }
1501
2029
  try {
1502
- const result = await setupAndServe({
1503
- ...parsed,
1504
- port: parsed.port,
1505
- silent: true
1506
- });
1507
- server = result.server;
1508
- serverUrl = result.serverUrl;
2030
+ const quietBoot = existsSync(PATHS.GITHUB_TOKEN_PATH) && !parsed.verbose && !parsed.showToken;
2031
+ const priorLevel = consola.level;
2032
+ if (quietBoot) consola.level = 1;
2033
+ let setupResult;
2034
+ try {
2035
+ setupResult = await setupAndServe({
2036
+ ...parsed,
2037
+ port: parsed.port,
2038
+ silent: true
2039
+ });
2040
+ } finally {
2041
+ if (quietBoot) consola.level = priorLevel;
2042
+ }
2043
+ server = setupResult.server;
2044
+ serverUrl = setupResult.serverUrl;
1509
2045
  } catch (error) {
2046
+ pendingInstall.abort?.();
1510
2047
  consola.error("Failed to start server:", error instanceof Error ? error.message : error);
1511
2048
  process$1.exit(1);
1512
2049
  }
1513
2050
  runSelfUpdate({ selfUpdate: args["self-update"] !== false });
1514
- const updateCheck = args["update-check"] !== false;
1515
- const autoUpdate = args["auto-update"] !== false;
1516
- if (updateCheck) try {
1517
- const check = await checkPiVersion();
1518
- if (!check.installed) try {
2051
+ if (pendingInstall.promise) try {
2052
+ installedVersion = await pendingInstall.promise;
2053
+ } catch (err) {
2054
+ consola.error(`Pi is not installed and automatic install failed (${err instanceof Error ? err.message : String(err)}). Install it with \`npm install -g @earendil-works/pi-coding-agent\`, then retry.`);
2055
+ process$1.exit(1);
2056
+ } finally {
2057
+ pendingInstall.promise = null;
2058
+ pendingInstall.abort = null;
2059
+ }
2060
+ if (updateCheck && installedVersion !== null) if (!meetsPiMinVersion(installedVersion)) {
2061
+ if (autoUpdate) try {
1519
2062
  await updatePi("latest");
1520
- if (!(await checkPiVersion({ force: true })).installed) throw new Error("install did not place pi on PATH");
1521
- } catch (err) {
1522
- consola.error(`Pi is not installed and automatic install failed (${err instanceof Error ? err.message : String(err)}). Install it with \`npm install -g @earendil-works/pi-coding-agent\`, then retry.`);
1523
- process$1.exit(1);
1524
- }
1525
- else if (check.needsMinUpgrade) if (autoUpdate && check.latestVersion) try {
1526
- await updatePi(check.latestVersion);
2063
+ installedVersion = await getInstalledPiVersion();
1527
2064
  } catch (err) {
1528
- consola.error(`Installed Pi v${check.installedVersion} is below the supported floor and auto-upgrade failed. Upgrade manually: \`npm install -g @earendil-works/pi-coding-agent@latest\`.`);
2065
+ consola.error(`Installed Pi v${installedVersion} is below the supported floor and auto-upgrade failed (${err instanceof Error ? err.message : String(err)}). Upgrade manually: \`npm install -g @earendil-works/pi-coding-agent@latest\`.`);
1529
2066
  process$1.exit(1);
1530
2067
  }
1531
- else {
1532
- consola.error(`Installed Pi v${check.installedVersion} is below the supported floor. Upgrade: \`npm install -g @earendil-works/pi-coding-agent@latest\`.`);
2068
+ if (!meetsPiMinVersion(installedVersion)) {
2069
+ consola.error(`Installed Pi v${installedVersion} is below the supported floor. Upgrade: \`npm install -g @earendil-works/pi-coding-agent@latest\`.`);
1533
2070
  process$1.exit(1);
1534
2071
  }
1535
- else if (check.needsUpdate && check.latestVersion) if (autoUpdate) try {
1536
- await updatePi(check.latestVersion);
1537
- } catch (err) {
1538
- consola.warn(`Auto-update of Pi to ${check.latestVersion} failed (${err instanceof Error ? err.message : String(err)}); continuing with installed v${check.installedVersion}.`);
1539
- }
1540
- else consola.warn(`Pi v${check.installedVersion} is installed; v${check.latestVersion} is available. Run with --auto-update (the default) to install on launch.`);
1541
- } catch (err) {
1542
- consola.debug("Pi version check failed:", err);
1543
- }
2072
+ } else refreshPiInBackground({ autoUpdate });
1544
2073
  const peersEnabled = args["peers"] !== false;
1545
2074
  const sweEnabled = args["swe"] === true;
2075
+ const helpersEnabled = args["helpers"] !== false;
2076
+ const uiEnabled = args["ui"] !== false;
2077
+ const searchEnabled = parsed.searchEnabled || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
2078
+ const browseEnabled = browserToolsEnabled();
1546
2079
  const prereqCheck = profileId === "cheapest" ? validateCheapestProfilePrerequisites(state.models, { peers: peersEnabled }) : validateBalancedProfilePrerequisites(state.models, { peers: peersEnabled });
1547
2080
  if (!prereqCheck.ok) {
1548
2081
  const message = profileId === "cheapest" ? formatCheapestPrerequisiteFailure(prereqCheck.missing) : formatBalancedPrerequisiteFailure(prereqCheck.missing);
@@ -1560,8 +2093,6 @@ const pi = defineCommand({
1560
2093
  }
1561
2094
  enableFileLogging();
1562
2095
  try {
1563
- const searchEnabled = parsed.searchEnabled || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
1564
- const browseEnabled = browserToolsEnabled();
1565
2096
  const catalog = state.models?.data.map((m) => {
1566
2097
  const cost = piUsdCostFor(m.billing?.token_prices);
1567
2098
  return {
@@ -1571,6 +2102,8 @@ const pi = defineCommand({
1571
2102
  maxOutputTokens: m.capabilities?.limits?.max_output_tokens ?? 0,
1572
2103
  efforts: m.capabilities?.supports?.reasoning_effort ?? [],
1573
2104
  endpoints: m.supported_endpoints ?? [],
2105
+ vision: m.capabilities?.supports?.vision,
2106
+ maxImageBytes: m.capabilities?.limits?.vision?.max_prompt_image_size,
1574
2107
  ...cost ? { cost } : {}
1575
2108
  };
1576
2109
  });
@@ -1583,21 +2116,28 @@ const pi = defineCommand({
1583
2116
  const settingsPath = path.join(mirror, "settings.json");
1584
2117
  let userSettings = {};
1585
2118
  try {
1586
- const raw = await fs.readFile(settingsPath, "utf8");
2119
+ const raw = await fs$1.readFile(settingsPath, "utf8");
1587
2120
  const parsedSettings = JSON.parse(raw);
1588
2121
  if (parsedSettings && typeof parsedSettings === "object") userSettings = parsedSettings;
1589
2122
  } catch {
1590
2123
  userSettings = {};
1591
2124
  }
2125
+ const builtSettings = buildPiSettingsJson({
2126
+ profileId,
2127
+ searchEnabled,
2128
+ browseEnabled,
2129
+ catalog,
2130
+ peers: peersEnabled,
2131
+ helpers: helpersEnabled,
2132
+ ui: uiEnabled
2133
+ });
2134
+ const mergedSubagents = mergeSubagentsSettings(userSettings["subagents"], builtSettings.subagents);
2135
+ const cosmeticOverrides = applyCosmeticUserOverrides(userSettings, builtSettings);
1592
2136
  await writeJsonFile(settingsPath, {
1593
2137
  ...userSettings,
1594
- ...buildPiSettingsJson({
1595
- profileId,
1596
- searchEnabled,
1597
- browseEnabled,
1598
- catalog,
1599
- peers: peersEnabled
1600
- })
2138
+ ...builtSettings,
2139
+ ...cosmeticOverrides,
2140
+ ...mergedSubagents ? { subagents: mergedSubagents } : {}
1601
2141
  });
1602
2142
  const bridgeDisabled = args["memory-bridge"] === false || process$1.env.GH_ROUTER_PI_BRIDGE === "0" || process$1.env.GH_ROUTER_DISABLE_PI_BRIDGE === "1";
1603
2143
  let bridgeStats;
@@ -1605,7 +2145,7 @@ const pi = defineCommand({
1605
2145
  if (!bridgeDisabled) {
1606
2146
  const passthrough = collectPiPassthroughArgs(rawArgs, piArgs);
1607
2147
  if (!(passthrough.includes("--no-context-files") || passthrough.includes("-nc"))) try {
1608
- const { collectBridgeInputs } = await import("./pi-memory-bridge-BWZJnjpz.js");
2148
+ const { collectBridgeInputs } = await import("./pi-memory-bridge-DEU1SUDz.js");
1609
2149
  const collected = await collectBridgeInputs(process$1.cwd());
1610
2150
  bridgeStats = {
1611
2151
  staticFiles: collected.copilotInstructions.length + collected.unscopedRules.length + collected.userGlobal.length,
@@ -1641,18 +2181,19 @@ const pi = defineCommand({
1641
2181
  })) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
1642
2182
  for (const prompt of buildPiPrompts({
1643
2183
  profileId,
1644
- swe: sweEnabled
2184
+ swe: sweEnabled,
2185
+ peers: peersEnabled
1645
2186
  })) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
1646
2187
  await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, { peers: peersEnabled }));
1647
2188
  try {
1648
2189
  const collected = globalThis.__ghRouterBridgeCollected;
1649
2190
  if (collected) {
1650
- const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-BWZJnjpz.js");
2191
+ const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-DEU1SUDz.js");
1651
2192
  const { section } = buildMirrorBridgeSection(collected, { repoRoot: process$1.cwd() });
1652
2193
  const agentsPath = path.join(mirror, "AGENTS.md");
1653
2194
  let existing;
1654
2195
  try {
1655
- existing = await fs.readFile(agentsPath, "utf8");
2196
+ existing = await fs$1.readFile(agentsPath, "utf8");
1656
2197
  } catch {
1657
2198
  existing = void 0;
1658
2199
  }
@@ -1710,8 +2251,24 @@ const pi = defineCommand({
1710
2251
  const extraArgs = collectPiPassthroughArgs(rawArgs, piArgs);
1711
2252
  const lead = piLeadModel(profileId);
1712
2253
  const modelIds = piProfileModelIds(profileId, { peers: peersEnabled });
1713
- const surface = [`peers=${peersEnabled ? "on" : "off"}`, `swe=${sweEnabled ? "on" : "off"}`].join(" ");
1714
- process$1.stderr.write(`Server ready on ${serverUrl}, launching Pi (${profileId} lead ${lead}, models ${modelIds.length}, ${surface})...\n`);
2254
+ process$1.stderr.write(`${buildPiLaunchCard({
2255
+ version: getPackageVersion(),
2256
+ profileId,
2257
+ accountType: parsed.accountType,
2258
+ login: state.githubUserLogin,
2259
+ copilotVersion: state.copilotVersion,
2260
+ vsCodeVersion: state.vsCodeVersion,
2261
+ lead,
2262
+ modelCount: modelIds.length,
2263
+ peers: peersEnabled,
2264
+ helpers: helpersEnabled && peersEnabled,
2265
+ ui: uiEnabled,
2266
+ swe: sweEnabled,
2267
+ search: searchEnabled,
2268
+ browse: browseEnabled,
2269
+ serverUrl
2270
+ })}\n`);
2271
+ 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");
1715
2272
  const { disposeBluebirdClients } = await import("./bluebird-client-bn9Yv6Cb.js");
1716
2273
  launchChild({
1717
2274
  kind: "pi",
@@ -1719,6 +2276,8 @@ const pi = defineCommand({
1719
2276
  ...getPiLaunchEnvVars(mirror),
1720
2277
  GH_ROUTER_HOOK_MCP_URL: serverUrl,
1721
2278
  GH_ROUTER_HOOK_NONCE: nonce,
2279
+ GH_ROUTER_WORKSPACE: process$1.cwd(),
2280
+ PI_SUBAGENT_MAX_DEPTH: "3",
1722
2281
  ...aicLedgerEnv ? { [AIC_LEDGER_ENV]: aicLedgerEnv } : {},
1723
2282
  ...aicStatusCommandEnv ? { [PI_STATUS_COMMAND_ENV]: aicStatusCommandEnv } : {}
1724
2283
  },
@@ -1736,4 +2295,4 @@ const pi = defineCommand({
1736
2295
  //#endregion
1737
2296
  export { pi };
1738
2297
 
1739
- //# sourceMappingURL=pi-WT6IahMr.js.map
2298
+ //# sourceMappingURL=pi-C8jxbK_2.js.map