github-router 0.3.355 → 0.3.356

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 (127) hide show
  1. package/dist/ado-tools-DokE2DbX.js +1 -0
  2. package/dist/{aic-ledger-BdvCgRmx.js → aic-ledger-BuFrsGur.js} +3 -3
  3. package/dist/{aic-ledger-BdvCgRmx.js.map → aic-ledger-BuFrsGur.js.map} +1 -1
  4. package/dist/{aic-statusline-settings-EdsV1gzY.js → aic-statusline-settings-DBS9sEGC.js} +2 -2
  5. package/dist/{aic-statusline-settings-EdsV1gzY.js.map → aic-statusline-settings-DBS9sEGC.js.map} +1 -1
  6. package/dist/{attribution-settings-N48QlHu2.js → attribution-settings-CnmV9MSv.js} +11 -11
  7. package/dist/{attribution-settings-N48QlHu2.js.map → attribution-settings-CnmV9MSv.js.map} +1 -1
  8. package/dist/{auth-a_1lXYZ1.js → auth-DFawaLJU.js} +4 -4
  9. package/dist/{auth-a_1lXYZ1.js.map → auth-DFawaLJU.js.map} +1 -1
  10. package/dist/{bluebird-client-ltPIiyJU.js → bluebird-client-C29-JOkG.js} +92 -4
  11. package/dist/bluebird-client-C29-JOkG.js.map +1 -0
  12. package/dist/bluebird-client-DGE3WZqh.js +1 -0
  13. package/dist/browser-ext/manifest.json +1 -1
  14. package/dist/{check-usage-Bsbc-Sn6.js → check-usage-BkVEl-Su.js} +4 -4
  15. package/dist/{check-usage-Bsbc-Sn6.js.map → check-usage-BkVEl-Su.js.map} +1 -1
  16. package/dist/{claude-BAKFTVqA.js → claude-DvR3Y7fu.js} +28 -27
  17. package/dist/claude-DvR3Y7fu.js.map +1 -0
  18. package/dist/{claude-md-injection-CDOoGNEJ.js → claude-md-injection-Cpzolxin.js} +4 -4
  19. package/dist/{claude-md-injection-CDOoGNEJ.js.map → claude-md-injection-Cpzolxin.js.map} +1 -1
  20. package/dist/{codex-CspHNGZA.js → codex-DQpSPjpQ.js} +9 -9
  21. package/dist/{codex-CspHNGZA.js.map → codex-DQpSPjpQ.js.map} +1 -1
  22. package/dist/{copilot-discount-kpOLluHm.js → copilot-discount-Bsmv_3OX.js} +2 -2
  23. package/dist/{copilot-discount-kpOLluHm.js.map → copilot-discount-Bsmv_3OX.js.map} +1 -1
  24. package/dist/{debug-BtqbflcL.js → debug-DkNTuErv.js} +2 -2
  25. package/dist/{debug-BtqbflcL.js.map → debug-DkNTuErv.js.map} +1 -1
  26. package/dist/engine-DgmsdkCe.js +1 -0
  27. package/dist/{gate-discovery-JeKibE14.js → gate-discovery-B2x_8hNL.js} +5 -5
  28. package/dist/{gate-discovery-JeKibE14.js.map → gate-discovery-B2x_8hNL.js.map} +1 -1
  29. package/dist/{get-copilot-usage-0_S8pRWJ.js → get-copilot-usage-P9chc-X2.js} +3 -3
  30. package/dist/{get-copilot-usage-0_S8pRWJ.js.map → get-copilot-usage-P9chc-X2.js.map} +1 -1
  31. package/dist/hooks.mjs +2 -0
  32. package/dist/hooks.sha256 +1 -1
  33. package/dist/{index-cmd-CJXUOH4q.js → index-cmd-BkfYr9FH.js} +4 -4
  34. package/dist/{index-cmd-CJXUOH4q.js.map → index-cmd-BkfYr9FH.js.map} +1 -1
  35. package/dist/{internal-aic-status-wYPsCG4r.js → internal-aic-status-C6L4-ncP.js} +3 -3
  36. package/dist/{internal-aic-status-wYPsCG4r.js.map → internal-aic-status-C6L4-ncP.js.map} +1 -1
  37. package/dist/{internal-artifact-open-C67gDjKo.js → internal-artifact-open-DgJ3PCtt.js} +2 -2
  38. package/dist/{internal-artifact-open-C67gDjKo.js.map → internal-artifact-open-DgJ3PCtt.js.map} +1 -1
  39. package/dist/{internal-fast-dispatch-guard-D_TCtJhQ.js → internal-fast-dispatch-guard-CgBtUsQI.js} +2 -2
  40. package/dist/{internal-fast-dispatch-guard-D_TCtJhQ.js.map → internal-fast-dispatch-guard-CgBtUsQI.js.map} +1 -1
  41. package/dist/{internal-fast-dispatch-guard-A8teEib4.js → internal-fast-dispatch-guard-CicGz6oM.js} +1 -1
  42. package/dist/{internal-first-mate-guard-BJvCsVlU.js → internal-first-mate-guard-BfWYN6Jb.js} +3 -3
  43. package/dist/{internal-first-mate-guard-BJvCsVlU.js.map → internal-first-mate-guard-BfWYN6Jb.js.map} +1 -1
  44. package/dist/{internal-first-mate-guard-D-IQGiTs.js → internal-first-mate-guard-DTXPT7JW.js} +1 -1
  45. package/dist/{internal-max-dispatch-guard-D7ByWH4v.js → internal-max-dispatch-guard-CY8l9SDw.js} +3 -3
  46. package/dist/{internal-max-dispatch-guard-D7ByWH4v.js.map → internal-max-dispatch-guard-CY8l9SDw.js.map} +1 -1
  47. package/dist/{internal-max-dispatch-guard-BM_B15EH.js → internal-max-dispatch-guard-mNl9CCir.js} +1 -1
  48. package/dist/{internal-plan-review-DIvaBBUd.js → internal-plan-review-2OHTs8Nk.js} +3 -3
  49. package/dist/{internal-plan-review-DIvaBBUd.js.map → internal-plan-review-2OHTs8Nk.js.map} +1 -1
  50. package/dist/{internal-prompt-submit-C77GnEaW.js → internal-prompt-submit-CkfUcu34.js} +4 -4
  51. package/dist/{internal-prompt-submit-C77GnEaW.js.map → internal-prompt-submit-CkfUcu34.js.map} +1 -1
  52. package/dist/{internal-prompt-submit-CDTwamkW.js → internal-prompt-submit-DZ_-2A6a.js} +2 -2
  53. package/dist/{internal-rebrief-DZygfGHp.js → internal-rebrief-EhBHAHsz.js} +4 -4
  54. package/dist/{internal-rebrief-DZygfGHp.js.map → internal-rebrief-EhBHAHsz.js.map} +1 -1
  55. package/dist/{internal-session-bind-CQLDPuTx.js → internal-session-bind-Bv50ju2n.js} +2 -2
  56. package/dist/{internal-session-bind-CQLDPuTx.js.map → internal-session-bind-Bv50ju2n.js.map} +1 -1
  57. package/dist/{internal-stop-hook-Dz6mdfcL.js → internal-stop-hook-Dm-m8RoA.js} +5 -5
  58. package/dist/{internal-stop-hook-Dz6mdfcL.js.map → internal-stop-hook-Dm-m8RoA.js.map} +1 -1
  59. package/dist/{internal-stop-review-X7zRRhyc.js → internal-stop-review-K6f8xsCh.js} +2 -2
  60. package/dist/{internal-stop-review-X7zRRhyc.js.map → internal-stop-review-K6f8xsCh.js.map} +1 -1
  61. package/dist/{internal-worker-guard-wP3UN-3D.js → internal-worker-guard-GVhTjVlR.js} +2 -2
  62. package/dist/{internal-worker-guard-wP3UN-3D.js.map → internal-worker-guard-GVhTjVlR.js.map} +1 -1
  63. package/dist/{internal-workspace-header-DiUnkUeU.js → internal-workspace-header-d2hFf9Jy.js} +2 -2
  64. package/dist/{internal-workspace-header-DiUnkUeU.js.map → internal-workspace-header-d2hFf9Jy.js.map} +1 -1
  65. package/dist/lifecycle-BU_d2QMs.js +1 -0
  66. package/dist/lifecycle-ByFyew_w.js +1 -0
  67. package/dist/{lifecycle-BJ83L0tz.js → lifecycle-C6cxM_Nk.js} +2 -2
  68. package/dist/{lifecycle-BJ83L0tz.js.map → lifecycle-C6cxM_Nk.js.map} +1 -1
  69. package/dist/{lifecycle-aApO0hZW.js → lifecycle-pl9QpvqD.js} +2 -2
  70. package/dist/{lifecycle-aApO0hZW.js.map → lifecycle-pl9QpvqD.js.map} +1 -1
  71. package/dist/main.js +23 -23
  72. package/dist/{max-profile-contract-CMvzKSsg.js → max-profile-contract-Cx5_Z1Y7.js} +2 -2
  73. package/dist/{max-profile-contract-CMvzKSsg.js.map → max-profile-contract-Cx5_Z1Y7.js.map} +1 -1
  74. package/dist/{mcp-workspace-header-DBQugQlQ.js → mcp-workspace-header-Su8uUxJg.js} +2 -2
  75. package/dist/{mcp-workspace-header-DBQugQlQ.js.map → mcp-workspace-header-Su8uUxJg.js.map} +1 -1
  76. package/dist/{models-JIvKAGn0.js → models-D8v8OTbN.js} +3 -3
  77. package/dist/{models-JIvKAGn0.js.map → models-D8v8OTbN.js.map} +1 -1
  78. package/dist/{orchestration-D-S_0GVt.js → orchestration-Bov4rZEi.js} +2 -2
  79. package/dist/{orchestration-D-S_0GVt.js.map → orchestration-Bov4rZEi.js.map} +1 -1
  80. package/dist/{paths-xTSEAWfN.js → paths-BSI_EtDT.js} +18 -18
  81. package/dist/paths-BSI_EtDT.js.map +1 -0
  82. package/dist/paths-BYxX9DfA.js +1 -0
  83. package/dist/{peer-mcp-personas-Ch4VWo40.js → peer-mcp-personas-CVxXq1Q-.js} +2836 -150
  84. package/dist/peer-mcp-personas-CVxXq1Q-.js.map +1 -0
  85. package/dist/{pi-Cwj383nc.js → pi-D-BgxVhx.js} +22 -16
  86. package/dist/{pi-Cwj383nc.js.map → pi-D-BgxVhx.js.map} +1 -1
  87. package/dist/{plan-review-hook-BQ29WGv7.js → plan-review-hook-CHK1wL3-.js} +3 -3
  88. package/dist/{plan-review-hook-BQ29WGv7.js.map → plan-review-hook-CHK1wL3-.js.map} +1 -1
  89. package/dist/{provision-PodfFQu-.js → provision-DYmZgZDr.js} +6 -5
  90. package/dist/provision-DYmZgZDr.js.map +1 -0
  91. package/dist/{self-invocation-Dr5zlbpM.js → self-invocation-Dk_UHD_v.js} +2 -2
  92. package/dist/{self-invocation-Dr5zlbpM.js.map → self-invocation-Dk_UHD_v.js.map} +1 -1
  93. package/dist/{serve-D-OuW7kz.js → serve-DfxxKLFl.js} +25 -17
  94. package/dist/serve-DfxxKLFl.js.map +1 -0
  95. package/dist/{server-setup-DDZxJgl0.js → server-setup-VYf8ptCH.js} +161 -27
  96. package/dist/server-setup-VYf8ptCH.js.map +1 -0
  97. package/dist/{service-backend-DV1u5x0Q.js → service-backend-DHyd9vjW.js} +3 -3
  98. package/dist/{service-backend-DV1u5x0Q.js.map → service-backend-DHyd9vjW.js.map} +1 -1
  99. package/dist/{start-CZZ0cTV9.js → start-BsY1d26G.js} +4 -4
  100. package/dist/{start-CZZ0cTV9.js.map → start-BsY1d26G.js.map} +1 -1
  101. package/dist/{state-CfEVoqBM.js → state-CiwCLVDZ.js} +3 -1
  102. package/dist/{state-CfEVoqBM.js.map → state-CiwCLVDZ.js.map} +1 -1
  103. package/dist/{static-context-pack-BRqt4ajJ.js → static-context-pack-dKrzbfIN.js} +3 -3
  104. package/dist/{static-context-pack-BRqt4ajJ.js.map → static-context-pack-dKrzbfIN.js.map} +1 -1
  105. package/dist/{stop-gate-hook-BYd0NruJ.js → stop-gate-hook-CC7VWkZM.js} +3 -3
  106. package/dist/{stop-gate-hook-BYd0NruJ.js.map → stop-gate-hook-CC7VWkZM.js.map} +1 -1
  107. package/dist/{stop-gate-policy-FGAfpfc-.js → stop-gate-policy-CoR8xKNQ.js} +2 -2
  108. package/dist/{stop-gate-policy-FGAfpfc-.js.map → stop-gate-policy-CoR8xKNQ.js.map} +1 -1
  109. package/dist/{token-CTf5jCmP.js → token-CA2s70qj.js} +3 -3
  110. package/dist/{token-CTf5jCmP.js.map → token-CA2s70qj.js.map} +1 -1
  111. package/dist/{worker-dispatch-BjfROaic.js → worker-dispatch-B_rriT7z.js} +2 -2
  112. package/dist/{worker-dispatch-BjfROaic.js.map → worker-dispatch-B_rriT7z.js.map} +1 -1
  113. package/docs/azure-mcp.md +10 -1
  114. package/package.json +1 -1
  115. package/dist/ado-tools-B5TCtnlQ.js +0 -1
  116. package/dist/bluebird-client-ltPIiyJU.js.map +0 -1
  117. package/dist/bluebird-client-mr3M67k-.js +0 -1
  118. package/dist/claude-BAKFTVqA.js.map +0 -1
  119. package/dist/engine-YvnWaTnR.js +0 -1
  120. package/dist/lifecycle-CVg2-zQ3.js +0 -1
  121. package/dist/lifecycle-Dk_BHtfz.js +0 -1
  122. package/dist/paths-C9x5U3dO.js +0 -1
  123. package/dist/paths-xTSEAWfN.js.map +0 -1
  124. package/dist/peer-mcp-personas-Ch4VWo40.js.map +0 -1
  125. package/dist/provision-PodfFQu-.js.map +0 -1
  126. package/dist/serve-D-OuW7kz.js.map +0 -1
  127. package/dist/server-setup-DDZxJgl0.js.map +0 -1
