github-router 0.3.343 → 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 (41) hide show
  1. package/README.md +13 -8
  2. package/dist/{attribution-settings-DJEBjfJQ.js → attribution-settings-BkhBJn_K.js} +4 -4
  3. package/dist/{attribution-settings-DJEBjfJQ.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-DJeYKVL2.js → claude-CarqHLsD.js} +7 -7
  10. package/dist/{claude-DJeYKVL2.js.map → claude-CarqHLsD.js.map} +1 -1
  11. package/dist/{codex-cUYAC32x.js → codex-AdG6FZIV.js} +5 -5
  12. package/dist/{codex-cUYAC32x.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-CnsdJGF0.js → pi-C8jxbK_2.js} +512 -88
  26. package/dist/pi-C8jxbK_2.js.map +1 -0
  27. package/dist/{provision-D_aHUCXt.js → provision-CJ3Zzs_Q.js} +2 -2
  28. package/dist/{provision-D_aHUCXt.js.map → provision-CJ3Zzs_Q.js.map} +1 -1
  29. package/dist/{serve-CwaKseAj.js → serve-DQhAmfp2.js} +6 -6
  30. package/dist/{serve-CwaKseAj.js.map → serve-DQhAmfp2.js.map} +1 -1
  31. package/dist/{server-setup-CtzSW7Ms.js → server-setup-BBbpJRWv.js} +25 -10
  32. package/dist/server-setup-BBbpJRWv.js.map +1 -0
  33. package/dist/{start-DqfQyqxD.js → start-C34seGtb.js} +3 -3
  34. package/dist/{start-DqfQyqxD.js.map → start-C34seGtb.js.map} +1 -1
  35. package/dist/state-CVp30CBF.js.map +1 -1
  36. package/dist/{token-DATA_OQK.js → token-s5Wd-Kwr.js} +2 -1
  37. package/dist/{token-DATA_OQK.js.map → token-s5Wd-Kwr.js.map} +1 -1
  38. package/package.json +2 -2
  39. package/dist/engine-DvGukHty.js +0 -2
  40. package/dist/pi-CnsdJGF0.js.map +0 -1
  41. package/dist/server-setup-CtzSW7Ms.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-CtzSW7Ms.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,11 +542,11 @@ 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
  }
@@ -499,7 +559,7 @@ async function ensurePiAgentMirror() {
499
559
  ]);
