github-router 0.3.340 → 0.3.341

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 (22) hide show
  1. package/dist/{aic-statusline-settings-Chf-IT45.js → aic-statusline-settings-YoDG20pq.js} +4 -2
  2. package/dist/{aic-statusline-settings-Chf-IT45.js.map → aic-statusline-settings-YoDG20pq.js.map} +1 -1
  3. package/dist/{attribution-settings-BTfKm-RU.js → attribution-settings-DTPVRoYF.js} +2 -2
  4. package/dist/{attribution-settings-BTfKm-RU.js.map → attribution-settings-DTPVRoYF.js.map} +1 -1
  5. package/dist/browser-ext/manifest.json +1 -1
  6. package/dist/{claude-DUpp7B4X.js → claude-DaSQnZXM.js} +4 -4
  7. package/dist/{claude-DUpp7B4X.js.map → claude-DaSQnZXM.js.map} +1 -1
  8. package/dist/{codex-Xn1xsoOw.js → codex-Eq758eVC.js} +2 -2
  9. package/dist/{codex-Xn1xsoOw.js.map → codex-Eq758eVC.js.map} +1 -1
  10. package/dist/{internal-aic-status-DV2ATIRT.js → internal-aic-status-BmXhfpTS.js} +5 -2
  11. package/dist/{internal-aic-status-DV2ATIRT.js.map → internal-aic-status-BmXhfpTS.js.map} +1 -1
  12. package/dist/main.js +6 -6
  13. package/dist/{pi-DwfSuefC.js → pi-BNvhtN7g.js} +417 -24
  14. package/dist/pi-BNvhtN7g.js.map +1 -0
  15. package/dist/{serve-DWL5kmB_.js → serve-DpfttCk6.js} +3 -3
  16. package/dist/{serve-DWL5kmB_.js.map → serve-DpfttCk6.js.map} +1 -1
  17. package/dist/{server-setup-UWugox0I.js → server-setup-LYpeaZ9B.js} +2 -2
  18. package/dist/{server-setup-UWugox0I.js.map → server-setup-LYpeaZ9B.js.map} +1 -1
  19. package/dist/{start-4OTehsYq.js → start-BoHdkXba.js} +2 -2
  20. package/dist/{start-4OTehsYq.js.map → start-BoHdkXba.js.map} +1 -1
  21. package/package.json +1 -1
  22. package/dist/pi-DwfSuefC.js.map +0 -1
@@ -1,13 +1,13 @@
1
1
  import { I as withInstallLock, N as warmTreeSitterPool } from "./service-backend-7SPDLUB9.js";
2
2
  import { t as state } from "./state-CVp30CBF.js";
3
3
  import { c as runCommandVoid, o as resolveExecutable, s as runCommandCapture } from "./exec-MCU1H-KZ.js";
4
- import { E as formatBalancedPrerequisiteFailure, I as validateCheapestProfilePrerequisites, M as resolveLaunchProfile, N as validateBalancedProfilePrerequisites, a as setupAndServe, c as startKeepAwake, f as enableFileLogging, i as parseSharedArgs, j as profileDescriptor, k as formatCheapestPrerequisiteFailure, l as stopKeepAwake, o as sharedServerArgs, r as getPiLaunchEnvVars, z as runSelfUpdate } from "./server-setup-UWugox0I.js";
4
+ import { E as formatBalancedPrerequisiteFailure, I as validateCheapestProfilePrerequisites, M as resolveLaunchProfile, N as validateBalancedProfilePrerequisites, a as setupAndServe, c as startKeepAwake, f as enableFileLogging, i as parseSharedArgs, j as profileDescriptor, k as formatCheapestPrerequisiteFailure, l as stopKeepAwake, o as sharedServerArgs, r as getPiLaunchEnvVars, z as runSelfUpdate } from "./server-setup-LYpeaZ9B.js";
5
5
  import { a as BALANCED_PROFILE_NATIVE_EFFORTS, c as BALANCED_PROFILE_ORACLE_MODEL, r as BALANCED_PROFILE_MODELS, s as BALANCED_PROFILE_ORACLE_EFFORT } from "./balanced-profile-contract-C6AgFJNp.js";