@@ -0,0 +1 @@
1
+ export { lt as disposeAdoClients } from "./peer-mcp-personas-CVxXq1Q-.js";
@@ -1,5 +1,5 @@
1
- import { t as PATHS } from "./paths-xTSEAWfN.js";
2
- import { d as resolveModel } from "./token-CTf5jCmP.js";
1
+ import { t as PATHS } from "./paths-BSI_EtDT.js";
2
+ import { d as resolveModel } from "./token-CA2s70qj.js";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import fs$1 from "node:fs/promises";
@@ -354,4 +354,4 @@ async function isPidAlive(pid) {
354
354
  //#endregion
355
355
  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 };
356
356
 
357
- //# sourceMappingURL=aic-ledger-BdvCgRmx.js.map
357
+ //# sourceMappingURL=aic-ledger-BuFrsGur.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"aic-ledger-BdvCgRmx.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-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\"\nimport { resolveModel } from \"~/lib/utils\"\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 * Normalize a ledger model key to the catalog-canonical id so the same\n * spend never splits across alias variants (`opus` vs `opus-1m`,\n * `claude-opus-4-7[1m]`, dotted vs dashed, dated slugs).\n *\n * Uses `resolveModel` (NOT `normalizeModelId`: the fuzzy form breaks\n * dotted discount keys like `gpt-5.3-codex`). Vendor prefixes\n * (`provider/model`) are stripped first. Never throws: on any failure\n * or catalog-miss the raw id is kept so spend is never dropped.\n */\nfunction aicModelKey(model: string | undefined): string {\n if (!model || model.length === 0) return \"unknown\"\n const noVendor = model.includes(\"/\")\n ? model.slice(model.lastIndexOf(\"/\") + 1)\n : model\n const trimmed = noVendor.trim()\n if (trimmed.length === 0) return \"unknown\"\n try {\n const resolved = resolveModel(trimmed)\n return resolved && resolved.length > 0 ? resolved : trimmed\n } catch {\n return trimmed\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 = aicModelKey(model)\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,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AO;CAC/C,IAAI;EACF,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"aic-ledger-BuFrsGur.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-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\"\nimport { resolveModel } from \"~/lib/utils\"\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 * Normalize a ledger model key to the catalog-canonical id so the same\n * spend never splits across alias variants (`opus` vs `opus-1m`,\n * `claude-opus-4-7[1m]`, dotted vs dashed, dated slugs).\n *\n * Uses `resolveModel` (NOT `normalizeModelId`: the fuzzy form breaks\n * dotted discount keys like `gpt-5.3-codex`). Vendor prefixes\n * (`provider/model`) are stripped first. Never throws: on any failure\n * or catalog-miss the raw id is kept so spend is never dropped.\n */\nfunction aicModelKey(model: string | undefined): string {\n if (!model || model.length === 0) return \"unknown\"\n const noVendor = model.includes(\"/\")\n ? model.slice(model.lastIndexOf(\"/\") + 1)\n : model\n const trimmed = noVendor.trim()\n if (trimmed.length === 0) return \"unknown\"\n try {\n const resolved = resolveModel(trimmed)\n return resolved && resolved.length > 0 ? resolved : trimmed\n } catch {\n return trimmed\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 = aicModelKey(model)\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,SAAS;CACf,IACE,OAAO,OAAO,mBAAmB,YAC9B,CAAC,OAAO,SAAS,OAAO,cAAc,KAC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,KAAK,IAAI;AACxB;;AAGA,eAAsB,sBAAqC;CACzD,IAAI;EACF,MAAMA,KAAI,GAAG,cAAc,GAAG,EAAE,OAAO,KAAK,CAAC;CAC/C,QAAQ,CAER;AACF;;AAGA,eAAsB,2BAA0C;CAC9D,IAAI;EACF,MAAM,MAAM,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,4 +1,4 @@
1
- import { t as buildSelfCommand } from "./self-invocation-Dr5zlbpM.js";
1
+ import { t as buildSelfCommand } from "./self-invocation-Dk_UHD_v.js";
2
2
  import fs from "node:fs/promises";