500
560
  await Promise.all(entries.filter((e) => !SKIP.has(e)).map(async (entry) => {
501
561
  try {
502
- 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 });
503
563
  } catch (err) {
504
564
  consola.debug(`Pi mirror: skipping ${entry}:`, err);
505
565
  }
@@ -509,7 +569,7 @@ async function ensurePiAgentMirror() {
509
569
  /** Remove THIS launch's Pi mirror on shutdown. Best-effort, never throws. */
510
570
  async function removeOwnPiAgentMirror() {
511
571
  try {
512
- await fs.rm(piMirrorDir(), {
572
+ await fs$1.rm(piMirrorDir(), {
513
573
  recursive: true,
514
574
  force: true
515
575
  });
@@ -525,14 +585,14 @@ async function sweepStalePiAgentMirrors() {
525
585
  const root = path.join(appDir(), "pi-mirrors");
526
586
  let entries;
527
587
  try {
528
- entries = await fs.readdir(root);
588
+ entries = await fs$1.readdir(root);
529
589
  } catch {
530
590
  return;
531
591
  }
532
592
  await Promise.all(entries.map(async (entry) => {
533
593
  const dir = path.join(root, entry);
534
594
  try {
535
- const stat = await fs.stat(dir);
595
+ const stat = await fs$1.stat(dir);
536
596
  const ageMs = Date.now() - stat.mtimeMs;
537
597
  const pidMatch = /^pi-agent-(\d+)-[0-9a-f]+$/.exec(entry);
538
598
  let dead = ageMs > 864e5;
@@ -544,7 +604,7 @@ async function sweepStalePiAgentMirrors() {
544
604
  dead = true;
545
605
  }
546
606
  }
547
- if (dead) await fs.rm(dir, {
607
+ if (dead) await fs$1.rm(dir, {
548
608
  recursive: true,
549
609
  force: true
550
610
  });
@@ -555,9 +615,36 @@ async function sweepStalePiAgentMirrors() {
555
615
  }
556
616
  //#endregion
557
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
+ }
558
645
  /** Provider key used in models.json and agent `provider/model` references. */
559
646
  const PI_PROVIDER_NAME = "gh-router";
560
- 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.";
561
648
  function piLeadModel(profileId) {
562
649
  return profileId === "cheapest" ? CHEAPEST_PROFILE_MODELS.lead : BALANCED_PROFILE_MODELS.lead;
563
650
  }
@@ -636,6 +723,51 @@ function piProfileModelIds(profileId, opts = {}) {
636
723
  return [...ids];
637
724
  }
638
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
+ /**
639
771
  * Fallback per-request output cap when the catalog carries no
640
772
  * max_output_tokens. Matches the documented Luna/Grok 128K ceiling;
641
773
  * the live catalog always wins. Never below the proxy's 16-token floor.
@@ -674,11 +806,23 @@ function piUsdCostFor(prices) {
674
806
  * Responses-only on Copilot, and Pi POSTs `{baseUrl}/responses` for
675
807
  * that API — i.e. our `/v1/responses`, the Codex-proven path. Sending
676
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`.
677
811
  *
678
812
  * Every row is BARE (no `[1m]`) with its cheap-tier window from
679
813
  * `piContextWindowFor` (272K Luna/Sol, 200K Grok/unknown): Pi budgets
680
814
  * `contextWindow` per model, so each role gets its cheapest tier and
681
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.
682
826
  */
683
827
  function buildPiModelsJson(opts) {
684
828
  const baseUrl = `${opts.serverUrl.replace(/\/+$/, "")}/v1`;
@@ -692,15 +836,20 @@ function buildPiModelsJson(opts) {
692
836
  const entry = opts.catalog?.find((m) => m.id === id);
693
837
  const out = entry?.maxOutputTokens;
694
838
  const maxTokens = typeof out === "number" && Number.isFinite(out) && out >= 16 ? Math.floor(out) : PI_MAX_TOKENS_FALLBACK;
695
- 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);
696
843
  return {
697
844
  id,
698
845
  name: id,
699
846
  reasoning: true,
700
- input: ["text"],
847
+ input: entry?.vision === false ? ["text"] : ["text", "image"],
701
848
  contextWindow: piContextWindowFor(id, entry?.maxContextTokens),
702
849
  maxTokens,
703
850
  ...entry?.cost ? { cost: entry.cost } : {},
851
+ ...thinkingLevelMap ? { thinkingLevelMap } : {},
852
+ ...inputLimits ? { inputLimits } : {},
704
853
  ...override && override !== providerApi ? { api: override } : {}
705
854
  };
706
855
  })
@@ -750,6 +899,138 @@ function derivePiCompactionSettings(catalog, modelIds) {
750
899
  };
751
900
  }
752
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
+ /**
753
1034
  * Build the per-launch `settings.json`. Additive over the snapshotted
754
1035
  * user settings (the launcher merges lists it owns): narrow model
755
1036
  * scope, fixed thinking, limited toolset, derived compaction, and the
@@ -758,6 +1039,11 @@ function derivePiCompactionSettings(catalog, modelIds) {
758
1039
  * `pi-subagents` rides `peersEnabled` and loads extensions ONLY
759
1040
  * (skills/prompts filtered out — the mode's own skills/prompts cover
760
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.
761
1047
  * The statusline footer is built into `local:gh-router-pi` (no
762
1048
  * third-party statusline package: the community bridge reads only the
763
1049
  * user's real global/project settings and never sees the launch mirror,
@@ -765,36 +1051,78 @@ function derivePiCompactionSettings(catalog, modelIds) {
765
1051
  */
766
1052
  function buildPiSettingsJson(opts) {
767
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;
768
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;
769
1064
  return {
770
1065
  defaultProvider: PI_PROVIDER_NAME,
771
1066
  defaultModel: piLeadModel(opts.profileId),
772
1067
  defaultThinkingLevel: piLeadThinking(opts.profileId),
773
1068
  enabledModels: modelIds.map((id) => `${PI_PROVIDER_NAME}/${id}`),
774
- defaultTools: [
775
- "read",
776
- "bash",
777
- "edit",
778
- "write",
779
- "grep",
780
- "find",
781
- "ls"
782
- ],
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
+ },
783
1098
  compaction: derivePiCompactionSettings(opts.catalog, modelIds),
784
1099
  retry: {
785
1100
  enabled: true,
786
- maxRetries: 3
1101
+ maxRetries: 3,
1102
+ provider: { maxRetries: 0 }
787
1103
  },
788
- packages: [...peers ? [{
789
- source: "npm:pi-subagents",
790
- skills: [],
791
- prompts: []
792
- }] : [], "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
+ ],
793
1115
  ...peers ? { subagents: { agentOverrides: {
794
1116
  scout: { disabled: true },
795
1117
  worker: { disabled: true },
796
1118
  researcher: { disabled: true },
797
- "evidence-auditor": { 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 }
798
1126
  } } } : {}
799
1127
  };
800
1128
  }
@@ -844,11 +1172,19 @@ function roleDescription(profileId, role) {
844
1172
  * is how the roster pins gh-router models/thinking for cost control.
845
1173
  * The shadowed `advisor` alias dies with the builtin oracle definition,
846
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).
847
1178
  * - `allowedAgents` only narrows an existing nesting grant, so every
848
1179
  * delegating agent also sets `allowNestedSubagents: true` and lists
849
1180
  * `subagent` in `tools`. Depth reaches 3 on balanced
850
1181
  * (lead → General-Purpose → reviewer → Explore), covered by
851
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.
852
1188
  * - Deliberately NO `output:`/`defaultReads`/`defaultProgress` file
853
1189
  * bindings: single-shot launches resolve relative outputs under
854
1190
  * per-run artifact dirs while `defaultReads` resolves against the
@@ -869,7 +1205,7 @@ function buildPiAgentFiles(profileId) {
869
1205
  for (const role of piNativeRoles(profileId)) {
870
1206
  const isImplementer = role.name === "General-Purpose";
871
1207
  const isReviewer = role.name === "reviewer";
872
- const tools = isImplementer ? "[read, grep, find, ls, bash, edit, write, subagent, contact_supervisor]" : isReviewer ? profileId === "balanced" ? "[read, grep, find, ls, watchdog_diff, contact_supervisor, subagent]" : "[read, grep, find, ls, watchdog_diff, contact_supervisor]" : "[read, grep, find, ls, bash]";
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";
873
1209
  const lines = [
874
1210
  "---",
875
1211
  `name: ${role.name}`,
@@ -878,6 +1214,7 @@ function buildPiAgentFiles(profileId) {
878
1214
  `model: ${PI_PROVIDER_NAME}/${role.model}`,
879
1215
  `thinking: ${role.thinking}`,
880
1216
  "advertise: true",
1217
+ "async: false",
881
1218
  "systemPromptMode: replace",
882
1219
  "inheritProjectContext: true",
883
1220
  "defaultContext: fresh"
@@ -895,10 +1232,11 @@ function buildPiAgentFiles(profileId) {
895
1232
  "---",
896
1233
  "name: oracle",
897
1234
  "description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.",
898
- "tools: [read, grep, find, ls, bash]",
1235
+ "tools: read, grep, find, ls, bash",
899
1236
  `model: ${PI_PROVIDER_NAME}/${piOracleModel(profileId)}`,
900
1237
  `thinking: ${piOracleThinking(profileId)}`,
901
1238
  "advertise: true",
1239
+ "async: false",
902
1240
  "systemPromptMode: replace",
903
1241
  "inheritProjectContext: true",
904
1242
  "defaultContext: fresh",
@@ -916,10 +1254,11 @@ function buildPiAgentFiles(profileId) {
916
1254
  "---",
917
1255
  "name: advisor",
918
1256
  "description: Advisory plan review for the lead: review the final plan before it is presented. Never executes.",
919
- "tools: [read, grep, find, ls]",
1257
+ "tools: read, grep, find, ls",
920
1258
  `model: ${PI_PROVIDER_NAME}/${advisor.model}`,
921
1259
  `thinking: ${advisor.thinking}`,
922
1260
  "advertise: true",
1261
+ "async: false",
923
1262
  "systemPromptMode: replace",
924
1263
  "inheritProjectContext: true",
925
1264
  "defaultContext: fresh",
@@ -934,6 +1273,32 @@ function buildPiAgentFiles(profileId) {
934
1273
  return files;
935
1274
  }
936
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
+ /**
937
1302
  * Short operating digest appended to APPEND_SYSTEM.md (prompt-cache-stable).
938
1303
  * Mode identity — always injected. Peer consult sentences drop out under
939
1304
  * `peers: false` so the digest never names tools that don't exist.
@@ -946,7 +1311,7 @@ function buildPiAppendSystem(profileId, opts = {}) {
946
1311
  "",
947
1312
  `- Lead owns planning directly; there is no Plan subagent.`
948
1313
  ];
949
- 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.`);
950
1315
  else lines.push(`- Peerless launch: no subagents or consultants in this session; plan, implement, and verify directly.`);
951
1316
  lines.push("", `(${PI_MIN_VERSION_NOTE})`, "");
952
1317
  return lines.join("\n");
@@ -1454,6 +1819,11 @@ function buildPiSkills(opts) {
1454
1819
  "into the `General-Purpose` brief to implement, `reviewer` to check,",
1455
1820
  "`General-Purpose` to apply feedback. Keep delegated tasks",
1456
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.",
1457
1827
  opts.profileId === "balanced" ? "Send work to reviewer ONLY when the change alters behavior." : "Send finished work to reviewer for assessment."
1458
1828
  ].join("\n")
1459
1829
  });
@@ -1531,12 +1901,12 @@ const piArgs = {
1531
1901
  "update-check": {
1532
1902
  type: "boolean",
1533
1903
  default: true,
1534
- 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)."
1535
1905
  },
1536
1906
  "auto-update": {
1537
1907
  type: "boolean",
1538
1908
  default: true,
1539
- 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)."
1540
1910
  },
1541
1911
  swe: {
1542
1912
  type: "boolean",
@@ -1548,6 +1918,16 @@ const piArgs = {
1548
1918
  default: true,
1549
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."
1550
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
+ },
1551
1931
  "memory-bridge": {
1552
1932
  type: "boolean",
1553
1933
  default: true,
@@ -1598,12 +1978,12 @@ function collectPiPassthroughArgs(rawArgs, argsDef) {
1598
1978
  return forwarded;
1599
1979
  }
1600
1980
  async function writeJsonFile(file, value) {
1601
- await fs.mkdir(path.dirname(file), { recursive: true });
1602
- 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 });
1603
1983
  }
1604
1984
  async function writeTextFile(file, content) {
1605
- await fs.mkdir(path.dirname(file), { recursive: true });
1606
- 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 });
1607
1987
  }
1608
1988
  const pi = defineCommand({
1609
1989
  meta: {
@@ -1626,51 +2006,76 @@ const pi = defineCommand({
1626
2006
  const profileId = launchProfileId;
1627
2007
  let server;
1628
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
+ }
1629
2029
  try {
1630
- const result = await setupAndServe({
1631
- ...parsed,
1632
- port: parsed.port,
1633
- silent: true
1634
- });
1635
- server = result.server;
1636
- 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;
1637
2045
  } catch (error) {
2046
+ pendingInstall.abort?.();
1638
2047
  consola.error("Failed to start server:", error instanceof Error ? error.message : error);
1639
2048
  process$1.exit(1);
1640
2049
  }
1641
2050
  runSelfUpdate({ selfUpdate: args["self-update"] !== false });
1642
- const updateCheck = args["update-check"] !== false;
1643
- const autoUpdate = args["auto-update"] !== false;
1644
- if (updateCheck) try {
1645
- const check = await checkPiVersion();
1646
- 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 {
1647
2062
  await updatePi("latest");
1648
- if (!(await checkPiVersion({ force: true })).installed) throw new Error("install did not place pi on PATH");
2063
+ installedVersion = await getInstalledPiVersion();
1649
2064
  } catch (err) {
1650
- 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.`);
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\`.`);
1651
2066
  process$1.exit(1);
1652
2067
  }
1653
- else if (check.needsMinUpgrade) if (autoUpdate && check.latestVersion) try {
1654
- await updatePi(check.latestVersion);
1655
- } catch (err) {
1656
- 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\`.`);
1657
- process$1.exit(1);
1658
- }
1659
- else {
1660
- 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\`.`);
1661
2070
  process$1.exit(1);
1662
2071
  }
1663
- else if (check.needsUpdate && check.latestVersion) if (autoUpdate) try {
1664
- await updatePi(check.latestVersion);
1665
- } catch (err) {
1666
- consola.warn(`Auto-update of Pi to ${check.latestVersion} failed (${err instanceof Error ? err.message : String(err)}); continuing with installed v${check.installedVersion}.`);
1667
- }
1668
- else consola.warn(`Pi v${check.installedVersion} is installed; v${check.latestVersion} is available. Run with --auto-update (the default) to install on launch.`);
1669
- } catch (err) {
1670
- consola.debug("Pi version check failed:", err);
1671
- }
2072
+ } else refreshPiInBackground({ autoUpdate });
1672
2073
  const peersEnabled = args["peers"] !== false;
1673
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();
1674
2079
  const prereqCheck = profileId === "cheapest" ? validateCheapestProfilePrerequisites(state.models, { peers: peersEnabled }) : validateBalancedProfilePrerequisites(state.models, { peers: peersEnabled });
1675
2080
  if (!prereqCheck.ok) {
1676
2081
  const message = profileId === "cheapest" ? formatCheapestPrerequisiteFailure(prereqCheck.missing) : formatBalancedPrerequisiteFailure(prereqCheck.missing);
@@ -1688,8 +2093,6 @@ const pi = defineCommand({
1688
2093
  }
1689
2094
  enableFileLogging();
1690
2095
  try {
1691
- const searchEnabled = parsed.searchEnabled || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
1692
- const browseEnabled = browserToolsEnabled();
1693
2096
  const catalog = state.models?.data.map((m) => {
1694
2097
  const cost = piUsdCostFor(m.billing?.token_prices);
1695
2098
  return {
@@ -1699,6 +2102,8 @@ const pi = defineCommand({
1699
2102
  maxOutputTokens: m.capabilities?.limits?.max_output_tokens ?? 0,
1700
2103
  efforts: m.capabilities?.supports?.reasoning_effort ?? [],
1701
2104
  endpoints: m.supported_endpoints ?? [],
2105
+ vision: m.capabilities?.supports?.vision,
2106
+ maxImageBytes: m.capabilities?.limits?.vision?.max_prompt_image_size,
1702
2107
  ...cost ? { cost } : {}
1703
2108
  };
1704
2109
  });
@@ -1711,7 +2116,7 @@ const pi = defineCommand({
1711
2116
  const settingsPath = path.join(mirror, "settings.json");
1712
2117
  let userSettings = {};
1713
2118
  try {
1714
- const raw = await fs.readFile(settingsPath, "utf8");
2119
+ const raw = await fs$1.readFile(settingsPath, "utf8");
1715
2120
  const parsedSettings = JSON.parse(raw);
1716
2121
  if (parsedSettings && typeof parsedSettings === "object") userSettings = parsedSettings;
1717
2122
  } catch {
@@ -1722,12 +2127,16 @@ const pi = defineCommand({
1722
2127
  searchEnabled,
1723
2128
  browseEnabled,
1724
2129
  catalog,
1725
- peers: peersEnabled
2130
+ peers: peersEnabled,
2131
+ helpers: helpersEnabled,
2132
+ ui: uiEnabled
1726
2133
  });
1727
2134
  const mergedSubagents = mergeSubagentsSettings(userSettings["subagents"], builtSettings.subagents);
2135
+ const cosmeticOverrides = applyCosmeticUserOverrides(userSettings, builtSettings);
1728
2136
  await writeJsonFile(settingsPath, {
1729
2137
  ...userSettings,
1730
2138
  ...builtSettings,
2139
+ ...cosmeticOverrides,
1731
2140
  ...mergedSubagents ? { subagents: mergedSubagents } : {}
1732
2141
  });
1733
2142
  const bridgeDisabled = args["memory-bridge"] === false || process$1.env.GH_ROUTER_PI_BRIDGE === "0" || process$1.env.GH_ROUTER_DISABLE_PI_BRIDGE === "1";
@@ -1784,7 +2193,7 @@ const pi = defineCommand({
1784
2193
  const agentsPath = path.join(mirror, "AGENTS.md");
1785
2194
  let existing;
1786
2195
  try {
1787
- existing = await fs.readFile(agentsPath, "utf8");
2196
+ existing = await fs$1.readFile(agentsPath, "utf8");
1788
2197
  } catch {
1789
2198
  existing = void 0;
1790
2199
  }
@@ -1842,8 +2251,23 @@ const pi = defineCommand({
1842
2251
  const extraArgs = collectPiPassthroughArgs(rawArgs, piArgs);
1843
2252
  const lead = piLeadModel(profileId);
1844
2253
  const modelIds = piProfileModelIds(profileId, { peers: peersEnabled });
1845
- const surface = [`peers=${peersEnabled ? "on" : "off"}`, `swe=${sweEnabled ? "on" : "off"}`].join(" ");
1846
- 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`);
1847
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");
1848
2272
  const { disposeBluebirdClients } = await import("./bluebird-client-bn9Yv6Cb.js");
1849
2273
  launchChild({
@@ -1871,4 +2295,4 @@ const pi = defineCommand({
1871
2295
  //#endregion
1872
2296
  export { pi };
1873
2297
 
1874
- //# sourceMappingURL=pi-CnsdJGF0.js.map
2298
+ //# sourceMappingURL=pi-C8jxbK_2.js.map