6
6
  import { D as toolbeltEnabled, Gt as registerLaunch, In as CHEAPEST_PROFILE_NATIVE_EFFORTS, Kt as unregisterLaunch, Mn as CHEAPEST_PROFILE_ADVISOR_EFFORT, Nn as CHEAPEST_PROFILE_ADVISOR_MODEL, Pn as CHEAPEST_PROFILE_MODELS, Rn as CHEAPEST_PROFILE_ORACLE_EFFORT, an as provisionAndIndexColbert, ft as browserToolsEnabled, in as colbertDegradedWarning, nn as provisionBrowserAssets, zn as CHEAPEST_PROFILE_ORACLE_MODEL } from "./peer-mcp-personas-Dt0VRKYz.js";
7
7
  import { r as resolveSelfInvocation } from "./self-invocation-DIUyoRgL.js";
8
8
  import { i as launchChild, t as provisionToolbelt } from "./provision-D_aHUCXt.js";
9
9
  import { d as sweepStaleAicLedgerFiles, t as aicLedgerPath } from "./aic-ledger-D4fmThbS.js";
10
- import { i as injectAicStatusLineIntoSettingsFile, n as AIC_USER_STATUSLINE_ENV, r as buildAicStatusHookCommand, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-Chf-IT45.js";
10
+ import { i as buildAicStatusHookCommand, n as AIC_STATUSLINE_DISABLE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-YoDG20pq.js";
11
11
  import { defineCommand } from "citty";
12
12
  import consola from "consola";
13
13
  import path from "node:path";
@@ -279,6 +279,174 @@ function warnOnTierPriceDriftForModels(models) {
279
279
  warnOnTierPriceDrift(liveInputPer1M(models));
280
280
  }
281
281
  //#endregion
282
+ //#region src/lib/pi-statusline.ts
283
+ /**
284
+ * Pi footer statusline: Claude-shaped payload builder + launch constants.
285
+ *
286
+ * `github-router pi` does NOT use the community `npm:pi-statusline` bridge
287
+ * (verified live against v0.0.2: it reads `statusLine` from the user's real
288
+ * `~/.pi/agent/settings.json` / project `.pi/settings.json` and never sees
289
+ * the router-owned mirror behind `PI_CODING_AGENT_DIR`, so a mirror-injected
290
+ * block is dead config; its payload also hardcodes
291
+ * `cost.total_lines_*` to null and derives `used_percentage` from the
292
+ * latest turn only). Instead the mode's own `local:gh-router-pi` extension
293
+ * (see `src/lib/pi-extension.ts`) builds this payload natively from the Pi
294
+ * extension context and spawns the SAME `internal-aic-status` runner Claude
295
+ * uses — one renderer, byte-identical segments.
296
+ *
297
+ * `buildPiStatusPayload` is intentionally dependency-free (no imports, no
298
+ * module-scope references — every helper is nested inside): the generated
299
+ * extension embeds its source via `Function.prototype.toString()`, and a
300
+ * drift test pins that the embedded copy equals this function exactly.
301
+ */
302
+ const PI_STATUS_COMMAND_ENV = "GH_ROUTER_AIC_STATUS_COMMAND";
303
+ /** Hard cap for one runner invocation; a hung script must never wedge the footer. */
304
+ const PI_STATUSLINE_TIMEOUT_MS = 5e3;
305
+ function buildPiStatusPayload(source, opts) {
306
+ function asRecord(value) {
307
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
308
+ return {};
309
+ }
310
+ function finiteNumber(value) {
311
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
312
+ }
313
+ function nonNegativeInt(value) {
314
+ const n = finiteNumber(value);
315
+ if (n === void 0 || n < 0) return void 0;
316
+ return Math.floor(n);
317
+ }
318
+ function nonEmptyString(value) {
319
+ return typeof value === "string" && value.length > 0 ? value : void 0;
320
+ }
321
+ function timestampMs(value) {
322
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return value < 0xe8d4a51000 ? Math.floor(value * 1e3) : Math.floor(value);
323
+ if (typeof value === "string" && value.length > 0) {
324
+ const parsed = Date.parse(value);
325
+ return Number.isFinite(parsed) ? parsed : void 0;
326
+ }
327
+ }
328
+ const src = asRecord(source);
329
+ const cwd = nonEmptyString(src.cwd) ?? "";
330
+ const sessionId = nonEmptyString(src.sessionId) ?? null;
331
+ const model = asRecord(src.model);
332
+ const modelId = nonEmptyString(model.id) ?? null;
333
+ const displayName = nonEmptyString(model.displayName) ?? nonEmptyString(model.name) ?? modelId;
334
+ const usage = asRecord(src.contextUsage);
335
+ const usedPct = finiteNumber(usage.percent);
336
+ const windowSize = nonNegativeInt(usage.contextWindow) ?? nonNegativeInt(model.contextWindow) ?? null;
337
+ const rawEntries = Array.isArray(src.entries) ? src.entries : [];
338
+ let totalIn = 0;
339
+ let totalOut = 0;
340
+ let seenUsage = false;
341
+ let linesAdded = 0;
342
+ let linesRemoved = 0;
343
+ let latestInput = null;
344
+ let latestOutput = null;
345
+ let latestCacheWrite = null;
346
+ let latestCacheRead = null;
347
+ let firstTs;
348
+ let lastTs;
349
+ function noteTimestamp(value) {
350
+ const ms = timestampMs(value);
351
+ if (ms === void 0) return;
352
+ if (firstTs === void 0 || ms < firstTs) firstTs = ms;
353
+ if (lastTs === void 0 || ms > lastTs) lastTs = ms;
354
+ }
355
+ function addLines(details) {
356
+ const record = asRecord(details);
357
+ if (Object.keys(record).length === 0) return;
358
+ const added = finiteNumber(record.linesAdded);
359
+ const removed = finiteNumber(record.linesRemoved);
360
+ if (added !== void 0 && added >= 0) linesAdded += Math.floor(added);
361
+ if (removed !== void 0 && removed >= 0) linesRemoved += Math.floor(removed);
362
+ for (const key of [
363
+ "details",
364
+ "result",
365
+ "data"
366
+ ]) {
367
+ const nested = asRecord(record[key]);
368
+ if (Object.keys(nested).length === 0) continue;
369
+ const nestedAdded = finiteNumber(nested.linesAdded);
370
+ const nestedRemoved = finiteNumber(nested.linesRemoved);
371
+ if (!(added !== void 0 || removed !== void 0)) {
372
+ if (nestedAdded !== void 0 && nestedAdded >= 0) linesAdded += Math.floor(nestedAdded);
373
+ if (nestedRemoved !== void 0 && nestedRemoved >= 0) linesRemoved += Math.floor(nestedRemoved);
374
+ }
375
+ }
376
+ }
377
+ for (const entry of rawEntries) {
378
+ const record = asRecord(entry);
379
+ if (record.type !== "message") continue;
380
+ const message = asRecord(record.message);
381
+ noteTimestamp(record.timestamp);
382
+ noteTimestamp(message.timestamp);
383
+ if (message.role === "assistant") {
384
+ if (message.stopReason === "aborted" || message.stopReason === "error") continue;
385
+ const entryUsage = asRecord(message.usage);
386
+ const input = nonNegativeInt(entryUsage.input);
387
+ const output = nonNegativeInt(entryUsage.output);
388
+ if (input !== void 0) {
389
+ totalIn += input;
390
+ seenUsage = true;
391
+ }
392
+ if (output !== void 0) {
393
+ totalOut += output;
394
+ seenUsage = true;
395
+ }
396
+ latestInput = input ?? latestInput;
397
+ latestOutput = output ?? latestOutput;
398
+ const cacheWrite = nonNegativeInt(entryUsage.cacheWrite);
399
+ const cacheRead = nonNegativeInt(entryUsage.cacheRead);
400
+ if (cacheWrite !== void 0) latestCacheWrite = cacheWrite;
401
+ if (cacheRead !== void 0) latestCacheRead = cacheRead;
402
+ } else if (message.role === "toolResult") addLines(message.details);
403
+ }
404
+ let durationMs = null;
405
+ const startMs = finiteNumber(opts.sessionStartMs);
406
+ if (startMs !== void 0 && startMs > 0) durationMs = Math.max(0, Math.floor(opts.nowMs - startMs));
407
+ else if (firstTs !== void 0 && lastTs !== void 0) durationMs = Math.max(0, lastTs - firstTs);
408
+ return {
409
+ cwd,
410
+ session_id: sessionId,
411
+ transcript_path: null,
412
+ model: {
413
+ id: modelId,
414
+ display_name: displayName
415
+ },
416
+ workspace: {
417
+ current_dir: cwd,
418
+ project_dir: cwd
419
+ },
420
+ version: null,
421
+ output_style: { name: "default" },
422
+ cost: {
423
+ total_cost_usd: null,
424
+ total_duration_ms: durationMs,
425
+ total_api_duration_ms: null,
426
+ total_lines_added: linesAdded,
427
+ total_lines_removed: linesRemoved
428
+ },
429
+ context_window: {
430
+ total_input_tokens: seenUsage ? totalIn : null,
431
+ total_output_tokens: seenUsage ? totalOut : null,
432
+ context_window_size: windowSize,
433
+ used_percentage: usedPct !== void 0 ? Math.max(0, Math.round(usedPct)) : null,
434
+ remaining_percentage: usedPct !== void 0 ? Math.max(0, 100 - Math.round(usedPct)) : null,
435
+ current_usage: latestInput !== null || latestOutput !== null ? {
436
+ input_tokens: latestInput,
437
+ output_tokens: latestOutput,
438
+ cache_creation_input_tokens: latestCacheWrite,
439
+ cache_read_input_tokens: latestCacheRead
440
+ } : null
441
+ },
442
+ exceeds_200k_tokens: false,
443
+ rate_limits: null,
444
+ vim: null,
445
+ agent: null,
446
+ worktree: null
447
+ };
448
+ }
449
+ //#endregion
282
450
  //#region src/lib/pi-paths.ts
283
451
  function appDir() {
284
452
  return path.join(os.homedir(), ".local", "share", "github-router");
@@ -588,7 +756,10 @@ function derivePiCompactionSettings(catalog, modelIds) {
588
756
  * `pi-subagents` rides `peersEnabled` and loads extensions ONLY
589
757
  * (skills/prompts filtered out — the mode's own skills/prompts cover
590
758
  * the roster, so the third-party sets never reach Ctrl+O).
591
- * `pi-statusline` is extension-only by manifest and always present.
759
+ * The statusline footer is built into `local:gh-router-pi` (no
760
+ * third-party statusline package: the community bridge reads only the
761
+ * user's real global/project settings and never sees the launch mirror,
762
+ * so it cannot drive a per-launch footer).
592
763
  */
593
764
  function buildPiSettingsJson(opts) {
594
765
  const peers = opts.peers !== false;
@@ -612,15 +783,11 @@ function buildPiSettingsJson(opts) {
612
783
  enabled: true,
613
784
  maxRetries: 3
614
785
  },
615
- packages: [
616
- ...peers ? [{
617
- source: "npm:pi-subagents",
618
- skills: [],
619
- prompts: []
620
- }] : [],
621
- "npm:pi-statusline",
622
- "local:gh-router-pi"
623
- ]
786
+ packages: [...peers ? [{
787
+ source: "npm:pi-subagents",
788
+ skills: [],
789
+ prompts: []
790
+ }] : [], "local:gh-router-pi"]
624
791
  };
625
792
  }
626
793
  function agentFileName(name) {
@@ -727,14 +894,244 @@ function buildPiAppendSystem(profileId, opts = {}) {
727
894
  * Claude hooks use), then return the text. No custom provider, no
728
895
  * compaction replacement: `session_before_compact` only routes the
729
896
  * summary model and always falls back to Pi native on failure.
897
+ *
898
+ * Statusline footer (always on): this extension owns Pi's footer and
899
+ * renders the SAME `internal-aic-status` runner Claude Code uses, fed a
900
+ * natively-built Claude-shaped payload — one renderer, identical
901
+ * segments. There is deliberately no third-party statusline package and
902
+ * no `statusLine` settings block (the community bridge only reads the
903
+ * user's real global/project settings, never the launch mirror).
730
904
  */
905
+ /**
906
+ * Statusline footer section for the generated extension. Owns Pi's footer
907
+ * and renders the shared `internal-aic-status` runner (the same binary
908
+ * Claude Code invokes) with a natively-built Claude-shaped payload, so Pi
909
+ * shows byte-identical segments: `[AIC x.xx]` pinned ahead of the rich
910
+ * session line.
911
+ *
912
+ * Fail-open everywhere: disabled via `GH_ROUTER_DISABLE_AIC_STATUSLINE=1`
913
+ * or a missing command env (the launcher always sets it — see `src/pi.ts`);
914
+ * every Pi API access is guarded (extension APIs drift across Pi versions);
915
+ * a hung runner is killed at `PI_STATUSLINE_TIMEOUT_MS`; any error clears
916
+ * back to Pi's native footer, never a broken session.
917
+ *
918
+ * Width: the runner drops segments right-to-left from `COLUMNS`; the last
919
+ * footer width is fed back into the next spawn, and `render()` truncates
920
+ * ANSI-aware as a backstop (same two-layer approach as the retired bridge).
921
+ */
922
+ function buildPiStatuslineFooterSection() {
923
+ return [
924
+ ` // Statusline footer: [AIC x.xx] + rich session line, identical to github-router claude.`,
925
+ ` {`,
926
+ ` const STATUS_COMMAND = (process.env.${PI_STATUS_COMMAND_ENV} ?? "").trim();`,
927
+ ` const STATUS_DISABLED = process.env.${AIC_STATUSLINE_DISABLE_ENV} === "1";`,
928
+ ` if (STATUS_COMMAND && !STATUS_DISABLED) {`,
929
+ ` const buildPayload = (${buildPiStatusPayload.toString()});`,
930
+ ` const DEBOUNCE_MS = 300;`,
931
+ ` const TIMEOUT_MS = ${PI_STATUSLINE_TIMEOUT_MS};`,
932
+ ` let sessionStartMs = 0;`,
933
+ ` let lastSessionId = null;`,
934
+ ` let lastWidth = 120;`,
935
+ ` let lines: Array<string> = [];`,
936
+ ` let lastApplied = "\\0none";`,
937
+ ` let timer: ReturnType<typeof setTimeout> | null = null;`,
938
+ ` let controller: AbortController | null = null;`,
939
+ ``,
940
+ ` function truncateVisible(line: string, maxWidth: number): string {`,
941
+ ` if (!(maxWidth > 0)) return line;`,
942
+ ` let output = "";`,
943
+ ` let width = 0;`,
944
+ ` let i = 0;`,
945
+ ` while (i < line.length) {`,
946
+ ` const ch = line[i];`,
947
+ ` if (ch === "\\u001b") {`,
948
+ ` let j = i + 1;`,
949
+ ` const next = line[j];`,
950
+ ` if (next === "[") {`,
951
+ ` j++;`,
952
+ ` while (j < line.length) {`,
953
+ ` const code = line.charCodeAt(j);`,
954
+ ` if (code >= 64 && code <= 126) { j++; break; }`,
955
+ ` j++;`,
956
+ ` }`,
957
+ ` } else if (next === "]") {`,
958
+ ` j++;`,
959
+ ` while (j < line.length) {`,
960
+ ` if (line[j] === "\\u0007") { j++; break; }`,
961
+ ` if (line[j] === "\\u001b" && line[j + 1] === "\\\\") { j += 2; break; }`,
962
+ ` j++;`,
963
+ ` }`,
964
+ ` } else {`,
965
+ ` j = Math.min(line.length, i + 2);`,
966
+ ` }`,
967
+ ` output += line.slice(i, j);`,
968
+ ` i = j;`,
969
+ ` continue;`,
970
+ ` }`,
971
+ ` if (width >= maxWidth) return output;`,
972
+ ` output += ch;`,
973
+ ` width++;`,
974
+ ` i++;`,
975
+ ` }`,
976
+ ` return output;`,
977
+ ` }`,
978
+ ``,
979
+ ` function runStatusCommand(command: string, input: string, cwd: string, signal: AbortSignal | undefined): Promise<string> {`,
980
+ ` return new Promise((resolve) => {`,
981
+ ` let child: ReturnType<typeof spawn> | undefined;`,
982
+ ` try {`,
983
+ ` child = spawn(command, { cwd, shell: true, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, COLUMNS: String(lastWidth) } });`,
984
+ ` } catch { resolve(""); return; }`,
985
+ ` let stdout = "";`,
986
+ ` let done = false;`,
987
+ ` let timeout: ReturnType<typeof setTimeout> | null = null;`,
988
+ ` const finish = (value: string): void => {`,
989
+ ` if (done) return;`,
990
+ ` done = true;`,
991
+ ` if (timeout) clearTimeout(timeout);`,
992
+ ` try { signal?.removeEventListener("abort", onAbort); } catch {}`,
993
+ ` resolve(value);`,
994
+ ` };`,
995
+ ` const onAbort = (): void => {`,
996
+ ` try { child?.kill("SIGTERM"); } catch {}`,
997
+ ` finish("");`,
998
+ ` };`,
999
+ ` if (signal) {`,
1000
+ ` if (signal.aborted) { onAbort(); return; }`,
1001
+ ` try { signal.addEventListener("abort", onAbort, { once: true }); } catch {}`,
1002
+ ` }`,
1003
+ ` timeout = setTimeout(() => {`,
1004
+ ` try { child?.kill("SIGTERM"); } catch {}`,
1005
+ ` finish("");`,
1006
+ ` }, TIMEOUT_MS);`,
1007
+ ` child.stdout.on("data", (chunk) => { stdout += String(chunk); });`,
1008
+ ` child.on("error", () => finish(""))`,
1009
+ ` child.on("close", (code) => {`,
1010
+ ` if (code !== 0) { finish(""); return; }`,
1011
+ ` finish(stdout.replace(/\\r\\n/g, "\\n").trim());`,
1012
+ ` });`,
1013
+ ` try { child.stdin.write(input); child.stdin.end(); } catch { finish(""); }`,
1014
+ ` });`,
1015
+ ` }`,
1016
+ ``,
1017
+ ` function applyFooter(ctx: any): void {`,
1018
+ ` const key = lines.join("\\0");`,
1019
+ ` if (key === lastApplied) return;`,
1020
+ ` lastApplied = key;`,
1021
+ ` try {`,
1022
+ ` if (lines.length === 0) { ctx.ui.setFooter(undefined); return; }`,
1023
+ ` const frozen = [...lines];`,
1024
+ ` ctx.ui.setFooter((_tui: any, _theme: any, footerData: any) => ({`,
1025
+ ` dispose() {},`,
1026
+ ` invalidate() {},`,
1027
+ ` render(width: number) {`,
1028
+ ` if (typeof width === "number" && width > 0) lastWidth = width;`,
1029
+ ` const out = frozen.map((l) => truncateVisible(l, lastWidth));`,
1030
+ ` try {`,
1031
+ ` const statuses = footerData?.getExtensionStatuses?.();`,
1032
+ ` const entries = statuses?.entries ? Array.from(statuses.entries()) : [];`,
1033
+ ` for (const pair of entries) {`,
1034
+ ` const text = String((pair as Array<unknown>)[1] ?? "").trim();`,
1035
+ ` if (text) out.push(truncateVisible(text, lastWidth));`,
1036
+ ` }`,
1037
+ ` } catch {}`,
1038
+ ` return out;`,
1039
+ ` },`,
1040
+ ` }));`,
1041
+ ` } catch {}`,
1042
+ ` }`,
1043
+ ``,
1044
+ ` async function refresh(ctx: any): Promise<void> {`,
1045
+ ` try {`,
1046
+ ` if (!ctx || !ctx.hasUI) return;`,
1047
+ ` } catch { return; }`,
1048
+ ` let entries: Array<unknown> = [];`,
1049
+ ` let modelInfo: Record<string, unknown> = {};`,
1050
+ ` let usageInfo: Record<string, unknown> | null = null;`,
1051
+ ` let sessionId: string | null = null;`,
1052
+ ` try {`,
1053
+ ` const sm = ctx.sessionManager;`,
1054
+ ` if (sm) {`,
1055
+ ` if (typeof sm.getBranch === "function") entries = sm.getBranch();`,
1056
+ ` else if (typeof sm.getEntries === "function") entries = sm.getEntries();`,
1057
+ ` if (typeof sm.getSessionId === "function") {`,
1058
+ ` const sid = sm.getSessionId();`,
1059
+ ` if (typeof sid === "string" && sid) sessionId = sid;`,
1060
+ ` }`,
1061
+ ` }`,
1062
+ ` } catch {}`,
1063
+ ` try {`,
1064
+ ` const m = ctx.model ?? {};`,
1065
+ ` modelInfo = { id: m.id, displayName: m.displayName, name: m.name, contextWindow: m.contextWindow };`,
1066
+ ` } catch {}`,
1067
+ ` try {`,
1068
+ ` if (typeof ctx.getContextUsage === "function") {`,
1069
+ ` const u = ctx.getContextUsage();`,
1070
+ ` if (u) usageInfo = { tokens: u.tokens, contextWindow: u.contextWindow, percent: u.percent };`,
1071
+ ` }`,
1072
+ ` } catch {}`,
1073
+ ` if (lastSessionId !== null && sessionId !== null && sessionId !== lastSessionId) {`,
1074
+ ` sessionStartMs = Date.now();`,
1075
+ ` lines = [];`,
1076
+ ` lastApplied = "\\0reset";`,
1077
+ ` }`,
1078
+ ` if (sessionId !== null) lastSessionId = sessionId;`,
1079
+ ` if (!sessionStartMs) sessionStartMs = Date.now();`,
1080
+ ` let payload: Record<string, unknown>;`,
1081
+ ` try {`,
1082
+ ` payload = buildPayload({ cwd: ctx.cwd, sessionId, model: modelInfo, contextUsage: usageInfo, entries }, { nowMs: Date.now(), sessionStartMs });`,
1083
+ ` } catch { return; }`,
1084
+ ` try { controller?.abort(); } catch {}`,
1085
+ ` controller = new AbortController();`,
1086
+ ` const signal = controller.signal;`,
1087
+ ` let text = "";`,
1088
+ ` try {`,
1089
+ ` text = await runStatusCommand(STATUS_COMMAND, JSON.stringify(payload), ctx.cwd, signal);`,
1090
+ ` } catch { text = ""; }`,
1091
+ ` if (signal.aborted) return;`,
1092
+ ` const first = (text.split("\\n")[0] ?? "").trim();`,
1093
+ ` lines = first ? [first] : [];`,
1094
+ ` applyFooter(ctx);`,
1095
+ ` }`,
1096
+ ``,
1097
+ ` function schedule(ctx: any): void {`,
1098
+ ` try {`,
1099
+ ` if (timer) clearTimeout(timer);`,
1100
+ ` } catch {}`,
1101
+ ` try {`,
1102
+ ` timer = setTimeout(() => { timer = null; void refresh(ctx); }, DEBOUNCE_MS);`,
1103
+ ` } catch {}`,
1104
+ ` }`,
1105
+ ``,
1106
+ ` for (const event of ["session_start", "turn_start", "turn_end", "model_select", "session_compact", "session_tree", "session_switch", "session_fork"]) {`,
1107
+ ` try {`,
1108
+ ` pi.on(event, (_event: any, ctx: any) => { schedule(ctx); });`,
1109
+ ` } catch {}`,
1110
+ ` }`,
1111
+ ` try {`,
1112
+ ` pi.on("session_shutdown", (_event: any, ctx: any) => {`,
1113
+ ` try { if (timer) clearTimeout(timer); } catch {}`,
1114
+ ` timer = null;`,
1115
+ ` try { controller?.abort(); } catch {}`,
1116
+ ` controller = null;`,
1117
+ ` lines = [];`,
1118
+ ` lastApplied = "\\0none";`,
1119
+ ` sessionStartMs = 0;`,
1120
+ ` lastSessionId = null;`,
1121
+ ` try { ctx?.ui?.setFooter(undefined); } catch {}`,
1122
+ ` });`,
1123
+ ` } catch {}`,
1124
+ ` }`,
1125
+ ` }`
1126
+ ];
1127
+ }
731
1128
  function buildPiExtensionSource(opts) {
732
1129
  const peers = opts.peers !== false;
733
1130
  const advisor = peers ? piAdvisorModel(opts.profileId) : void 0;
734
1131
  const oracleModel = piOracleModel(opts.profileId);
735
1132
  const oracleThinking = piOracleThinking(opts.profileId);
736
1133
  const lines = [];
737
- 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";`, ``, ...peers ? [
1134
+ 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 ? [
738
1135
  `const OracleParams = Type.Object({`,
739
1136
  ` decision: Type.String({ description: "The risky decision to get a second opinion on" }),`,
740
1137
  ` options: Type.Optional(Type.String({ description: "Options considered" })),`,
@@ -759,7 +1156,7 @@ function buildPiExtensionSource(opts) {
759
1156
  if (advisor) lines.push(` pi.registerTool({`, ` name: "advisor",`, ` label: "Advisor",`, ` description: "Advisory plan review for the lead: review the final plan before presenting it. Never executes.",`, ` parameters: AdvisorParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("peers", "oracle", { decision: "Review this plan (advisory)", options: params.plan, context: params.context || "", model: ADVISOR_MODEL, thinking: ADVISOR_THINKING }, signal));`, ` },`, ` });`);
760
1157
  if (opts.searchEnabled) lines.push(` pi.registerTool({`, ` name: "code_search",`, ` label: "Code search",`, ` description: "Semantic-first code search over the workspace index (falls back to lexical with a label). Use for finding code by meaning.",`, ` parameters: CodeSearchParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("search", "code", { query: params.query, mode: params.mode || "semantic", limit: params.limit || 15 }, signal));`, ` },`, ` });`);
761
1158
  if (opts.browseEnabled) lines.push(` const BROWSER_TOOLS = ["browser_open_tab", "browser_navigate", "browser_screenshot", "browser_act", "browser_observe", "browser_extract"];`, ` for (const wireName of BROWSER_TOOLS) {`, ` pi.registerTool({`, ` name: wireName,`, ` description: "Browser control (" + wireName + "). Returns install_required with setup steps when the extension is not loaded.",`, ` parameters: BrowserParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("browser", wireName, { url: params.url || "", intent: params.intent || "" }, signal));`, ` },`, ` });`, ` }`);
762
- lines.push(` // 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;`, ` }`, ` });`, `}`, ``);
1159
+ 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;`, ` }`, ` });`, `}`, ``);
763
1160
  return `${lines.join("\n")}\n`;
764
1161
  }
765
1162
  /**
@@ -1111,17 +1508,13 @@ const pi = defineCommand({
1111
1508
  consola.debug("Pi tier drift check skipped:", err);
1112
1509
  }
1113
1510
  let aicLedgerEnv;
1114
- let aicUserStatuslineEnv;
1511
+ let aicStatusCommandEnv;
1115
1512
  if (process$1.env.GH_ROUTER_DISABLE_AIC_STATUSLINE !== "1") try {
1116
1513
  sweepStaleAicLedgerFiles();
1117
1514
  const selfInvocation = await resolveSelfInvocation();
1118
- const statusCommand = buildAicStatusHookCommand(selfInvocation);
1119
- const injected = await injectAicStatusLineIntoSettingsFile(path.join(mirror, "settings.json"), statusCommand, { routerWins: true });
1120
- if (injected.written) {
1121
- aicLedgerEnv = aicLedgerPath();
1122
- if (injected.mode === "wrapped" && injected.userCommand) aicUserStatuslineEnv = injected.userCommand;
1123
- if (injected.mode === "forced") consola.info(`Pinned status line installed natively for ${profileId}; a pre-existing statusLine was backed up in this launch's isolated settings and will not run.`);
1124
- }
1515
+ aicStatusCommandEnv = buildAicStatusHookCommand(selfInvocation);
1516
+ aicLedgerEnv = aicLedgerPath();
1517
+ consola.info(`Status line wired via the gh-router-pi footer for ${profileId} (shared internal-aic-status runner).`);
1125
1518
  } catch (err) {
1126
1519
  consola.warn(`AIC status line skipped: ${err instanceof Error ? err.message : String(err)}.`);
1127
1520
  }
@@ -1156,7 +1549,7 @@ const pi = defineCommand({
1156
1549
  GH_ROUTER_HOOK_MCP_URL: serverUrl,
1157
1550
  GH_ROUTER_HOOK_NONCE: nonce,
1158
1551
  ...aicLedgerEnv ? { [AIC_LEDGER_ENV]: aicLedgerEnv } : {},
1159
- ...aicUserStatuslineEnv ? { [AIC_USER_STATUSLINE_ENV]: aicUserStatuslineEnv } : {}
1552
+ ...aicStatusCommandEnv ? { [PI_STATUS_COMMAND_ENV]: aicStatusCommandEnv } : {}
1160
1553
  },
1161
1554
  extraArgs,
1162
1555
  model: lead,
@@ -1172,4 +1565,4 @@ const pi = defineCommand({
1172
1565
  //#endregion
1173
1566
  export { pi };
1174
1567
 
1175
- //# sourceMappingURL=pi-DwfSuefC.js.map
1568
+ //# sourceMappingURL=pi-BNvhtN7g.js.map