github-router 0.3.330 → 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.
Files changed (128) hide show
  1. package/README.md +4 -2
  2. package/dist/{aic-ledger-CsBx1crE.js → aic-ledger-D4fmThbS.js} +2 -2
  3. package/dist/{aic-ledger-CsBx1crE.js.map → aic-ledger-D4fmThbS.js.map} +1 -1
  4. package/dist/{attribution-settings-DepziZU8.js → attribution-settings-BeO1w_DL.js} +62 -51
  5. package/dist/attribution-settings-BeO1w_DL.js.map +1 -0
  6. package/dist/{auth-xgFZGZbf.js → auth-DjKEIiqG.js} +4 -4
  7. package/dist/{auth-xgFZGZbf.js.map → auth-DjKEIiqG.js.map} +1 -1
  8. package/dist/bluebird-client-DpYl1YmJ.js +1163 -0
  9. package/dist/bluebird-client-DpYl1YmJ.js.map +1 -0
  10. package/dist/bluebird-client-bn9Yv6Cb.js +2 -0
  11. package/dist/browser-ext/manifest.json +1 -1
  12. package/dist/{check-usage-vUDk6oV7.js → check-usage-B7UrDwD8.js} +4 -4
  13. package/dist/{check-usage-vUDk6oV7.js.map → check-usage-B7UrDwD8.js.map} +1 -1
  14. package/dist/{claude-Dw4V8o8l.js → claude-BQQPdXLb.js} +37 -29
  15. package/dist/claude-BQQPdXLb.js.map +1 -0
  16. package/dist/{codex-CXOpv4WP.js → codex-fW-hbxtT.js} +12 -8
  17. package/dist/codex-fW-hbxtT.js.map +1 -0
  18. package/dist/{copilot-discount-0lG67i9O.js → copilot-discount-BcUa3f-k.js} +2 -2
  19. package/dist/{copilot-discount-0lG67i9O.js.map → copilot-discount-BcUa3f-k.js.map} +1 -1
  20. package/dist/{debug-a737qcCC.js → debug-CigFsS-h.js} +2 -2
  21. package/dist/{debug-a737qcCC.js.map → debug-CigFsS-h.js.map} +1 -1
  22. package/dist/engine-E4WJGSeg.js +2 -0
  23. package/dist/{exec-COUT4QsS.js → exec-MCU1H-KZ.js} +63 -13
  24. package/dist/exec-MCU1H-KZ.js.map +1 -0
  25. package/dist/{gate-discovery-BGqS7R2g.js → gate-discovery-DbwVeERm.js} +6 -6
  26. package/dist/{gate-discovery-BGqS7R2g.js.map → gate-discovery-DbwVeERm.js.map} +1 -1
  27. package/dist/{get-copilot-usage-VKU2IvuE.js → get-copilot-usage-CGaV01dC.js} +4 -3
  28. package/dist/{get-copilot-usage-VKU2IvuE.js.map → get-copilot-usage-CGaV01dC.js.map} +1 -1
  29. package/dist/hooks.mjs +90 -27
  30. package/dist/hooks.sha256 +1 -1
  31. package/dist/index-cmd-DXYWgKS6.js +330 -0
  32. package/dist/index-cmd-DXYWgKS6.js.map +1 -0
  33. package/dist/{internal-aic-status-Cfl5HiAN.js → internal-aic-status-Bma0r0ZS.js} +6 -5
  34. package/dist/internal-aic-status-Bma0r0ZS.js.map +1 -0
  35. package/dist/{internal-artifact-open-CX2fRP_D.js → internal-artifact-open-lta2UPnE.js} +2 -2
  36. package/dist/{internal-artifact-open-CX2fRP_D.js.map → internal-artifact-open-lta2UPnE.js.map} +1 -1
  37. package/dist/{internal-fast-dispatch-guard-Cxattkm4.js → internal-fast-dispatch-guard-DPR16qUE.js} +1 -1
  38. package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js → internal-fast-dispatch-guard-DoXO3X7P.js} +2 -2
  39. package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js.map → internal-fast-dispatch-guard-DoXO3X7P.js.map} +1 -1
  40. package/dist/{internal-first-mate-guard-D_JFcrl_.js → internal-first-mate-guard-BEwDjHfX.js} +3 -3
  41. package/dist/{internal-first-mate-guard-D_JFcrl_.js.map → internal-first-mate-guard-BEwDjHfX.js.map} +1 -1
  42. package/dist/{internal-first-mate-guard-97qsseTP.js → internal-first-mate-guard-CAefr6Ce.js} +1 -1
  43. package/dist/{internal-max-dispatch-guard-DQMyOds8.js → internal-max-dispatch-guard-6ZCEanI6.js} +1 -1
  44. package/dist/{internal-max-dispatch-guard-Cxe8h12x.js → internal-max-dispatch-guard-CtIO7pm1.js} +3 -3
  45. package/dist/{internal-max-dispatch-guard-Cxe8h12x.js.map → internal-max-dispatch-guard-CtIO7pm1.js.map} +1 -1
  46. package/dist/{internal-plan-review-O2dwnQv3.js → internal-plan-review-jIts3KYd.js} +3 -3
  47. package/dist/{internal-plan-review-O2dwnQv3.js.map → internal-plan-review-jIts3KYd.js.map} +1 -1
  48. package/dist/{internal-prompt-submit-CD0UFkT-.js → internal-prompt-submit-BfoWVyzs.js} +10 -7
  49. package/dist/internal-prompt-submit-BfoWVyzs.js.map +1 -0
  50. package/dist/{internal-session-bind-CHIOd5ys.js → internal-session-bind-IpZ5hJzR.js} +2 -2
  51. package/dist/{internal-session-bind-CHIOd5ys.js.map → internal-session-bind-IpZ5hJzR.js.map} +1 -1
  52. package/dist/{internal-stop-hook-CH9SKjZ9.js → internal-stop-hook-DO8RKfKB.js} +6 -6
  53. package/dist/{internal-stop-hook-CH9SKjZ9.js.map → internal-stop-hook-DO8RKfKB.js.map} +1 -1
  54. package/dist/{internal-stop-review-a3rpzzhd.js → internal-stop-review-BtGDVrv-.js} +2 -2
  55. package/dist/{internal-stop-review-a3rpzzhd.js.map → internal-stop-review-BtGDVrv-.js.map} +1 -1
  56. package/dist/{internal-worker-guard-BY5seBqp.js → internal-worker-guard-C0FJ4b29.js} +2 -2
  57. package/dist/{internal-worker-guard-BY5seBqp.js.map → internal-worker-guard-C0FJ4b29.js.map} +1 -1
  58. package/dist/{internal-workspace-header-CPZNphnk.js → internal-workspace-header-tvJVAXpv.js} +2 -2
  59. package/dist/{internal-workspace-header-CPZNphnk.js.map → internal-workspace-header-tvJVAXpv.js.map} +1 -1
  60. package/dist/{lifecycle-D8vQXfeC.js → lifecycle-BqWTXaeC.js} +3 -3
  61. package/dist/{lifecycle-D8vQXfeC.js.map → lifecycle-BqWTXaeC.js.map} +1 -1
  62. package/dist/lifecycle-DMRZswwc.js +2 -0
  63. package/dist/lifecycle-FT75ohVw.js +2 -0
  64. package/dist/{lifecycle-MmpJWRcl.js → lifecycle-kpLzHUgD.js} +2 -2
  65. package/dist/{lifecycle-MmpJWRcl.js.map → lifecycle-kpLzHUgD.js.map} +1 -1
  66. package/dist/main.js +21 -21
  67. package/dist/{max-profile-contract-Bl7I_EOC.js → max-profile-contract-MJJt0zm-.js} +2 -2
  68. package/dist/{max-profile-contract-Bl7I_EOC.js.map → max-profile-contract-MJJt0zm-.js.map} +1 -1
  69. package/dist/{mcp-workspace-header-DX_mD0JT.js → mcp-workspace-header-B77WqVFw.js} +2 -2
  70. package/dist/{mcp-workspace-header-DX_mD0JT.js.map → mcp-workspace-header-B77WqVFw.js.map} +1 -1
  71. package/dist/{models-BjCRO0AC.js → models-68HDOEPK.js} +3 -3
  72. package/dist/{models-BjCRO0AC.js.map → models-68HDOEPK.js.map} +1 -1
  73. package/dist/{orchestration-Dn5v8c0a.js → orchestration-Ccmfslh4.js} +3 -3
  74. package/dist/{orchestration-Dn5v8c0a.js.map → orchestration-Ccmfslh4.js.map} +1 -1
  75. package/dist/{paths-P5ajjpzU.js → paths-CpbTHKeP.js} +3 -3
  76. package/dist/{paths-P5ajjpzU.js.map → paths-CpbTHKeP.js.map} +1 -1
  77. package/dist/paths-Dfivvq21.js +2 -0
  78. package/dist/{peer-mcp-personas-CnYMTizo.js → peer-mcp-personas-CeB2Kcn2.js} +184 -76
  79. package/dist/peer-mcp-personas-CeB2Kcn2.js.map +1 -0
  80. package/dist/{plan-review-hook-CfZBvsHd.js → plan-review-hook-ciat1jgZ.js} +4 -4
  81. package/dist/{plan-review-hook-CfZBvsHd.js.map → plan-review-hook-ciat1jgZ.js.map} +1 -1
  82. package/dist/{prompt-submit-hook-CRH6m7Vz.js → prompt-submit-hook-C8q_hDOv.js} +21 -17
  83. package/dist/prompt-submit-hook-C8q_hDOv.js.map +1 -0
  84. package/dist/{provision-D5KOOw6n.js → provision-DZLsyRYh.js} +7 -6
  85. package/dist/provision-DZLsyRYh.js.map +1 -0
  86. package/dist/{self-invocation-DBWyjvGm.js → self-invocation-DIUyoRgL.js} +2 -2
  87. package/dist/{self-invocation-DBWyjvGm.js.map → self-invocation-DIUyoRgL.js.map} +1 -1
  88. package/dist/{serve-fJWhiivo.js → serve-ik_96Q2Z.js} +33 -21
  89. package/dist/serve-ik_96Q2Z.js.map +1 -0
  90. package/dist/{server-setup-DHMPOXKT.js → server-setup-CK3O_Hwf.js} +37 -13
  91. package/dist/{server-setup-DHMPOXKT.js.map → server-setup-CK3O_Hwf.js.map} +1 -1
  92. package/dist/{service-backend-DYEPoszR.js → service-backend-7SPDLUB9.js} +411 -25
  93. package/dist/service-backend-7SPDLUB9.js.map +1 -0
  94. package/dist/{start-Gs4jAwUR.js → start-DPOJJSvp.js} +4 -4
  95. package/dist/{start-Gs4jAwUR.js.map → start-DPOJJSvp.js.map} +1 -1
  96. package/dist/{state-BlMpEFAt.js → state-CVp30CBF.js} +7 -1
  97. package/dist/state-CVp30CBF.js.map +1 -0
  98. package/dist/{stop-gate-hook-BACb8dlj.js → stop-gate-hook-DZVfKoSh.js} +4 -4
  99. package/dist/{stop-gate-hook-BACb8dlj.js.map → stop-gate-hook-DZVfKoSh.js.map} +1 -1
  100. package/dist/{stop-gate-policy-D6jIeOXB.js → stop-gate-policy-Gd_cNT9-.js} +3 -3
  101. package/dist/{stop-gate-policy-D6jIeOXB.js.map → stop-gate-policy-Gd_cNT9-.js.map} +1 -1
  102. package/dist/{token-Dlb_84hW.js → token-DATA_OQK.js} +5 -383
  103. package/dist/token-DATA_OQK.js.map +1 -0
  104. package/dist/upstream-retry-i1k1Xai2.js +383 -0
  105. package/dist/upstream-retry-i1k1Xai2.js.map +1 -0
  106. package/dist/{worker-dispatch-DtjQchvM.js → worker-dispatch-lRhno09M.js} +2 -2
  107. package/dist/{worker-dispatch-DtjQchvM.js.map → worker-dispatch-lRhno09M.js.map} +1 -1
  108. package/docs/bluebird-search.md +338 -0
  109. package/package.json +3 -2
  110. package/dist/attribution-settings-DepziZU8.js.map +0 -1
  111. package/dist/claude-Dw4V8o8l.js.map +0 -1
  112. package/dist/codex-CXOpv4WP.js.map +0 -1
  113. package/dist/engine-CYba_zi7.js +0 -2
  114. package/dist/exec-COUT4QsS.js.map +0 -1
  115. package/dist/index-cmd-DUjQs9zw.js +0 -182
  116. package/dist/index-cmd-DUjQs9zw.js.map +0 -1
  117. package/dist/internal-aic-status-Cfl5HiAN.js.map +0 -1
  118. package/dist/internal-prompt-submit-CD0UFkT-.js.map +0 -1
  119. package/dist/lifecycle-B2eB8nRg.js +0 -2
  120. package/dist/lifecycle-Dz-Rq8pD.js +0 -2
  121. package/dist/paths-DVXBtLyo.js +0 -2
  122. package/dist/peer-mcp-personas-CnYMTizo.js.map +0 -1
  123. package/dist/prompt-submit-hook-CRH6m7Vz.js.map +0 -1
  124. package/dist/provision-D5KOOw6n.js.map +0 -1
  125. package/dist/serve-fJWhiivo.js.map +0 -1
  126. package/dist/service-backend-DYEPoszR.js.map +0 -1
  127. package/dist/state-BlMpEFAt.js.map +0 -1
  128. package/dist/token-Dlb_84hW.js.map +0 -1
