github-router 0.3.372 → 0.3.374
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ado-tools-BOW1k1KW.js +1 -0
- package/dist/{aic-ledger-Cp7Yk9-Q.js → aic-ledger-CeSXqTEE.js} +5 -7
- package/dist/{aic-ledger-Cp7Yk9-Q.js.map → aic-ledger-CeSXqTEE.js.map} +1 -1
- package/dist/{aic-statusline-settings-B5EMMSFC.js → aic-statusline-settings-BKveu679.js} +3 -4
- package/dist/{aic-statusline-settings-B5EMMSFC.js.map → aic-statusline-settings-BKveu679.js.map} +1 -1
- package/dist/{attribution-settings-HI_5bN_-.js → attribution-settings-BLTnz2_A.js} +33 -53
- package/dist/{attribution-settings-HI_5bN_-.js.map → attribution-settings-BLTnz2_A.js.map} +1 -1
- package/dist/{auth-B1egtvt4.js → auth-BZHpTtfF.js} +5 -6
- package/dist/{auth-B1egtvt4.js.map → auth-BZHpTtfF.js.map} +1 -1
- package/dist/{balanced-profile-contract-Dm_usmw7.js → balanced-profile-contract-B6pSoWjm.js} +2 -3
- package/dist/{balanced-profile-contract-Dm_usmw7.js.map → balanced-profile-contract-B6pSoWjm.js.map} +1 -1
- package/dist/{bluebird-client-ByCRusGQ.js → bluebird-client-BasIdv5J.js} +8 -12
- package/dist/{bluebird-client-ByCRusGQ.js.map → bluebird-client-BasIdv5J.js.map} +1 -1
- package/dist/{bluebird-client-CY6NBHQu.js → bluebird-client-BvoMTmEv.js} +1 -1
- package/dist/browser-bridge/index.js +84 -55
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-T_z84Pgc.js → check-usage-BlIWDuV2.js} +5 -6
- package/dist/{check-usage-T_z84Pgc.js.map → check-usage-BlIWDuV2.js.map} +1 -1
- package/dist/{claude-BBSsqwln.js → claude-DSXrdz0v.js} +37 -43
- package/dist/{claude-BBSsqwln.js.map → claude-DSXrdz0v.js.map} +1 -1
- package/dist/{claude-md-injection-BMon6WUD.js → claude-md-injection-DU5KYXNc.js} +6 -7
- package/dist/{claude-md-injection-BMon6WUD.js.map → claude-md-injection-DU5KYXNc.js.map} +1 -1
- package/dist/{client-CQMfroGV.js → client-Bjp3XAMK.js} +3 -5
- package/dist/{client-CQMfroGV.js.map → client-Bjp3XAMK.js.map} +1 -1
- package/dist/{codex-PRWoBiOH.js → codex-DGMUk65v.js} +10 -11
- package/dist/{codex-PRWoBiOH.js.map → codex-DGMUk65v.js.map} +1 -1
- package/dist/{copilot-discount-T-cfWmc4.js → copilot-discount-CHNQLYDJ.js} +3 -4
- package/dist/{copilot-discount-T-cfWmc4.js.map → copilot-discount-CHNQLYDJ.js.map} +1 -1
- package/dist/{debug-DL2JsRqY.js → debug-1HUHCWFl.js} +3 -4
- package/dist/{debug-DL2JsRqY.js.map → debug-1HUHCWFl.js.map} +1 -1
- package/dist/engine-BC4TF4pt.js +1 -0
- package/dist/{exec-Bf8g_bIR.js → exec-BC0MAnoA.js} +2 -3
- package/dist/{exec-Bf8g_bIR.js.map → exec-BC0MAnoA.js.map} +1 -1
- package/dist/{fast-profile-contract-JOnZBgFB.js → fast-profile-contract-BLnKg0Ay.js} +2 -3
- package/dist/{fast-profile-contract-JOnZBgFB.js.map → fast-profile-contract-BLnKg0Ay.js.map} +1 -1
- package/dist/{gate-discovery-BNy8GKsC.js → gate-discovery-DiXu_olc.js} +8 -10
- package/dist/{gate-discovery-BNy8GKsC.js.map → gate-discovery-DiXu_olc.js.map} +1 -1
- package/dist/{get-copilot-usage-BSXeQEx8.js → get-copilot-usage-CKg42gSH.js} +5 -6
- package/dist/{get-copilot-usage-BSXeQEx8.js.map → get-copilot-usage-CKg42gSH.js.map} +1 -1
- package/dist/{hook-mcp-client-DERIkeR7.js → hook-mcp-client-CYx10nlU.js} +2 -3
- package/dist/hook-mcp-client-CYx10nlU.js.map +1 -0
- package/dist/hooks.mjs +1766 -1548
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-CjRcmYk3.js → index-cmd-BPXhTfGQ.js} +8 -9
- package/dist/index-cmd-BPXhTfGQ.js.map +1 -0
- package/dist/{internal-aic-status-CY0QxSa7.js → internal-aic-status-FQB1DQzX.js} +6 -8
- package/dist/{internal-aic-status-CY0QxSa7.js.map → internal-aic-status-FQB1DQzX.js.map} +1 -1
- package/dist/{internal-artifact-open-NAGn9Mgt.js → internal-artifact-open-DbHjipxU.js} +5 -7
- package/dist/{internal-artifact-open-NAGn9Mgt.js.map → internal-artifact-open-DbHjipxU.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-De_DJOyZ.js → internal-fast-dispatch-guard-DMzqs-r8.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-_n-A8hgo.js → internal-fast-dispatch-guard-PDdlkPU3.js} +6 -8
- package/dist/{internal-fast-dispatch-guard-_n-A8hgo.js.map → internal-fast-dispatch-guard-PDdlkPU3.js.map} +1 -1
- package/dist/{internal-first-mate-guard-GufCUMl3.js → internal-first-mate-guard-4Yro9xNM.js} +5 -7
- package/dist/{internal-first-mate-guard-GufCUMl3.js.map → internal-first-mate-guard-4Yro9xNM.js.map} +1 -1
- package/dist/{internal-first-mate-guard-C8GwLbaX.js → internal-first-mate-guard-BxPDUsV3.js} +1 -1
- package/dist/{internal-max-dispatch-guard-4rh6KSd8.js → internal-max-dispatch-guard-D3L00YXj.js} +5 -7
- package/dist/{internal-max-dispatch-guard-4rh6KSd8.js.map → internal-max-dispatch-guard-D3L00YXj.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-CKnzgJje.js → internal-max-dispatch-guard-fhBX_w49.js} +1 -1
- package/dist/{internal-plan-review-ChFx8wTX.js → internal-plan-review-BfHLeszV.js} +6 -7
- package/dist/{internal-plan-review-ChFx8wTX.js.map → internal-plan-review-BfHLeszV.js.map} +1 -1
- package/dist/{internal-prompt-submit-BW5g3MjD.js → internal-prompt-submit-BbnaMF2R.js} +7 -8
- package/dist/{internal-prompt-submit-BW5g3MjD.js.map → internal-prompt-submit-BbnaMF2R.js.map} +1 -1
- package/dist/{internal-prompt-submit-C4uDwr7G.js → internal-prompt-submit-DKzCckz-.js} +2 -2
- package/dist/{internal-rebrief-DvBS8myn.js → internal-rebrief-aEvxp7jw.js} +7 -9
- package/dist/{internal-rebrief-DvBS8myn.js.map → internal-rebrief-aEvxp7jw.js.map} +1 -1
- package/dist/{internal-session-bind-dsUOcKxU.js → internal-session-bind-pN1V11Mn.js} +3 -4
- package/dist/{internal-session-bind-dsUOcKxU.js.map → internal-session-bind-pN1V11Mn.js.map} +1 -1
- package/dist/{internal-stop-hook-CXlOsW63.js → internal-stop-hook-VQuOYpUC.js} +9 -10
- package/dist/{internal-stop-hook-CXlOsW63.js.map → internal-stop-hook-VQuOYpUC.js.map} +1 -1
- package/dist/{internal-stop-review-D_KEV_04.js → internal-stop-review-BWp-4XWW.js} +4 -5
- package/dist/{internal-stop-review-D_KEV_04.js.map → internal-stop-review-BWp-4XWW.js.map} +1 -1
- package/dist/{internal-worker-guard-DB6shBIn.js → internal-worker-guard-C9OZPgzu.js} +3 -4
- package/dist/{internal-worker-guard-DB6shBIn.js.map → internal-worker-guard-C9OZPgzu.js.map} +1 -1
- package/dist/{internal-workspace-header-DBg5Y7oN.js → internal-workspace-header-B4TXFBLU.js} +3 -4
- package/dist/{internal-workspace-header-DBg5Y7oN.js.map → internal-workspace-header-B4TXFBLU.js.map} +1 -1
- package/dist/lib/tree-sitter-pool/{lifecycle-Dx0SnP7Z.js → lifecycle-BPpOigPZ.js} +1 -2
- package/dist/lib/tree-sitter-pool/{lifecycle-C7W8D2lx.js → lifecycle-C3vsqXjS.js} +1 -3
- package/dist/lib/tree-sitter-pool/worker.js +29 -35
- package/dist/lifecycle-BENRuuX6.js +1 -0
- package/dist/{lifecycle-K9oVtGde.mjs → lifecycle-DBKu1T5r.mjs} +0 -1
- package/dist/{lifecycle-Gge2Dadd.js → lifecycle-Dh9y8OF1.js} +3 -4
- package/dist/{lifecycle-Gge2Dadd.js.map → lifecycle-Dh9y8OF1.js.map} +1 -1
- package/dist/lifecycle-Dli9vGI2.js +1 -0
- package/dist/{lifecycle-9nX09dBl.js → lifecycle-vjHAFCaY.js} +4 -6
- package/dist/{lifecycle-9nX09dBl.js.map → lifecycle-vjHAFCaY.js.map} +1 -1
- package/dist/main.js +26 -27
- package/dist/{max-profile-contract-CRj7N211.js → max-profile-contract-DLLTsSs2.js} +5 -8
- package/dist/{max-profile-contract-CRj7N211.js.map → max-profile-contract-DLLTsSs2.js.map} +1 -1
- package/dist/{mcp-workspace-header-Xw9B1W6T.js → mcp-workspace-header-C5-dOWNa.js} +3 -4
- package/dist/{mcp-workspace-header-Xw9B1W6T.js.map → mcp-workspace-header-C5-dOWNa.js.map} +1 -1
- package/dist/{models-Ca-HQTYi.js → models-B6nH1sS6.js} +4 -5
- package/dist/{models-Ca-HQTYi.js.map → models-B6nH1sS6.js.map} +1 -1
- package/dist/{orchestration-D3-2ulhX.js → orchestration-B93jxrWI.js} +4 -5
- package/dist/{orchestration-D3-2ulhX.js.map → orchestration-B93jxrWI.js.map} +1 -1
- package/dist/{package-root-B-osctCk.js → package-root-BXgdIM3q.js} +2 -3
- package/dist/{package-root-B-osctCk.js.map → package-root-BXgdIM3q.js.map} +1 -1
- package/dist/paths-Be9_ujQ3.js +1 -0
- package/dist/{paths-C5477RGC.js → paths-CVEO8jEH.js} +5 -7
- package/dist/{paths-C5477RGC.js.map → paths-CVEO8jEH.js.map} +1 -1
- package/dist/{peer-mcp-personas-Dxxw5X1g.js → peer-mcp-personas-Cv21q_YR.js} +244 -372
- package/dist/peer-mcp-personas-Cv21q_YR.js.map +1 -0
- package/dist/{pi-IYAvKF50.js → pi-DI2QtaiZ.js} +305 -89
- package/dist/pi-DI2QtaiZ.js.map +1 -0
- package/dist/{pi-memory-bridge-DEU1SUDz.js → pi-memory-bridge-Dvj1T3e3.js} +2 -3
- package/dist/{pi-memory-bridge-DEU1SUDz.js.map → pi-memory-bridge-Dvj1T3e3.js.map} +1 -1
- package/dist/{plan-review-hook-C9K-em4D.js → plan-review-hook-MhjK92wq.js} +5 -6
- package/dist/{plan-review-hook-C9K-em4D.js.map → plan-review-hook-MhjK92wq.js.map} +1 -1
- package/dist/{provision-CIn6I4w_.js → provision-CRmtV6ew.js} +10 -14
- package/dist/{provision-CIn6I4w_.js.map → provision-CRmtV6ew.js.map} +1 -1
- package/dist/rolldown-runtime-D3PmRqjj.js +4 -0
- package/dist/{self-invocation-BtcGj-lY.js → self-invocation-DMUnXVGT.js} +5 -7
- package/dist/{self-invocation-BtcGj-lY.js.map → self-invocation-DMUnXVGT.js.map} +1 -1
- package/dist/{serve-CttHP8dJ.js → serve-DRASJ-ZO.js} +24 -30
- package/dist/{serve-CttHP8dJ.js.map → serve-DRASJ-ZO.js.map} +1 -1
- package/dist/{server-setup-D7XHUrhM.js → server-setup-DldGizZR.js} +67 -117
- package/dist/{server-setup-D7XHUrhM.js.map → server-setup-DldGizZR.js.map} +1 -1
- package/dist/{service-backend-B6D_DY1Z.js → service-backend-Ce6b2XEe.js} +146 -146
- package/dist/service-backend-Ce6b2XEe.js.map +1 -0
- package/dist/{start-XU5HwLd9.js → start-C0gngUPK.js} +6 -8
- package/dist/{start-XU5HwLd9.js.map → start-C0gngUPK.js.map} +1 -1
- package/dist/{state-DzsaGHr9.js → state-CCGDJ43X.js} +2 -3
- package/dist/{state-DzsaGHr9.js.map → state-CCGDJ43X.js.map} +1 -1
- package/dist/{static-context-pack-CsOAC87F.js → static-context-pack-DwC69_VA.js} +14 -24
- package/dist/{static-context-pack-CsOAC87F.js.map → static-context-pack-DwC69_VA.js.map} +1 -1
- package/dist/{stop-gate-hook-DnLC09Lg.js → stop-gate-hook-CBVLD8iB.js} +9 -14
- package/dist/{stop-gate-hook-DnLC09Lg.js.map → stop-gate-hook-CBVLD8iB.js.map} +1 -1
- package/dist/{stop-gate-policy-Dx9c98_d.js → stop-gate-policy-BehNiNix.js} +4 -5
- package/dist/{stop-gate-policy-Dx9c98_d.js.map → stop-gate-policy-BehNiNix.js.map} +1 -1
- package/dist/{token-Dqjs5ixP.js → token-CPzYxU4Y.js} +16 -28
- package/dist/{token-Dqjs5ixP.js.map → token-CPzYxU4Y.js.map} +1 -1
- package/dist/{token-CVG0yI_j.js → token-DHEkiO4g.js} +3 -4
- package/dist/{token-CVG0yI_j.js.map → token-DHEkiO4g.js.map} +1 -1
- package/dist/{upstream-retry-i1k1Xai2.js → upstream-retry-VNR-bCuT.js} +2 -3
- package/dist/{upstream-retry-i1k1Xai2.js.map → upstream-retry-VNR-bCuT.js.map} +1 -1
- package/dist/{version-C8x2hQrZ.js → version-CTqwKr26.js} +3 -4
- package/dist/{version-C8x2hQrZ.js.map → version-CTqwKr26.js.map} +1 -1
- package/dist/{worker-dispatch-B1w2qfjX.js → worker-dispatch-C7RtNOXv.js} +3 -4
- package/dist/{worker-dispatch-B1w2qfjX.js.map → worker-dispatch-C7RtNOXv.js.map} +1 -1
- package/dist/{workiq-qnJR5_n2.js → workiq-CQauEAMc.js} +3 -4
- package/dist/{workiq-qnJR5_n2.js.map → workiq-CQauEAMc.js.map} +1 -1
- package/dist/{workiq-tools-CMoDjrO0.js → workiq-tools-7n2xXMrQ.js} +1 -1
- package/package.json +19 -17
- package/dist/ado-tools-CAtopk36.js +0 -1
- package/dist/engine-CDZdAx8N.js +0 -1
- package/dist/hook-mcp-client-DERIkeR7.js.map +0 -1
- package/dist/index-cmd-CjRcmYk3.js.map +0 -1
- package/dist/lifecycle-C_CT13c9.js +0 -1
- package/dist/lifecycle-DibiH857.js +0 -1
- package/dist/paths-CEswtFj5.js +0 -1
- package/dist/peer-mcp-personas-Dxxw5X1g.js.map +0 -1
- package/dist/pi-IYAvKF50.js.map +0 -1
- package/dist/service-backend-B6D_DY1Z.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { xt as disposeAdoClients } from "./peer-mcp-personas-Cv21q_YR.js";
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { t as PATHS } from "./paths-
|
|
2
|
-
import { f as resolveModel } from "./token-
|
|
1
|
+
import { t as PATHS } from "./paths-CVEO8jEH.js";
|
|
2
|
+
import { f as resolveModel } from "./token-CPzYxU4Y.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs$1 from "node:fs/promises";
|
|
6
|
-
|
|
6
|
+
// src/lib/aic-usage.ts
|
|
7
7
|
/** Nano-AIU per AI credit (SI prefix, per Copilot SDK docs). */
|
|
8
8
|
const NANO_AIU_PER_CREDIT = 1e9;
|
|
9
9
|
function nonNegativeNumber(value) {
|
|
@@ -75,8 +75,7 @@ function formatAic(credits) {
|
|
|
75
75
|
if (credits >= .01) return credits.toFixed(3);
|
|
76
76
|
return credits.toPrecision(2);
|
|
77
77
|
}
|
|
78
|
-
|
|
79
|
-
//#region src/lib/aic-ledger.ts
|
|
78
|
+
// src/lib/aic-ledger.ts
|
|
80
79
|
/**
|
|
81
80
|
* Per-launch AIC (AI Credits) ledger.
|
|
82
81
|
*
|
|
@@ -386,7 +385,6 @@ async function isPidAlive(pid) {
|
|
|
386
385
|
return false;
|
|
387
386
|
}
|
|
388
387
|
}
|
|
389
|
-
//#endregion
|
|
390
388
|
export { extractAndRecordPricedAic as a, readAicSnapshotFile as c, removeAicLedgerFile as d, sweepStaleAicLedgerFiles as f, nanoAiuToCredits as g, formatAic as h, extractAndRecordAic as i, recordAic as l, extractCopilotUsage as m, aicSnapshot as n, formatAicExitSummary as o, copilotUsageToWire as p, aicTotalCredits as r, formatAicStatus as s, aicLedgerPath as t, recordZeroCostRequest as u };
|
|
391
389
|
|
|
392
|
-
//# sourceMappingURL=aic-ledger-
|
|
390
|
+
//# sourceMappingURL=aic-ledger-CeSXqTEE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aic-ledger-Cp7Yk9-Q.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 * Record one request the router knows cost nothing: a `-m local` / `-m local2`\n * lead turn served by the operator's own local model server.\n *\n * A local response carries no `copilot_usage` and never will, so without this\n * the ledger would count zero REQUESTS as well as zero credits and the whole\n * session would read like a broken ledger rather than a free one.\n *\n * The key is the RAW model id on purpose. `aicModelKey` resolves through the\n * Copilot catalog, which maps `opus` onto `claude-opus-5.5` — filing a free\n * local turn under a Copilot model would be a false attribution in the exit\n * cost table. Local ids are not catalog ids and must not be treated as such.\n */\nexport function recordZeroCostRequest(model: string | undefined): void {\n const key =\n typeof model === \"string\" && model.trim().length > 0 ?\n model.trim()\n : \"unknown\"\n ledger.requests += 1\n // An existing entry keeps whatever spend it already has (a local id can\n // never have any, but the ledger is shared with a launch that may switch\n // models), so the credit total is untouched here by construction.\n const entry = ledger.perModel[key] ?? { nanoAiu: 0, requests: 0 }\n entry.requests += 1\n ledger.perModel[key] = entry\n ledger.tokensByModel[key] ??= emptyModelTokens()\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/**\n * One-line status fragment: `[AIC 12.42]`. Empty string only when nothing has\n * been recorded at all.\n *\n * The guard is `requests === 0`, NOT `totalNanoAiu <= 0`: a recorded request\n * that cost nothing is a MEASURED zero, and hiding it would make a local\n * session indistinguishable from a session whose ledger never worked. Zero\n * keeps the two-decimal shape (`formatAic(0)` is a bare `\"0\"`) so it reads as\n * a number rather than an absence.\n */\nexport function formatAicStatus(snapshot: AicSnapshot): string {\n if (snapshot.requests === 0) return \"\"\n const total = aicTotalCredits(snapshot)\n return `[AIC ${total > 0 ? formatAic(total) : \"0.00\"}]`\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,k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,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-CeSXqTEE.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 * Record one request the router knows cost nothing: a `-m local` / `-m local2`\n * lead turn served by the operator's own local model server.\n *\n * A local response carries no `copilot_usage` and never will, so without this\n * the ledger would count zero REQUESTS as well as zero credits and the whole\n * session would read like a broken ledger rather than a free one.\n *\n * The key is the RAW model id on purpose. `aicModelKey` resolves through the\n * Copilot catalog, which maps `opus` onto `claude-opus-5.5` — filing a free\n * local turn under a Copilot model would be a false attribution in the exit\n * cost table. Local ids are not catalog ids and must not be treated as such.\n */\nexport function recordZeroCostRequest(model: string | undefined): void {\n const key =\n typeof model === \"string\" && model.trim().length > 0 ?\n model.trim()\n : \"unknown\"\n ledger.requests += 1\n // An existing entry keeps whatever spend it already has (a local id can\n // never have any, but the ledger is shared with a launch that may switch\n // models), so the credit total is untouched here by construction.\n const entry = ledger.perModel[key] ?? { nanoAiu: 0, requests: 0 }\n entry.requests += 1\n ledger.perModel[key] = entry\n ledger.tokensByModel[key] ??= emptyModelTokens()\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/**\n * One-line status fragment: `[AIC 12.42]`. Empty string only when nothing has\n * been recorded at all.\n *\n * The guard is `requests === 0`, NOT `totalNanoAiu <= 0`: a recorded request\n * that cost nothing is a MEASURED zero, and hiding it would make a local\n * session indistinguishable from a session whose ledger never worked. Zero\n * keeps the two-decimal shape (`formatAic(0)` is a bare `\"0\"`) so it reads as\n * a number rather than an absence.\n */\nexport function formatAicStatus(snapshot: AicSnapshot): string {\n if (snapshot.requests === 0) return \"\"\n const total = aicTotalCredits(snapshot)\n return `[AIC ${total > 0 ? formatAic(total) : \"0.00\"}]`\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,O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OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as buildSelfCommand } from "./self-invocation-
|
|
1
|
+
import { t as buildSelfCommand } from "./self-invocation-DMUnXVGT.js";
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
|
-
|
|
3
|
+
// src/lib/aic-statusline-settings.ts
|
|
4
4
|
/**
|
|
5
5
|
* Claude Code `statusLine` injection for the per-session AIC total + rich
|
|
6
6
|
* default session line.
|
|
@@ -135,7 +135,6 @@ async function writeBackupSidecar(settingsPath, previous) {
|
|
|
135
135
|
await fs.writeFile(backupPath, `${JSON.stringify(payload, null, 2)}\n`, { mode: 384 });
|
|
136
136
|
} catch {}
|
|
137
137
|
}
|
|
138
|
-
//#endregion
|
|
139
138
|
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
139
|
|
|
141
|
-
//# sourceMappingURL=aic-statusline-settings-
|
|
140
|
+
//# sourceMappingURL=aic-statusline-settings-BKveu679.js.map
|
package/dist/{aic-statusline-settings-B5EMMSFC.js.map → aic-statusline-settings-BKveu679.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aic-statusline-settings-
|
|
1
|
+
{"version":3,"file":"aic-statusline-settings-BKveu679.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,KA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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,20 +1,20 @@
|
|
|
1
|
-
import { p as writeRuntimeFileSecure, t as PATHS } from "./paths-
|
|
2
|
-
import { A as CHEAP_EXPLORE_ALIAS_ID, C as BALANCED_EXPLORE_ALIAS_ID, D as CHEAPEST_EXPLORE_ALIAS_ID, E as BROWSE_LOW_ALIAS_ID, F as MAX_BROWSE_LOW_ALIAS_ID, M as CHEAP_PLAN_ALIAS_ID, N as CHEAP_REVIEWER_ALIAS_ID, O as CHEAPEST_GENERAL_PURPOSE_ALIAS_ID, P as LUNA_SCOUT_ALIAS_ID, T as BALANCED_REVIEWER_ALIAS_ID, j as CHEAP_GENERAL_PURPOSE_ALIAS_ID, k as CHEAPEST_REVIEWER_ALIAS_ID, w as BALANCED_GENERAL_PURPOSE_ALIAS_ID } from "./server-setup-
|
|
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-
|
|
4
|
-
import { In as CONDENSED_OPERATING_SEQUENCE, Ln as DEFINITION_OF_GREATNESS, Wn as LOCAL_CONSULT_REDACTION_LINE, a as buildAgentPrompt, dr as withOneMSuffix, gr as CHEAP_PROFILE_NATIVE_EFFORTS, hr as CHEAP_PROFILE_NATIVE_AGENT_NAMES, l as maxPersonasFor, n as MCP_GROUPS, t as GROUP_META, u as personasFor, ur as oneMContextDisabled } from "./peer-mcp-personas-
|
|
5
|
-
import { D as LOCAL_PROFILE_NATIVE_MODELS, E as LOCAL_PROFILE_NATIVE_AGENT_NAMES, L as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, R as CHEAPEST_PROFILE_NATIVE_EFFORTS, _ as isBalancedFamily, b as isLocalFamily, v as isCheapestFamily } from "./static-context-pack-
|
|
6
|
-
import { a as BALANCED_PROFILE_NATIVE_EFFORTS, i as BALANCED_PROFILE_NATIVE_AGENT_NAMES } from "./balanced-profile-contract-
|
|
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-
|
|
8
|
-
import "./self-invocation-
|
|
9
|
-
import { a as STRIPPED_AUTH_ROUTING_ENV_KEYS, n as buildCodexProviderConfigFlags } from "./provision-
|
|
10
|
-
import { n as buildWorkspaceHeaderHelperCommand } from "./mcp-workspace-header-
|
|
11
|
-
import { a as dispatcherAgentName, c as dispatcherTools, n as activeDispatchModes, o as dispatcherDescription, s as dispatcherPrompt } from "./worker-dispatch-
|
|
12
|
-
import { o as isUnderClaudeConfigMirrorRealpath, u as renameWithRetry } from "./claude-md-injection-
|
|
1
|
+
import { p as writeRuntimeFileSecure, t as PATHS } from "./paths-CVEO8jEH.js";
|
|
2
|
+
import { A as CHEAP_EXPLORE_ALIAS_ID, C as BALANCED_EXPLORE_ALIAS_ID, D as CHEAPEST_EXPLORE_ALIAS_ID, E as BROWSE_LOW_ALIAS_ID, F as MAX_BROWSE_LOW_ALIAS_ID, M as CHEAP_PLAN_ALIAS_ID, N as CHEAP_REVIEWER_ALIAS_ID, O as CHEAPEST_GENERAL_PURPOSE_ALIAS_ID, P as LUNA_SCOUT_ALIAS_ID, T as BALANCED_REVIEWER_ALIAS_ID, j as CHEAP_GENERAL_PURPOSE_ALIAS_ID, k as CHEAPEST_REVIEWER_ALIAS_ID, w as BALANCED_GENERAL_PURPOSE_ALIAS_ID } from "./server-setup-DldGizZR.js";
|
|
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-BLnKg0Ay.js";
|
|
4
|
+
import { In as CONDENSED_OPERATING_SEQUENCE, Ln as DEFINITION_OF_GREATNESS, Wn as LOCAL_CONSULT_REDACTION_LINE, a as buildAgentPrompt, dr as withOneMSuffix, gr as CHEAP_PROFILE_NATIVE_EFFORTS, hr as CHEAP_PROFILE_NATIVE_AGENT_NAMES, l as maxPersonasFor, n as MCP_GROUPS, t as GROUP_META, u as personasFor, ur as oneMContextDisabled } from "./peer-mcp-personas-Cv21q_YR.js";
|
|
5
|
+
import { D as LOCAL_PROFILE_NATIVE_MODELS, E as LOCAL_PROFILE_NATIVE_AGENT_NAMES, L as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, R as CHEAPEST_PROFILE_NATIVE_EFFORTS, _ as isBalancedFamily, b as isLocalFamily, v as isCheapestFamily } from "./static-context-pack-DwC69_VA.js";
|
|
6
|
+
import { a as BALANCED_PROFILE_NATIVE_EFFORTS, i as BALANCED_PROFILE_NATIVE_AGENT_NAMES } from "./balanced-profile-contract-B6pSoWjm.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-DLLTsSs2.js";
|
|
8
|
+
import "./self-invocation-DMUnXVGT.js";
|
|
9
|
+
import { a as STRIPPED_AUTH_ROUTING_ENV_KEYS, n as buildCodexProviderConfigFlags } from "./provision-CRmtV6ew.js";
|
|
10
|
+
import { n as buildWorkspaceHeaderHelperCommand } from "./mcp-workspace-header-C5-dOWNa.js";
|
|
11
|
+
import { a as dispatcherAgentName, c as dispatcherTools, n as activeDispatchModes, o as dispatcherDescription, s as dispatcherPrompt } from "./worker-dispatch-C7RtNOXv.js";
|
|
12
|
+
import { o as isUnderClaudeConfigMirrorRealpath, u as renameWithRetry } from "./claude-md-injection-DU5KYXNc.js";
|
|
13
13
|
import consola from "consola";
|
|
14
14
|
import path from "node:path";
|
|
15
15
|
import { randomBytes } from "node:crypto";
|
|
16
16
|
import fs from "node:fs/promises";
|
|
17
|
-
|
|
17
|
+
// src/lib/codex-mcp-config.ts
|
|
18
18
|
/** The `peers` server is always enabled, so its resolved key always exists;
|
|
19
19
|
* this convenience reads it with the bare-key fallback for safety. */
|
|
20
20
|
function peersKeyOf(groupKeys) {
|
|
@@ -1511,8 +1511,7 @@ async function writePeerMcpRuntimeFiles(serverUrl, opts) {
|
|
|
1511
1511
|
cleanup
|
|
1512
1512
|
};
|
|
1513
1513
|
}
|
|
1514
|
-
|
|
1515
|
-
//#region src/lib/mcp-permissions-settings.ts
|
|
1514
|
+
// src/lib/mcp-permissions-settings.ts
|
|
1516
1515
|
/**
|
|
1517
1516
|
* CLAUDE_CODE_* / auth / routing env keys that must NOT reach the CloudCLI-spawned
|
|
1518
1517
|
* serve agent through the mirror `settings.json` `env` block. CloudCLI applies
|
|
@@ -1722,8 +1721,7 @@ async function configureServeDefaultPermissionMode(settingsPath) {
|
|
|
1722
1721
|
}, "servemode");
|
|
1723
1722
|
return { written: true };
|
|
1724
1723
|
}
|
|
1725
|
-
|
|
1726
|
-
//#region src/lib/injected-skills/first-mate-conduct-skill.ts
|
|
1724
|
+
// src/lib/injected-skills/first-mate-conduct-skill.ts
|
|
1727
1725
|
function buildFirstMateConductSkill(_searchEnabled) {
|
|
1728
1726
|
return {
|
|
1729
1727
|
name: "gh-first-mate-conduct",
|
|
@@ -1777,8 +1775,7 @@ ${DEFINITION_OF_GREATNESS}
|
|
|
1777
1775
|
};
|
|
1778
1776
|
}
|
|
1779
1777
|
buildFirstMateConductSkill(true);
|
|
1780
|
-
|
|
1781
|
-
//#region src/lib/injected-skills/first-mate-operate-skill.ts
|
|
1778
|
+
// src/lib/injected-skills/first-mate-operate-skill.ts
|
|
1782
1779
|
function buildFirstMateOperateSkill(_searchEnabled) {
|
|
1783
1780
|
return {
|
|
1784
1781
|
name: "gh-first-mate-operate",
|
|
@@ -1881,16 +1878,14 @@ Report the current phase, its checkpoint and whether it is met with reproducible
|
|
|
1881
1878
|
};
|
|
1882
1879
|
}
|
|
1883
1880
|
buildFirstMateOperateSkill(true);
|
|
1884
|
-
|
|
1885
|
-
//#region src/lib/injected-skills/first-mate-setup-skill.ts
|
|
1881
|
+
// src/lib/injected-skills/first-mate-setup-skill.ts
|
|
1886
1882
|
function buildFirstMateSetupSkill(_searchEnabled) {
|
|
1887
1883
|
return {
|
|
1888
1884
|
name: "gh-first-mate-scaffold",
|
|
1889
1885
|
md: "---\nname: gh-first-mate-scaffold\ndescription: Scaffolds a repo-geared agentic-dev foundation through first-mate: seeds guidance files, role agents, ADRs, changelog, learnings, PR template, test instructions, Copilot setup, and CI through a scaffold branch and PR. Use before the first build wave on an owned repository.\nuser-invocable: true\n---\n\n# gh-first-mate-scaffold\n\nInvoke the `scaffold_repo` MCP tool (`mcp__first-mate__scaffold_repo`) before the first build wave on an owned repository. The goal is not generic TODO stubs; it is a repo-geared foundation that GitHub agents, local agents, reviewers, and CI can read.\n\n## What it seeds\n\n- `AGENTS.md` / `CLAUDE.md` / `GEMINI.md` / `.github/copilot-instructions.md` — identical guidance with overview, detected stack, commands, hard DoD gate, primary OS, conventions, structure, decisions/memory, handoff, testing, and gotchas.\n- `.github/agents/{ceo,cto,cpo,planner,implementer,reviewer,researcher,tester}.md` mirrored into `.claude/agents/` — C-suite operator hats plus execution roles, each with frontmatter, cold-start contract, method, quality bar, output contract, and self-reminder.\n- `docs/playbook/README.md` — the autonomous DISCOVER → NICHE → POSITION → SCOPE → BUILD → LAUNCH → MEASURE → ITERATE → GROW protocol, externally verifiable phase gates, OODA / Build-Measure-Learn governance, and authority limits.\n- `docs/adrs/0000-template.md` plus `docs/adr/0001-record-architecture-decisions.md` — Nygard-style decision record foundation.\n- `LEARNINGS.md`, `CHANGELOG.md`, `docs/history/0000-template.md`, `docs/plans/README.md`, and `docs/research/README.md` — durable memory, history, plans, and research conventions.\n- `.github/pull_request_template.md` — summary, type, failure-modes-considered-and-tested, and DoD checklist.\n- `.github/instructions/tests.instructions.md` — path-scoped test guidance filled from detected framework/dir/glob where possible.\n- `.github/workflows/copilot-setup-steps.yml` and starter `.github/workflows/ci.yml` — detected toolchain setup with stable quality-gate job names.\n\nIt does not seed factory-protocol or `docs/factory/` files. Orchestration remains outside the product repo in first-mate.\n\n## Usage\n\n```\nmcp__first-mate__scaffold_repo({ repo: \"owner/repo\" })\nmcp__first-mate__scaffold_repo({ repo: \"owner/repo\", mode: \"enhance\" })\nmcp__first-mate__scaffold_repo({\n repo: \"owner/repo\",\n mode: \"add-missing-only\",\n detection_overrides: { primary_os: \"windows-latest\", test_command: \"npm test\" }\n})\n```\n\nModes:\n\n- `add-missing-only` (default): seed absent files and skip present files.\n- `enhance`: for guidance files, product playbook, ADR index, changelog, and learnings, append only missing `##` sections; never rewrite existing prose. Other present files are skipped.\n- `overwrite-approved`: replace existing files only when explicitly approved.\n\nAlways inspect the returned per-file report and PR. A no-op result means the repo already has the foundation or has no missing enhanceable sections.\n"
|
|
1890
1886
|
};
|
|
1891
1887
|
}
|
|
1892
|
-
|
|
1893
|
-
//#region src/lib/injected-skills/first-mate-skill.ts
|
|
1888
|
+
// src/lib/injected-skills/first-mate-skill.ts
|
|
1894
1889
|
function buildFirstMateSkill(_searchEnabled) {
|
|
1895
1890
|
return {
|
|
1896
1891
|
name: "gh-first-mate",
|
|
@@ -2052,8 +2047,7 @@ When reporting progress, return:
|
|
|
2052
2047
|
`
|
|
2053
2048
|
};
|
|
2054
2049
|
}
|
|
2055
|
-
|
|
2056
|
-
//#region src/lib/injected-skills/floor-keeper-skill.ts
|
|
2050
|
+
// src/lib/injected-skills/floor-keeper-skill.ts
|
|
2057
2051
|
function buildFloorKeeperSkill(_searchEnabled) {
|
|
2058
2052
|
return {
|
|
2059
2053
|
name: "gh-floor-keeper",
|
|
@@ -2204,8 +2198,7 @@ Return a compact final checkpoint:
|
|
|
2204
2198
|
`
|
|
2205
2199
|
};
|
|
2206
2200
|
}
|
|
2207
|
-
|
|
2208
|
-
//#region src/lib/injected-skills/plan-skill.ts
|
|
2201
|
+
// src/lib/injected-skills/plan-skill.ts
|
|
2209
2202
|
/**
|
|
2210
2203
|
* Whether the profile roster includes an `implementer` native.
|
|
2211
2204
|
*
|
|
@@ -2378,8 +2371,7 @@ Return:
|
|
|
2378
2371
|
};
|
|
2379
2372
|
}
|
|
2380
2373
|
buildPlanSkill(true);
|
|
2381
|
-
|
|
2382
|
-
//#region src/lib/injected-skills/gather-context-skill.ts
|
|
2374
|
+
// src/lib/injected-skills/gather-context-skill.ts
|
|
2383
2375
|
function buildGatherContextSkill(searchEnabled, bluebirdEnabled = false, profile) {
|
|
2384
2376
|
const semanticAvailable = searchEnabled || bluebirdEnabled;
|
|
2385
2377
|
const modelNote = isLocalFamily(profile) ? "All reasoning runs at the 200K default window: the lead and every Explore\nsubagent run with bare slugs (no 1M accounting)." : "All reasoning runs at the 200K default window: the lead and every Explore\nsubagent use the Luna model at high effort with bare slugs (no 1M accounting).";
|
|
@@ -2507,8 +2499,7 @@ ${outputNote}
|
|
|
2507
2499
|
};
|
|
2508
2500
|
}
|
|
2509
2501
|
buildGatherContextSkill(true);
|
|
2510
|
-
|
|
2511
|
-
//#region src/lib/injected-skills/implement-skill.ts
|
|
2502
|
+
// src/lib/injected-skills/implement-skill.ts
|
|
2512
2503
|
function buildImplementSkill(_searchEnabled, profile) {
|
|
2513
2504
|
const planDispatches = isCheapestFamily(profile) || isBalancedFamily(profile) || isLocalFamily(profile) ? "planning work" : "Plan dispatches";
|
|
2514
2505
|
const implementerFirst = rosterEmitsImplementer(profile) ? "If an implementer subagent exists (max profile), use it first for implementation tasks, then General-Purpose for handoffs; otherwise use General-Purpose for all tasks" : "Use General-Purpose for every implementation task and handoff";
|
|
@@ -2625,8 +2616,7 @@ Return:
|
|
|
2625
2616
|
};
|
|
2626
2617
|
}
|
|
2627
2618
|
buildImplementSkill(true);
|
|
2628
|
-
|
|
2629
|
-
//#region src/lib/injected-skills/orchestrate-skill.ts
|
|
2619
|
+
// src/lib/injected-skills/orchestrate-skill.ts
|
|
2630
2620
|
function buildOrchestrateSkill(searchEnabled, bluebirdEnabled = false) {
|
|
2631
2621
|
return {
|
|
2632
2622
|
name: "gh-orchestrate",
|
|
@@ -2765,8 +2755,7 @@ Return:
|
|
|
2765
2755
|
`
|
|
2766
2756
|
};
|
|
2767
2757
|
}
|
|
2768
|
-
|
|
2769
|
-
//#region src/lib/injected-skills/research-skill.ts
|
|
2758
|
+
// src/lib/injected-skills/research-skill.ts
|
|
2770
2759
|
function buildResearchSkill(searchEnabled, bluebirdEnabled = false) {
|
|
2771
2760
|
return {
|
|
2772
2761
|
name: "gh-research",
|
|
@@ -2884,8 +2873,7 @@ Return a compact brief, not the whole research dump:
|
|
|
2884
2873
|
`
|
|
2885
2874
|
};
|
|
2886
2875
|
}
|
|
2887
|
-
|
|
2888
|
-
//#region src/lib/injected-skills/rebrief-skill.ts
|
|
2876
|
+
// src/lib/injected-skills/rebrief-skill.ts
|
|
2889
2877
|
/**
|
|
2890
2878
|
* User-only on-demand cheapest rebrief (`/gh-rebrief`).
|
|
2891
2879
|
*
|
|
@@ -2948,8 +2936,7 @@ ${bluebirdEnabled ? "Grounding uses Bluebird semantic + lexical code search (fai
|
|
|
2948
2936
|
`
|
|
2949
2937
|
};
|
|
2950
2938
|
}
|
|
2951
|
-
|
|
2952
|
-
//#region src/lib/injected-skills/swe-pipeline-skill.ts
|
|
2939
|
+
// src/lib/injected-skills/swe-pipeline-skill.ts
|
|
2953
2940
|
function buildSwePipelineSkill(_searchEnabled, profile) {
|
|
2954
2941
|
const leadPlansDirectly = isCheapestFamily(profile) || isBalancedFamily(profile) || isLocalFamily(profile);
|
|
2955
2942
|
const roster = leadPlansDirectly ? "Explore, General-Purpose, reviewer" : "Explore, Plan, General-Purpose, reviewer, implementer where provided";
|
|
@@ -3075,8 +3062,7 @@ Return:
|
|
|
3075
3062
|
};
|
|
3076
3063
|
}
|
|
3077
3064
|
buildSwePipelineSkill(true);
|
|
3078
|
-
|
|
3079
|
-
//#region src/lib/injected-skills/worker-skill.ts
|
|
3065
|
+
// src/lib/injected-skills/worker-skill.ts
|
|
3080
3066
|
/**
|
|
3081
3067
|
* The `/gh-worker` skill: the operating model for the NON-BLOCKING workers
|
|
3082
3068
|
* surface. Materialized into the per-launch mirror whenever `workerToolsEnabled()`
|
|
@@ -3137,8 +3123,7 @@ The dispatcher calls the worker once and relays its result verbatim.
|
|
|
3137
3123
|
`
|
|
3138
3124
|
};
|
|
3139
3125
|
}
|
|
3140
|
-
|
|
3141
|
-
//#region src/lib/skill-model-contract.ts
|
|
3126
|
+
// src/lib/skill-model-contract.ts
|
|
3142
3127
|
/**
|
|
3143
3128
|
* Universal skill model contract for the `/gh-gather-context`, `/gh-plan`,
|
|
3144
3129
|
* and `/gh-implement` pipeline skills.
|
|
@@ -3224,8 +3209,7 @@ const PIPELINE_SKILL_PROFILES = [
|
|
|
3224
3209
|
function isPipelineSkillProfile(profileId) {
|
|
3225
3210
|
return PIPELINE_SKILL_PROFILES.includes(profileId);
|
|
3226
3211
|
}
|
|
3227
|
-
|
|
3228
|
-
//#region src/lib/injected-skills/artifact-review-skill.ts
|
|
3212
|
+
// src/lib/injected-skills/artifact-review-skill.ts
|
|
3229
3213
|
function buildArtifactReviewSkill(peersKey = "peers") {
|
|
3230
3214
|
const toolPrefix = `mcp__${peersKey}__artifact_`;
|
|
3231
3215
|
return {
|
|
@@ -3301,8 +3285,7 @@ To let the human act on the artifact (not just comment), emit declarative contro
|
|
|
3301
3285
|
};
|
|
3302
3286
|
}
|
|
3303
3287
|
buildArtifactReviewSkill();
|
|
3304
|
-
|
|
3305
|
-
//#region src/lib/injected-skills/write.ts
|
|
3288
|
+
// src/lib/injected-skills/write.ts
|
|
3306
3289
|
/**
|
|
3307
3290
|
* Writer for injected skills: materializes a `SKILL.md` into the per-launch
|
|
3308
3291
|
* `CLAUDE_CONFIG_DIR` mirror so the spawned Claude Code session discovers it as a
|
|
@@ -3370,8 +3353,7 @@ async function writeInjectedSkill(name, md) {
|
|
|
3370
3353
|
path: target
|
|
3371
3354
|
};
|
|
3372
3355
|
}
|
|
3373
|
-
|
|
3374
|
-
//#region src/lib/injected-skills/index.ts
|
|
3356
|
+
// src/lib/injected-skills/index.ts
|
|
3375
3357
|
/**
|
|
3376
3358
|
* Injected-skill registry: the floor-raising / controller skills the `claude`
|
|
3377
3359
|
* launcher materializes into the per-launch `CLAUDE_CONFIG_DIR` mirror so the
|
|
@@ -3438,8 +3420,7 @@ function injectedSkillsForLaunch(selection) {
|
|
|
3438
3420
|
if (!selection.workerSkillsActive) return [];
|
|
3439
3421
|
return allSkills.filter((skill) => selection.firstMateEnabled || !skill.name.startsWith("gh-first-mate"));
|
|
3440
3422
|
}
|
|
3441
|
-
|
|
3442
|
-
//#region src/lib/attribution-settings.ts
|
|
3423
|
+
// src/lib/attribution-settings.ts
|
|
3443
3424
|
/**
|
|
3444
3425
|
* Deterministic backstop for the injected "no attribution" style directive.
|
|
3445
3426
|
*
|
|
@@ -3502,7 +3483,6 @@ async function injectAttributionSuppressionIntoSettingsFile(settingsPath) {
|
|
|
3502
3483
|
await fs.rename(tmp, settingsPath);
|
|
3503
3484
|
return { written: true };
|
|
3504
3485
|
}
|
|
3505
|
-
//#endregion
|
|
3506
3486
|
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 };
|
|
3507
3487
|
|
|
3508
|
-
//# sourceMappingURL=attribution-settings-
|
|
3488
|
+
//# sourceMappingURL=attribution-settings-BLTnz2_A.js.map
|