3
3
  //#region src/lib/aic-statusline-settings.ts
4
4
  /**
@@ -138,4 +138,4 @@ async function writeBackupSidecar(settingsPath, previous) {
138
138
  //#endregion
139
139
  export { injectAicStatusLineIntoSettingsFile as a, buildAicStatusHookCommand as i, AIC_STATUSLINE_DISABLE_ENV as n, AIC_USER_STATUSLINE_ENV as r, AIC_LEDGER_ENV as t };
140
140
 
141
- //# sourceMappingURL=aic-statusline-settings-EdsV1gzY.js.map
141
+ //# sourceMappingURL=aic-statusline-settings-DBS9sEGC.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"aic-statusline-settings-EdsV1gzY.js","names":[],"sources":["../src/lib/aic-statusline-settings.ts"],"sourcesContent":["/**\n * Claude Code `statusLine` injection for the per-session AIC total + rich\n * default session line.\n *\n * `github-router claude` writes `{ statusLine: { type: \"command\", command } }`\n * into the mirrored settings.json so the status bar shows\n * `[AIC 12.42] [####------] 42%·200K | model | dir (branch) | ...`,\n * updating as the ledger file grows. The command itself\n * (`internal-aic-status`) reads the ledger path from `GH_ROUTER_AIC_LEDGER`\n * in the spawned child's env — never a path baked into settings — so the\n * same mirror mechanics work for concurrent launches. AIC is pinned: it\n * renders even when the terminal is too narrow for any other segment.\n *\n * Standard launches use wrap-don't-clobber: when the user's own config\n * already defines `statusLine` as a `{type:\"command\", command:string}`\n * shape, that command is preserved via `GH_ROUTER_AIC_USER_STATUSLINE`\n * (set by the caller from the returned `userCommand`) and the hook\n * composes one line: `[AIC x.xx] <user line>`. Any other pre-existing\n * `statusLine` shape is left untouched (`reason: \"unrecognized\"`) rather\n * than risk breaking an exotic config.\n *\n * Pinned launches (`isPinnedLaunchProfile(profileId)`, `routerWins: true`)\n * run router-provided surfaces only: ANY pre-existing `statusLine` is backed\n * up to a mirror sidecar and replaced with ours (`mode: \"forced\"`), so the\n * native rich line always renders and the user command never executes. The\n * predicate — not an inline alias list — is the source of truth, so a newly\n * pinned profile cannot silently keep wrap-don't-clobber behaviour.\n *\n * Failure model matches the sibling settings writers: a transient read error\n * or a non-object settings.json throws (never clobber a file we don't\n * understand); the caller wraps this in warn-and-continue so a settings-write\n * hiccup never blocks launch. Writes use a same-directory temp file, mode\n * 0o600, then rename.\n */\n\nimport fs from \"node:fs/promises\"\n\nimport type { SelfInvocation } from \"./hook-launcher/self-invocation\"\nimport { buildSelfCommand } from \"./hook-launcher/self-invocation\"\n\n/** Env var carrying the ledger snapshot path into the spawned child. */\nexport const AIC_LEDGER_ENV = \"GH_ROUTER_AIC_LEDGER\"\n/** Env var carrying the user's own statusLine command (wrap mode only). */\nexport const AIC_USER_STATUSLINE_ENV = \"GH_ROUTER_AIC_USER_STATUSLINE\"\n/** Opt-out for the whole injection (mirrors GH_ROUTER_DISABLE_NO_ATTRIBUTION). */\nexport const AIC_STATUSLINE_DISABLE_ENV = \"GH_ROUTER_DISABLE_AIC_STATUSLINE\"\n\nexport function buildAicStatusHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-aic-status\")\n}\n\nexport type AicStatuslineInjectionResult =\n | { written: true; mode: \"injected\" | \"wrapped\" | \"forced\"; userCommand?: string; hadPrevious?: boolean }\n | { written: false; reason: \"already-set\" | \"unrecognized\" }\n\nfunction isCommandStatusLine(value: unknown): value is {\n type: string\n command: string\n} {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return (\n record.type === \"command\"\n && typeof record.command === \"string\"\n && record.command.length > 0\n )\n}\n\nexport async function injectAicStatusLineIntoSettingsFile(\n settingsPath: string,\n statusCommand: string,\n opts: { routerWins?: boolean } = {},\n): Promise<AicStatuslineInjectionResult> {\n let existing: Record<string, unknown> = {}\n let raw: string | undefined\n try {\n raw = await fs.readFile(settingsPath, \"utf8\")\n } catch (err) {\n // Never clobber on a transient read error; a missing file starts clean.\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err\n raw = undefined\n }\n if (raw !== undefined) {\n // A parse failure means a real file we don't understand: do NOT replace it.\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n existing = parsed as Record<string, unknown>\n } else {\n throw new Error(\n `settings.json at ${settingsPath} is not a JSON object; refusing to overwrite`,\n )\n }\n }\n\n const current = existing.statusLine\n if (current !== undefined) {\n // Idempotency: a previous injection already points at our hook.\n if (\n isCommandStatusLine(current)\n && current.command.includes(\"internal-aic-status\")\n ) {\n return { written: false, reason: \"already-set\" }\n }\n // Pinned profiles run the router line only: back up whatever was\n // there (command or exotic shape) to a mirror sidecar for audit and\n // replace it. The user command is recorded but never executed.\n if (opts.routerWins) {\n const hadPrevious = true\n const merged = {\n ...existing,\n statusLine: { type: \"command\", command: statusCommand },\n }\n await writeSettingsAtomically(settingsPath, merged)\n await writeBackupSidecar(settingsPath, current)\n return { written: true, mode: \"forced\", hadPrevious }\n }\n // Wrap-don't-clobber: preserve the user's command via env.\n if (isCommandStatusLine(current)) {\n const userCommand = current.command\n const merged = {\n ...existing,\n statusLine: { type: \"command\", command: statusCommand },\n }\n await writeSettingsAtomically(settingsPath, merged)\n return { written: true, mode: \"wrapped\", userCommand }\n }\n return { written: false, reason: \"unrecognized\" }\n }\n\n const merged = {\n ...existing,\n statusLine: { type: \"command\", command: statusCommand },\n }\n await writeSettingsAtomically(settingsPath, merged)\n return { written: true, mode: \"injected\" }\n}\n\nasync function writeSettingsAtomically(\n settingsPath: string,\n merged: Record<string, unknown>,\n): Promise<void> {\n const tmp = `${settingsPath}.${process.pid}.aicstatus.tmp`\n await fs.writeFile(tmp, `${JSON.stringify(merged, null, 2)}\\n`, { mode: 0o600 })\n await fs.rename(tmp, settingsPath)\n}\n\n/**\n * Record a replaced `statusLine` value in a mirror sidecar for audit.\n * Mirror-only (same dir as the mirrored settings.json); the operator's\n * real settings are never touched. Best-effort: a backup failure must\n * not fail the injection that already succeeded.\n */\nasync function writeBackupSidecar(\n settingsPath: string,\n previous: unknown,\n): Promise<void> {\n const backupPath = `${settingsPath}.aic-statusline-backup.json`\n const payload = { replacedStatusLine: previous }\n try {\n await fs.writeFile(backupPath, `${JSON.stringify(payload, null, 2)}\\n`, { mode: 0o600 })\n } catch {\n // Audit-only; the injection itself already landed.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,iBAAiB;;AAE9B,MAAa,0BAA0B;;AAEvC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AC;GAClD,OAAO;IAAE,SAAS;IAAM,MAAM;IAAW;GAAY;EACvD;EACA,OAAO;GAAE,SAAS;GAAO,QAAQ;EAAe;CAClD;CAMA,MAAM,wBAAwB,cAAc;EAH1C,GAAG;EACH,YAAY;GAAE,MAAM;GAAW,SAAS;EAAc;CAEP,CAAC;CAClD,OAAO;EAAE,SAAS;EAAM,MAAM;CAAW;AAC3C;AAEA,eAAe,wBACb,cACA,QACe;CACf,MAAM,MAAM,GAAG,aAAa,GAAG,QAAQ,IAAI;CAC3C,MAAM,GAAG,UAAU,KAAK,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;CAC/E,MAAM,GAAG,OAAO,KAAK,YAAY;AACnC;;;;;;;AAQA,eAAe,mBACb,cACA,UACe;CACf,MAAM,aAAa,GAAG,aAAa;CACnC,MAAM,UAAU,EAAE,oBAAoB,SAAS;CAC/C,IAAI;EACF,MAAM,GAAG,UAAU,YAAY,GAAG,KAAK,UAAU,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;CACzF,QAAQ,CAER;AACF"}
1
+ {"version":3,"file":"aic-statusline-settings-DBS9sEGC.js","names":[],"sources":["../src/lib/aic-statusline-settings.ts"],"sourcesContent":["/**\n * Claude Code `statusLine` injection for the per-session AIC total + rich\n * default session line.\n *\n * `github-router claude` writes `{ statusLine: { type: \"command\", command } }`\n * into the mirrored settings.json so the status bar shows\n * `[AIC 12.42] [####------] 42%·200K | model | dir (branch) | ...`,\n * updating as the ledger file grows. The command itself\n * (`internal-aic-status`) reads the ledger path from `GH_ROUTER_AIC_LEDGER`\n * in the spawned child's env — never a path baked into settings — so the\n * same mirror mechanics work for concurrent launches. AIC is pinned: it\n * renders even when the terminal is too narrow for any other segment.\n *\n * Standard launches use wrap-don't-clobber: when the user's own config\n * already defines `statusLine` as a `{type:\"command\", command:string}`\n * shape, that command is preserved via `GH_ROUTER_AIC_USER_STATUSLINE`\n * (set by the caller from the returned `userCommand`) and the hook\n * composes one line: `[AIC x.xx] <user line>`. Any other pre-existing\n * `statusLine` shape is left untouched (`reason: \"unrecognized\"`) rather\n * than risk breaking an exotic config.\n *\n * Pinned launches (`isPinnedLaunchProfile(profileId)`, `routerWins: true`)\n * run router-provided surfaces only: ANY pre-existing `statusLine` is backed\n * up to a mirror sidecar and replaced with ours (`mode: \"forced\"`), so the\n * native rich line always renders and the user command never executes. The\n * predicate — not an inline alias list — is the source of truth, so a newly\n * pinned profile cannot silently keep wrap-don't-clobber behaviour.\n *\n * Failure model matches the sibling settings writers: a transient read error\n * or a non-object settings.json throws (never clobber a file we don't\n * understand); the caller wraps this in warn-and-continue so a settings-write\n * hiccup never blocks launch. Writes use a same-directory temp file, mode\n * 0o600, then rename.\n */\n\nimport fs from \"node:fs/promises\"\n\nimport type { SelfInvocation } from \"./hook-launcher/self-invocation\"\nimport { buildSelfCommand } from \"./hook-launcher/self-invocation\"\n\n/** Env var carrying the ledger snapshot path into the spawned child. */\nexport const AIC_LEDGER_ENV = \"GH_ROUTER_AIC_LEDGER\"\n/** Env var carrying the user's own statusLine command (wrap mode only). */\nexport const AIC_USER_STATUSLINE_ENV = \"GH_ROUTER_AIC_USER_STATUSLINE\"\n/** Opt-out for the whole injection (mirrors GH_ROUTER_DISABLE_NO_ATTRIBUTION). */\nexport const AIC_STATUSLINE_DISABLE_ENV = \"GH_ROUTER_DISABLE_AIC_STATUSLINE\"\n\nexport function buildAicStatusHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-aic-status\")\n}\n\nexport type AicStatuslineInjectionResult =\n | { written: true; mode: \"injected\" | \"wrapped\" | \"forced\"; userCommand?: string; hadPrevious?: boolean }\n | { written: false; reason: \"already-set\" | \"unrecognized\" }\n\nfunction isCommandStatusLine(value: unknown): value is {\n type: string\n command: string\n} {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return (\n record.type === \"command\"\n && typeof record.command === \"string\"\n && record.command.length > 0\n )\n}\n\nexport async function injectAicStatusLineIntoSettingsFile(\n settingsPath: string,\n statusCommand: string,\n opts: { routerWins?: boolean } = {},\n): Promise<AicStatuslineInjectionResult> {\n let existing: Record<string, unknown> = {}\n let raw: string | undefined\n try {\n raw = await fs.readFile(settingsPath, \"utf8\")\n } catch (err) {\n // Never clobber on a transient read error; a missing file starts clean.\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err\n raw = undefined\n }\n if (raw !== undefined) {\n // A parse failure means a real file we don't understand: do NOT replace it.\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n existing = parsed as Record<string, unknown>\n } else {\n throw new Error(\n `settings.json at ${settingsPath} is not a JSON object; refusing to overwrite`,\n )\n }\n }\n\n const current = existing.statusLine\n if (current !== undefined) {\n // Idempotency: a previous injection already points at our hook.\n if (\n isCommandStatusLine(current)\n && current.command.includes(\"internal-aic-status\")\n ) {\n return { written: false, reason: \"already-set\" }\n }\n // Pinned profiles run the router line only: back up whatever was\n // there (command or exotic shape) to a mirror sidecar for audit and\n // replace it. The user command is recorded but never executed.\n if (opts.routerWins) {\n const hadPrevious = true\n const merged = {\n ...existing,\n statusLine: { type: \"command\", command: statusCommand },\n }\n await writeSettingsAtomically(settingsPath, merged)\n await writeBackupSidecar(settingsPath, current)\n return { written: true, mode: \"forced\", hadPrevious }\n }\n // Wrap-don't-clobber: preserve the user's command via env.\n if (isCommandStatusLine(current)) {\n const userCommand = current.command\n const merged = {\n ...existing,\n statusLine: { type: \"command\", command: statusCommand },\n }\n await writeSettingsAtomically(settingsPath, merged)\n return { written: true, mode: \"wrapped\", userCommand }\n }\n return { written: false, reason: \"unrecognized\" }\n }\n\n const merged = {\n ...existing,\n statusLine: { type: \"command\", command: statusCommand },\n }\n await writeSettingsAtomically(settingsPath, merged)\n return { written: true, mode: \"injected\" }\n}\n\nasync function writeSettingsAtomically(\n settingsPath: string,\n merged: Record<string, unknown>,\n): Promise<void> {\n const tmp = `${settingsPath}.${process.pid}.aicstatus.tmp`\n await fs.writeFile(tmp, `${JSON.stringify(merged, null, 2)}\\n`, { mode: 0o600 })\n await fs.rename(tmp, settingsPath)\n}\n\n/**\n * Record a replaced `statusLine` value in a mirror sidecar for audit.\n * Mirror-only (same dir as the mirrored settings.json); the operator's\n * real settings are never touched. Best-effort: a backup failure must\n * not fail the injection that already succeeded.\n */\nasync function writeBackupSidecar(\n settingsPath: string,\n previous: unknown,\n): Promise<void> {\n const backupPath = `${settingsPath}.aic-statusline-backup.json`\n const payload = { replacedStatusLine: previous }\n try {\n await fs.writeFile(backupPath, `${JSON.stringify(payload, null, 2)}\\n`, { mode: 0o600 })\n } catch {\n // Audit-only; the injection itself already landed.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,iBAAiB;;AAE9B,MAAa,0BAA0B;;AAEvC,MAAa,6BAA6B;AAE1C,SAAgB,0BAA0B,YAAoC;CAC5E,OAAO,iBAAiB,YAAY,qBAAqB;AAC3D;AAMA,SAAS,oBAAoB,OAG3B;CACA,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO;CACxE,MAAM,SAAS;CACf,OACE,OAAO,SAAS,aACb,OAAO,OAAO,YAAY,YAC1B,OAAO,QAAQ,SAAS;AAE/B;AAEA,eAAsB,oCACpB,cACA,eACA,OAAiC,CAAC,GACK;CACvC,IAAI,WAAoC,CAAC;CACzC,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,GAAG,SAAS,cAAc,MAAM;CAC9C,SAAS,KAAK;EAEZ,IAAK,IAA8B,SAAS,UAAU,MAAM;EAC5D,MAAM,KAAA;CACR;CACA,IAAI,QAAQ,KAAA,GAAW;EAErB,MAAM,SAAkB,KAAK,MAAM,GAAG;EACtC,IAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,G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AAS,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;CACzF,QAAQ,CAER;AACF"}
@@ -1,15 +1,15 @@
1
- import { f as writeRuntimeFileSecure, t as PATHS } from "./paths-xTSEAWfN.js";
2
- import { C as CHEAP_REVIEWER_ALIAS_ID, S as CHEAP_PLAN_ALIAS_ID, T as MAX_BROWSE_LOW_ALIAS_ID, _ as CHEAPEST_EXPLORE_ALIAS_ID, b as CHEAP_EXPLORE_ALIAS_ID, g as BROWSE_LOW_ALIAS_ID, h as BALANCED_REVIEWER_ALIAS_ID, m as BALANCED_GENERAL_PURPOSE_ALIAS_ID, p as BALANCED_EXPLORE_ALIAS_ID, v as CHEAPEST_GENERAL_PURPOSE_ALIAS_ID, w as LUNA_SCOUT_ALIAS_ID, x as CHEAP_GENERAL_PURPOSE_ALIAS_ID, y as CHEAPEST_REVIEWER_ALIAS_ID } from "./server-setup-DDZxJgl0.js";
1
+ import { f as writeRuntimeFileSecure, t as PATHS } from "./paths-BSI_EtDT.js";
2
+ import { C as CHEAP_REVIEWER_ALIAS_ID, S as CHEAP_PLAN_ALIAS_ID, T as MAX_BROWSE_LOW_ALIAS_ID, _ as CHEAPEST_EXPLORE_ALIAS_ID, b as CHEAP_EXPLORE_ALIAS_ID, g as BROWSE_LOW_ALIAS_ID, h as BALANCED_REVIEWER_ALIAS_ID, m as BALANCED_GENERAL_PURPOSE_ALIAS_ID, p as BALANCED_EXPLORE_ALIAS_ID, v as CHEAPEST_GENERAL_PURPOSE_ALIAS_ID, w as LUNA_SCOUT_ALIAS_ID, x as CHEAP_GENERAL_PURPOSE_ALIAS_ID, y as CHEAPEST_REVIEWER_ALIAS_ID } from "./server-setup-VYf8ptCH.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-JOnZBgFB.js";
4
- import { Bn as withOneMSuffix, Gn as CHEAP_PROFILE_NATIVE_EFFORTS, Wn as CHEAP_PROFILE_NATIVE_AGENT_NAMES, a as buildAgentPrompt, gn as DEFINITION_OF_GREATNESS, hn as CONDENSED_OPERATING_SEQUENCE, l as maxPersonasFor, n as MCP_GROUPS, t as GROUP_META, u as personasFor, zn as oneMContextDisabled } from "./peer-mcp-personas-Ch4VWo40.js";
5
- import { O as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, _ as isBalancedFamily, k as CHEAPEST_PROFILE_NATIVE_EFFORTS, v as isCheapestFamily } from "./static-context-pack-BRqt4ajJ.js";
4
+ import { Hn as withOneMSuffix, Kn as CHEAP_PROFILE_NATIVE_AGENT_NAMES, Vn as oneMContextDisabled, _n as CONDENSED_OPERATING_SEQUENCE, a as buildAgentPrompt, l as maxPersonasFor, n as MCP_GROUPS, qn as CHEAP_PROFILE_NATIVE_EFFORTS, t as GROUP_META, u as personasFor, vn as DEFINITION_OF_GREATNESS } from "./peer-mcp-personas-CVxXq1Q-.js";
5
+ import { O as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, _ as isBalancedFamily, k as CHEAPEST_PROFILE_NATIVE_EFFORTS, v as isCheapestFamily } from "./static-context-pack-dKrzbfIN.js";
6
6
  import { a as BALANCED_PROFILE_NATIVE_EFFORTS, i as BALANCED_PROFILE_NATIVE_AGENT_NAMES } from "./balanced-profile-contract-DtnTIBjL.js";
7
- import { 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-CMvzKSsg.js";
8
- import "./self-invocation-Dr5zlbpM.js";
9
- import { a as STRIPPED_AUTH_ROUTING_ENV_KEYS, n as buildCodexProviderConfigFlags } from "./provision-PodfFQu-.js";
10
- import { n as buildWorkspaceHeaderHelperCommand } from "./mcp-workspace-header-DBQugQlQ.js";
11
- import { a as dispatcherAgentName, c as dispatcherTools, n as activeDispatchModes, o as dispatcherDescription, s as dispatcherPrompt } from "./worker-dispatch-BjfROaic.js";
12
- import { o as isUnderClaudeConfigMirrorRealpath, u as renameWithRetry } from "./claude-md-injection-CDOoGNEJ.js";
7
+ import { 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-Cx5_Z1Y7.js";
8
+ import "./self-invocation-Dk_UHD_v.js";
9
+ import { a as STRIPPED_AUTH_ROUTING_ENV_KEYS, n as buildCodexProviderConfigFlags } from "./provision-DYmZgZDr.js";
10
+ import { n as buildWorkspaceHeaderHelperCommand } from "./mcp-workspace-header-Su8uUxJg.js";
11
+ import { a as dispatcherAgentName, c as dispatcherTools, n as activeDispatchModes, o as dispatcherDescription, s as dispatcherPrompt } from "./worker-dispatch-B_rriT7z.js";
12
+ import { o as isUnderClaudeConfigMirrorRealpath, u as renameWithRetry } from "./claude-md-injection-Cpzolxin.js";
13
13
  import consola from "consola";
14
14
  import path from "node:path";
15
15
  import { randomBytes } from "node:crypto";
@@ -3349,4 +3349,4 @@ async function injectAttributionSuppressionIntoSettingsFile(settingsPath) {
3349
3349
  //#endregion
3350
3350
  export { buildArtifactReviewSkill as a, injectAllowRules as c, BUILTIN_SUBAGENT_DEFINITIONS as d, injectPeerMcpIntoMirror as f, writePeerMcpRuntimeFiles as g, workersKeyOf as h, writeInjectedSkill as i, planModeAllowRules as l, resolveGroupKeysFromMirror as m, getInjectedSkills as n, SEAMLESS_BUILTIN_TOOLS as o, resolveCodexCliBackend as p, injectedSkillsForLaunch as r, configureServeDefaultPermissionMode as s, injectAttributionSuppressionIntoSettingsFile as t, sanitizeServeSettingsEnv as u };
3351
3351
 
3352
- //# sourceMappingURL=attribution-settings-N48QlHu2.js.map
3352
+ //# sourceMappingURL=attribution-settings-CnmV9MSv.js.map