github-router 0.3.331 → 0.3.332
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.
- package/README.md +4 -2
- package/dist/{aic-ledger-CsBx1crE.js → aic-ledger-D4fmThbS.js} +2 -2
- package/dist/{aic-ledger-CsBx1crE.js.map → aic-ledger-D4fmThbS.js.map} +1 -1
- package/dist/{attribution-settings-7dFpObGh.js → attribution-settings-BeO1w_DL.js} +62 -51
- package/dist/attribution-settings-BeO1w_DL.js.map +1 -0
- package/dist/{auth-xgFZGZbf.js → auth-DjKEIiqG.js} +4 -4
- package/dist/{auth-xgFZGZbf.js.map → auth-DjKEIiqG.js.map} +1 -1
- package/dist/bluebird-client-DpYl1YmJ.js +1163 -0
- package/dist/bluebird-client-DpYl1YmJ.js.map +1 -0
- package/dist/bluebird-client-bn9Yv6Cb.js +2 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-vUDk6oV7.js → check-usage-B7UrDwD8.js} +4 -4
- package/dist/{check-usage-vUDk6oV7.js.map → check-usage-B7UrDwD8.js.map} +1 -1
- package/dist/{claude-C3-yBGzw.js → claude-BQQPdXLb.js} +37 -29
- package/dist/claude-BQQPdXLb.js.map +1 -0
- package/dist/{codex-C3hcVSOm.js → codex-fW-hbxtT.js} +12 -8
- package/dist/codex-fW-hbxtT.js.map +1 -0
- package/dist/{copilot-discount-0lG67i9O.js → copilot-discount-BcUa3f-k.js} +2 -2
- package/dist/{copilot-discount-0lG67i9O.js.map → copilot-discount-BcUa3f-k.js.map} +1 -1
- package/dist/{debug-a737qcCC.js → debug-CigFsS-h.js} +2 -2
- package/dist/{debug-a737qcCC.js.map → debug-CigFsS-h.js.map} +1 -1
- package/dist/engine-E4WJGSeg.js +2 -0
- package/dist/{exec-COUT4QsS.js → exec-MCU1H-KZ.js} +63 -13
- package/dist/exec-MCU1H-KZ.js.map +1 -0
- package/dist/{gate-discovery-BUhtwkyE.js → gate-discovery-DbwVeERm.js} +6 -6
- package/dist/{gate-discovery-BUhtwkyE.js.map → gate-discovery-DbwVeERm.js.map} +1 -1
- package/dist/{get-copilot-usage-VKU2IvuE.js → get-copilot-usage-CGaV01dC.js} +4 -3
- package/dist/{get-copilot-usage-VKU2IvuE.js.map → get-copilot-usage-CGaV01dC.js.map} +1 -1
- package/dist/hooks.mjs +90 -27
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-k3oWl0n4.js → index-cmd-DXYWgKS6.js} +5 -5
- package/dist/{index-cmd-k3oWl0n4.js.map → index-cmd-DXYWgKS6.js.map} +1 -1
- package/dist/{internal-aic-status-Cfl5HiAN.js → internal-aic-status-Bma0r0ZS.js} +6 -5
- package/dist/internal-aic-status-Bma0r0ZS.js.map +1 -0
- package/dist/{internal-artifact-open-CX2fRP_D.js → internal-artifact-open-lta2UPnE.js} +2 -2
- package/dist/{internal-artifact-open-CX2fRP_D.js.map → internal-artifact-open-lta2UPnE.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-Cxattkm4.js → internal-fast-dispatch-guard-DPR16qUE.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js → internal-fast-dispatch-guard-DoXO3X7P.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js.map → internal-fast-dispatch-guard-DoXO3X7P.js.map} +1 -1
- package/dist/{internal-first-mate-guard-D_JFcrl_.js → internal-first-mate-guard-BEwDjHfX.js} +3 -3
- package/dist/{internal-first-mate-guard-D_JFcrl_.js.map → internal-first-mate-guard-BEwDjHfX.js.map} +1 -1
- package/dist/{internal-first-mate-guard-97qsseTP.js → internal-first-mate-guard-CAefr6Ce.js} +1 -1
- package/dist/{internal-max-dispatch-guard-DQMyOds8.js → internal-max-dispatch-guard-6ZCEanI6.js} +1 -1
- package/dist/{internal-max-dispatch-guard-Cxe8h12x.js → internal-max-dispatch-guard-CtIO7pm1.js} +3 -3
- package/dist/{internal-max-dispatch-guard-Cxe8h12x.js.map → internal-max-dispatch-guard-CtIO7pm1.js.map} +1 -1
- package/dist/{internal-plan-review-O2dwnQv3.js → internal-plan-review-jIts3KYd.js} +3 -3
- package/dist/{internal-plan-review-O2dwnQv3.js.map → internal-plan-review-jIts3KYd.js.map} +1 -1
- package/dist/{internal-prompt-submit-CD0UFkT-.js → internal-prompt-submit-BfoWVyzs.js} +10 -7
- package/dist/internal-prompt-submit-BfoWVyzs.js.map +1 -0
- package/dist/{internal-session-bind-CHIOd5ys.js → internal-session-bind-IpZ5hJzR.js} +2 -2
- package/dist/{internal-session-bind-CHIOd5ys.js.map → internal-session-bind-IpZ5hJzR.js.map} +1 -1
- package/dist/{internal-stop-hook-DBrlosd0.js → internal-stop-hook-DO8RKfKB.js} +6 -6
- package/dist/{internal-stop-hook-DBrlosd0.js.map → internal-stop-hook-DO8RKfKB.js.map} +1 -1
- package/dist/{internal-stop-review-a3rpzzhd.js → internal-stop-review-BtGDVrv-.js} +2 -2
- package/dist/{internal-stop-review-a3rpzzhd.js.map → internal-stop-review-BtGDVrv-.js.map} +1 -1
- package/dist/{internal-worker-guard-BY5seBqp.js → internal-worker-guard-C0FJ4b29.js} +2 -2
- package/dist/{internal-worker-guard-BY5seBqp.js.map → internal-worker-guard-C0FJ4b29.js.map} +1 -1
- package/dist/{internal-workspace-header-CPZNphnk.js → internal-workspace-header-tvJVAXpv.js} +2 -2
- package/dist/{internal-workspace-header-CPZNphnk.js.map → internal-workspace-header-tvJVAXpv.js.map} +1 -1
- package/dist/{lifecycle-D8vQXfeC.js → lifecycle-BqWTXaeC.js} +3 -3
- package/dist/{lifecycle-D8vQXfeC.js.map → lifecycle-BqWTXaeC.js.map} +1 -1
- package/dist/lifecycle-DMRZswwc.js +2 -0
- package/dist/lifecycle-FT75ohVw.js +2 -0
- package/dist/{lifecycle-MmpJWRcl.js → lifecycle-kpLzHUgD.js} +2 -2
- package/dist/{lifecycle-MmpJWRcl.js.map → lifecycle-kpLzHUgD.js.map} +1 -1
- package/dist/main.js +21 -21
- package/dist/{max-profile-contract-Bl7I_EOC.js → max-profile-contract-MJJt0zm-.js} +2 -2
- package/dist/{max-profile-contract-Bl7I_EOC.js.map → max-profile-contract-MJJt0zm-.js.map} +1 -1
- package/dist/{mcp-workspace-header-DX_mD0JT.js → mcp-workspace-header-B77WqVFw.js} +2 -2
- package/dist/{mcp-workspace-header-DX_mD0JT.js.map → mcp-workspace-header-B77WqVFw.js.map} +1 -1
- package/dist/{models-BjCRO0AC.js → models-68HDOEPK.js} +3 -3
- package/dist/{models-BjCRO0AC.js.map → models-68HDOEPK.js.map} +1 -1
- package/dist/{orchestration-Dn5v8c0a.js → orchestration-Ccmfslh4.js} +3 -3
- package/dist/{orchestration-Dn5v8c0a.js.map → orchestration-Ccmfslh4.js.map} +1 -1
- package/dist/{paths-P5ajjpzU.js → paths-CpbTHKeP.js} +3 -3
- package/dist/{paths-P5ajjpzU.js.map → paths-CpbTHKeP.js.map} +1 -1
- package/dist/paths-Dfivvq21.js +2 -0
- package/dist/{peer-mcp-personas-Dztywua2.js → peer-mcp-personas-CeB2Kcn2.js} +184 -76
- package/dist/peer-mcp-personas-CeB2Kcn2.js.map +1 -0
- package/dist/{plan-review-hook-CfZBvsHd.js → plan-review-hook-ciat1jgZ.js} +4 -4
- package/dist/{plan-review-hook-CfZBvsHd.js.map → plan-review-hook-ciat1jgZ.js.map} +1 -1
- package/dist/{prompt-submit-hook-CRH6m7Vz.js → prompt-submit-hook-C8q_hDOv.js} +21 -17
- package/dist/prompt-submit-hook-C8q_hDOv.js.map +1 -0
- package/dist/{provision-CjBt5wEK.js → provision-DZLsyRYh.js} +7 -6
- package/dist/provision-DZLsyRYh.js.map +1 -0
- package/dist/{self-invocation-DBWyjvGm.js → self-invocation-DIUyoRgL.js} +2 -2
- package/dist/{self-invocation-DBWyjvGm.js.map → self-invocation-DIUyoRgL.js.map} +1 -1
- package/dist/{serve-C3LCkM-o.js → serve-ik_96Q2Z.js} +33 -21
- package/dist/serve-ik_96Q2Z.js.map +1 -0
- package/dist/{server-setup-DrSUlFZ_.js → server-setup-CK3O_Hwf.js} +37 -13
- package/dist/{server-setup-DrSUlFZ_.js.map → server-setup-CK3O_Hwf.js.map} +1 -1
- package/dist/{service-backend-ByT0gUc8.js → service-backend-7SPDLUB9.js} +7 -7
- package/dist/service-backend-7SPDLUB9.js.map +1 -0
- package/dist/{start-CY1nnbB4.js → start-DPOJJSvp.js} +4 -4
- package/dist/{start-CY1nnbB4.js.map → start-DPOJJSvp.js.map} +1 -1
- package/dist/{state-BlMpEFAt.js → state-CVp30CBF.js} +7 -1
- package/dist/state-CVp30CBF.js.map +1 -0
- package/dist/{stop-gate-hook-BACb8dlj.js → stop-gate-hook-DZVfKoSh.js} +4 -4
- package/dist/{stop-gate-hook-BACb8dlj.js.map → stop-gate-hook-DZVfKoSh.js.map} +1 -1
- package/dist/{stop-gate-policy-D6jIeOXB.js → stop-gate-policy-Gd_cNT9-.js} +3 -3
- package/dist/{stop-gate-policy-D6jIeOXB.js.map → stop-gate-policy-Gd_cNT9-.js.map} +1 -1
- package/dist/{token-Dlb_84hW.js → token-DATA_OQK.js} +5 -383
- package/dist/token-DATA_OQK.js.map +1 -0
- package/dist/upstream-retry-i1k1Xai2.js +383 -0
- package/dist/upstream-retry-i1k1Xai2.js.map +1 -0
- package/dist/{worker-dispatch-DtjQchvM.js → worker-dispatch-lRhno09M.js} +2 -2
- package/dist/{worker-dispatch-DtjQchvM.js.map → worker-dispatch-lRhno09M.js.map} +1 -1
- package/docs/bluebird-search.md +338 -0
- package/package.json +3 -2
- package/dist/attribution-settings-7dFpObGh.js.map +0 -1
- package/dist/claude-C3-yBGzw.js.map +0 -1
- package/dist/codex-C3hcVSOm.js.map +0 -1
- package/dist/engine-CPdWX70n.js +0 -2
- package/dist/exec-COUT4QsS.js.map +0 -1
- package/dist/internal-aic-status-Cfl5HiAN.js.map +0 -1
- package/dist/internal-prompt-submit-CD0UFkT-.js.map +0 -1
- package/dist/lifecycle-B2eB8nRg.js +0 -2
- package/dist/lifecycle-Dz-Rq8pD.js +0 -2
- package/dist/paths-DVXBtLyo.js +0 -2
- package/dist/peer-mcp-personas-Dztywua2.js.map +0 -1
- package/dist/prompt-submit-hook-CRH6m7Vz.js.map +0 -1
- package/dist/provision-CjBt5wEK.js.map +0 -1
- package/dist/serve-C3LCkM-o.js.map +0 -1
- package/dist/service-backend-ByT0gUc8.js.map +0 -1
- package/dist/state-BlMpEFAt.js.map +0 -1
- package/dist/token-Dlb_84hW.js.map +0 -1
package/dist/hooks.mjs
CHANGED
|
@@ -2486,8 +2486,11 @@ var init_version = __esmMin((() => {
|
|
|
2486
2486
|
* Why this module exists: on Windows, npm-installed CLIs (`claude`,
|
|
2487
2487
|
* `npm`, `codex`) are `.cmd`/`.bat` shims. Node's `execFile`/`spawn`
|
|
2488
2488
|
* with `shell:false` cannot launch them (CreateProcess only resolves
|
|
2489
|
-
* `.exe`), so callers must
|
|
2490
|
-
*
|
|
2489
|
+
* `.exe`), so callers must invoke `cmd.exe` explicitly. Using
|
|
2490
|
+
* `shell:true` delegates quoting back to the runtime and breaks absolute shim
|
|
2491
|
+
* paths containing spaces, so this module builds one verified `/s /c`
|
|
2492
|
+
* envelope and asks CreateProcess to pass it verbatim. That opens two hazards
|
|
2493
|
+
* this module closes:
|
|
2491
2494
|
*
|
|
2492
2495
|
* 1. **Metacharacter injection** (`& | < > ^ ( ) ! %`). A naive
|
|
2493
2496
|
* "quote only tokens with spaces" scheme lets `pkg@latest&calc`
|
|
@@ -2615,24 +2618,65 @@ function quoteWinArg(arg) {
|
|
|
2615
2618
|
}
|
|
2616
2619
|
return quoted.replace(/[()!^"<>&|]/g, "^$&");
|
|
2617
2620
|
}
|
|
2621
|
+
function assertSafeBatchToken(value, kind) {
|
|
2622
|
+
if ([...value].some((char) => char.charCodeAt(0) < 32) || value.includes("\"") || value.includes("%")) throw new Error(`buildExecInvocation: ${kind} contains a character that cannot be safely passed through cmd.exe; refusing to build the command.`);
|
|
2623
|
+
}
|
|
2624
|
+
function quoteBatchArg(arg) {
|
|
2625
|
+
assertSafeBatchToken(arg, "argument");
|
|
2626
|
+
return `"${arg.replaceAll("^", "^^").replace(/[&|<>]/g, "^$&")}"`;
|
|
2627
|
+
}
|
|
2628
|
+
function windowsCmdExe() {
|
|
2629
|
+
const systemRoot = g.env.SystemRoot ?? g.env.SYSTEMROOT;
|
|
2630
|
+
return systemRoot ? path.win32.join(systemRoot, "System32", "cmd.exe") : g.env.ComSpec ?? "cmd.exe";
|
|
2631
|
+
}
|
|
2618
2632
|
/**
|
|
2619
2633
|
* Build the platform-correct `spawn` invocation for a command given as
|
|
2620
2634
|
* an argv array. Pure / unit-testable (no spawn).
|
|
2621
2635
|
*
|
|
2622
|
-
* - win32
|
|
2623
|
-
*
|
|
2624
|
-
*
|
|
2625
|
-
*
|
|
2636
|
+
* - win32 native executables (`.exe`/`.com`) → direct spawn with split
|
|
2637
|
+
* argv. This avoids cmd.exe quoting and correctly handles absolute paths
|
|
2638
|
+
* containing spaces (for example `C:\\Program Files\\Git\\...\\git.exe`).
|
|
2639
|
+
* - win32 batch shims (`.cmd`/`.bat`) → explicit cmd.exe with `shell:false`
|
|
2640
|
+
* and one verbatim `/s /c` envelope. Every token is quoted, so shell
|
|
2641
|
+
* metacharacters are data; `%`, quotes, and controls fail closed.
|
|
2642
|
+
* - unresolved win32 bare commands retain the legacy quoted `shell:true`
|
|
2643
|
+
* path. Normal callers resolve first, so this is only a compatibility
|
|
2644
|
+
* fallback.
|
|
2626
2645
|
* - posix → `(cmd[0], cmd.slice(1))` with `shell:false` — no shell,
|
|
2627
2646
|
* no injection surface.
|
|
2628
2647
|
*/
|
|
2629
2648
|
function buildExecInvocation(cmd, platform = g.platform) {
|
|
2630
2649
|
if (cmd.length === 0) throw new Error("buildExecInvocation: empty command");
|
|
2631
|
-
if (platform === "win32")
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2650
|
+
if (platform === "win32") {
|
|
2651
|
+
const ext = path.extname(cmd[0]).toLowerCase();
|
|
2652
|
+
if (ext === ".exe" || ext === ".com") return {
|
|
2653
|
+
command: cmd[0],
|
|
2654
|
+
args: cmd.slice(1),
|
|
2655
|
+
shell: false
|
|
2656
|
+
};
|
|
2657
|
+
if (ext === ".cmd" || ext === ".bat") {
|
|
2658
|
+
if (!path.win32.isAbsolute(cmd[0])) throw new Error("buildExecInvocation: Windows batch executable must be an absolute path");
|
|
2659
|
+
assertSafeBatchToken(cmd[0], "executable");
|
|
2660
|
+
const line = `""${cmd[0]}"${cmd.slice(1).map((arg) => ` ${quoteBatchArg(arg)}`).join("")}"`;
|
|
2661
|
+
return {
|
|
2662
|
+
command: windowsCmdExe(),
|
|
2663
|
+
args: [
|
|
2664
|
+
"/d",
|
|
2665
|
+
"/s",
|
|
2666
|
+
"/v:OFF",
|
|
2667
|
+
"/c",
|
|
2668
|
+
line
|
|
2669
|
+
],
|
|
2670
|
+
shell: false,
|
|
2671
|
+
windowsVerbatimArguments: true
|
|
2672
|
+
};
|
|
2673
|
+
}
|
|
2674
|
+
return {
|
|
2675
|
+
command: cmd.map(quoteWinArg).join(" "),
|
|
2676
|
+
args: [],
|
|
2677
|
+
shell: true
|
|
2678
|
+
};
|
|
2679
|
+
}
|
|
2636
2680
|
return {
|
|
2637
2681
|
command: cmd[0],
|
|
2638
2682
|
args: cmd.slice(1),
|
|
@@ -2640,7 +2684,7 @@ function buildExecInvocation(cmd, platform = g.platform) {
|
|
|
2640
2684
|
};
|
|
2641
2685
|
}
|
|
2642
2686
|
function runInternal(cmd, stdoutMode, opts) {
|
|
2643
|
-
const { command, args, shell } = buildExecInvocation(cmd);
|
|
2687
|
+
const { command, args, shell, windowsVerbatimArguments } = buildExecInvocation(cmd);
|
|
2644
2688
|
return new Promise((resolve, reject) => {
|
|
2645
2689
|
let child;
|
|
2646
2690
|
try {
|
|
@@ -2648,6 +2692,7 @@ function runInternal(cmd, stdoutMode, opts) {
|
|
|
2648
2692
|
cwd: opts.cwd,
|
|
2649
2693
|
env: opts.env ?? g.env,
|
|
2650
2694
|
shell,
|
|
2695
|
+
windowsVerbatimArguments,
|
|
2651
2696
|
windowsHide: true,
|
|
2652
2697
|
stdio: [
|
|
2653
2698
|
"ignore",
|
|
@@ -2675,6 +2720,9 @@ function runInternal(cmd, stdoutMode, opts) {
|
|
|
2675
2720
|
killTree(child.pid);
|
|
2676
2721
|
}, opts.timeoutMs) : void 0;
|
|
2677
2722
|
timer?.unref?.();
|
|
2723
|
+
const onAbort = () => killTree(child.pid);
|
|
2724
|
+
if (opts.signal?.aborted) onAbort();
|
|
2725
|
+
else opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
2678
2726
|
child.stdout?.on("data", (c) => {
|
|
2679
2727
|
if (truncated) return;
|
|
2680
2728
|
const room = maxStdoutBytes - stdoutBytes;
|
|
@@ -2706,6 +2754,7 @@ function runInternal(cmd, stdoutMode, opts) {
|
|
|
2706
2754
|
if (settled) return;
|
|
2707
2755
|
settled = true;
|
|
2708
2756
|
if (timer) clearTimeout(timer);
|
|
2757
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
2709
2758
|
if (!truncated) stdout += stdoutDecoder.decode();
|
|
2710
2759
|
if (!stderrTruncated) stderr += stderrDecoder.decode();
|
|
2711
2760
|
resolve({
|
|
@@ -2721,6 +2770,7 @@ function runInternal(cmd, stdoutMode, opts) {
|
|
|
2721
2770
|
if (settled) return;
|
|
2722
2771
|
settled = true;
|
|
2723
2772
|
if (timer) clearTimeout(timer);
|
|
2773
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
2724
2774
|
reject(err);
|
|
2725
2775
|
});
|
|
2726
2776
|
child.on("close", (code) => finish(code));
|
|
@@ -10937,6 +10987,12 @@ var init_state = __esmMin((() => {
|
|
|
10937
10987
|
agentsEnabled: false,
|
|
10938
10988
|
powerBrowseEnabled: false,
|
|
10939
10989
|
searchEnabled: false,
|
|
10990
|
+
bluebirdEnabled: false,
|
|
10991
|
+
bluebirdClient: null,
|
|
10992
|
+
bluebirdOrganization: null,
|
|
10993
|
+
bluebirdProject: null,
|
|
10994
|
+
bluebirdRepositories: [],
|
|
10995
|
+
bluebirdBranch: null,
|
|
10940
10996
|
humanlikeForce: "auto",
|
|
10941
10997
|
sessionId: randomUUID(),
|
|
10942
10998
|
machineId: randomBytes(32).toString("hex"),
|
|
@@ -35284,21 +35340,22 @@ function decidePromptSubmit(input) {
|
|
|
35284
35340
|
return decision;
|
|
35285
35341
|
}
|
|
35286
35342
|
/**
|
|
35287
|
-
* Build the search tip for the launch's search
|
|
35288
|
-
*
|
|
35289
|
-
*
|
|
35343
|
+
* Build the search tip for the launch's search backend. When Bluebird is
|
|
35344
|
+
* enabled it owns both semantic and lexical calls; otherwise local ColBERT is
|
|
35345
|
+
* used when enabled, or lexical-only search when neither backend is enabled.
|
|
35290
35346
|
*/
|
|
35291
|
-
function getPromptSearchTip(searchEnabled) {
|
|
35347
|
+
function getPromptSearchTip(searchEnabled, bluebirdEnabled = false) {
|
|
35348
|
+
if (bluebirdEnabled) return "TIP (advisory): when this task needs code context, search Bluebird semantic + lexical in parallel — two `mcp__search__code` calls issued in the same turn. Bluebird failures are visible and do not fall back locally.";
|
|
35292
35349
|
if (searchEnabled) return "TIP (advisory): when this task needs code context, search lexical + semantic in parallel — one `mcp__search__code` call with mode:\"lexical\" and one with mode:\"semantic\", issued in the same turn — before concluding.";
|
|
35293
35350
|
return "TIP (advisory): when this task needs code context, search lexical (`mcp__search__code` with mode:\"lexical\"/\"exact\"/\"regex\" for exact symbols, filenames, errors, routes, flags, and config keys), issuing parallel calls in the same turn — before concluding.";
|
|
35294
35351
|
}
|
|
35295
35352
|
/**
|
|
35296
|
-
* Build the scope-inference system prompt for the launch's search
|
|
35297
|
-
* Mirrors `getPromptSearchTip`:
|
|
35298
|
-
* in lexical + semantic results; the
|
|
35353
|
+
* Build the scope-inference system prompt for the launch's search backend.
|
|
35354
|
+
* Mirrors `getPromptSearchTip`: Bluebird and local ColBERT variants ground the
|
|
35355
|
+
* inference in lexical + semantic results; the local-only variant in lexical results.
|
|
35299
35356
|
*/
|
|
35300
|
-
function getPromptScopeSystem(searchEnabled) {
|
|
35301
|
-
return `You are a scoping assistant for a coding agent about to act on a user's request. You are given the user's request and the results of ${searchEnabled ? "a lexical + semantic code search" : "a lexical code search"} over the relevant repository. Produce a SHORT advisory note (<= 120 words), plain text only:
|
|
35357
|
+
function getPromptScopeSystem(searchEnabled, bluebirdEnabled = false) {
|
|
35358
|
+
return `You are a scoping assistant for a coding agent about to act on a user's request. You are given the user's request and the results of ${bluebirdEnabled ? "a Bluebird lexical + semantic code search" : searchEnabled ? "a local lexical + semantic code search" : "a lexical code search"} over the relevant repository. Produce a SHORT advisory note (<= 120 words), plain text only:
|
|
35302
35359
|
1. SCOPE: one line — is this trivial, focused (one area), or large/cross-cutting — grounded in what the search surfaced (reference the most relevant file(s) by name).
|
|
35303
35360
|
2. GOAL: restate the user's OWN ask as a single measurable objective, in THEIR terms. Do NOT invent new requirements or acceptance criteria beyond what they asked.
|
|
35304
35361
|
3. Only if the task is large/cross-cutting, add a final line: "Consider /gh-research first to saturate understanding, then /gh-orchestrate to compose a floor-raising workflow." Omit it for a focused or trivial task.
|
|
@@ -35321,8 +35378,9 @@ function joinSections(sections) {
|
|
|
35321
35378
|
* - findings -> always surfaced (+ cleared) regardless of triviality.
|
|
35322
35379
|
* - trivial prompt -> findings only (no search tip, no model call).
|
|
35323
35380
|
* - substantive prompt -> search tip + grounded enrichment (parallel
|
|
35324
|
-
* lexical+semantic when
|
|
35325
|
-
* lexical-only)
|
|
35381
|
+
* lexical+semantic through Bluebird when enabled,
|
|
35382
|
+
* otherwise local semantic when enabled, else lexical-only)
|
|
35383
|
+
* -> ONE gpt-5.6-luna call
|
|
35326
35384
|
* -> grounded scope/goal note. Fail-open to PROMPT_STEER_GOAL.
|
|
35327
35385
|
* - steerEnabled=false -> findings only (no goal/tip).
|
|
35328
35386
|
*/
|
|
@@ -35357,15 +35415,17 @@ async function decidePromptSubmitV2(input) {
|
|
|
35357
35415
|
return decision;
|
|
35358
35416
|
}
|
|
35359
35417
|
const searchEnabled = input.searchEnabled === true;
|
|
35360
|
-
const
|
|
35361
|
-
const
|
|
35418
|
+
const bluebirdEnabled = input.bluebirdEnabled === true;
|
|
35419
|
+
const semanticAvailable = searchEnabled || bluebirdEnabled;
|
|
35420
|
+
const searchTip = getPromptSearchTip(searchEnabled, bluebirdEnabled);
|
|
35421
|
+
const scopeSystem = getPromptScopeSystem(searchEnabled, bluebirdEnabled);
|
|
35362
35422
|
const timeoutMs = input.io.timeoutMs ?? 22e3;
|
|
35363
35423
|
let goal = PROMPT_STEER_GOAL;
|
|
35364
35424
|
let timer;
|
|
35365
35425
|
const controller = new AbortController();
|
|
35366
35426
|
try {
|
|
35367
35427
|
const enrich = (async () => {
|
|
35368
|
-
if (!
|
|
35428
|
+
if (!semanticAvailable) {
|
|
35369
35429
|
const searchContext = `Lexical search results:\n${(await input.io.searchCode(prompt, "lexical", controller.signal).catch(() => "")).slice(0, SEARCH_CONTEXT_CAP)}`;
|
|
35370
35430
|
return (await input.io.infer(scopeSystem, `USER REQUEST:\n${prompt}\n\n${searchContext}`, controller.signal)).trim();
|
|
35371
35431
|
}
|
|
@@ -35446,6 +35506,7 @@ var init_internal_prompt_submit = __esmMin((() => {
|
|
|
35446
35506
|
const stdin = readStdin$5();
|
|
35447
35507
|
const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true;
|
|
35448
35508
|
const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== void 0 ? process.env.GH_ROUTER_SEARCH_ENABLED === "1" : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
|
|
35509
|
+
const bluebirdEnabled = process.env.GH_ROUTER_BLUEBIRD_ENABLED === "1";
|
|
35449
35510
|
const runtime = hookMcpRuntimeFromEnv();
|
|
35450
35511
|
let decision;
|
|
35451
35512
|
if (runtime) {
|
|
@@ -35454,6 +35515,7 @@ var init_internal_prompt_submit = __esmMin((() => {
|
|
|
35454
35515
|
stdin,
|
|
35455
35516
|
steerEnabled,
|
|
35456
35517
|
searchEnabled,
|
|
35518
|
+
bluebirdEnabled,
|
|
35457
35519
|
io: {
|
|
35458
35520
|
searchCode: async (query, mode, signal) => {
|
|
35459
35521
|
const r = await callMcpTool({
|
|
@@ -38869,7 +38931,7 @@ function resolveGitBranch(cwd) {
|
|
|
38869
38931
|
if (!cwd) return "";
|
|
38870
38932
|
const gitPath = resolveExecutable("git");
|
|
38871
38933
|
if (!gitPath) return "";
|
|
38872
|
-
const { command, args, shell } = buildExecInvocation([
|
|
38934
|
+
const { command, args, shell, windowsVerbatimArguments } = buildExecInvocation([
|
|
38873
38935
|
gitPath,
|
|
38874
38936
|
"-C",
|
|
38875
38937
|
cwd,
|
|
@@ -38879,6 +38941,7 @@ function resolveGitBranch(cwd) {
|
|
|
38879
38941
|
]);
|
|
38880
38942
|
const result = spawnSync(command, args, {
|
|
38881
38943
|
shell,
|
|
38944
|
+
windowsVerbatimArguments,
|
|
38882
38945
|
timeout: GIT_TIMEOUT_MS,
|
|
38883
38946
|
encoding: "utf8",
|
|
38884
38947
|
stdio: [
|
package/dist/hooks.sha256
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
cf748ccad7b76489cb8f52dfd09e402e725905e35840a7b6a396e09c9ea213e6
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as provisionColbert, a as semanticBackend, b as validateIndexIntegrity, c as serviceFreshness, g as freshnessVerdict, h as completedIndexOnDisk, i as selectServerVariant, k as validateWorkspace, l as stopServiceServer, m as colbertProjectDir, n as populateWorkspace, p as waitForInit, s as serviceBackendProvisionable, t as ensureServerForeground, u as kickBackgroundInit, v as indexDirSignature, w as provisionNextPlaidServer, y as readColbertMeta } from "./service-backend-
|
|
2
|
-
import { t as PATHS } from "./paths-
|
|
3
|
-
import { i as parseBoolEnv } from "./exec-
|
|
4
|
-
import { r as registerColbertExitHandlers } from "./lifecycle-
|
|
1
|
+
import { C as provisionColbert, a as semanticBackend, b as validateIndexIntegrity, c as serviceFreshness, g as freshnessVerdict, h as completedIndexOnDisk, i as selectServerVariant, k as validateWorkspace, l as stopServiceServer, m as colbertProjectDir, n as populateWorkspace, p as waitForInit, s as serviceBackendProvisionable, t as ensureServerForeground, u as kickBackgroundInit, v as indexDirSignature, w as provisionNextPlaidServer, y as readColbertMeta } from "./service-backend-7SPDLUB9.js";
|
|
2
|
+
import { t as PATHS } from "./paths-CpbTHKeP.js";
|
|
3
|
+
import { i as parseBoolEnv } from "./exec-MCU1H-KZ.js";
|
|
4
|
+
import { r as registerColbertExitHandlers } from "./lifecycle-BqWTXaeC.js";
|
|
5
5
|
import { defineCommand } from "citty";
|
|
6
6
|
import consola from "consola";
|
|
7
7
|
import * as os$1 from "node:os";
|
|
@@ -327,4 +327,4 @@ async function runColbertIndex(workspace, deadlineMs, timeoutMin) {
|
|
|
327
327
|
//#endregion
|
|
328
328
|
export { indexCmd };
|
|
329
329
|
|
|
330
|
-
//# sourceMappingURL=index-cmd-
|
|
330
|
+
//# sourceMappingURL=index-cmd-DXYWgKS6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-cmd-k3oWl0n4.js","names":["os"],"sources":["../src/index-cmd.ts"],"sourcesContent":["/**\n * `github-router index` — build the semantic code-search index in the\n * foreground, without starting the proxy (`start`/`claude`/`codex`).\n *\n * Phase 4a: drives the CURRENT colbert backend (foreground `init` with\n * progress). Phase 5: `auto` (default) prefers the persistent service\n * backend — foreground all-core encode with CUDA when a GPU is visible —\n * with TRUE DELTA indexing (only changed files are re-embedded); falls\n * back to colbert when the service is not actionable. `--backend` forces\n * `service` or `colbert`. The explicit invocation IS the opt-in — `--search` is not\n * required — but `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` still hard-disables\n * (building an index that can never be served is pointless).\n *\n * Exit codes: 0 = fresh or successfully built; 1 = provision/build\n * failure; 2 = usage error (bad workspace, hard-disabled).\n */\n\nimport { defineCommand } from \"citty\";\nimport consola from \"consola\";\nimport * as os from \"node:os\";\nimport process from \"node:process\";\n\nimport { validateWorkspace } from \"~/lib/code-search\";\nimport {\n colbertProjectDir,\n completedIndexOnDisk,\n freshnessVerdict,\n indexDirSignature,\n readColbertMeta,\n validateIndexIntegrity,\n} from \"~/lib/colbert/index-store\";\nimport { registerColbertExitHandlers } from \"~/lib/colbert/lifecycle\";\nimport { provisionColbert, provisionNextPlaidServer } from \"~/lib/colbert/provision\";\nimport { kickBackgroundInit, waitForInit } from \"~/lib/colbert/runner\";\nimport {\n ensureServerForeground,\n populateWorkspace,\n selectServerVariant,\n semanticBackend,\n serviceBackendProvisionable,\n serviceFreshness,\n stopServiceServer,\n} from \"~/lib/colbert/service-backend\";\nimport { PATHS } from \"~/lib/paths\";\nimport { parseBoolEnv } from \"~/lib/exec\";\n\nconst POLL_MS = 10_000;\n\nfunction cpuCount(): number {\n try {\n const n = os.cpus().length;\n return Number.isSafeInteger(n) && n > 0 ? n : 4;\n } catch {\n return 4;\n }\n}\n\ninterface IndexStatus {\n workspace: string;\n verdict: string;\n indexOnDisk: boolean;\n shards?: number;\n embeddings?: number;\n integrity?: string;\n head?: string;\n dirty?: boolean;\n lastIndexedAt?: string;\n}\n\nasync function collectStatus(workspace: string): Promise<IndexStatus> {\n const { verdict, head, dirty } = await freshnessVerdict(workspace);\n const onDisk = await completedIndexOnDisk(workspace);\n const status: IndexStatus = {\n workspace,\n verdict,\n indexOnDisk: onDisk,\n };\n const projectDir = await colbertProjectDir(workspace);\n if (projectDir) {\n const integrity = validateIndexIntegrity(`${projectDir}/index`);\n if (integrity.verdict === \"coherent\") {\n status.shards = integrity.shardCount;\n status.embeddings = integrity.embeddingCount;\n } else {\n status.integrity = integrity.verdict;\n }\n }\n const meta = await readColbertMeta(workspace);\n if (meta?.lastIndexedAt) status.lastIndexedAt = meta.lastIndexedAt;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printStatus(s: IndexStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`verdict: ${s.verdict}`);\n consola.info(`index: ${s.indexOnDisk ? \"present\" : \"absent\"}`);\n if (s.shards !== undefined) {\n consola.info(`shards: ${s.shards} (${s.embeddings ?? 0} embeddings)`);\n }\n if (s.integrity && s.integrity !== \"not-built\") {\n consola.info(`integrity: ${s.integrity}`);\n }\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.lastIndexedAt) consola.info(`indexed: ${s.lastIndexedAt}`);\n}\n\ninterface IndexServiceStatus {\n workspace: string;\n backend: string;\n verdict: string;\n indexedAt?: string;\n docCount?: number;\n head?: string;\n dirty?: boolean;\n}\n\nasync function collectServiceStatus(workspace: string): Promise<IndexServiceStatus> {\n const { verdict, meta, head, dirty } = await serviceFreshness(workspace);\n const status: IndexServiceStatus = {\n workspace,\n backend: \"service\",\n verdict,\n };\n if (meta?.indexedAt) status.indexedAt = meta.indexedAt;\n if (meta?.docCount !== undefined) status.docCount = meta.docCount;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printServiceStatus(s: IndexServiceStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`backend: ${s.backend}`);\n consola.info(`verdict: ${s.verdict}`);\n if (s.docCount !== undefined) consola.info(`documents: ${s.docCount}`);\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.indexedAt) consola.info(`indexed: ${s.indexedAt}`);\n}\n\ntype IndexBackend = \"service\" | \"colgrep\";\n\nfunction resolveIndexBackend(requested: unknown): { backend: IndexBackend; explicit: boolean } | { error: string } {\n const raw = typeof requested === \"string\" && requested.length > 0 ? requested.toLowerCase() : \"auto\";\n if (raw !== \"auto\" && raw !== \"service\" && raw !== \"colgrep\") {\n return { error: `index: --backend must be auto, service, or colgrep (got ${String(requested)})` };\n }\n // Explicit opt-in (flag or env) always means service.\n if (raw === \"service\" || (raw === \"auto\" && semanticBackend() === \"service\")) {\n return { backend: \"service\", explicit: true };\n }\n if (raw === \"colgrep\") return { backend: \"colgrep\", explicit: false };\n // Auto: service when provisionable (binary on disk or promoted\n // download + model present), else the colgrep fallback.\n return serviceBackendProvisionable()\n ? { backend: \"service\", explicit: false }\n : { backend: \"colgrep\", explicit: false };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const t = setTimeout(resolve, ms);\n t.unref?.();\n });\n}\n\nexport const indexCmd = defineCommand({\n meta: {\n name: \"index\",\n description:\n \"Build the semantic code-search index for a workspace in the foreground (no proxy needed)\",\n },\n args: {\n workspace: {\n alias: \"w\",\n type: \"string\",\n description: \"Absolute path to the repo to index (default: cwd)\",\n },\n status: {\n type: \"boolean\",\n default: false,\n description: \"Print index status and exit (no build)\",\n },\n timeout: {\n type: \"string\",\n description: \"Max minutes to wait for the build (0 = none, default 0)\",\n },\n backend: {\n type: \"string\",\n description: \"Index backend: auto (service with CUDA/CPU autodetect, colgrep fallback), service, or colgrep (default auto)\",\n },\n full: {\n type: \"boolean\",\n default: false,\n description: \"Force a full rebuild, ignoring content hashes (service backend)\",\n },\n dryRun: {\n type: \"boolean\",\n default: false,\n description: \"Classify changed files without building (service backend)\",\n },\n },\n async run({ args }) {\n const rawWorkspace =\n typeof args.workspace === \"string\" && args.workspace.length > 0\n ? args.workspace\n : process.cwd();\n const ws = validateWorkspace(rawWorkspace);\n if (!ws.ok || !ws.canonical) {\n consola.error(`index: ${ws.error ?? \"workspace validation failed\"}`);\n process.exitCode = 2;\n return;\n }\n const workspace = ws.canonical;\n\n if (parseBoolEnv(process.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) {\n consola.error(\n \"index: semantic search is hard-disabled (GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1); nothing to build\",\n );\n process.exitCode = 2;\n return;\n }\n\n const backendSelection = resolveIndexBackend(args.backend);\n if (\"error\" in backendSelection) {\n consola.error(backendSelection.error);\n process.exitCode = 2;\n return;\n }\n const { backend, explicit: backendExplicit } = backendSelection;\n\n if (args.status === true) {\n if (backend === \"service\") {\n printServiceStatus(await collectServiceStatus(workspace));\n } else {\n printStatus(await collectStatus(workspace));\n }\n return;\n }\n\n const timeoutMin = args.timeout === undefined ? 0 : Number(args.timeout);\n if (\n args.timeout !== undefined &&\n !(Number.isFinite(timeoutMin) && timeoutMin >= 0)\n ) {\n consola.error(\n \"index: --timeout must be a non-negative number of minutes\",\n );\n process.exitCode = 2;\n return;\n }\n const deadlineMs =\n timeoutMin > 0\n ? Date.now() + timeoutMin * 60_000\n : Number.POSITIVE_INFINITY;\n\n // Foreground dedicated build: use all cores unless the operator capped\n // explicitly. Background auto-indexing stays at 25% (the colbert\n // default); an explicit `index` invocation expects speed.\n if (process.env.GH_ROUTER_COLBERT_PARALLEL === undefined) {\n process.env.GH_ROUTER_COLBERT_PARALLEL = String(cpuCount());\n consola.debug(\n `index: parallelism defaulted to ${cpuCount()} sessions (override with GH_ROUTER_COLBERT_PARALLEL)`,\n );\n }\n\n registerColbertExitHandlers();\n\n consola.info(\n `Provisioning semantic-search artifacts into ${PATHS.COLBERT_INDICES_DIR}…`,\n );\n try {\n const result = await provisionColbert();\n if (result.status !== \"ready\") {\n consola.error(\n `index: provision ${result.status}${result.reason ? ` (${result.reason})` : \"\"}`,\n );\n process.exitCode = 1;\n return;\n }\n } catch (err) {\n consola.error(\"index: provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n\n // Auto resolves the backend AFTER provisioning (the model dir must\n // exist before provisionability can report actionable). An\n // explicit service request that cannot provision the server binary\n // fails closed; auto silently falls back to colgrep.\n if (backend === \"service\") {\n let variant: Awaited<ReturnType<typeof selectServerVariant>> | undefined;\n try {\n variant = await selectServerVariant();\n const server = await provisionNextPlaidServer(variant);\n if (server.path) {\n consola.info(`index: service backend ready (${variant}: ${server.path})`);\n } else if (backendExplicit) {\n consola.error(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — retry with --backend=colgrep`,\n );\n process.exitCode = 1;\n return;\n } else {\n consola.warn(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — falling back to colgrep`,\n );\n if (args.full === true || args.dryRun === true) {\n consola.warn(\n \"index: --full/--dry-run apply to the service backend only; ignored for colgrep\",\n );\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n } catch (err) {\n if (backendExplicit) {\n consola.error(\"index: service provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n consola.warn(\"index: service provision skipped:\", err);\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n // Foreground service build (all-core encode; CUDA when detected).\n if (variant === undefined) {\n consola.error(\"index: no service variant resolved\");\n process.exitCode = 1;\n return;\n }\n await runServiceIndex(workspace, {\n full: args.full === true,\n dryRun: args.dryRun === true,\n deadlineMs,\n timeoutMin,\n variant,\n });\n return;\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n },\n});\n\nasync function runServiceIndex(\n workspace: string,\n opts: {\n full: boolean;\n dryRun: boolean;\n deadlineMs: number;\n timeoutMin: number;\n variant: string;\n },\n): Promise<void> {\n const startMs = Date.now();\n const signal =\n Number.isFinite(opts.deadlineMs) && opts.deadlineMs !== Number.POSITIVE_INFINITY\n ? AbortSignal.timeout(Math.max(1, opts.deadlineMs - Date.now()))\n : undefined;\n\n if (opts.dryRun) {\n const plan = await populateWorkspace(workspace, { dryRun: true }).catch((err) => {\n consola.error(\"index: dry-run failed:\", err);\n process.exitCode = 1;\n return null;\n });\n if (!plan) return;\n consola.info(\n `dry-run: ${plan.scanned} files scanned → ${plan.updatedFiles} to index, ${plan.removedFiles} to remove, ${plan.unchanged} unchanged`,\n );\n return;\n }\n\n const first = await serviceFreshness(workspace);\n if (first.verdict === \"fresh\" && !opts.full) {\n consola.success(\"index is already fresh — nothing to build\");\n printServiceStatus(await collectServiceStatus(workspace));\n return;\n }\n\n consola.info(\n `Building service index for ${workspace} (freshness: ${first.verdict}, variant: ${opts.variant})…`,\n );\n const server = await ensureServerForeground();\n if (!server) {\n consola.error(\n \"index: service server failed to start — retry with --backend=colgrep\",\n );\n process.exitCode = 1;\n return;\n }\n let lastLogMs = 0;\n try { const result = await populateWorkspace(workspace, {\n full: opts.full,\n foreground: true,\n ...(signal ? { signal } : {}),\n onProgress: (p) => {\n const now = Date.now();\n if (p.phase !== \"done\" && now - lastLogMs < POLL_MS) return;\n lastLogMs = now;\n if (p.phase === \"done\") return;\n consola.info(\n `… ${p.phase}: ${p.scanned}/${p.total} files` +\n (p.phase === \"encode\" || p.phase === \"extract\"\n ? ` (${p.updatedFiles} changed, ${p.units} units)`\n : \"\"),\n );\n },\n });\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (result.status === \"unchanged\") {\n consola.success(`index ready in ${elapsedS}s (no changes)`);\n } else {\n consola.success(\n `index ready in ${elapsedS}s (delta: ${result.unchanged} unchanged, ${result.updatedFiles} updated, ${result.removedFiles} removed, ${result.units} units)`,\n );\n }\n printServiceStatus(await collectServiceStatus(workspace));\n } catch (err) {\n if (signal?.aborted || Date.now() > opts.deadlineMs) {\n consola.error(\n `index: timed out after ${opts.timeoutMin}min — retry or raise --timeout`,\n );\n } else {\n consola.error(\"index: service build failed:\", err);\n }\n process.exitCode = 1;\n } finally {\n // The persistent server holds the event loop open — stop it or this\n // foreground command never exits (and orphans a server per run).\n await stopServiceServer();\n }\n}\n\nasync function runColbertIndex(\n workspace: string,\n deadlineMs: number,\n timeoutMin: number,\n): Promise<void> {\n const first = await freshnessVerdict(workspace);\n if (first.verdict === \"fresh\") {\n consola.success(\"index is already fresh — nothing to build\");\n printStatus(await collectStatus(workspace));\n return;\n }\n if (first.verdict === \"failed\") {\n consola.warn(\n \"index: last build failed; starting one bounded rebuild attempt\",\n );\n }\n\n consola.info(\n `Building semantic index for ${workspace} (freshness: ${first.verdict})…`,\n );\n kickBackgroundInit(workspace);\n const startMs = Date.now();\n\n for (;;) {\n if (Date.now() > deadlineMs) {\n consola.error(\n `index: timed out after ${timeoutMin}min — the background build continues; retry or raise --timeout`,\n );\n process.exitCode = 1;\n return;\n }\n // Wait for this process's tracked build; resolves immediately when\n // another proxy owns it, in which case the sleep below paces polling.\n await waitForInit(workspace).catch(() => {});\n const v = await freshnessVerdict(workspace);\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (v.verdict === \"fresh\") {\n consola.success(`index ready in ${elapsedS}s`);\n printStatus(await collectStatus(workspace));\n return;\n }\n if (\n v.verdict === \"failed\" ||\n v.verdict === \"crashed\" ||\n v.verdict === \"corrupt\"\n ) {\n consola.error(\n `index: build ended ${v.verdict} — lexical code search still works; see the proxy error log for the failure class`,\n );\n process.exitCode = 1;\n return;\n }\n // building | stale | absent: report progress, keep waiting. colgrep\n // is silent on pipes during encode, so disk growth is the signal.\n const sig = indexDirSignature(workspace);\n const progress =\n sig.kind === \"observed\" ? ` [${sig.signature}]` : \" [starting…]\";\n consola.info(\n `… ${elapsedS}s elapsed (freshness: ${v.verdict})${progress}`,\n );\n await sleep(POLL_MS);\n // Re-kick if nothing owns the build (crash between kick and track).\n kickBackgroundInit(workspace);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,UAAU;AAEhB,SAAS,WAAmB;CAC1B,IAAI;EACF,MAAM,IAAIA,KAAG,KAAK,CAAC,CAAC;EACpB,OAAO,OAAO,cAAc,CAAC,KAAK,IAAI,IAAI,IAAI;CAChD,QAAQ;EACN,OAAO;CACT;AACF;AAcA,eAAe,cAAc,WAAyC;CACpE,MAAM,EAAE,SAAS,MAAM,UAAU,MAAM,iBAAiB,SAAS;CAEjE,MAAM,SAAsB;EAC1B;EACA;EACA,aAAa,MAJM,qBAAqB,SAAS;CAKnD;CACA,MAAM,aAAa,MAAM,kBAAkB,SAAS;CACpD,IAAI,YAAY;EAC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EACF;EACA,IACE,EAAE,YAAY,YACd,EAAE,YAAY,aACd,EAAE,YAAY,WACd;GACA,QAAQ,MACN,sBAAsB,EAAE,QAAQ,kFAClC;GACA,QAAQ,WAAW;GACnB;EACF;EAGA,MAAM,MAAM,kBAAkB,SAAS;EACvC,MAAM,WACJ,IAAI,SAAS,aAAa,KAAK,IAAI,UAAU,KAAK;EACpD,QAAQ,KACN,KAAK,SAAS,wBAAwB,EAAE,QAAQ,GAAG,UACrD;EACA,MAAM,MAAM,OAAO;EAEnB,mBAAmB,SAAS;CAC9B;AACF"}
|
|
1
|
+
{"version":3,"file":"index-cmd-DXYWgKS6.js","names":["os"],"sources":["../src/index-cmd.ts"],"sourcesContent":["/**\n * `github-router index` — build the semantic code-search index in the\n * foreground, without starting the proxy (`start`/`claude`/`codex`).\n *\n * Phase 4a: drives the CURRENT colbert backend (foreground `init` with\n * progress). Phase 5: `auto` (default) prefers the persistent service\n * backend — foreground all-core encode with CUDA when a GPU is visible —\n * with TRUE DELTA indexing (only changed files are re-embedded); falls\n * back to colbert when the service is not actionable. `--backend` forces\n * `service` or `colbert`. The explicit invocation IS the opt-in — `--search` is not\n * required — but `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` still hard-disables\n * (building an index that can never be served is pointless).\n *\n * Exit codes: 0 = fresh or successfully built; 1 = provision/build\n * failure; 2 = usage error (bad workspace, hard-disabled).\n */\n\nimport { defineCommand } from \"citty\";\nimport consola from \"consola\";\nimport * as os from \"node:os\";\nimport process from \"node:process\";\n\nimport { validateWorkspace } from \"~/lib/code-search\";\nimport {\n colbertProjectDir,\n completedIndexOnDisk,\n freshnessVerdict,\n indexDirSignature,\n readColbertMeta,\n validateIndexIntegrity,\n} from \"~/lib/colbert/index-store\";\nimport { registerColbertExitHandlers } from \"~/lib/colbert/lifecycle\";\nimport { provisionColbert, provisionNextPlaidServer } from \"~/lib/colbert/provision\";\nimport { kickBackgroundInit, waitForInit } from \"~/lib/colbert/runner\";\nimport {\n ensureServerForeground,\n populateWorkspace,\n selectServerVariant,\n semanticBackend,\n serviceBackendProvisionable,\n serviceFreshness,\n stopServiceServer,\n} from \"~/lib/colbert/service-backend\";\nimport { PATHS } from \"~/lib/paths\";\nimport { parseBoolEnv } from \"~/lib/exec\";\n\nconst POLL_MS = 10_000;\n\nfunction cpuCount(): number {\n try {\n const n = os.cpus().length;\n return Number.isSafeInteger(n) && n > 0 ? n : 4;\n } catch {\n return 4;\n }\n}\n\ninterface IndexStatus {\n workspace: string;\n verdict: string;\n indexOnDisk: boolean;\n shards?: number;\n embeddings?: number;\n integrity?: string;\n head?: string;\n dirty?: boolean;\n lastIndexedAt?: string;\n}\n\nasync function collectStatus(workspace: string): Promise<IndexStatus> {\n const { verdict, head, dirty } = await freshnessVerdict(workspace);\n const onDisk = await completedIndexOnDisk(workspace);\n const status: IndexStatus = {\n workspace,\n verdict,\n indexOnDisk: onDisk,\n };\n const projectDir = await colbertProjectDir(workspace);\n if (projectDir) {\n const integrity = validateIndexIntegrity(`${projectDir}/index`);\n if (integrity.verdict === \"coherent\") {\n status.shards = integrity.shardCount;\n status.embeddings = integrity.embeddingCount;\n } else {\n status.integrity = integrity.verdict;\n }\n }\n const meta = await readColbertMeta(workspace);\n if (meta?.lastIndexedAt) status.lastIndexedAt = meta.lastIndexedAt;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printStatus(s: IndexStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`verdict: ${s.verdict}`);\n consola.info(`index: ${s.indexOnDisk ? \"present\" : \"absent\"}`);\n if (s.shards !== undefined) {\n consola.info(`shards: ${s.shards} (${s.embeddings ?? 0} embeddings)`);\n }\n if (s.integrity && s.integrity !== \"not-built\") {\n consola.info(`integrity: ${s.integrity}`);\n }\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.lastIndexedAt) consola.info(`indexed: ${s.lastIndexedAt}`);\n}\n\ninterface IndexServiceStatus {\n workspace: string;\n backend: string;\n verdict: string;\n indexedAt?: string;\n docCount?: number;\n head?: string;\n dirty?: boolean;\n}\n\nasync function collectServiceStatus(workspace: string): Promise<IndexServiceStatus> {\n const { verdict, meta, head, dirty } = await serviceFreshness(workspace);\n const status: IndexServiceStatus = {\n workspace,\n backend: \"service\",\n verdict,\n };\n if (meta?.indexedAt) status.indexedAt = meta.indexedAt;\n if (meta?.docCount !== undefined) status.docCount = meta.docCount;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printServiceStatus(s: IndexServiceStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`backend: ${s.backend}`);\n consola.info(`verdict: ${s.verdict}`);\n if (s.docCount !== undefined) consola.info(`documents: ${s.docCount}`);\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.indexedAt) consola.info(`indexed: ${s.indexedAt}`);\n}\n\ntype IndexBackend = \"service\" | \"colgrep\";\n\nfunction resolveIndexBackend(requested: unknown): { backend: IndexBackend; explicit: boolean } | { error: string } {\n const raw = typeof requested === \"string\" && requested.length > 0 ? requested.toLowerCase() : \"auto\";\n if (raw !== \"auto\" && raw !== \"service\" && raw !== \"colgrep\") {\n return { error: `index: --backend must be auto, service, or colgrep (got ${String(requested)})` };\n }\n // Explicit opt-in (flag or env) always means service.\n if (raw === \"service\" || (raw === \"auto\" && semanticBackend() === \"service\")) {\n return { backend: \"service\", explicit: true };\n }\n if (raw === \"colgrep\") return { backend: \"colgrep\", explicit: false };\n // Auto: service when provisionable (binary on disk or promoted\n // download + model present), else the colgrep fallback.\n return serviceBackendProvisionable()\n ? { backend: \"service\", explicit: false }\n : { backend: \"colgrep\", explicit: false };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const t = setTimeout(resolve, ms);\n t.unref?.();\n });\n}\n\nexport const indexCmd = defineCommand({\n meta: {\n name: \"index\",\n description:\n \"Build the semantic code-search index for a workspace in the foreground (no proxy needed)\",\n },\n args: {\n workspace: {\n alias: \"w\",\n type: \"string\",\n description: \"Absolute path to the repo to index (default: cwd)\",\n },\n status: {\n type: \"boolean\",\n default: false,\n description: \"Print index status and exit (no build)\",\n },\n timeout: {\n type: \"string\",\n description: \"Max minutes to wait for the build (0 = none, default 0)\",\n },\n backend: {\n type: \"string\",\n description: \"Index backend: auto (service with CUDA/CPU autodetect, colgrep fallback), service, or colgrep (default auto)\",\n },\n full: {\n type: \"boolean\",\n default: false,\n description: \"Force a full rebuild, ignoring content hashes (service backend)\",\n },\n dryRun: {\n type: \"boolean\",\n default: false,\n description: \"Classify changed files without building (service backend)\",\n },\n },\n async run({ args }) {\n const rawWorkspace =\n typeof args.workspace === \"string\" && args.workspace.length > 0\n ? args.workspace\n : process.cwd();\n const ws = validateWorkspace(rawWorkspace);\n if (!ws.ok || !ws.canonical) {\n consola.error(`index: ${ws.error ?? \"workspace validation failed\"}`);\n process.exitCode = 2;\n return;\n }\n const workspace = ws.canonical;\n\n if (parseBoolEnv(process.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) {\n consola.error(\n \"index: semantic search is hard-disabled (GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1); nothing to build\",\n );\n process.exitCode = 2;\n return;\n }\n\n const backendSelection = resolveIndexBackend(args.backend);\n if (\"error\" in backendSelection) {\n consola.error(backendSelection.error);\n process.exitCode = 2;\n return;\n }\n const { backend, explicit: backendExplicit } = backendSelection;\n\n if (args.status === true) {\n if (backend === \"service\") {\n printServiceStatus(await collectServiceStatus(workspace));\n } else {\n printStatus(await collectStatus(workspace));\n }\n return;\n }\n\n const timeoutMin = args.timeout === undefined ? 0 : Number(args.timeout);\n if (\n args.timeout !== undefined &&\n !(Number.isFinite(timeoutMin) && timeoutMin >= 0)\n ) {\n consola.error(\n \"index: --timeout must be a non-negative number of minutes\",\n );\n process.exitCode = 2;\n return;\n }\n const deadlineMs =\n timeoutMin > 0\n ? Date.now() + timeoutMin * 60_000\n : Number.POSITIVE_INFINITY;\n\n // Foreground dedicated build: use all cores unless the operator capped\n // explicitly. Background auto-indexing stays at 25% (the colbert\n // default); an explicit `index` invocation expects speed.\n if (process.env.GH_ROUTER_COLBERT_PARALLEL === undefined) {\n process.env.GH_ROUTER_COLBERT_PARALLEL = String(cpuCount());\n consola.debug(\n `index: parallelism defaulted to ${cpuCount()} sessions (override with GH_ROUTER_COLBERT_PARALLEL)`,\n );\n }\n\n registerColbertExitHandlers();\n\n consola.info(\n `Provisioning semantic-search artifacts into ${PATHS.COLBERT_INDICES_DIR}…`,\n );\n try {\n const result = await provisionColbert();\n if (result.status !== \"ready\") {\n consola.error(\n `index: provision ${result.status}${result.reason ? ` (${result.reason})` : \"\"}`,\n );\n process.exitCode = 1;\n return;\n }\n } catch (err) {\n consola.error(\"index: provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n\n // Auto resolves the backend AFTER provisioning (the model dir must\n // exist before provisionability can report actionable). An\n // explicit service request that cannot provision the server binary\n // fails closed; auto silently falls back to colgrep.\n if (backend === \"service\") {\n let variant: Awaited<ReturnType<typeof selectServerVariant>> | undefined;\n try {\n variant = await selectServerVariant();\n const server = await provisionNextPlaidServer(variant);\n if (server.path) {\n consola.info(`index: service backend ready (${variant}: ${server.path})`);\n } else if (backendExplicit) {\n consola.error(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — retry with --backend=colgrep`,\n );\n process.exitCode = 1;\n return;\n } else {\n consola.warn(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — falling back to colgrep`,\n );\n if (args.full === true || args.dryRun === true) {\n consola.warn(\n \"index: --full/--dry-run apply to the service backend only; ignored for colgrep\",\n );\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n } catch (err) {\n if (backendExplicit) {\n consola.error(\"index: service provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n consola.warn(\"index: service provision skipped:\", err);\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n // Foreground service build (all-core encode; CUDA when detected).\n if (variant === undefined) {\n consola.error(\"index: no service variant resolved\");\n process.exitCode = 1;\n return;\n }\n await runServiceIndex(workspace, {\n full: args.full === true,\n dryRun: args.dryRun === true,\n deadlineMs,\n timeoutMin,\n variant,\n });\n return;\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n },\n});\n\nasync function runServiceIndex(\n workspace: string,\n opts: {\n full: boolean;\n dryRun: boolean;\n deadlineMs: number;\n timeoutMin: number;\n variant: string;\n },\n): Promise<void> {\n const startMs = Date.now();\n const signal =\n Number.isFinite(opts.deadlineMs) && opts.deadlineMs !== Number.POSITIVE_INFINITY\n ? AbortSignal.timeout(Math.max(1, opts.deadlineMs - Date.now()))\n : undefined;\n\n if (opts.dryRun) {\n const plan = await populateWorkspace(workspace, { dryRun: true }).catch((err) => {\n consola.error(\"index: dry-run failed:\", err);\n process.exitCode = 1;\n return null;\n });\n if (!plan) return;\n consola.info(\n `dry-run: ${plan.scanned} files scanned → ${plan.updatedFiles} to index, ${plan.removedFiles} to remove, ${plan.unchanged} unchanged`,\n );\n return;\n }\n\n const first = await serviceFreshness(workspace);\n if (first.verdict === \"fresh\" && !opts.full) {\n consola.success(\"index is already fresh — nothing to build\");\n printServiceStatus(await collectServiceStatus(workspace));\n return;\n }\n\n consola.info(\n `Building service index for ${workspace} (freshness: ${first.verdict}, variant: ${opts.variant})…`,\n );\n const server = await ensureServerForeground();\n if (!server) {\n consola.error(\n \"index: service server failed to start — retry with --backend=colgrep\",\n );\n process.exitCode = 1;\n return;\n }\n let lastLogMs = 0;\n try { const result = await populateWorkspace(workspace, {\n full: opts.full,\n foreground: true,\n ...(signal ? { signal } : {}),\n onProgress: (p) => {\n const now = Date.now();\n if (p.phase !== \"done\" && now - lastLogMs < POLL_MS) return;\n lastLogMs = now;\n if (p.phase === \"done\") return;\n consola.info(\n `… ${p.phase}: ${p.scanned}/${p.total} files` +\n (p.phase === \"encode\" || p.phase === \"extract\"\n ? ` (${p.updatedFiles} changed, ${p.units} units)`\n : \"\"),\n );\n },\n });\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (result.status === \"unchanged\") {\n consola.success(`index ready in ${elapsedS}s (no changes)`);\n } else {\n consola.success(\n `index ready in ${elapsedS}s (delta: ${result.unchanged} unchanged, ${result.updatedFiles} updated, ${result.removedFiles} removed, ${result.units} units)`,\n );\n }\n printServiceStatus(await collectServiceStatus(workspace));\n } catch (err) {\n if (signal?.aborted || Date.now() > opts.deadlineMs) {\n consola.error(\n `index: timed out after ${opts.timeoutMin}min — retry or raise --timeout`,\n );\n } else {\n consola.error(\"index: service build failed:\", err);\n }\n process.exitCode = 1;\n } finally {\n // The persistent server holds the event loop open — stop it or this\n // foreground command never exits (and orphans a server per run).\n await stopServiceServer();\n }\n}\n\nasync function runColbertIndex(\n workspace: string,\n deadlineMs: number,\n timeoutMin: number,\n): Promise<void> {\n const first = await freshnessVerdict(workspace);\n if (first.verdict === \"fresh\") {\n consola.success(\"index is already fresh — nothing to build\");\n printStatus(await collectStatus(workspace));\n return;\n }\n if (first.verdict === \"failed\") {\n consola.warn(\n \"index: last build failed; starting one bounded rebuild attempt\",\n );\n }\n\n consola.info(\n `Building semantic index for ${workspace} (freshness: ${first.verdict})…`,\n );\n kickBackgroundInit(workspace);\n const startMs = Date.now();\n\n for (;;) {\n if (Date.now() > deadlineMs) {\n consola.error(\n `index: timed out after ${timeoutMin}min — the background build continues; retry or raise --timeout`,\n );\n process.exitCode = 1;\n return;\n }\n // Wait for this process's tracked build; resolves immediately when\n // another proxy owns it, in which case the sleep below paces polling.\n await waitForInit(workspace).catch(() => {});\n const v = await freshnessVerdict(workspace);\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (v.verdict === \"fresh\") {\n consola.success(`index ready in ${elapsedS}s`);\n printStatus(await collectStatus(workspace));\n return;\n }\n if (\n v.verdict === \"failed\" ||\n v.verdict === \"crashed\" ||\n v.verdict === \"corrupt\"\n ) {\n consola.error(\n `index: build ended ${v.verdict} — lexical code search still works; see the proxy error log for the failure class`,\n );\n process.exitCode = 1;\n return;\n }\n // building | stale | absent: report progress, keep waiting. colgrep\n // is silent on pipes during encode, so disk growth is the signal.\n const sig = indexDirSignature(workspace);\n const progress =\n sig.kind === \"observed\" ? ` [${sig.signature}]` : \" [starting…]\";\n consola.info(\n `… ${elapsedS}s elapsed (freshness: ${v.verdict})${progress}`,\n );\n await sleep(POLL_MS);\n // Re-kick if nothing owns the build (crash between kick and track).\n kickBackgroundInit(workspace);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,UAAU;AAEhB,SAAS,WAAmB;CAC1B,IAAI;EACF,MAAM,IAAIA,KAAG,KAAK,CAAC,CAAC;EACpB,OAAO,OAAO,cAAc,CAAC,KAAK,IAAI,IAAI,IAAI;CAChD,QAAQ;EACN,OAAO;CACT;AACF;AAcA,eAAe,cAAc,WAAyC;CACpE,MAAM,EAAE,SAAS,MAAM,UAAU,MAAM,iBAAiB,SAAS;CAEjE,MAAM,SAAsB;EAC1B;EACA;EACA,aAAa,MAJM,qBAAqB,SAAS;CAKnD;CACA,MAAM,aAAa,MAAM,kBAAkB,SAAS;CACpD,IAAI,YAAY;EACd,MAAM,YAAY,uBAAuB,GAAG,WAAW,OAAO;EAC9D,IAAI,UAAU,YAAY,YAAY;GACpC,OAAO,SAAS,UAAU;GAC1B,OAAO,aAAa,UAAU;EAChC,OACE,OAAO,YAAY,UAAU;CAEjC;CACA,MAAM,OAAO,MAAM,gBAAgB,SAAS;CAC5C,IAAI,MAAM,eAAe,OAAO,gBAAgB,KAAK;CACrD,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,KAAK,MAAM,GAAG,EAAE;CACtD,IAAI,UAAU,KAAA,GAAW,OAAO,QAAQ;CACxC,OAAO;AACT;AAEA,SAAS,YAAY,GAAsB;CACzC,QA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veExecutable, t as buildExecInvocation } from "./exec-
|
|
2
|
-
import { c as readAicSnapshotFile, s as formatAicStatus } from "./aic-ledger-
|
|
3
|
-
import { t as discountedUsdForSnapshot } from "./copilot-discount-
|
|
1
|
+
import { o as resolveExecutable, t as buildExecInvocation } from "./exec-MCU1H-KZ.js";
|
|
2
|
+
import { c as readAicSnapshotFile, s as formatAicStatus } from "./aic-ledger-D4fmThbS.js";
|
|
3
|
+
import { t as discountedUsdForSnapshot } from "./copilot-discount-BcUa3f-k.js";
|
|
4
4
|
import { defineCommand } from "citty";
|
|
5
5
|
import { readFileSync } from "node:fs";
|
|
6
6
|
import { spawnSync } from "node:child_process";
|
|
@@ -223,7 +223,7 @@ function resolveGitBranch(cwd) {
|
|
|
223
223
|
if (!cwd) return "";
|
|
224
224
|
const gitPath = resolveExecutable("git");
|
|
225
225
|
if (!gitPath) return "";
|
|
226
|
-
const { command, args, shell } = buildExecInvocation([
|
|
226
|
+
const { command, args, shell, windowsVerbatimArguments } = buildExecInvocation([
|
|
227
227
|
gitPath,
|
|
228
228
|
"-C",
|
|
229
229
|
cwd,
|
|
@@ -233,6 +233,7 @@ function resolveGitBranch(cwd) {
|
|
|
233
233
|
]);
|
|
234
234
|
const result = spawnSync(command, args, {
|
|
235
235
|
shell,
|
|
236
|
+
windowsVerbatimArguments,
|
|
236
237
|
timeout: GIT_TIMEOUT_MS,
|
|
237
238
|
encoding: "utf8",
|
|
238
239
|
stdio: [
|
|
@@ -436,4 +437,4 @@ const internalAicStatus = defineCommand({
|
|
|
436
437
|
//#endregion
|
|
437
438
|
export { internalAicStatus };
|
|
438
439
|
|
|
439
|
-
//# sourceMappingURL=internal-aic-status-
|
|
440
|
+
//# sourceMappingURL=internal-aic-status-Bma0r0ZS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-aic-status-Bma0r0ZS.js","names":[],"sources":["../src/lib/default-statusline.ts","../src/internal-aic-status.ts"],"sourcesContent":["/**\n * Rich default status line for `github-router claude` sessions.\n *\n * Replaces the need for users to maintain their own PowerShell/bash status\n * script: `internal-aic-status` renders these segments natively from the\n * Claude Code stdin JSON, then pins the `[AIC x.xx]` ledger fragment ahead\n * of them. Zero dependencies, cross-platform (Windows 11 is the primary\n * target — no `powershell`/`bash`/`jq` required), and fast (no shell\n * startup; one bounded `git rev-parse` at most).\n *\n * Segment order (left = highest priority; narrow terminals drop from the\n * right, `AIC` is never dropped):\n *\n * `[AIC] | [ctx bar] % | model | dir (branch) | ~$actual | in/out | dur | +a -r`\n *\n * The `$` segment is the DISCOUNTED actual (`~$` = factor-discounted\n * session total from `copilot-discount.ts`, capped at AIC × $0.01) — NOT\n * Claude's `cost.total_cost_usd`, which prices at Anthropic list rates and\n * reads ~10-100x high against Copilot billing (a 28-day sample: 41.1B tokens\n * for $5,142 ≈ $0.13/1M blended vs $15-75/1M list). Rendering list price\n * next to the real `[AIC]` billing unit would show two contradictory\n * numbers, so list price is deliberately not rendered at all.\n *\n * Width comes from `COLUMNS` (set by Claude Code for status scripts since\n * v2.1.153); fallback is 120 when unset/unparseable so a missing `COLUMNS`\n * never needlessly drops segments.\n */\n\nimport { spawnSync } from \"node:child_process\"\n\nimport { USD_PER_AIC_CREDIT } from \"./copilot-discount\"\nimport {\n buildExecInvocation,\n resolveExecutable,\n} from \"./exec\"\n\nconst ESC = \"\\x1b\"\nconst RESET = `${ESC}[0m`\nconst DIM = `${ESC}[90m`\nconst GREEN = `${ESC}[32m`\nconst YELLOW = `${ESC}[33m`\nconst RED = `${ESC}[31m`\nconst ORANGE = `${ESC}[38;5;208m`\nconst CYAN = `${ESC}[36m`\nconst MAGENTA = `${ESC}[35m`\nconst BLUE = `${ESC}[34m`\nconst AIC_COLOR = `${ESC}[1;33m`\n\nconst CTX_BAR_LEN = 10\nconst GIT_TIMEOUT_MS = 300\nconst WIDTH_FALLBACK = 120\nconst SEP_PLAIN = \" | \"\nconst SEP_TEXT = `${DIM} | ${RESET}`\n\nexport interface StatusInput {\n usedPct?: number\n totalInputTokens?: number\n totalOutputTokens?: number\n totalDurationMs?: number\n linesAdded?: number\n linesRemoved?: number\n cwd?: string\n modelName?: string\n}\n\nexport interface StatusSegment {\n text: string\n plain: string\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined\n }\n return value as Record<string, unknown>\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined\n}\n\n/**\n * Parse Claude Code's status-line stdin JSON into the fields we render.\n * Total function: malformed JSON or unexpected shapes yield `{}` (every\n * segment then renders its `--` placeholder or is omitted) — never throws.\n */\nexport function parseStatusInput(raw: string): StatusInput {\n if (!raw.trim()) return {}\n let parsed: unknown\n try {\n parsed = JSON.parse(raw) as unknown\n } catch {\n return {}\n }\n const root = asRecord(parsed)\n if (!root) return {}\n const out: StatusInput = {}\n\n const ctx = asRecord(root.context_window)\n if (ctx) {\n const pct = finiteNumber(ctx.used_percentage)\n if (pct !== undefined) out.usedPct = pct\n const tIn = finiteNumber(ctx.total_input_tokens)\n if (tIn !== undefined && tIn >= 0) out.totalInputTokens = Math.floor(tIn)\n const tOut = finiteNumber(ctx.total_output_tokens)\n if (tOut !== undefined && tOut >= 0) out.totalOutputTokens = Math.floor(tOut)\n }\n\n const cost = asRecord(root.cost)\n if (cost) {\n const dur = finiteNumber(cost.total_duration_ms)\n if (dur !== undefined && dur >= 0) out.totalDurationMs = dur\n const la = finiteNumber(cost.total_lines_added)\n if (la !== undefined && la >= 0) out.linesAdded = Math.floor(la)\n const lr = finiteNumber(cost.total_lines_removed)\n if (lr !== undefined && lr >= 0) out.linesRemoved = Math.floor(lr)\n }\n\n const workspace = asRecord(root.workspace)\n const wsDir = workspace ? nonEmptyString(workspace.current_dir) : undefined\n const cwd = wsDir ?? nonEmptyString(root.cwd)\n if (cwd) out.cwd = cwd\n\n const model = asRecord(root.model)\n if (model) {\n const name =\n nonEmptyString(model.display_name) ?? nonEmptyString(model.id)\n if (name) out.modelName = name\n }\n\n return out\n}\n\n/** Compact token count: `999` → `999`, `15234` → `15.2k`, `2.1M`. */\nexport function compactTokens(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`\n if (n >= 1000) return `${(n / 1000).toFixed(1)}k`\n return `${n}`\n}\n\n/** `45000` → `0m45s`, `198000` → `3m18s`, `3720000` → `1h02m`. */\nexport function formatDurationMs(ms: number): string {\n const totalSeconds = Math.floor(ms / 1000)\n const hours = Math.floor(totalSeconds / 3600)\n const minutes = Math.floor((totalSeconds % 3600) / 60)\n const seconds = totalSeconds % 60\n if (hours >= 1) {\n return `${hours}h${String(minutes).padStart(2, \"0\")}m`\n }\n return `${minutes}m${String(seconds).padStart(2, \"0\")}s`\n}\n\n/** Basename of a cwd, tolerant of `/` and `\\` separators + trailing slash. */\nexport function dirLeaf(cwd: string): string {\n const trimmed = cwd.replace(/[/\\\\]+$/, \"\")\n const parts = trimmed.split(/[/\\\\]/)\n return parts[parts.length - 1] ?? trimmed\n}\n\nexport function buildCtxSegment(usedPct: number | undefined): StatusSegment {\n if (usedPct === undefined || !Number.isFinite(usedPct)) {\n return {\n text: `${DIM}[----------] --%${RESET}`,\n plain: \"[----------] --%\",\n }\n }\n const u = Math.max(0, Math.min(100, Math.round(usedPct)))\n let filled = Math.round((u / 100) * CTX_BAR_LEN)\n if (filled > CTX_BAR_LEN) filled = CTX_BAR_LEN\n if (filled < 0) filled = 0\n const bar = `#`.repeat(filled) + `-`.repeat(CTX_BAR_LEN - filled)\n const color = u < 50 ? GREEN : u < 75 ? YELLOW : RED\n return {\n text: `${color}[${bar}] ${u}%${RESET}`,\n plain: `[${bar}] ${u}%`,\n }\n}\n\n/**\n * AIC credits → undiscounted USD. 1 credit ≈ $0.01 — the same convention as\n * the session exit summary (`aic-ledger.ts`). Kept for tests/callers that\n * need the raw conversion; the status line itself shows the\n * factor-discounted total from `copilot-discount.ts`.\n */\nexport function usdFromAicCredits(credits: number): number {\n return credits * USD_PER_AIC_CREDIT\n}\n\n/**\n * Discounted-actual `$` segment. Callers pass the capped total from\n * `discountedUsdForSnapshot` — this function only formats. Placeholder\n * `~$--` until the first priced upstream response lands in the ledger.\n * Thresholds are tuned for ACTUALS scale (a session runs ~$0.10-2.00) —\n * not the old list-price scale.\n */\nexport function buildUsdSegment(\n actualUsd: number | undefined,\n): StatusSegment {\n if (actualUsd === undefined || !Number.isFinite(actualUsd) || actualUsd < 0) {\n return { text: `${DIM}~$--${RESET}`, plain: \"~$--\" }\n }\n const c = actualUsd\n const color = c < 1 ? GREEN : c < 5 ? YELLOW : c < 20 ? ORANGE : RED\n const formatted = c < 10 ? c.toFixed(2) : c.toFixed(1)\n return {\n text: `${color}~$${formatted}${RESET}`,\n plain: `~$${formatted}`,\n }\n}\n\nexport function buildToksSegment(\n tIn: number | undefined,\n tOut: number | undefined,\n): StatusSegment {\n if (tIn === undefined || tOut === undefined) {\n return { text: `${DIM}--/--${RESET}`, plain: \"--/--\" }\n }\n const cin = compactTokens(tIn)\n const cout = compactTokens(tOut)\n return {\n text: `${CYAN}${cin}${RESET}${DIM}/${RESET}${MAGENTA}${cout}${RESET}`,\n plain: `${cin}/${cout}`,\n }\n}\n\nexport function buildDurSegment(durMs: number | undefined): StatusSegment {\n if (durMs === undefined || !Number.isFinite(durMs) || durMs < 0) {\n return { text: `${DIM}--${RESET}`, plain: \"--\" }\n }\n const formatted = formatDurationMs(durMs)\n return { text: `${DIM}${formatted}${RESET}`, plain: formatted }\n}\n\nexport function buildLinesSegment(\n added: number | undefined,\n removed: number | undefined,\n): StatusSegment {\n const a = added ?? 0\n const r = removed ?? 0\n return {\n text: `${GREEN}+${a}${RESET} ${RED}-${r}${RESET}`,\n plain: `+${a} -${r}`,\n }\n}\n\nexport function buildModelSegment(\n modelName: string | undefined,\n): StatusSegment | undefined {\n if (!modelName || modelName === \"--\") return undefined\n return {\n text: `${MAGENTA}${modelName}${RESET}`,\n plain: modelName,\n }\n}\n\nexport function buildDirGitSegment(\n cwd: string | undefined,\n branch: string | undefined,\n): StatusSegment | undefined {\n const leaf = cwd ? dirLeaf(cwd) : \"\"\n const br = branch && branch !== \"HEAD\" ? branch : \"\"\n if (!leaf && !br) return undefined\n if (leaf && br) {\n return {\n text: `${BLUE}${leaf}${RESET} ${CYAN}(${br})${RESET}`,\n plain: `${leaf} (${br})`,\n }\n }\n if (leaf) {\n return { text: `${BLUE}${leaf}${RESET}`, plain: leaf }\n }\n return { text: `${CYAN}${br}${RESET}`, plain: br }\n}\n\n/**\n * Resolve the current git branch for `cwd`. Bounded (`GIT_TIMEOUT_MS`) and\n * total: any failure (no git binary, not a repo, detached `HEAD`, timeout,\n * `%` in a Windows path that cmd.exe cannot safely quote) yields `\"\"`\n * (caller omits the branch) — never throws.\n */\nexport function resolveGitBranch(cwd: string | undefined): string {\n try {\n if (!cwd) return \"\"\n const gitPath = resolveExecutable(\"git\")\n if (!gitPath) return \"\"\n const { command, args, shell, windowsVerbatimArguments } =\n buildExecInvocation([\n gitPath,\n \"-C\",\n cwd,\n \"rev-parse\",\n \"--abbrev-ref\",\n \"HEAD\",\n ])\n const result = spawnSync(command, args, {\n shell,\n windowsVerbatimArguments,\n timeout: GIT_TIMEOUT_MS,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n if (result.error) return \"\"\n const out =\n typeof result.stdout === \"string\" ? result.stdout.trim() : \"\"\n if (!out || out === \"HEAD\") return \"\"\n return out.split(\"\\n\")[0]?.trim() ?? \"\"\n } catch {\n return \"\"\n }\n}\n\n/** Terminal width for the drop-right-to-left assembly. */\nexport function terminalWidth(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env.COLUMNS\n if (raw !== undefined) {\n const n = Number(raw)\n if (Number.isInteger(n) && n > 0) return n\n }\n return WIDTH_FALLBACK\n}\n\n/**\n * Assemble the full status line. `aicFragment` (e.g. `[AIC 12.42]`) is\n * PINNED — it renders even when nothing else fits. `actualUsd` feeds the\n * `~$` segment (the capped factor-discounted total from\n * `discountedUsdForSnapshot`, same snapshot the fragment came from).\n * Droppable segments in priority order: ctx, model, dir/git, ~$, toks,\n * dur, lines.\n */\nexport function assembleStatusLine(\n aicFragment: string,\n input: StatusInput,\n opts: { width?: number; branch?: string; actualUsd?: number } = {},\n): string {\n const aic = aicFragment.trim()\n const aicText = aic ? `${AIC_COLOR}${aic}${RESET}` : \"\"\n\n const droppable: Array<StatusSegment> = [buildCtxSegment(input.usedPct)]\n const model = buildModelSegment(input.modelName)\n if (model) droppable.push(model)\n // Location context sits right after ctx/model: more useful than the\n // numbers when the bar is wide, still dropped before ctx/model.\n const dirGit = buildDirGitSegment(input.cwd, opts.branch)\n if (dirGit) droppable.push(dirGit)\n droppable.push(\n buildUsdSegment(opts.actualUsd),\n buildToksSegment(input.totalInputTokens, input.totalOutputTokens),\n buildDurSegment(input.totalDurationMs),\n buildLinesSegment(input.linesAdded, input.linesRemoved),\n )\n\n const width = opts.width ?? terminalWidth()\n const sepLen = SEP_PLAIN.length\n\n // Drop from the end (lowest priority) until the line fits. AIC is pinned:\n // it is excluded from the dropping loop entirely.\n let count = droppable.length\n while (count > 0) {\n let total = aic ? aic.length : 0\n for (let i = 0; i < count; i++) {\n if (aic || i > 0) total += sepLen\n total += droppable[i].plain.length\n }\n if (total <= width) break\n // Never drop the last segment when there is no AIC: an over-wide line\n // with real data beats an empty status line.\n if (count === 1 && !aic) break\n count--\n }\n\n const parts: Array<string> = []\n if (aic) parts.push(aicText)\n for (let i = 0; i < count; i++) parts.push(droppable[i].text)\n if (parts.length === 0) return \"\"\n return parts.join(SEP_TEXT)\n}\n\n/**\n * Convenience: parse stdin JSON + assemble with branch resolution.\n * `branchOverride` skips the `git` spawn (used by tests). `actualUsd`\n * comes from `discountedUsdForSnapshot` on the same ledger snapshot as\n * `aicFragment` (read by the caller — this module never touches the\n * ledger file).\n */\nexport function buildRichStatusLine(\n stdinRaw: string,\n aicFragment: string,\n opts: { width?: number; branchOverride?: string; actualUsd?: number } = {},\n): string {\n const input = parseStatusInput(stdinRaw)\n const branch =\n opts.branchOverride !== undefined\n ? opts.branchOverride\n : resolveGitBranch(input.cwd)\n return assembleStatusLine(aicFragment, input, {\n ...(opts.width !== undefined ? { width: opts.width } : {}),\n ...(branch ? { branch } : {}),\n ...(opts.actualUsd !== undefined ? { actualUsd: opts.actualUsd } : {}),\n })\n}\n","/**\n * The internal `internal-aic-status` subcommand: the executable a spawned\n * Claude Code session's `statusLine` invokes (registered into the mirrored\n * settings.json by the launcher — see `src/lib/aic-statusline-settings.ts`).\n *\n * Default-on rich status line: Claude Code's stdin JSON is rendered natively\n * (see `src/lib/default-statusline.ts`) as\n * `[ctx bar] % | model | dir (branch) | ~$actual | in/out | dur | +a -r`,\n * with this launch's AIC ledger total PINNED ahead of it: `[AIC 12.42] ...`.\n * The `~$` segment is the factor-discounted actual (per-model static\n * factors over ledger nano, capped at AIC × $0.01 — see\n * `src/lib/copilot-discount.ts`), not Claude's list-price `total_cost_usd`.\n * Narrow terminals drop segments right-to-left; AIC is never dropped.\n *\n * When the user already had a `statusLine` command, its text arrives via\n * `GH_ROUTER_AIC_USER_STATUSLINE` and is run instead of the rich default\n * (their script already renders ctx/cost/model itself — rendering both\n * would duplicate every segment), so the output stays one composed line:\n * `[AIC 12.42] <user line>`.\n *\n * Status-line contract: stdout is the rendered line (first line wins), fast\n * (<1s budget — ledger read is local, git branch has a 300ms cap, the user\n * command gets a 5s cap), and NEVER failing (any error → print whatever is\n * available → exit 0).\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { spawnSync } from \"node:child_process\"\nimport { readFileSync } from \"node:fs\"\n\nimport {\n formatAicStatus,\n readAicSnapshotFile,\n} from \"./lib/aic-ledger\"\nimport { discountedUsdForSnapshot } from \"./lib/copilot-discount\"\nimport { buildRichStatusLine } from \"./lib/default-statusline\"\n\n/**\n * Read stdin synchronously. Claude Code pipes session JSON to the\n * statusLine command; an unread pipe can SIGPIPE the writer on some\n * platforms. Returns \"\" when stdin is a TTY or unreadable — callers render\n * placeholders/omit segments rather than failing.\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n // Best-effort; the ledger read below does not depend on stdin.\n return \"\"\n }\n}\n\n/**\n * Pure core: compose the status line from an AIC fragment and a user line.\n * Exported for unit tests.\n */\nexport function composeAicStatusLine(\n aicFragment: string,\n userLine: string,\n): string {\n const aic = aicFragment.trim()\n const user = userLine.split(\"\\n\")[0]?.trim() ?? \"\"\n if (aic && user) return `${aic} ${user}`\n return aic || user\n}\n\n/**\n * Run the user's own statusLine command (from `GH_ROUTER_AIC_USER_STATUSLINE`),\n * returning its first stdout line or \"\" on any failure/timeout. Exported for\n * unit tests (command + timeout injectable).\n *\n * Claude Code pipes session JSON to the statusLine command's stdin, and\n * user scripts commonly block reading it to EOF — so the received\n * `stdinRaw` is forwarded via `input` (written then closed) rather than\n * leaving stdin disconnected, which would hang such scripts until the\n * timeout and silently drop their segment.\n */\nexport function runUserStatusLine(\n command: string,\n stdinRaw: string,\n timeoutMs = 5000,\n): string {\n if (!command.trim()) return \"\"\n try {\n const result = spawnSync(command, {\n shell: true,\n timeout: timeoutMs,\n encoding: \"utf8\",\n input: stdinRaw,\n stdio: [\"pipe\", \"pipe\", \"ignore\"],\n // Inherit env so user scripts see the same session context they would\n // under their own statusLine (cwd included — spawnSync inherits it).\n env: process.env,\n })\n if (result.error) return \"\"\n const out = typeof result.stdout === \"string\" ? result.stdout : \"\"\n return out.split(\"\\n\")[0]?.trim() ?? \"\"\n } catch {\n return \"\"\n }\n}\n\nfunction readAicSnapshot(): { fragment: string; actualUsd?: number } {\n try {\n const ledgerPath = process.env.GH_ROUTER_AIC_LEDGER\n if (!ledgerPath) return { fragment: \"\" }\n const snapshot = readAicSnapshotFile(ledgerPath)\n if (!snapshot) return { fragment: \"\" }\n // No priced responses yet → no fragment AND no USD: the `~$`\n // segment renders its `~$--` placeholder instead of `~$0.00`.\n if (snapshot.requests === 0 || snapshot.totalNanoAiu <= 0) {\n return { fragment: \"\" }\n }\n return {\n fragment: formatAicStatus(snapshot),\n actualUsd: discountedUsdForSnapshot(snapshot).total,\n }\n } catch {\n return { fragment: \"\" }\n }\n}\n\nexport const internalAicStatus = defineCommand({\n meta: {\n name: \"internal-aic-status\",\n description:\n \"Internal: Claude Code statusLine handler printing AIC total + rich session line.\",\n },\n async run() {\n const stdinRaw = readStdin()\n const { fragment: aic, actualUsd } = readAicSnapshot()\n const userCommand = process.env.GH_ROUTER_AIC_USER_STATUSLINE ?? \"\"\n // Wrap mode: the user's own script already renders ctx/cost/model from\n // the same stdin JSON — run it and prepend AIC only.\n if (userCommand.trim()) {\n const userLine = runUserStatusLine(userCommand, stdinRaw)\n const line = composeAicStatusLine(aic, userLine)\n if (line) process.stdout.write(`${line}\\n`)\n process.exitCode = 0\n return\n }\n // Default mode: native rich line with AIC pinned ahead of it. The\n // builder never throws; an empty result (no ledger yet AND no stdin)\n // prints nothing rather than a placeholder line.\n let line: string\n try {\n line = buildRichStatusLine(stdinRaw, aic, {\n ...(actualUsd !== undefined ? { actualUsd } : {}),\n })\n } catch {\n line = aic.trim()\n }\n if (line) process.stdout.write(`${line}\\n`)\n // Signal success WITHOUT tearing the loop down — same resolution as the\n // other internal hooks (see main.ts help-path comment): a hard\n // process.exit() can abort through a pipe on Windows.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,MAAM;AACZ,MAAM,QAAQ,GAAG,IAAI;AACrB,MAAM,MAAM,GAAG,IAAI;AACnB,MAAM,QAAQ,GAAG,IAAI;AACrB,MAAM,SAAS,GAAG,IAAI;AACtB,MAAM,MAAM,GAAG,IAAI;AACnB,MAAM,SAAS,GAAG,IAAI;AACtB,MAAM,OAAO,GAAG,I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BAAkB,aAAa,QACF,CAAC;GAC/C,IAAI,MAAM,QAAQ,OAAO,MAAM,GAAG,KAAK,GAAG;GAC1C,QAAQ,WAAW;GACnB;EACF;EAIA,IAAI;EACJ,IAAI;GACF,OAAO,oBAAoB,UAAU,KAAK,EACxC,GAAI,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC,EACjD,CAAC;EACH,QAAQ;GACN,OAAO,IAAI,KAAK;EAClB;EACA,IAAI,MAAM,QAAQ,OAAO,MAAM,GAAG,KAAK,GAAG;EAI1C,QAAQ,WAAW;CACrB;AACF,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as ArtifactClient } from "./client-CQMfroGV.js";
|
|
2
|
-
import { a as isSubagentContext } from "./stop-gate-policy-
|
|
2
|
+
import { a as isSubagentContext } from "./stop-gate-policy-Gd_cNT9-.js";
|
|
3
3
|
import { defineCommand } from "citty";
|
|
4
4
|
import { readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
@@ -316,4 +316,4 @@ const internalArtifactOpen = defineCommand({
|
|
|
316
316
|
//#endregion
|
|
317
317
|
export { internalArtifactOpen };
|
|
318
318
|
|
|
319
|
-
//# sourceMappingURL=internal-artifact-open-
|
|
319
|
+
//# sourceMappingURL=internal-artifact-open-lta2UPnE.js.map
|