@@ -1,182 +0,0 @@
1
- import { a as kickBackgroundInit, c as waitForInit, d as freshnessVerdict, h as validateIndexIntegrity, l as colbertProjectDir, m as readColbertMeta, n as selectServerVariant, p as indexDirSignature, r as semanticBackend, u as completedIndexOnDisk, v as provisionColbert, w as validateWorkspace, y as provisionNextPlaidServer } from "./service-backend-DYEPoszR.js";
2
- import { t as PATHS } from "./paths-P5ajjpzU.js";
3
- import { i as parseBoolEnv } from "./exec-COUT4QsS.js";
4
- import { r as registerColbertExitHandlers } from "./lifecycle-D8vQXfeC.js";
5
- import { defineCommand } from "citty";
6
- import consola from "consola";
7
- import * as os$1 from "node:os";
8
- import process from "node:process";
9
- //#region src/index-cmd.ts
10
- /**
11
- * `github-router index` — build the semantic code-search index in the
12
- * foreground, without starting the proxy (`start`/`claude`/`codex`).
13
- *
14
- * Phase 4a: drives the CURRENT colbert backend (foreground `init` with
15
- * progress). The explicit invocation IS the opt-in — `--search` is not
16
- * required — but `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` still hard-disables
17
- * (building an index that can never be served is pointless). With
18
- * `GH_ROUTER_SEMANTIC_BACKEND=service`, the command additionally
19
- * pre-pulls the server binary for the auto-detected variant (GPU→cuda,
20
- * else cpu); the CLI surface (workspace/status/timeout/exit codes) stays
21
- * stable across backends.
22
- *
23
- * Exit codes: 0 = fresh or successfully built; 1 = provision/build
24
- * failure; 2 = usage error (bad workspace, hard-disabled).
25
- */
26
- const POLL_MS = 1e4;
27
- function cpuCount() {
28
- try {
29
- const n = os$1.cpus().length;
30
- return Number.isSafeInteger(n) && n > 0 ? n : 4;
31
- } catch {
32
- return 4;
33
- }
34
- }
35
- async function collectStatus(workspace) {
36
- const { verdict, head, dirty } = await freshnessVerdict(workspace);
37
- const status = {
38
- workspace,
39
- verdict,
40
- indexOnDisk: await completedIndexOnDisk(workspace)
41
- };
42
- const projectDir = await colbertProjectDir(workspace);
43
- if (projectDir) {
44
- const integrity = validateIndexIntegrity(`${projectDir}/index`);
45
- if (integrity.verdict === "coherent") {
46
- status.shards = integrity.shardCount;
47
- status.embeddings = integrity.embeddingCount;
48
- } else status.integrity = integrity.verdict;
49
- }
50
- const meta = await readColbertMeta(workspace);
51
- if (meta?.lastIndexedAt) status.lastIndexedAt = meta.lastIndexedAt;
52
- if (head !== void 0) status.head = head.slice(0, 12);
53
- if (dirty !== void 0) status.dirty = dirty;
54
- return status;
55
- }
56
- function printStatus(s) {
57
- consola.info(`workspace: ${s.workspace}`);
58
- consola.info(`verdict: ${s.verdict}`);
59
- consola.info(`index: ${s.indexOnDisk ? "present" : "absent"}`);
60
- if (s.shards !== void 0) consola.info(`shards: ${s.shards} (${s.embeddings ?? 0} embeddings)`);
61
- if (s.integrity && s.integrity !== "not-built") consola.info(`integrity: ${s.integrity}`);
62
- if (s.head !== void 0) consola.info(`head: ${s.head}${s.dirty ? " (dirty)" : ""}`);
63
- if (s.lastIndexedAt) consola.info(`indexed: ${s.lastIndexedAt}`);
64
- }
65
- function sleep(ms) {
66
- return new Promise((resolve) => {
67
- setTimeout(resolve, ms).unref?.();
68
- });
69
- }
70
- const indexCmd = defineCommand({
71
- meta: {
72
- name: "index",
73
- description: "Build the semantic code-search index for a workspace in the foreground (no proxy needed)"
74
- },
75
- args: {
76
- workspace: {
77
- alias: "w",
78
- type: "string",
79
- description: "Absolute path to the repo to index (default: cwd)"
80
- },
81
- status: {
82
- type: "boolean",
83
- default: false,
84
- description: "Print index status and exit (no build)"
85
- },
86
- timeout: {
87
- type: "string",
88
- description: "Max minutes to wait for the build (0 = none, default 0)"
89
- }
90
- },
91
- async run({ args }) {
92
- const rawWorkspace = typeof args.workspace === "string" && args.workspace.length > 0 ? args.workspace : process.cwd();
93
- const ws = validateWorkspace(rawWorkspace);
94
- if (!ws.ok || !ws.canonical) {
95
- consola.error(`index: ${ws.error ?? "workspace validation failed"}`);
96
- process.exitCode = 2;
97
- return;
98
- }
99
- const workspace = ws.canonical;
100
- if (parseBoolEnv(process.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) {
101
- consola.error("index: semantic search is hard-disabled (GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1); nothing to build");
102
- process.exitCode = 2;
103
- return;
104
- }
105
- if (args.status === true) {
106
- printStatus(await collectStatus(workspace));
107
- return;
108
- }
109
- const timeoutMin = args.timeout === void 0 ? 0 : Number(args.timeout);
110
- if (args.timeout !== void 0 && !(Number.isFinite(timeoutMin) && timeoutMin >= 0)) {
111
- consola.error("index: --timeout must be a non-negative number of minutes");
112
- process.exitCode = 2;
113
- return;
114
- }
115
- const deadlineMs = timeoutMin > 0 ? Date.now() + timeoutMin * 6e4 : Number.POSITIVE_INFINITY;
116
- if (process.env.GH_ROUTER_COLBERT_PARALLEL === void 0) {
117
- process.env.GH_ROUTER_COLBERT_PARALLEL = String(cpuCount());
118
- consola.debug(`index: parallelism defaulted to ${cpuCount()} sessions (override with GH_ROUTER_COLBERT_PARALLEL)`);
119
- }
120
- registerColbertExitHandlers();
121
- consola.info(`Provisioning semantic-search artifacts into ${PATHS.COLBERT_INDICES_DIR}…`);
122
- try {
123
- const result = await provisionColbert();
124
- if (result.status !== "ready") {
125
- consola.error(`index: provision ${result.status}${result.reason ? ` (${result.reason})` : ""}`);
126
- process.exitCode = 1;
127
- return;
128
- }
129
- } catch (err) {
130
- consola.error("index: provision threw:", err);
131
- process.exitCode = 1;
132
- return;
133
- }
134
- if (semanticBackend() === "service") try {
135
- const variant = await selectServerVariant();
136
- const server = await provisionNextPlaidServer(variant);
137
- if (server.path) consola.info(`index: service backend ready (${variant}: ${server.path})`);
138
- else consola.warn(`index: service binary unavailable (${server.reason ?? "unknown"}) — first query provisions on demand`);
139
- } catch (err) {
140
- consola.warn("index: service provision skipped:", err);
141
- }
142
- const first = await freshnessVerdict(workspace);
143
- if (first.verdict === "fresh") {
144
- consola.success("index is already fresh — nothing to build");
145
- printStatus(await collectStatus(workspace));
146
- return;
147
- }
148
- if (first.verdict === "failed") consola.warn("index: last build failed; starting one bounded rebuild attempt");
149
- consola.info(`Building semantic index for ${workspace} (freshness: ${first.verdict})…`);
150
- kickBackgroundInit(workspace);
151
- const startMs = Date.now();
152
- for (;;) {
153
- if (Date.now() > deadlineMs) {
154
- consola.error(`index: timed out after ${timeoutMin}min — the background build continues; retry or raise --timeout`);
155
- process.exitCode = 1;
156
- return;
157
- }
158
- await waitForInit(workspace).catch(() => {});
159
- const v = await freshnessVerdict(workspace);
160
- const elapsedS = Math.round((Date.now() - startMs) / 1e3);
161
- if (v.verdict === "fresh") {
162
- consola.success(`index ready in ${elapsedS}s`);
163
- printStatus(await collectStatus(workspace));
164
- return;
165
- }
166
- if (v.verdict === "failed" || v.verdict === "crashed" || v.verdict === "corrupt") {
167
- consola.error(`index: build ended ${v.verdict} — lexical code search still works; see the proxy error log for the failure class`);
168
- process.exitCode = 1;
169
- return;
170
- }
171
- const sig = indexDirSignature(workspace);
172
- const progress = sig.kind === "observed" ? ` [${sig.signature}]` : " [starting…]";
173
- consola.info(`… ${elapsedS}s elapsed (freshness: ${v.verdict})${progress}`);
174
- await sleep(POLL_MS);
175
- kickBackgroundInit(workspace);
176
- }
177
- }
178
- });
179
- //#endregion
180
- export { indexCmd };
181
-
182
- //# sourceMappingURL=index-cmd-DUjQs9zw.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-cmd-DUjQs9zw.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). 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). With\n * `GH_ROUTER_SEMANTIC_BACKEND=service`, the command additionally\n * pre-pulls the server binary for the auto-detected variant (GPU→cuda,\n * else cpu); the CLI surface (workspace/status/timeout/exit codes) stays\n * stable across backends.\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 selectServerVariant,\n semanticBackend,\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\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 },\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 if (args.status === true) {\n printStatus(await collectStatus(workspace));\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 // Service backend selected: pre-pull the server binary for the\n // auto-detected variant now, so the first query doesn't pay the\n // download + cold start. Best-effort — a miss just defers to the\n // lazy provision on first query (or the colgrep/lexical fallback).\n if (semanticBackend() === \"service\") {\n try {\n const 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 {\n consola.warn(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — first query provisions on demand`,\n );\n }\n } catch (err) {\n consola.warn(\"index: service provision skipped:\", err);\n }\n }\n\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});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,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,QAAQ,KAAK,cAAc,EAAE,WAAW;CACxC,QAAQ,KAAK,cAAc,EAAE,SAAS;CACtC,QAAQ,KAAK,cAAc,EAAE,cAAc,YAAY,UAAU;CACjE,IAAI,EAAE,WAAW,KAAA,GACf,QAAQ,KAAK,cAAc,EAAE,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Y;IAC3B,QAAQ,MACN,0BAA0B,WAAW,+DACvC;IACA,QAAQ,WAAW;IACnB;GACF;GAGA,MAAM,YAAY,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;GAC3C,MAAM,IAAI,MAAM,iBAAiB,SAAS;GAC1C,MAAM,WAAW,KAAK,OAAO,KAAK,IAAI,IAAI,WAAW,GAAI;GACzD,IAAI,EAAE,YAAY,SAAS;IACzB,QAAQ,QAAQ,kBAAkB,SAAS,EAAE;IAC7C,YAAY,MAAM,cAAc,SAAS,CAAC;IAC1C;GACF;GACA,IACE,EAAE,YAAY,YACd,EAAE,YAAY,aACd,EAAE,YAAY,WACd;IACA,QAAQ,MACN,sBAAsB,EAAE,QAAQ,kFAClC;IACA,QAAQ,WAAW;IACnB;GACF;GAGA,MAAM,MAAM,kBAAkB,SAAS;GACvC,MAAM,WACJ,IAAI,SAAS,aAAa,KAAK,IAAI,UAAU,KAAK;GACpD,QAAQ,KACN,KAAK,SAAS,wBAAwB,EAAE,QAAQ,GAAG,UACrD;GACA,MAAM,MAAM,OAAO;GAEnB,mBAAmB,SAAS;EAC9B;CACF;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"internal-aic-status-Cfl5HiAN.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 } = 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 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,IAAI;AACpB,MAAM,UAAU,GAAG,IAAI;AACvB,MAAM,OAAO,GAAG,IAAI;AACpB,MAAM,YAAY,GAAG,IAAI;AAEzB,MAAM,cAAc;AACpB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,MAAM,WAAW,GAAG,IAAI,KAAK;AAkB7B,SAAS,SAAS,OAAqD;CACrE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D;CAEF,OAAO;AACT;AAEA,SAAS,aAAa,OAAoC;CACxD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AACvE;AAEA,SAAS,eAAe,OAAoC;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-prompt-submit.ts"],"sourcesContent":["/**\n * The internal `internal-prompt-submit` subcommand: the executable a spawned\n * Claude Code session's `UserPromptSubmit` hook invokes (registered into the\n * mirrored settings.json by the launcher). It serves the front-end of the\n * floor-raising surface on one event:\n * 1. resets the Stop-gate's per-session block budget (making `maxBlocks`\n * per-prompt);\n * 2. stashes the prompt + surfaces the prior turn's advisory review findings;\n * 3. for a non-trivial prompt, injects a GROUNDED, user-derived scope/goal\n * note (one gpt-5.6-luna call at high effort over the prompt + grounding\n * code search — semantic-first when --search is on, lexical-only\n * otherwise) — or, when the proxy URL/nonce isn't wired or anything errors,\n * falls open to the v1 regex goal.\n *\n * ALWAYS exits 0 (never blocks the prompt): the steer is additive context, and a\n * UserPromptSubmit hook that exit-2'd would refuse the user's prompt. The pure\n * v1 path (`decidePromptSubmit`) is the fail-open fallback; V2\n * (`decidePromptSubmitV2`) layers the grounded enrichment on top via injected IO.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { readFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { parseBoolEnv } from \"./lib/exec\"\nimport { callInference, callMcpTool, hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport { fileBlockBudget } from \"./lib/orchestration/stop-gate-hook\"\nimport {\n decidePromptSubmit,\n decidePromptSubmitV2,\n type PromptSubmitDecision,\n} from \"./lib/orchestration/prompt-submit-hook\"\nimport {\n fileFindingsStore,\n fileLastPromptStore,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races the\n * process teardown and trips a `uv_async_send` assertion; a synchronous read has\n * no such handle. Hooks always receive piped/redirected stdin, so this never\n * blocks (guarded against an interactive TTY, and any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/** Parse the session cwd from the payload — the workspace the grounding search\n * runs in. Falls back to the process cwd. */\nfunction workspaceFromStdin(stdin: string): string {\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const cwd = (p as { cwd?: unknown }).cwd\n if (typeof cwd === \"string\" && cwd.length > 0) return cwd\n }\n } catch {\n /* fall through */\n }\n return process.cwd()\n}\n\n/** Per-call timeout for the grounding search (short — it must not stall the prompt). */\nconst SEARCH_TIMEOUT_MS = 8_000\n/** Per-call timeout for the single scope/goal inference. */\nconst INFER_TIMEOUT_MS = 18_000\n\nexport const internalPromptSubmit = defineCommand({\n meta: {\n name: \"internal-prompt-submit\",\n description:\n \"Internal: the UserPromptSubmit hook. Resets the Stop-gate per-prompt block \"\n + \"budget, surfaces prior-turn review findings, and injects a grounded advisory goal \"\n + \"for non-trivial prompts. Always exit 0.\",\n },\n async run() {\n try {\n const stdin = readStdin()\n const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true\n // Search capability for tip/enrichment text. The launcher exports\n // GH_ROUTER_SEARCH_ENABLED (\"1\"/\"0\") from its resolved\n // `state.searchEnabled` before spawning the session, so this\n // short-lived hook process inherits the launch's capability even when\n // the opt-in came from the `--search` CLI flag (which otherwise would\n // not survive the process boundary). Falls back to the raw opt-in env\n // for standalone invocations.\n const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== undefined\n ? process.env.GH_ROUTER_SEARCH_ENABLED === \"1\"\n : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const runtime = hookMcpRuntimeFromEnv()\n\n let decision: PromptSubmitDecision\n if (runtime) {\n const workspace = workspaceFromStdin(stdin)\n decision = await decidePromptSubmitV2({\n stdin,\n steerEnabled,\n searchEnabled,\n io: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n infer: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: \"gpt-5.6-luna\",\n instructions: system,\n input: user,\n effort: \"high\",\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n readFindings: (sid) => fileFindingsStore(stopReviewStateDir()).read(sid),\n clearFindings: (sid) => fileFindingsStore(stopReviewStateDir()).clear(sid),\n storePrompt: (sid, prompt) => fileLastPromptStore(stopReviewStateDir()).write(sid, prompt),\n },\n })\n } else {\n // Proxy URL/nonce not wired -> the LLM layer is off; use the pure v1 path.\n decision = decidePromptSubmit({ stdin, steerEnabled })\n }\n\n if (decision.resetSession) {\n // Same budget store the Stop hook uses, so a new prompt clears its count.\n await fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\"))\n .reset(decision.resetSession)\n .catch(() => {})\n }\n if (decision.inject.length > 0) {\n await new Promise<void>((resolve) => process.stdout.write(`${decision.inject}\\n`, () => resolve()))\n }\n } catch {\n /* never let the front-end hook disrupt a prompt */\n }\n // Natural exit (exit code 0): a hard process.exit() races libuv stdio teardown\n // on Windows. No handles are kept alive once the (aborted) enrichment settles,\n // so returning lets the process exit cleanly with code 0.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,SAAS,mBAAmB,OAAuB;CACjD,IAAI;EACF,MAAM,IAAa,KAAK,MAAM,KAAK;EACnC,IAAI,KAAK,OAAO,MAAM,UAAU;GAC9B,MAAM,MAAO,EAAwB;GACrC,IAAI,OAAO,QAAQ,YAAY,IAAI,SAAS,GAAG,OAAO;EACxD;CACF,QAAQ,CAER;CACA,OAAO,QAAQ,I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AY,CAAC,CAAC;GAEnB,IAAI,SAAS,OAAO,SAAS,GAC3B,MAAM,IAAI,SAAe,YAAY,QAAQ,OAAO,MAAM,GAAG,SAAS,OAAO,WAAW,QAAQ,CAAC,CAAC;EAEtG,QAAQ,CAER;EAIA,QAAQ,WAAW;CACrB;AACF,CAAC"}
@@ -1,2 +0,0 @@
1
- import { o as sweepStaleWorktreesAtBoot } from "./lifecycle-MmpJWRcl.js";
2
- export { sweepStaleWorktreesAtBoot };
@@ -1,2 +0,0 @@
1
- import { o as sweepStaleColbertMetaAtBoot } from "./lifecycle-D8vQXfeC.js";
2
- export { sweepStaleColbertMetaAtBoot };
@@ -1,2 +0,0 @@
1
- import { t as PATHS } from "./paths-P5ajjpzU.js";
2
- export { PATHS };