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.
Files changed (126) 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-7dFpObGh.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-C3-yBGzw.js → claude-BQQPdXLb.js} +37 -29
  15. package/dist/claude-BQQPdXLb.js.map +1 -0
  16. package/dist/{codex-C3hcVSOm.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-BUhtwkyE.js → gate-discovery-DbwVeERm.js} +6 -6
  26. package/dist/{gate-discovery-BUhtwkyE.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-k3oWl0n4.js → index-cmd-DXYWgKS6.js} +5 -5
  32. package/dist/{index-cmd-k3oWl0n4.js.map → index-cmd-DXYWgKS6.js.map} +1 -1
  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-DBrlosd0.js → internal-stop-hook-DO8RKfKB.js} +6 -6
  53. package/dist/{internal-stop-hook-DBrlosd0.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-Dztywua2.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-CjBt5wEK.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-C3LCkM-o.js → serve-ik_96Q2Z.js} +33 -21
  89. package/dist/serve-ik_96Q2Z.js.map +1 -0
  90. package/dist/{server-setup-DrSUlFZ_.js → server-setup-CK3O_Hwf.js} +37 -13
  91. package/dist/{server-setup-DrSUlFZ_.js.map → server-setup-CK3O_Hwf.js.map} +1 -1
  92. package/dist/{service-backend-ByT0gUc8.js → service-backend-7SPDLUB9.js} +7 -7
  93. package/dist/service-backend-7SPDLUB9.js.map +1 -0
  94. package/dist/{start-CY1nnbB4.js → start-DPOJJSvp.js} +4 -4
  95. package/dist/{start-CY1nnbB4.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-7dFpObGh.js.map +0 -1
  111. package/dist/claude-C3-yBGzw.js.map +0 -1
  112. package/dist/codex-C3hcVSOm.js.map +0 -1
  113. package/dist/engine-CPdWX70n.js +0 -2
  114. package/dist/exec-COUT4QsS.js.map +0 -1
  115. package/dist/internal-aic-status-Cfl5HiAN.js.map +0 -1
  116. package/dist/internal-prompt-submit-CD0UFkT-.js.map +0 -1
  117. package/dist/lifecycle-B2eB8nRg.js +0 -2
  118. package/dist/lifecycle-Dz-Rq8pD.js +0 -2
  119. package/dist/paths-DVXBtLyo.js +0 -2
  120. package/dist/peer-mcp-personas-Dztywua2.js.map +0 -1
  121. package/dist/prompt-submit-hook-CRH6m7Vz.js.map +0 -1
  122. package/dist/provision-CjBt5wEK.js.map +0 -1
  123. package/dist/serve-C3LCkM-o.js.map +0 -1
  124. package/dist/service-backend-ByT0gUc8.js.map +0 -1
  125. package/dist/state-BlMpEFAt.js.map +0 -1
  126. package/dist/token-Dlb_84hW.js.map +0 -1
package/README.md CHANGED
@@ -115,9 +115,9 @@ For codex-side write capability (a `codex-implementer` persona that can mutate f
115
115
 
116
116
  ### Code search (`mcp__search__code`)
117
117
 
118
- Alongside the peer reviewers, the same MCP surface exposes a `code` tool (under the `search` server — `mcp__search__code`) — fast structured code search over the workspace, ranked by **BM25F** (Robertson, Zaragoza, Taylor 2004) over four code-aware fields: matched line, surrounding context, file path tokens, and a symbol-definition heuristic. On top of that, the top hits get a tree-sitter pass that promotes true identifier-definition sites over incidental string matches; depth is controlled by the optional `structural` argument (`"full"` parses the top 50 hits, `"topN"` parses the top 10 for tighter latency on big repos). A single `notice` field surfaces in the response on the rare occasions an actionable degradation fires — the structural pass overran its 200ms wall-clock budget, or the response hit the 256KB size cap and was truncated; the message text tells the model what to retry. Defaults to a semantic mode (`mode: "semantic"`): it ranks by MEANING via ColBERT over a per-workspace index, and transparently falls back to lexical BM25F when that index isn't ready (building / stale / not yet provisioned), labelling the response `source` (`semantic`, `lexical`, or `lexical-fallback`) so a degrade is never silent. The `lexical` mode is the BM25F + tree-sitter path with shoulder pruning (best for exact symbols); `exact` and `regex` force fixed-string / PCRE2 search, and `ast` matches ast-grep structural patterns. Single-identifier queries in the lexical modes auto-expand across camelCase / snake_case / kebab-case skeletons so `getUserName` also matches `get_user_name`. (This one tool absorbs what was previously a separate `semantic_search` tool; ColBERT semantic search is just its default mode.)
118
+ Alongside the peer reviewers, the same MCP surface exposes a `code` tool (under the `search` server — `mcp__search__code`) — fast structured code search over the workspace. Without a search flag it uses the local lexical engine. Pass `--search` for router-managed local ColBERT semantic search with transparent lexical fallback, or `--bluebird` to route semantic and lexical modes through the Bluebird Azure DevOps index. Bluebird failures remain visible and never silently fall back locally; `exact`, `regex`, and `ast` always stay local. The flags are independent, so `--bluebird` alone never provisions local ColBERT artifacts. See [local semantic search](docs/semantic-search.md) and the [Bluebird protocol and routing reference](docs/bluebird-search.md).
119
119
 
120
- `workspace` is any absolute path the proxy process can read — typically the project root or a sub-tree you're working in. The model picks it. There's no allow-set or secret-shape file denylist: the threat model is symmetric since Claude Code already has Read / Bash / Edit tools that reach the same paths, so gating one tool would have been inconsistency rather than defense. Paths in results are returned relative to the workspace, never absolute.
120
+ The local lexical engine ranks with **BM25F** (Robertson, Zaragoza, Taylor 2004) over matched lines, context, paths, and symbol definitions, then refines top hits with tree-sitter. Single-identifier queries auto-expand across camelCase / snake_case / kebab-case skeletons so `getUserName` also matches `get_user_name`. `workspace` is any absolute path the proxy process can read, and result paths are repository-relative rather than absolute.
121
121
 
122
122
  Ripgrep is provided via the `@vscode/ripgrep` npm dependency (per-platform binary via `optionalDependencies` — no postinstall script needed). The proxy prefers system `rg` on `PATH` when available and falls back to the bundled binary otherwise. To opt into raw query/path logging for debugging, set `GH_ROUTER_DEBUG_CODE_SEARCH=1` — by default the proxy logs only counts and timings.
123
123
 
@@ -269,6 +269,8 @@ Fallback chains fire only on the implicit-default path; explicit `-m`/`--model`
269
269
  | `--codex` | Generate Codex CLI launch command | false |
270
270
  | `--show-token` | Print tokens to console | false |
271
271
  | `--proxy-env` | Use HTTP_PROXY/HTTPS_PROXY env vars | false |
272
+ | `--search` | Enable router-managed local ColBERT semantic search with lexical fallback | false |
273
+ | `--bluebird` | Route semantic and lexical code search through Bluebird; keep exact/regex/AST local | false |
272
274
 
273
275
  Additional flags accepted only by the `claude` subcommand:
274
276
 
@@ -1,4 +1,4 @@
1
- import { t as PATHS } from "./paths-P5ajjpzU.js";
1
+ import { t as PATHS } from "./paths-CpbTHKeP.js";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import fs$1 from "node:fs/promises";
@@ -332,4 +332,4 @@ async function isPidAlive(pid) {
332
332
  //#endregion
333
333
  export { extractAndRecordPricedAic as a, readAicSnapshotFile as c, sweepStaleAicLedgerFiles as d, copilotUsageToWire as f, nanoAiuToCredits as h, extractAndRecordAic as i, recordAic as l, formatAic as m, aicSnapshot as n, formatAicExitSummary as o, extractCopilotUsage as p, aicTotalCredits as r, formatAicStatus as s, aicLedgerPath as t, removeAicLedgerFile as u };
334
334
 
335
- //# sourceMappingURL=aic-ledger-CsBx1crE.js.map
335
+ //# sourceMappingURL=aic-ledger-D4fmThbS.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"aic-ledger-CsBx1crE.js","names":["fsp"],"sources":["../src/lib/aic-usage.ts","../src/lib/aic-ledger.ts"],"sourcesContent":["/**\n * AIC (AI Credits) extraction from upstream Copilot `copilot_usage` fields.\n *\n * Verified live (2026-09-14) on all three native endpoints: `/responses`\n * (non-stream top-level + terminal `response.completed` event), `/chat/completions`\n * (non-stream top-level), and `/v1/messages` (non-stream top-level + terminal\n * `message_delta` event). No special request header is required — the field\n * arrives with the proxy's stock headers.\n *\n * Shape:\n * ```json\n * \"copilot_usage\": {\n * \"token_details\": [\n * {\"batch_size\":1000000,\"cost_per_batch\":20000000000,\n * \"model\":\"gpt-5.6-luna\",\"token_count\":11,\"token_type\":\"input\"},\n * ...\n * ],\n * \"total_nano_aiu\": 820000\n * }\n * ```\n * Credits = `total_nano_aiu / 1e9` (SI nano prefix — the same convention the\n * Copilot SDK docs use; treat GitHub billing docs as source of truth before\n * surfacing currency equivalents). Per-type cost reconstructs as\n * `token_count × cost_per_batch / batch_size / 1e9` (verified arithmetically\n * against `total_nano_aiu` on live captures).\n *\n * All parsing is total and never throws: malformed entries are skipped, and a\n * missing/invalid field yields `undefined` so callers fall back cleanly.\n */\n\n/** One entry of `copilot_usage.token_details`. */\nexport interface CopilotTokenDetail {\n model?: string\n tokenType?: string\n tokenCount: number\n batchSize: number\n costPerBatch: number\n}\n\n/** Parsed `copilot_usage` object. */\nexport interface CopilotUsage {\n totalNanoAiu: number\n tokenDetails: Array<CopilotTokenDetail>\n}\n\n/** Nano-AIU per AI credit (SI prefix, per Copilot SDK docs). */\nexport const NANO_AIU_PER_CREDIT = 1_000_000_000\n\nfunction nonNegativeNumber(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n return 0\n }\n return value\n}\n\nfunction parseTokenDetail(value: unknown): CopilotTokenDetail | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined\n }\n const record = value as Record<string, unknown>\n const batchSize = nonNegativeNumber(record.batch_size)\n if (batchSize <= 0) return undefined\n return {\n ...(typeof record.model === \"string\" && record.model.length > 0\n ? { model: record.model }\n : {}),\n ...(typeof record.token_type === \"string\" && record.token_type.length > 0\n ? { tokenType: record.token_type }\n : {}),\n tokenCount: Math.floor(nonNegativeNumber(record.token_count)),\n batchSize: Math.floor(batchSize),\n costPerBatch: nonNegativeNumber(record.cost_per_batch),\n }\n}\n\n/**\n * Extract a validated `CopilotUsage` from an unknown value (typically\n * `responseBody.copilot_usage` or an SSE event's `copilot_usage`).\n * Returns `undefined` when absent or invalid — never throws.\n */\nexport function extractCopilotUsage(value: unknown): CopilotUsage | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined\n }\n const record = value as Record<string, unknown>\n if (\n typeof record.total_nano_aiu !== \"number\"\n || !Number.isFinite(record.total_nano_aiu)\n || record.total_nano_aiu < 0\n ) {\n return undefined\n }\n const details: Array<CopilotTokenDetail> = []\n if (Array.isArray(record.token_details)) {\n for (const entry of record.token_details) {\n const parsed = parseTokenDetail(entry)\n if (parsed) details.push(parsed)\n }\n }\n return {\n totalNanoAiu: Math.floor(record.total_nano_aiu),\n tokenDetails: details,\n }\n}\n\n/** Convert nano-AIU to AI credits. */\nexport function nanoAiuToCredits(nanoAiu: number): number {\n if (!Number.isFinite(nanoAiu) || nanoAiu <= 0) return 0\n return nanoAiu / NANO_AIU_PER_CREDIT\n}\n\n/** Wire form of `copilot_usage` (as Copilot emits it) for client-facing replay. */\nexport interface CopilotUsageWire {\n total_nano_aiu: number\n token_details: Array<{\n batch_size: number\n cost_per_batch: number\n token_count: number\n token_type?: string\n model?: string\n }>\n}\n\n/**\n * Map a parsed `CopilotUsage` to the upstream wire shape. Client-facing only:\n * used to re-emit the SAME priced reading a synthesizer already recorded to\n * the ledger — the replay must never be recorded again.\n */\nexport function copilotUsageToWire(usage: CopilotUsage): CopilotUsageWire {\n return {\n total_nano_aiu: usage.totalNanoAiu,\n token_details: usage.tokenDetails.map((d) => ({\n batch_size: d.batchSize,\n cost_per_batch: d.costPerBatch,\n token_count: d.tokenCount,\n ...(d.tokenType ? { token_type: d.tokenType } : {}),\n ...(d.model ? { model: d.model } : {}),\n })),\n }\n}\n\n/** Credits for one token-detail entry. */\nexport function creditsForDetail(detail: CopilotTokenDetail): number {\n return nanoAiuToCredits(\n (detail.tokenCount * detail.costPerBatch) / detail.batchSize,\n )\n}\n\n/**\n * Compact display: `12.42` for totals ≥ 0.01, more precision below.\n * Always a plain number string — callers add units/context.\n */\nexport function formatAic(credits: number): string {\n if (!Number.isFinite(credits) || credits <= 0) return \"0\"\n if (credits >= 100) return credits.toFixed(1)\n if (credits >= 1) return credits.toFixed(2)\n if (credits >= 0.01) return credits.toFixed(3)\n return credits.toPrecision(2)\n}\n","/**\n * Per-launch AIC (AI Credits) ledger.\n *\n * Every route handler records upstream `copilot_usage` here as a side effect\n * (bytes pass through untouched). The totals feed two consumers:\n *\n * 1. `internal-aic-status` — runs as a SEPARATE process on every status-line\n * tick, so it cannot read in-process memory. Each `record()` therefore\n * also persists an atomic snapshot file; the ledger path is handed to the\n * spawned child via `GH_ROUTER_AIC_LEDGER` and baked into the statusLine\n * command.\n * 2. The `claude` exit summary — reads the in-process snapshot.\n *\n * Keyed per proxy process (one file per PID under `<APP_DIR>/aic-ledger/`),\n * so concurrent launches never mix. Snapshot writes are best-effort and never\n * throw into the request path. Stale files (dead PID, >24h) are swept at\n * startup of the next record and on shutdown.\n */\n\nimport fs from \"node:fs\"\nimport fsp from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { PATHS } from \"~/lib/paths\"\n\nimport {\n extractCopilotUsage,\n formatAic,\n nanoAiuToCredits,\n type CopilotUsage,\n} from \"./aic-usage\"\n\nexport interface AicModelEntry {\n nanoAiu: number\n requests: number\n}\n\n/** Token counts per model per upstream `token_type`, for the cost table. */\nexport interface AicModelTokens {\n /** Upstream `input` type: fresh (uncached) input tokens. */\n input: number\n /** Upstream `cache_read` type. */\n cache_read: number\n /** Upstream `cache_write` type. */\n cache_write: number\n /** Upstream `output` type. */\n output: number\n /** Any other/missing `token_type`: never dropped silently, priced at input. */\n other: number\n}\n\nexport interface AicSnapshot {\n totalNanoAiu: number\n requests: number\n perModel: Record<string, AicModelEntry>\n /** Reconstructed nano-AIU per token_type (input/cache_read/cache_write/output). */\n perTokenType: Record<string, number>\n /** Raw token counts per model per type (exit cost table + rate math). */\n tokensByModel: Record<string, AicModelTokens>\n}\n\nfunction emptyModelTokens(): AicModelTokens {\n return { input: 0, cache_read: 0, cache_write: 0, output: 0, other: 0 }\n}\n\nfunction emptySnapshot(): AicSnapshot {\n return {\n totalNanoAiu: 0,\n requests: 0,\n perModel: {},\n perTokenType: {},\n tokensByModel: {},\n }\n}\n\nlet ledger: AicSnapshot = emptySnapshot()\n\n/** @internal — reset module state between test cases. */\nexport function __resetAicLedgerForTests(): void {\n ledger = emptySnapshot()\n}\n\nfunction ledgerDir(): string {\n return (\n process.env.GH_ROUTER_AIC_LEDGER_DIR ?? path.join(PATHS.APP_DIR, \"aic-ledger\")\n )\n}\n\n/**\n * Snapshot file for this proxy process. Overridable via `GH_ROUTER_AIC_LEDGER`\n * (used by tests and by the spawned child's env).\n */\nexport function aicLedgerPath(): string {\n const override = process.env.GH_ROUTER_AIC_LEDGER\n if (override && override.length > 0) return override\n return path.join(ledgerDir(), `${process.pid}.json`)\n}\n\n/** Best-effort persist; never throws. */\nfunction persistBestEffort(): void {\n try {\n const file = aicLedgerPath()\n fs.mkdirSync(path.dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.tmp`\n fs.writeFileSync(tmp, `${JSON.stringify(ledger)}\\n`, { mode: 0o600 })\n fs.renameSync(tmp, file)\n } catch {\n // Telemetry must never break a request.\n }\n}\n\n/**\n * Record one upstream `copilot_usage` reading. No-op on undefined.\n * `model` is the resolved (Copilot-side) model id when known.\n */\nexport function recordAic(\n model: string | undefined,\n usage: CopilotUsage | undefined,\n): void {\n if (!usage) return\n ledger.totalNanoAiu += usage.totalNanoAiu\n ledger.requests += 1\n const key = model && model.length > 0 ? model : \"unknown\"\n const entry = ledger.perModel[key] ?? { nanoAiu: 0, requests: 0 }\n entry.nanoAiu += usage.totalNanoAiu\n entry.requests += 1\n ledger.perModel[key] = entry\n ledger.tokensByModel[key] ??= emptyModelTokens()\n for (const detail of usage.tokenDetails) {\n const type = detail.tokenType ?? \"unknown\"\n // Reconstruct nano-AIU per token type from the priced detail.\n const nano = Math.round(\n (detail.tokenCount * detail.costPerBatch) / detail.batchSize,\n )\n ledger.perTokenType[type] = (ledger.perTokenType[type] ?? 0) + nano\n // Retain raw counts per model per type for the exit cost table. The\n // hook only reads them; pricing still flows exclusively through nano.\n const counts = ledger.tokensByModel[key] ?? emptyModelTokens()\n const bucket = tokenBucket(type)\n counts[bucket] += detail.tokenCount\n ledger.tokensByModel[key] = counts\n }\n persistBestEffort()\n}\n\n/**\n * Map an upstream `token_type` to its count bucket. Unknown/missing types\n * land in `other` (priced at the model's input factor downstream) rather\n * than being dropped — the observed universe is the four known types, this\n * is the just-in-case bucket.\n */\nfunction tokenBucket(type: string): keyof AicModelTokens {\n switch (type) {\n case \"input\":\n return \"input\"\n case \"cache_read\":\n return \"cache_read\"\n case \"cache_write\":\n return \"cache_write\"\n case \"output\":\n return \"output\"\n default:\n return \"other\"\n }\n}\n\n/**\n * Extract `copilot_usage` from a response object or SSE event-data object,\n * record it under `model`, and return its nano-AIU for `logRequest`.\n * Returns `undefined` when absent/invalid. Never throws.\n */\nexport function extractAndRecordAic(\n model: string | undefined,\n container: unknown,\n): number | undefined {\n if (!container || typeof container !== \"object\" || Array.isArray(container)) {\n return undefined\n }\n const usage = extractCopilotUsage(\n (container as Record<string, unknown>).copilot_usage,\n )\n if (!usage) return undefined\n recordAic(model, usage)\n return usage.totalNanoAiu\n}\n\n/**\n * Streaming-tap variant of `extractAndRecordAic`: identical, except a\n * zero-nano reading is treated as \"no reading yet\" — it is NOT recorded\n * and `undefined` is returned so the tap keeps scanning.\n *\n * Why: Copilot's `/chat/completions` streams emit interim chunks carrying\n * `copilot_usage` with `total_nano_aiu: 0` before the terminal chunk with\n * the real value (verified live on gemini-3.8-flash). A first-wins tap\n * built on `extractAndRecordAic` latches on the zero frame and drops the\n * terminal value, under-recording the whole stream as free. Every\n * streaming tap must use this variant; non-streaming callers keep\n * `extractAndRecordAic` so a genuinely free call still counts its request.\n */\nexport function extractAndRecordPricedAic(\n model: string | undefined,\n container: unknown,\n): number | undefined {\n if (!container || typeof container !== \"object\" || Array.isArray(container)) {\n return undefined\n }\n const usage = extractCopilotUsage(\n (container as Record<string, unknown>).copilot_usage,\n )\n if (!usage || usage.totalNanoAiu <= 0) return undefined\n recordAic(model, usage)\n return usage.totalNanoAiu\n}\n\n/** In-process snapshot (defensive copy). */\nexport function aicSnapshot(): AicSnapshot {\n return {\n totalNanoAiu: ledger.totalNanoAiu,\n requests: ledger.requests,\n perModel: Object.fromEntries(\n Object.entries(ledger.perModel).map(([k, v]) => [k, { ...v }]),\n ),\n perTokenType: { ...ledger.perTokenType },\n tokensByModel: Object.fromEntries(\n Object.entries(ledger.tokensByModel).map(([k, v]) => [k, { ...v }]),\n ),\n }\n}\n\n/**\n * Read a persisted snapshot file (the status-hook path). Returns undefined\n * when missing/unreadable — the hook then prints nothing.\n */\nexport function readAicSnapshotFile(file: string): AicSnapshot | undefined {\n try {\n const raw = fs.readFileSync(file, \"utf8\")\n const parsed: unknown = JSON.parse(raw)\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return undefined\n }\n const record = parsed as Record<string, unknown>\n if (\n typeof record.totalNanoAiu !== \"number\"\n || typeof record.requests !== \"number\"\n ) {\n return undefined\n }\n return {\n totalNanoAiu: Math.max(0, Math.floor(record.totalNanoAiu)),\n requests: Math.max(0, Math.floor(record.requests)),\n perModel:\n record.perModel && typeof record.perModel === \"object\"\n ? (record.perModel as AicSnapshot[\"perModel\"])\n : {},\n perTokenType:\n record.perTokenType && typeof record.perTokenType === \"object\"\n ? (record.perTokenType as AicSnapshot[\"perTokenType\"])\n : {},\n // Pre-tokens files (written before this field existed) read as empty\n // rather than failing the hook.\n tokensByModel: sanitizeModelTokens(record.tokensByModel),\n }\n } catch {\n return undefined\n }\n}\n\n/** Best-effort sanitize of persisted per-model token counts; `{}` when absent. */\nfunction sanitizeModelTokens(value: unknown): Record<string, AicModelTokens> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {}\n const out: Record<string, AicModelTokens> = {}\n for (const [model, counts] of Object.entries(value as Record<string, unknown>)) {\n if (!counts || typeof counts !== \"object\" || Array.isArray(counts)) continue\n const entry = counts as Record<string, unknown>\n const clean = emptyModelTokens()\n let ok = true\n for (const field of [\"input\", \"cache_read\", \"cache_write\", \"output\", \"other\"] as const) {\n const n = entry[field]\n if (n === undefined) continue\n if (typeof n !== \"number\" || !Number.isFinite(n) || n < 0) {\n ok = false\n break\n }\n clean[field] = Math.floor(n)\n }\n if (ok) out[model] = clean\n }\n return out\n}\n\n/** Total credits for a snapshot. */\nexport function aicTotalCredits(snapshot: AicSnapshot): number {\n return nanoAiuToCredits(snapshot.totalNanoAiu)\n}\n\n/** One-line status fragment: `[AIC 12.42]`. Empty string when nothing recorded. */\nexport function formatAicStatus(snapshot: AicSnapshot): string {\n if (snapshot.requests === 0 || snapshot.totalNanoAiu <= 0) return \"\"\n return `[AIC ${formatAic(aicTotalCredits(snapshot))}]`\n}\n\n/**\n * Multi-line exit summary. `verbose` adds per-model and per-type breakdowns\n * (only from upstream-measured values — never estimates).\n */\nexport function formatAicExitSummary(\n snapshot: AicSnapshot,\n opts: { verbose?: boolean } = {},\n): string {\n const total = aicTotalCredits(snapshot)\n const reqWord = snapshot.requests === 1 ? \"request\" : \"requests\"\n const lines = [\n `AIC consumed this session: ${formatAic(total)} credits (~$${(total / 100).toFixed(2)}) across ${snapshot.requests} ${reqWord}`,\n ]\n if (opts.verbose) {\n const models = Object.entries(snapshot.perModel).sort(\n (a, b) => b[1].nanoAiu - a[1].nanoAiu,\n )\n for (const [model, entry] of models) {\n const rWord = entry.requests === 1 ? \"request\" : \"requests\"\n lines.push(\n ` ${model}: ${formatAic(nanoAiuToCredits(entry.nanoAiu))} credits across ${entry.requests} ${rWord}`,\n )\n }\n const types = Object.entries(snapshot.perTokenType).sort(\n (a, b) => b[1] - a[1],\n )\n if (types.length > 0) {\n lines.push(\n ` by type: ${types.map(([t, n]) => `${t}=${formatAic(nanoAiuToCredits(n))}`).join(\" \")}`,\n )\n }\n }\n return lines.join(\"\\n\")\n}\n\n/** Remove this process's snapshot file; never throws. */\nexport async function removeAicLedgerFile(): Promise<void> {\n try {\n await fsp.rm(aicLedgerPath(), { force: true })\n } catch {\n // Best-effort cleanup.\n }\n}\n\n/** Sweep stale ledger files (dead PID or >24h old); never throws. */\nexport async function sweepStaleAicLedgerFiles(): Promise<void> {\n try {\n const dir = ledgerDir()\n const entries = await fsp.readdir(dir).catch(() => [] as Array<string>)\n const now = Date.now()\n await Promise.all(\n entries.map(async (entry) => {\n if (!/^\\d+\\.json$/.test(entry)) return\n const file = path.join(dir, entry)\n try {\n const stat = await fsp.stat(file)\n const pid = Number(entry.slice(0, -\".json\".length))\n const alive = await isPidAlive(pid)\n if (!alive || now - stat.mtimeMs > 24 * 60 * 60 * 1000) {\n await fsp.rm(file, { force: true })\n }\n } catch {\n // Best-effort per file.\n }\n }),\n )\n } catch {\n // Best-effort sweep.\n }\n}\n\nasync function isPidAlive(pid: number): Promise<boolean> {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;AA8CA,MAAa,sBAAsB;AAEnC,SAAS,kBAAkB,OAAwB;CACjD,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAClE,OAAO;CAET,OAAO;AACT;AAEA,SAAS,iBAAiB,OAAgD;CACxE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D;CAEF,MAAM,SAAS;CACf,MAAM,YAAY,kBAAkB,OAAO,UAAU;CACrD,IAAI,aAAa,GAAG,OAAO,KAAA;CAC3B,OAAO;EACL,GAAI,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,SAAS,IAC1D,EAAE,OAAO,OAAO,MAAM,IACtB,CAAC;EACL,GAAI,OAAO,OAAO,eAAe,YAAY,OAAO,WAAW,SAAS,IACpE,EAAE,WAAW,OAAO,WAAW,IAC/B,CAAC;EACL,YAAY,KAAK,MAAM,kBAAkB,OAAO,WAAW,CAAC;EAC5D,WAAW,KAAK,MAAM,SAAS;EAC/B,cAAc,kBAAkB,OAAO,cAAc;CACvD;AACF;;;;;;AAOA,SAAgB,oBAAoB,OAA0C;CAC5E,IAAI,C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M,UAAU;EACtB,MAAM,UAAU,MAAMA,KAAI,QAAQ,GAAG,CAAC,CAAC,YAAY,CAAC,CAAkB;EACtE,MAAM,MAAM,KAAK,IAAI;EACrB,MAAM,QAAQ,IACZ,QAAQ,IAAI,OAAO,UAAU;GAC3B,IAAI,CAAC,cAAc,KAAK,KAAK,GAAG;GAChC,MAAM,OAAO,KAAK,KAAK,KAAK,KAAK;GACjC,IAAI;IACF,MAAM,OAAO,MAAMA,KAAI,KAAK,IAAI;IAGhC,IAAI,CAAC,MADe,WADR,OAAO,MAAM,MAAM,GAAG,EAAe,CAChB,CAAC,KACpB,MAAM,KAAK,UAAU,OACjC,MAAMA,KAAI,GAAG,MAAM,EAAE,OAAO,KAAK,CAAC;GAEtC,QAAQ,CAER;EACF,CAAC,CACH;CACF,QAAQ,CAER;AACF;AAEA,eAAe,WAAW,KAA+B;CACvD,IAAI,CAAC,OAAO,UAAU,GAAG,KAAK,OAAO,GAAG,OAAO;CAC/C,IAAI;EACF,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"aic-ledger-D4fmThbS.js","names":["fsp"],"sources":["../src/lib/aic-usage.ts","../src/lib/aic-ledger.ts"],"sourcesContent":["/**\n * AIC (AI Credits) extraction from upstream Copilot `copilot_usage` fields.\n *\n * Verified live (2026-09-14) on all three native endpoints: `/responses`\n * (non-stream top-level + terminal `response.completed` event), `/chat/completions`\n * (non-stream top-level), and `/v1/messages` (non-stream top-level + terminal\n * `message_delta` event). No special request header is required — the field\n * arrives with the proxy's stock headers.\n *\n * Shape:\n * ```json\n * \"copilot_usage\": {\n * \"token_details\": [\n * {\"batch_size\":1000000,\"cost_per_batch\":20000000000,\n * \"model\":\"gpt-5.6-luna\",\"token_count\":11,\"token_type\":\"input\"},\n * ...\n * ],\n * \"total_nano_aiu\": 820000\n * }\n * ```\n * Credits = `total_nano_aiu / 1e9` (SI nano prefix — the same convention the\n * Copilot SDK docs use; treat GitHub billing docs as source of truth before\n * surfacing currency equivalents). Per-type cost reconstructs as\n * `token_count × cost_per_batch / batch_size / 1e9` (verified arithmetically\n * against `total_nano_aiu` on live captures).\n *\n * All parsing is total and never throws: malformed entries are skipped, and a\n * missing/invalid field yields `undefined` so callers fall back cleanly.\n */\n\n/** One entry of `copilot_usage.token_details`. */\nexport interface CopilotTokenDetail {\n model?: string\n tokenType?: string\n tokenCount: number\n batchSize: number\n costPerBatch: number\n}\n\n/** Parsed `copilot_usage` object. */\nexport interface CopilotUsage {\n totalNanoAiu: number\n tokenDetails: Array<CopilotTokenDetail>\n}\n\n/** Nano-AIU per AI credit (SI prefix, per Copilot SDK docs). */\nexport const NANO_AIU_PER_CREDIT = 1_000_000_000\n\nfunction nonNegativeNumber(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n return 0\n }\n return value\n}\n\nfunction parseTokenDetail(value: unknown): CopilotTokenDetail | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined\n }\n const record = value as Record<string, unknown>\n const batchSize = nonNegativeNumber(record.batch_size)\n if (batchSize <= 0) return undefined\n return {\n ...(typeof record.model === \"string\" && record.model.length > 0\n ? { model: record.model }\n : {}),\n ...(typeof record.token_type === \"string\" && record.token_type.length > 0\n ? { tokenType: record.token_type }\n : {}),\n tokenCount: Math.floor(nonNegativeNumber(record.token_count)),\n batchSize: Math.floor(batchSize),\n costPerBatch: nonNegativeNumber(record.cost_per_batch),\n }\n}\n\n/**\n * Extract a validated `CopilotUsage` from an unknown value (typically\n * `responseBody.copilot_usage` or an SSE event's `copilot_usage`).\n * Returns `undefined` when absent or invalid — never throws.\n */\nexport function extractCopilotUsage(value: unknown): CopilotUsage | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined\n }\n const record = value as Record<string, unknown>\n if (\n typeof record.total_nano_aiu !== \"number\"\n || !Number.isFinite(record.total_nano_aiu)\n || record.total_nano_aiu < 0\n ) {\n return undefined\n }\n const details: Array<CopilotTokenDetail> = []\n if (Array.isArray(record.token_details)) {\n for (const entry of record.token_details) {\n const parsed = parseTokenDetail(entry)\n if (parsed) details.push(parsed)\n }\n }\n return {\n totalNanoAiu: Math.floor(record.total_nano_aiu),\n tokenDetails: details,\n }\n}\n\n/** Convert nano-AIU to AI credits. */\nexport function nanoAiuToCredits(nanoAiu: number): number {\n if (!Number.isFinite(nanoAiu) || nanoAiu <= 0) return 0\n return nanoAiu / NANO_AIU_PER_CREDIT\n}\n\n/** Wire form of `copilot_usage` (as Copilot emits it) for client-facing replay. */\nexport interface CopilotUsageWire {\n total_nano_aiu: number\n token_details: Array<{\n batch_size: number\n cost_per_batch: number\n token_count: number\n token_type?: string\n model?: string\n }>\n}\n\n/**\n * Map a parsed `CopilotUsage` to the upstream wire shape. Client-facing only:\n * used to re-emit the SAME priced reading a synthesizer already recorded to\n * the ledger — the replay must never be recorded again.\n */\nexport function copilotUsageToWire(usage: CopilotUsage): CopilotUsageWire {\n return {\n total_nano_aiu: usage.totalNanoAiu,\n token_details: usage.tokenDetails.map((d) => ({\n batch_size: d.batchSize,\n cost_per_batch: d.costPerBatch,\n token_count: d.tokenCount,\n ...(d.tokenType ? { token_type: d.tokenType } : {}),\n ...(d.model ? { model: d.model } : {}),\n })),\n }\n}\n\n/** Credits for one token-detail entry. */\nexport function creditsForDetail(detail: CopilotTokenDetail): number {\n return nanoAiuToCredits(\n (detail.tokenCount * detail.costPerBatch) / detail.batchSize,\n )\n}\n\n/**\n * Compact display: `12.42` for totals ≥ 0.01, more precision below.\n * Always a plain number string — callers add units/context.\n */\nexport function formatAic(credits: number): string {\n if (!Number.isFinite(credits) || credits <= 0) return \"0\"\n if (credits >= 100) return credits.toFixed(1)\n if (credits >= 1) return credits.toFixed(2)\n if (credits >= 0.01) return credits.toFixed(3)\n return credits.toPrecision(2)\n}\n","/**\n * Per-launch AIC (AI Credits) ledger.\n *\n * Every route handler records upstream `copilot_usage` here as a side effect\n * (bytes pass through untouched). The totals feed two consumers:\n *\n * 1. `internal-aic-status` — runs as a SEPARATE process on every status-line\n * tick, so it cannot read in-process memory. Each `record()` therefore\n * also persists an atomic snapshot file; the ledger path is handed to the\n * spawned child via `GH_ROUTER_AIC_LEDGER` and baked into the statusLine\n * command.\n * 2. The `claude` exit summary — reads the in-process snapshot.\n *\n * Keyed per proxy process (one file per PID under `<APP_DIR>/aic-ledger/`),\n * so concurrent launches never mix. Snapshot writes are best-effort and never\n * throw into the request path. Stale files (dead PID, >24h) are swept at\n * startup of the next record and on shutdown.\n */\n\nimport fs from \"node:fs\"\nimport fsp from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { PATHS } from \"~/lib/paths\"\n\nimport {\n extractCopilotUsage,\n formatAic,\n nanoAiuToCredits,\n type CopilotUsage,\n} from \"./aic-usage\"\n\nexport interface AicModelEntry {\n nanoAiu: number\n requests: number\n}\n\n/** Token counts per model per upstream `token_type`, for the cost table. */\nexport interface AicModelTokens {\n /** Upstream `input` type: fresh (uncached) input tokens. */\n input: number\n /** Upstream `cache_read` type. */\n cache_read: number\n /** Upstream `cache_write` type. */\n cache_write: number\n /** Upstream `output` type. */\n output: number\n /** Any other/missing `token_type`: never dropped silently, priced at input. */\n other: number\n}\n\nexport interface AicSnapshot {\n totalNanoAiu: number\n requests: number\n perModel: Record<string, AicModelEntry>\n /** Reconstructed nano-AIU per token_type (input/cache_read/cache_write/output). */\n perTokenType: Record<string, number>\n /** Raw token counts per model per type (exit cost table + rate math). */\n tokensByModel: Record<string, AicModelTokens>\n}\n\nfunction emptyModelTokens(): AicModelTokens {\n return { input: 0, cache_read: 0, cache_write: 0, output: 0, other: 0 }\n}\n\nfunction emptySnapshot(): AicSnapshot {\n return {\n totalNanoAiu: 0,\n requests: 0,\n perModel: {},\n perTokenType: {},\n tokensByModel: {},\n }\n}\n\nlet ledger: AicSnapshot = emptySnapshot()\n\n/** @internal — reset module state between test cases. */\nexport function __resetAicLedgerForTests(): void {\n ledger = emptySnapshot()\n}\n\nfunction ledgerDir(): string {\n return (\n process.env.GH_ROUTER_AIC_LEDGER_DIR ?? path.join(PATHS.APP_DIR, \"aic-ledger\")\n )\n}\n\n/**\n * Snapshot file for this proxy process. Overridable via `GH_ROUTER_AIC_LEDGER`\n * (used by tests and by the spawned child's env).\n */\nexport function aicLedgerPath(): string {\n const override = process.env.GH_ROUTER_AIC_LEDGER\n if (override && override.length > 0) return override\n return path.join(ledgerDir(), `${process.pid}.json`)\n}\n\n/** Best-effort persist; never throws. */\nfunction persistBestEffort(): void {\n try {\n const file = aicLedgerPath()\n fs.mkdirSync(path.dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.tmp`\n fs.writeFileSync(tmp, `${JSON.stringify(ledger)}\\n`, { mode: 0o600 })\n fs.renameSync(tmp, file)\n } catch {\n // Telemetry must never break a request.\n }\n}\n\n/**\n * Record one upstream `copilot_usage` reading. No-op on undefined.\n * `model` is the resolved (Copilot-side) model id when known.\n */\nexport function recordAic(\n model: string | undefined,\n usage: CopilotUsage | undefined,\n): void {\n if (!usage) return\n ledger.totalNanoAiu += usage.totalNanoAiu\n ledger.requests += 1\n const key = model && model.length > 0 ? model : \"unknown\"\n const entry = ledger.perModel[key] ?? { nanoAiu: 0, requests: 0 }\n entry.nanoAiu += usage.totalNanoAiu\n entry.requests += 1\n ledger.perModel[key] = entry\n ledger.tokensByModel[key] ??= emptyModelTokens()\n for (const detail of usage.tokenDetails) {\n const type = detail.tokenType ?? \"unknown\"\n // Reconstruct nano-AIU per token type from the priced detail.\n const nano = Math.round(\n (detail.tokenCount * detail.costPerBatch) / detail.batchSize,\n )\n ledger.perTokenType[type] = (ledger.perTokenType[type] ?? 0) + nano\n // Retain raw counts per model per type for the exit cost table. The\n // hook only reads them; pricing still flows exclusively through nano.\n const counts = ledger.tokensByModel[key] ?? emptyModelTokens()\n const bucket = tokenBucket(type)\n counts[bucket] += detail.tokenCount\n ledger.tokensByModel[key] = counts\n }\n persistBestEffort()\n}\n\n/**\n * Map an upstream `token_type` to its count bucket. Unknown/missing types\n * land in `other` (priced at the model's input factor downstream) rather\n * than being dropped — the observed universe is the four known types, this\n * is the just-in-case bucket.\n */\nfunction tokenBucket(type: string): keyof AicModelTokens {\n switch (type) {\n case \"input\":\n return \"input\"\n case \"cache_read\":\n return \"cache_read\"\n case \"cache_write\":\n return \"cache_write\"\n case \"output\":\n return \"output\"\n default:\n return \"other\"\n }\n}\n\n/**\n * Extract `copilot_usage` from a response object or SSE event-data object,\n * record it under `model`, and return its nano-AIU for `logRequest`.\n * Returns `undefined` when absent/invalid. Never throws.\n */\nexport function extractAndRecordAic(\n model: string | undefined,\n container: unknown,\n): number | undefined {\n if (!container || typeof container !== \"object\" || Array.isArray(container)) {\n return undefined\n }\n const usage = extractCopilotUsage(\n (container as Record<string, unknown>).copilot_usage,\n )\n if (!usage) return undefined\n recordAic(model, usage)\n return usage.totalNanoAiu\n}\n\n/**\n * Streaming-tap variant of `extractAndRecordAic`: identical, except a\n * zero-nano reading is treated as \"no reading yet\" — it is NOT recorded\n * and `undefined` is returned so the tap keeps scanning.\n *\n * Why: Copilot's `/chat/completions` streams emit interim chunks carrying\n * `copilot_usage` with `total_nano_aiu: 0` before the terminal chunk with\n * the real value (verified live on gemini-3.8-flash). A first-wins tap\n * built on `extractAndRecordAic` latches on the zero frame and drops the\n * terminal value, under-recording the whole stream as free. Every\n * streaming tap must use this variant; non-streaming callers keep\n * `extractAndRecordAic` so a genuinely free call still counts its request.\n */\nexport function extractAndRecordPricedAic(\n model: string | undefined,\n container: unknown,\n): number | undefined {\n if (!container || typeof container !== \"object\" || Array.isArray(container)) {\n return undefined\n }\n const usage = extractCopilotUsage(\n (container as Record<string, unknown>).copilot_usage,\n )\n if (!usage || usage.totalNanoAiu <= 0) return undefined\n recordAic(model, usage)\n return usage.totalNanoAiu\n}\n\n/** In-process snapshot (defensive copy). */\nexport function aicSnapshot(): AicSnapshot {\n return {\n totalNanoAiu: ledger.totalNanoAiu,\n requests: ledger.requests,\n perModel: Object.fromEntries(\n Object.entries(ledger.perModel).map(([k, v]) => [k, { ...v }]),\n ),\n perTokenType: { ...ledger.perTokenType },\n tokensByModel: Object.fromEntries(\n Object.entries(ledger.tokensByModel).map(([k, v]) => [k, { ...v }]),\n ),\n }\n}\n\n/**\n * Read a persisted snapshot file (the status-hook path). Returns undefined\n * when missing/unreadable — the hook then prints nothing.\n */\nexport function readAicSnapshotFile(file: string): AicSnapshot | undefined {\n try {\n const raw = fs.readFileSync(file, \"utf8\")\n const parsed: unknown = JSON.parse(raw)\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return undefined\n }\n const record = parsed as Record<string, unknown>\n if (\n typeof record.totalNanoAiu !== \"number\"\n || typeof record.requests !== \"number\"\n ) {\n return undefined\n }\n return {\n totalNanoAiu: Math.max(0, Math.floor(record.totalNanoAiu)),\n requests: Math.max(0, Math.floor(record.requests)),\n perModel:\n record.perModel && typeof record.perModel === \"object\"\n ? (record.perModel as AicSnapshot[\"perModel\"])\n : {},\n perTokenType:\n record.perTokenType && typeof record.perTokenType === \"object\"\n ? (record.perTokenType as AicSnapshot[\"perTokenType\"])\n : {},\n // Pre-tokens files (written before this field existed) read as empty\n // rather than failing the hook.\n tokensByModel: sanitizeModelTokens(record.tokensByModel),\n }\n } catch {\n return undefined\n }\n}\n\n/** Best-effort sanitize of persisted per-model token counts; `{}` when absent. */\nfunction sanitizeModelTokens(value: unknown): Record<string, AicModelTokens> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {}\n const out: Record<string, AicModelTokens> = {}\n for (const [model, counts] of Object.entries(value as Record<string, unknown>)) {\n if (!counts || typeof counts !== \"object\" || Array.isArray(counts)) continue\n const entry = counts as Record<string, unknown>\n const clean = emptyModelTokens()\n let ok = true\n for (const field of [\"input\", \"cache_read\", \"cache_write\", \"output\", \"other\"] as const) {\n const n = entry[field]\n if (n === undefined) continue\n if (typeof n !== \"number\" || !Number.isFinite(n) || n < 0) {\n ok = false\n break\n }\n clean[field] = Math.floor(n)\n }\n if (ok) out[model] = clean\n }\n return out\n}\n\n/** Total credits for a snapshot. */\nexport function aicTotalCredits(snapshot: AicSnapshot): number {\n return nanoAiuToCredits(snapshot.totalNanoAiu)\n}\n\n/** One-line status fragment: `[AIC 12.42]`. Empty string when nothing recorded. */\nexport function formatAicStatus(snapshot: AicSnapshot): string {\n if (snapshot.requests === 0 || snapshot.totalNanoAiu <= 0) return \"\"\n return `[AIC ${formatAic(aicTotalCredits(snapshot))}]`\n}\n\n/**\n * Multi-line exit summary. `verbose` adds per-model and per-type breakdowns\n * (only from upstream-measured values — never estimates).\n */\nexport function formatAicExitSummary(\n snapshot: AicSnapshot,\n opts: { verbose?: boolean } = {},\n): string {\n const total = aicTotalCredits(snapshot)\n const reqWord = snapshot.requests === 1 ? \"request\" : \"requests\"\n const lines = [\n `AIC consumed this session: ${formatAic(total)} credits (~$${(total / 100).toFixed(2)}) across ${snapshot.requests} ${reqWord}`,\n ]\n if (opts.verbose) {\n const models = Object.entries(snapshot.perModel).sort(\n (a, b) => b[1].nanoAiu - a[1].nanoAiu,\n )\n for (const [model, entry] of models) {\n const rWord = entry.requests === 1 ? \"request\" : \"requests\"\n lines.push(\n ` ${model}: ${formatAic(nanoAiuToCredits(entry.nanoAiu))} credits across ${entry.requests} ${rWord}`,\n )\n }\n const types = Object.entries(snapshot.perTokenType).sort(\n (a, b) => b[1] - a[1],\n )\n if (types.length > 0) {\n lines.push(\n ` by type: ${types.map(([t, n]) => `${t}=${formatAic(nanoAiuToCredits(n))}`).join(\" \")}`,\n )\n }\n }\n return lines.join(\"\\n\")\n}\n\n/** Remove this process's snapshot file; never throws. */\nexport async function removeAicLedgerFile(): Promise<void> {\n try {\n await fsp.rm(aicLedgerPath(), { force: true })\n } catch {\n // Best-effort cleanup.\n }\n}\n\n/** Sweep stale ledger files (dead PID or >24h old); never throws. */\nexport async function sweepStaleAicLedgerFiles(): Promise<void> {\n try {\n const dir = ledgerDir()\n const entries = await fsp.readdir(dir).catch(() => [] as Array<string>)\n const now = Date.now()\n await Promise.all(\n entries.map(async (entry) => {\n if (!/^\\d+\\.json$/.test(entry)) return\n const file = path.join(dir, entry)\n try {\n const stat = await fsp.stat(file)\n const pid = Number(entry.slice(0, -\".json\".length))\n const alive = await isPidAlive(pid)\n if (!alive || now - stat.mtimeMs > 24 * 60 * 60 * 1000) {\n await fsp.rm(file, { force: true })\n }\n } catch {\n // Best-effort per file.\n }\n }),\n )\n } catch {\n // Best-effort sweep.\n }\n}\n\nasync function isPidAlive(pid: number): Promise<boolean> {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;AA8CA,MAAa,sBAAsB;AAEnC,SAAS,kBAAkB,OAAwB;CACjD,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAClE,OAAO;CAET,OAAO;AACT;AAEA,SAAS,iBAAiB,OAAgD;CACxE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D;CAEF,MAAM,SAAS;CACf,MAAM,YAAY,kBAAkB,OAAO,UAAU;CACrD,IAAI,aAAa,GAAG,OAAO,KAAA;CAC3B,OAAO;EACL,GAAI,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,SAAS,IAC1D,EAAE,OAAO,OAAO,MAAM,IACtB,CAAC;EACL,GAAI,OAAO,OAAO,eAAe,YAAY,OAAO,WAAW,SAAS,IACpE,EAAE,WAAW,OAAO,WAAW,IAC/B,CAAC;EACL,YAAY,KAAK,MAAM,kBAAkB,OAAO,WAAW,CAAC;EAC5D,WAAW,KAAK,MAAM,SAAS;EAC/B,cAAc,kBAAkB,OAAO,cAAc;CACvD;AACF;;;;;;AAOA,SAAgB,oBAAoB,OAA0C;CAC5E,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D;CAEF,MAAM,S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Y,CAAC,CAAkB;EACtE,MAAM,MAAM,KAAK,IAAI;EACrB,MAAM,QAAQ,IACZ,QAAQ,IAAI,OAAO,UAAU;GAC3B,IAAI,CAAC,cAAc,KAAK,KAAK,GAAG;GAChC,MAAM,OAAO,KAAK,KAAK,KAAK,KAAK;GACjC,IAAI;IACF,MAAM,OAAO,MAAMA,KAAI,KAAK,IAAI;IAGhC,IAAI,CAAC,MADe,WADR,OAAO,MAAM,MAAM,GAAG,EAAe,CAChB,CAAC,KACpB,MAAM,KAAK,UAAU,OACjC,MAAMA,KAAI,GAAG,MAAM,EAAE,OAAO,KAAK,CAAC;GAEtC,QAAQ,CAER;EACF,CAAC,CACH;CACF,QAAQ,CAER;AACF;AAEA,eAAe,WAAW,KAA+B;CACvD,IAAI,CAAC,OAAO,UAAU,GAAG,KAAK,OAAO,GAAG,OAAO;CAC/C,IAAI;EACF,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -1,12 +1,12 @@
1
- import { a as isUnderClaudeConfigMirror, f as writeRuntimeFileSecure, t as PATHS } from "./paths-P5ajjpzU.js";
2
- import { C as CHEAP_REVIEWER_ALIAS_ID, S as CHEAP_PLAN_ALIAS_ID, _ as CHEAPEST_GENERAL_PURPOSE_ALIAS_ID, b as CHEAP_EXPLORE_ALIAS_ID, f as BALANCED_EXPLORE_ALIAS_ID, g as CHEAPEST_EXPLORE_ALIAS_ID, h as BALANCED_REVIEWER_ALIAS_ID, m as BALANCED_PLAN_ALIAS_ID, p as BALANCED_GENERAL_PURPOSE_ALIAS_ID, v as CHEAPEST_PLAN_ALIAS_ID, w as LUNA_SCOUT_ALIAS_ID, x as CHEAP_GENERAL_PURPOSE_ALIAS_ID, y as CHEAPEST_REVIEWER_ALIAS_ID } from "./server-setup-DrSUlFZ_.js";
1
+ import { a as isUnderClaudeConfigMirror, f as writeRuntimeFileSecure, t as PATHS } from "./paths-CpbTHKeP.js";
2
+ import { C as CHEAP_REVIEWER_ALIAS_ID, S as CHEAP_PLAN_ALIAS_ID, _ as CHEAPEST_GENERAL_PURPOSE_ALIAS_ID, b as CHEAP_EXPLORE_ALIAS_ID, f as BALANCED_EXPLORE_ALIAS_ID, g as CHEAPEST_EXPLORE_ALIAS_ID, h as BALANCED_REVIEWER_ALIAS_ID, m as BALANCED_PLAN_ALIAS_ID, p as BALANCED_GENERAL_PURPOSE_ALIAS_ID, v as CHEAPEST_PLAN_ALIAS_ID, w as LUNA_SCOUT_ALIAS_ID, x as CHEAP_GENERAL_PURPOSE_ALIAS_ID, y as CHEAPEST_REVIEWER_ALIAS_ID } from "./server-setup-CK3O_Hwf.js";
3
3
  import { c as FAST_PROFILE_MODELS, d as FAST_PROFILE_NATIVE_MODELS, l as FAST_PROFILE_NATIVE_AGENT_NAMES, u as FAST_PROFILE_NATIVE_EFFORTS } from "./fast-profile-contract-DmsyQQrw.js";
4
- import { An as withOneMSuffix, Bn as CHEAPEST_PROFILE_NATIVE_EFFORTS, Gn as CHEAP_PROFILE_NATIVE_AGENT_NAMES, Kn as CHEAP_PROFILE_NATIVE_EFFORTS, Nn as BALANCED_PROFILE_NATIVE_AGENT_NAMES, Pn as BALANCED_PROFILE_NATIVE_EFFORTS, a as buildAgentPrompt, cn as CONDENSED_OPERATING_SEQUENCE, kn as oneMContextDisabled, l as maxPersonasFor, ln as DEFINITION_OF_GREATNESS, n as MCP_GROUPS, t as GROUP_META, u as personasFor, zn as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES } from "./peer-mcp-personas-Dztywua2.js";
5
- import { C as MAX_PARALLELISM_RULE, S as MAX_COORDINATOR_PROMPT, T as maxNativePrompt, a as MAX_PROFILE_NATIVE_AGENT_NAMES, i as MAX_PROFILE_MODELS, o as MAX_PROFILE_NATIVE_EFFORTS, s as MAX_PROFILE_NATIVE_MODELS, w as maxNativeDescription, x as MAX_COORDINATOR_DESCRIPTION } from "./max-profile-contract-Bl7I_EOC.js";
6
- import "./self-invocation-DBWyjvGm.js";
7
- import { a as STRIPPED_AUTH_ROUTING_ENV_KEYS, n as buildCodexProviderConfigFlags } from "./provision-CjBt5wEK.js";
8
- import { n as buildWorkspaceHeaderHelperCommand } from "./mcp-workspace-header-DX_mD0JT.js";
9
- import { a as dispatcherAgentName, c as dispatcherTools, n as activeDispatchModes, o as dispatcherDescription, s as dispatcherPrompt } from "./worker-dispatch-DtjQchvM.js";
4
+ import { An as withOneMSuffix, Bn as CHEAPEST_PROFILE_NATIVE_EFFORTS, Gn as CHEAP_PROFILE_NATIVE_AGENT_NAMES, Kn as CHEAP_PROFILE_NATIVE_EFFORTS, Nn as BALANCED_PROFILE_NATIVE_AGENT_NAMES, Pn as BALANCED_PROFILE_NATIVE_EFFORTS, a as buildAgentPrompt, cn as CONDENSED_OPERATING_SEQUENCE, kn as oneMContextDisabled, l as maxPersonasFor, ln as DEFINITION_OF_GREATNESS, n as MCP_GROUPS, t as GROUP_META, u as personasFor, zn as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES } from "./peer-mcp-personas-CeB2Kcn2.js";
5
+ import { C as MAX_PARALLELISM_RULE, S as MAX_COORDINATOR_PROMPT, T as maxNativePrompt, a as MAX_PROFILE_NATIVE_AGENT_NAMES, i as MAX_PROFILE_MODELS, o as MAX_PROFILE_NATIVE_EFFORTS, s as MAX_PROFILE_NATIVE_MODELS, w as maxNativeDescription, x as MAX_COORDINATOR_DESCRIPTION } from "./max-profile-contract-MJJt0zm-.js";
6
+ import "./self-invocation-DIUyoRgL.js";
7
+ import { a as STRIPPED_AUTH_ROUTING_ENV_KEYS, n as buildCodexProviderConfigFlags } from "./provision-DZLsyRYh.js";
8
+ import { n as buildWorkspaceHeaderHelperCommand } from "./mcp-workspace-header-B77WqVFw.js";
9
+ import { a as dispatcherAgentName, c as dispatcherTools, n as activeDispatchModes, o as dispatcherDescription, s as dispatcherPrompt } from "./worker-dispatch-lRhno09M.js";
10
10
  import consola from "consola";
11
11
  import path from "node:path";
12
12
  import { randomBytes } from "node:crypto";
@@ -385,10 +385,11 @@ function buildMaxProfileAgentDefinitions(opts) {
385
385
  * Cost doctrine, cheapest to most expensive:
386
386
  * 1. LEXICAL code search (`mode:"lexical"`/`"exact"`) — zero model cost,
387
387
  * exact symbols, filenames, errors, routes, config keys. Always first.
388
- * 2. SEMANTIC code search (`mode:"semantic"`) — meaning-ranked via ColBERT,
389
- * for concepts and intent questions. Mentioned ONLY when the launch
390
- * enabled it (`semanticSearchAvailable`); otherwise the `code` tool is
391
- * lexical-only and agents must not be told to reach for semantic.
388
+ * 2. SEMANTIC code search (`mode:"semantic"`) — meaning-ranked via local
389
+ * ColBERT or Bluebird, for concepts and intent questions. Mentioned ONLY
390
+ * when this launch enabled one of those backends (`semanticSearchAvailable`);
391
+ * otherwise the `code` tool is lexical-only and agents must not be told
392
+ * to reach for semantic.
392
393
  * 3. `Explore` (budget model) — reads the narrowed files and synthesizes a
393
394
  * file:line evidence report. Only the conclusion flows upward.
394
395
  * 4. `Plan` (Sol) / `reviewer` (Sonnet/Luna/Gemini) / `oracle` — expensive
@@ -404,10 +405,12 @@ function buildMaxProfileAgentDefinitions(opts) {
404
405
  * `Plan`-first architecture, `General-Purpose` mixed execution, and
405
406
  * post-integration `reviewer` verification.
406
407
  */
407
- function pinnedSearchGuidance(semanticAvailable, capitalize = true) {
408
- const lexical = `${capitalize ? "Start with" : "start with"} exact lexical and symbol search (\`code\` with mode:"lexical" or "exact", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys — it costs no model call`;
408
+ function pinnedSearchGuidance(semanticAvailable, capitalize = true, bluebirdEnabled = false) {
409
+ const start = capitalize ? "Start with" : "start with";
410
+ if (bluebirdEnabled) return `${start} Bluebird indexed keyword search (\`code\` with mode:"lexical") for symbols, filenames, errors, routes, flags, and config keys; pair it with Bluebird semantic search for intent/concept questions where literal keywords may not appear. Bluebird failures remain visible and never fall back locally; mode:"exact", regex, AST, Grep, and Glob stay on the local live tree. Include surrounding context lines in your results so callers, guards, and types are visible without a second round trip, and inspect the file whenever the surrounding logic determines the answer.`;
411
+ const lexical = `${start} local exact lexical and symbol search (\`code\` with mode:"lexical" or "exact", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys — it costs no model call`;
409
412
  if (!semanticAvailable) return `${lexical}. Pair it with surrounding context lines so callers, guards, and types are visible without a second round trip, and inspect the file whenever the surrounding logic determines the answer.`;
410
- return `${lexical}; pair semantic search (meaning-ranked, best for intent/concept questions where literal keywords may not appear) with exact lexical and symbol search so that neither naming drift nor synonym mismatch hides a result. Include surrounding context lines in your search results so that callers, guards, and types are visible without a second round trip, and inspect the file whenever the surrounding logic determines the answer.`;
413
+ return `${lexical}; pair local ColBERT semantic search (meaning-ranked, with lexical fallback while its index is unavailable) with exact lexical and symbol search so that neither naming drift nor synonym mismatch hides a result. Include surrounding context lines in your search results so that callers, guards, and types are visible without a second round trip, and inspect the file whenever the surrounding logic determines the answer.`;
411
414
  }
412
415
  /**
413
416
  * Implicit (cheapest) tuning is composed from the SAME shared remainder as
@@ -421,7 +424,7 @@ function pinnedExploreDescription(explicit) {
421
424
  return (explicit ? "Read-only codebase exploration specialist. Use proactively, and launch several in parallel via `Task(subagent_type:\"Explore\")`, to map architecture, trace call chains, or locate the files and symbols a task will touch. " : "Read-only codebase exploration specialist for mapping architecture, tracing call chains, or locating the files and symbols a task touches. ") + EXPLORE_DESC_TAIL;
422
425
  }
423
426
  function pinnedExplorePrompt(opts) {
424
- const searchGuidance = pinnedSearchGuidance(opts.semanticAvailable, !opts.explicit);
427
+ const searchGuidance = pinnedSearchGuidance(opts.semanticAvailable, !opts.explicit, opts.bluebirdEnabled === true);
425
428
  return `You are a codebase exploration specialist. Your mission is to map repository structure, discover implementation patterns, trace call chains, and locate the exact files, symbols, and declarations that are relevant to the request. This is read-only work. Do not modify files, do not propose diffs, and do not delegate to other agents. You cannot ask clarifying questions mid-run: ground every answer in repository evidence. If the request is ambiguous, explore the most probable interpretations and record the ambiguity in your report. Start broad, then converge. ${opts.explicit ? "Issue independent searches in parallel in one turn rather than one at a time, and " : ""}${searchGuidance} Confirm every claim at the source before you report it. Stop when further searching stops changing your answer. When you can name the exact files and lines a change would touch, you are done. Report what the repository contains, not what it ought to contain. Do not design a solution or recommend an approach. Return a self-contained result the lead can act on immediately without needing to re-run your discovery.
426
429
 
427
430
  Return format:
@@ -501,7 +504,8 @@ function buildFastProfileAgentDefinitions(opts) {
501
504
  description: pinnedExploreDescription(true),
502
505
  prompt: pinnedExplorePrompt({
503
506
  explicit: true,
504
- semanticAvailable
507
+ semanticAvailable,
508
+ bluebirdEnabled: opts.bluebirdEnabled
505
509
  }),
506
510
  tools: readSearchTools,
507
511
  model: decorateGuaranteedOneM(LUNA_SCOUT_ALIAS_ID),
@@ -594,7 +598,8 @@ function buildCheapProfileAgentDefinitions(opts) {
594
598
  description: pinnedExploreDescription(true),
595
599
  prompt: pinnedExplorePrompt({
596
600
  explicit: true,
597
- semanticAvailable
601
+ semanticAvailable,
602
+ bluebirdEnabled: opts.bluebirdEnabled
598
603
  }),
599
604
  tools: readSearchTools,
600
605
  model: exploreModel,
@@ -687,7 +692,8 @@ function buildCheapestProfileAgentDefinitions(opts) {
687
692
  description: pinnedExploreDescription(false),
688
693
  prompt: pinnedExplorePrompt({
689
694
  explicit: false,
690
- semanticAvailable
695
+ semanticAvailable,
696
+ bluebirdEnabled: opts.bluebirdEnabled
691
697
  }),
692
698
  tools: readSearchTools,
693
699
  model: exploreModel,
@@ -779,7 +785,8 @@ function buildBalancedProfileAgentDefinitions(opts) {
779
785
  description: pinnedExploreDescription(true),
780
786
  prompt: pinnedExplorePrompt({
781
787
  explicit: true,
782
- semanticAvailable
788
+ semanticAvailable,
789
+ bluebirdEnabled: opts.bluebirdEnabled
783
790
  }),
784
791
  tools: readSearchTools,
785
792
  model: exploreModel,
@@ -1305,6 +1312,7 @@ async function writePeerMcpRuntimeFiles(serverUrl, opts) {
1305
1312
  balancedGeneralPurposeModel: opts.balancedGeneralPurposeModel,
1306
1313
  balancedReviewerModel: opts.balancedReviewerModel,
1307
1314
  semanticSearchAvailable: opts.semanticSearchAvailable,
1315
+ bluebirdEnabled: opts.bluebirdEnabled,
1308
1316
  nativeRoster: opts.nativeRoster,
1309
1317
  personaAllowlist: opts.personaAllowlist,
1310
1318
  includeCoordinator: opts.includeCoordinator,
@@ -2082,7 +2090,8 @@ Return a compact final checkpoint:
2082
2090
  }
2083
2091
  //#endregion
2084
2092
  //#region src/lib/injected-skills/gather-context-skill.ts
2085
- function buildGatherContextSkill(searchEnabled) {
2093
+ function buildGatherContextSkill(searchEnabled, bluebirdEnabled = false) {
2094
+ const semanticAvailable = searchEnabled || bluebirdEnabled;
2086
2095
  return {
2087
2096
  name: "gh-gather-context",
2088
2097
  md: `---
@@ -2109,7 +2118,7 @@ stage: Explore evidence plus targeted follow-up reads is the verification path.
2109
2118
 
2110
2119
  - Maximum rounds: 3.
2111
2120
  - Maximum parallel Explore subagents per round: 6.
2112
- - ${searchEnabled ? "Maximum searches per round: 10." : "Maximum lexical searches per round: 10."}
2121
+ - ${semanticAvailable ? "Maximum searches per round: 10." : "Maximum lexical searches per round: 10."}
2113
2122
  - Maximum follow-up reads per round: 5.
2114
2123
  - Advisory budget: keep each Explore dispatch under ~3 minutes of wall-clock;
2115
2124
  the Task tool has no maxWallClockMs parameter, so count your own dispatches
@@ -2135,8 +2144,8 @@ Use these exact tags on every finding and claim:
2135
2144
  - Extract symbols, filenames, error strings, routes, flags, config keys, and types.
2136
2145
  - Define what must be true for a correct implementation.
2137
2146
 
2138
- ${searchEnabled ? `3. Run semantic search first for concepts, then lexical for symbols, in parallel, in a single turn.
2139
- - Use mcp__search__code semantically first to find concepts and likely files.
2147
+ ${semanticAvailable ? `3. Run semantic search first for concepts, then lexical for symbols, in parallel, in a single turn.
2148
+ - Use mcp__search__code semantically first to find concepts and likely files via ${bluebirdEnabled ? "Bluebird's Azure DevOps index; failures stay visible with no local fallback" : "the local ColBERT index, with transparent lexical fallback while unavailable"}.
2140
2149
  - Then use mcp__search__code lexically for exact symbols, filenames, errors, routes, flags, and config keys.
2141
2150
  - Use git log and git blame when authorship, regression timing, or intent matters.
2142
2151
  - Use mcp__search__web for upstream APIs, package behavior, protocol docs, or public issues.` : `3. Run lexical search first, in parallel, in a single turn.
@@ -2321,7 +2330,7 @@ Return:
2321
2330
  }
2322
2331
  //#endregion
2323
2332
  //#region src/lib/injected-skills/orchestrate-skill.ts
2324
- function buildOrchestrateSkill(searchEnabled) {
2333
+ function buildOrchestrateSkill(searchEnabled, bluebirdEnabled = false) {
2325
2334
  return {
2326
2335
  name: "gh-orchestrate",
2327
2336
  md: `---
@@ -2407,7 +2416,7 @@ Parallelism (the Workflow tool's core optimization rule):
2407
2416
 
2408
2417
  Role to tool mapping:
2409
2418
 
2410
- ${searchEnabled ? "- research: worker-explore (Agent subagent) and mcp__search__code for focused follow-ups (semantic for concepts, lexical for exact symbols)." : "- research: worker-explore (Agent subagent) and mcp__search__code for focused follow-ups (lexical for exact symbols, filenames, errors, routes, flags, and config keys)."}
2419
+ ${searchEnabled || bluebirdEnabled ? `- research: worker-explore (Agent subagent) and mcp__search__code for focused follow-ups (${bluebirdEnabled ? "Bluebird-backed" : "local ColBERT-backed"} semantic for concepts, lexical for exact symbols).` : "- research: worker-explore (Agent subagent) and mcp__search__code for focused follow-ups (lexical for exact symbols, filenames, errors, routes, flags, and config keys)."}
2411
2420
  - plan: worker-plan (Agent subagent).
2412
2421
  - implement: worker-implement (Agent subagent), with worktree:true for parallel writers.
2413
2422
  - test: worker-test (Agent subagent), authored by a DIFFERENT LAB than the implementer when possible. This is an advisory practice, not enforced provenance.
@@ -2605,7 +2614,7 @@ Return:
2605
2614
  }
2606
2615
  //#endregion
2607
2616
  //#region src/lib/injected-skills/research-skill.ts
2608
- function buildResearchSkill(searchEnabled) {
2617
+ function buildResearchSkill(searchEnabled, bluebirdEnabled = false) {
2609
2618
  return {
2610
2619
  name: "gh-research",
2611
2620
  md: `---
@@ -2659,9 +2668,9 @@ Default caps unless the user explicitly gives a smaller or larger budget:
2659
2668
  - Mark each unknown as code, behavior, dependency, history, external, or acceptance-criteria related.
2660
2669
  - Add newly discovered unknowns as they appear.
2661
2670
 
2662
- ${searchEnabled ? `3. Fan out in parallel.
2671
+ ${searchEnabled || bluebirdEnabled ? `3. Fan out in parallel.
2663
2672
  - Run independent code, web, history, and explore calls concurrently where possible; only the semantic-to-lexical code-search refinement is ordered. Issue the independent calls in a SINGLE turn (one message, multiple tool calls) so the harness actually runs them in parallel rather than serializing.
2664
- - Use mcp__search__code semantically first to find concepts and likely files.
2673
+ - Use mcp__search__code semantically first to find concepts and likely files. This launch uses ${bluebirdEnabled ? "Bluebird (semantic and lexical requests use its Azure DevOps index; failures stay visible with no local fallback)" : "local ColBERT (with transparent lexical fallback while its index is unavailable)"}.
2665
2674
  - Then use mcp__search__code lexically for exact symbols, filenames, errors, routes, flags, and config keys.
2666
2675
  - Use git blame or history when authorship, regression timing, or intent matters.
2667
2676
  - Use mcp__search__web for upstream APIs, package behavior, protocol docs, or public issues.
@@ -3258,7 +3267,7 @@ function buildOperatingDefaultsDirective(opts = {}) {
3258
3267
  const profileLabel = isCheapest ? "Cheapest" : isCheap ? "Cheap" : isBalanced ? "Balanced" : "Fast";
3259
3268
  const oracleDescriptor = isCheapest ? "GPT-5.6 Sol (200K/high)" : isCheap || isBalanced ? "Grok 4.6 (200K/medium)" : "exact Opus 5 (1M/high)";
3260
3269
  const astraDescriptor = isCheap && !isCheapest ? "200K/medium" : "200K/high";
3261
- const searchGuidance = opts.semanticSearchAvailable === true ? "Search strategy (cheapest first): (1) LEXICAL `code` search (mode:\"lexical\"/\"exact\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys — zero model cost; (2) SEMANTIC `code` search for intent/concept questions where literal keywords may not appear; (3) `Explore` subagents read the narrowed files and return file:line conclusions — expensive models (Plan, reviewer, Oracle) see only the synthesized subset, never raw search output. " : "Search strategy (cheapest first): LEXICAL `code` search (mode:\"lexical\"/\"exact\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys — zero model cost. `Explore` subagents read the narrowed files and return file:line conclusions — expensive models (Plan, reviewer, Oracle) see only the synthesized subset, never raw search output. ";
3270
+ const searchGuidance = opts.bluebirdEnabled === true ? "Search strategy: use Bluebird `code` search in `lexical` mode for indexed keyword queries and `semantic` mode for intent/concept questions. Bluebird failures remain visible and never fall back locally; `exact`, `regex`, and `ast` stay on the local live tree. `Explore` subagents read the narrowed files and return file:line conclusions; expensive models (Plan, reviewer, Oracle) see only the synthesized subset, never raw search output. " : opts.semanticSearchAvailable === true ? "Search strategy (cheapest first): (1) LOCAL LEXICAL `code` search (mode:\"lexical\"/\"exact\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys; (2) local ColBERT SEMANTIC `code` search for intent/concept questions where literal keywords may not appear, with lexical fallback while its index is unavailable; (3) `Explore` subagents read the narrowed files and return file:line conclusions — expensive models (Plan, reviewer, Oracle) see only the synthesized subset, never raw search output. " : "Search strategy (cheapest first): LOCAL LEXICAL `code` search (mode:\"lexical\"/\"exact\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys. `Explore` subagents read the narrowed files and return file:line conclusions — expensive models (Plan, reviewer, Oracle) see only the synthesized subset, never raw search output. ";
3262
3271
  if (opts.fastRuntimeAvailable === false) return `## Operating defaults (these layer with the user's explicit direction and the domain's own standards as addons, not replacements: follow all three together; on a direct conflict the user's direction wins, then the domain standard, then the default below)
3263
3272
 
3264
3273
  ${profileLabel} profile runtime wiring is unavailable. Work directly, use only tools actually listed in this session, verify with the repository's relevant build/tests before declaring done, report uncertainty, and do not invent unavailable capabilities.`;
@@ -3769,37 +3778,39 @@ async function writeInjectedSkill(name, md) {
3769
3778
  * other three in strict sequence; the three stages stay individually
3770
3779
  * invokable for users who only want one stage.
3771
3780
  */
3772
- function getPipelineSkills(searchEnabled) {
3781
+ function getPipelineSkills(searchEnabled, bluebirdEnabled = false) {
3773
3782
  return [
3774
- buildGatherContextSkill(searchEnabled),
3775
- buildPlanSkill(searchEnabled),
3776
- buildImplementSkill(searchEnabled),
3777
- buildSwePipelineSkill(searchEnabled)
3783
+ buildGatherContextSkill(searchEnabled, bluebirdEnabled),
3784
+ buildPlanSkill(searchEnabled || bluebirdEnabled),
3785
+ buildImplementSkill(searchEnabled || bluebirdEnabled),
3786
+ buildSwePipelineSkill(searchEnabled || bluebirdEnabled)
3778
3787
  ];
3779
3788
  }
3780
3789
  /**
3781
3790
  * Build all injected skills in dependency order (research underpins the
3782
- * others), with search guidance matched to the launch's search capability.
3791
+ * others), with search guidance matched to the launch's search backend.
3783
3792
  */
3784
- function getInjectedSkills(searchEnabled) {
3793
+ function getInjectedSkills(searchEnabled, bluebirdEnabled = false) {
3794
+ const semanticAvailable = searchEnabled || bluebirdEnabled;
3785
3795
  return [
3786
- buildResearchSkill(searchEnabled),
3787
- buildGatherContextSkill(searchEnabled),
3788
- buildPlanSkill(searchEnabled),
3789
- buildImplementSkill(searchEnabled),
3790
- buildOrchestrateSkill(searchEnabled),
3791
- buildFloorKeeperSkill(searchEnabled),
3792
- buildWorkerSkill(searchEnabled),
3793
- buildFirstMateSkill(searchEnabled),
3794
- buildFirstMateSetupSkill(searchEnabled),
3795
- buildFirstMateOperateSkill(searchEnabled),
3796
- buildFirstMateConductSkill(searchEnabled)
3796
+ buildResearchSkill(searchEnabled, bluebirdEnabled),
3797
+ buildGatherContextSkill(searchEnabled, bluebirdEnabled),
3798
+ buildPlanSkill(semanticAvailable),
3799
+ buildImplementSkill(semanticAvailable),
3800
+ buildOrchestrateSkill(searchEnabled, bluebirdEnabled),
3801
+ buildFloorKeeperSkill(semanticAvailable),
3802
+ buildWorkerSkill(semanticAvailable),
3803
+ buildFirstMateSkill(semanticAvailable),
3804
+ buildFirstMateSetupSkill(semanticAvailable),
3805
+ buildFirstMateOperateSkill(semanticAvailable),
3806
+ buildFirstMateConductSkill(semanticAvailable)
3797
3807
  ];
3798
3808
  }
3799
3809
  function injectedSkillsForLaunch(selection) {
3800
3810
  const searchEnabled = selection.searchEnabled === true;
3801
- const allSkills = getInjectedSkills(searchEnabled);
3802
- const pipelineSkills = getPipelineSkills(searchEnabled);
3811
+ const bluebirdEnabled = selection.bluebirdEnabled === true;
3812
+ const allSkills = getInjectedSkills(searchEnabled, bluebirdEnabled);
3813
+ const pipelineSkills = getPipelineSkills(searchEnabled, bluebirdEnabled);
3803
3814
  if (isPipelineSkillProfile(selection.profileId)) {
3804
3815
  if (!selection.sweEnabled) {
3805
3816
  if (selection.profileId === "max" && selection.firstMateEnabled) return allSkills.filter((skill) => skill.name.startsWith("gh-first-mate"));
@@ -3882,4 +3893,4 @@ async function injectAttributionSuppressionIntoSettingsFile(settingsPath) {
3882
3893
  //#endregion
3883
3894
  export { writePeerMcpRuntimeFiles as C, workersKeyOf as S, sanitizeServeSettingsEnv as _, appendPeerAwarenessToMirroredClaudeMd as a, resolveCodexCliBackend as b, buildOperatingDefaultsDirective as c, prependStyleDirectiveToMirroredClaudeMd as d, buildArtifactReviewSkill as f, planModeAllowRules as g, injectAllowRules as h, writeInjectedSkill as i, prependArtifactPanelDirectiveToMirroredClaudeMd as l, configureServeDefaultPermissionMode as m, getInjectedSkills as n, appendToolbeltAwarenessToMirroredClaudeMd as o, SEAMLESS_BUILTIN_TOOLS as p, injectedSkillsForLaunch as r, buildOperatingDefaultsDigest as s, injectAttributionSuppressionIntoSettingsFile as t, prependOperatingDefaultsToMirroredClaudeMd as u, BUILTIN_SUBAGENT_DEFINITIONS as v, resolveGroupKeysFromMirror as x, injectPeerMcpIntoMirror as y };
3884
3895
 
3885
- //# sourceMappingURL=attribution-settings-7dFpObGh.js.map
3896
+ //# sourceMappingURL=attribution-settings-BeO1w_DL.js.map