github-router 0.3.381 → 0.3.383
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/ado-tools-Ddv910Zl.js +1 -0
- package/dist/{aic-ledger-6GKI28nY.js → aic-ledger-Bz87EuHl.js} +3 -3
- package/dist/{aic-ledger-6GKI28nY.js.map → aic-ledger-Bz87EuHl.js.map} +1 -1
- package/dist/{aic-statusline-settings-wLL1l_Z6.js → aic-statusline-settings-dkVZbpRL.js} +2 -2
- package/dist/{aic-statusline-settings-wLL1l_Z6.js.map → aic-statusline-settings-dkVZbpRL.js.map} +1 -1
- package/dist/{attribution-settings-BEwSkdhK.js → attribution-settings-BcPiSoZe.js} +27 -30
- package/dist/{attribution-settings-BEwSkdhK.js.map → attribution-settings-BcPiSoZe.js.map} +1 -1
- package/dist/{auth-5TKcQbbH.js → auth-D9eTY_W6.js} +3 -3
- package/dist/{auth-5TKcQbbH.js.map → auth-D9eTY_W6.js.map} +1 -1
- package/dist/bin.js +21 -4
- package/dist/bin.js.map +1 -1
- package/dist/bluebird-client-CLXs7q-X.js +1 -0
- package/dist/{bluebird-client-BasIdv5J.js → bluebird-client-bykMZyn1.js} +2 -2
- package/dist/{bluebird-client-BasIdv5J.js.map → bluebird-client-bykMZyn1.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-DM39fdel.js → check-usage-BBaD35u4.js} +4 -4
- package/dist/{check-usage-DM39fdel.js.map → check-usage-BBaD35u4.js.map} +1 -1
- package/dist/{claude-CkrhHkPQ.js → claude-DOKuv2zZ.js} +29 -29
- package/dist/{claude-CkrhHkPQ.js.map → claude-DOKuv2zZ.js.map} +1 -1
- package/dist/{claude-md-injection-DNMDcw1W.js → claude-md-injection-BadtN0-I.js} +17 -8
- package/dist/claude-md-injection-BadtN0-I.js.map +1 -0
- package/dist/{codex-50GzveCD.js → codex-Dw_eBfXW.js} +9 -9
- package/dist/{codex-50GzveCD.js.map → codex-Dw_eBfXW.js.map} +1 -1
- package/dist/{copilot-discount-DM98PuAF.js → copilot-discount-BSDefQRW.js} +2 -2
- package/dist/{copilot-discount-DM98PuAF.js.map → copilot-discount-BSDefQRW.js.map} +1 -1
- package/dist/{debug-Df0Kuzi3.js → debug-B8eRYH-c.js} +2 -2
- package/dist/{debug-Df0Kuzi3.js.map → debug-B8eRYH-c.js.map} +1 -1
- package/dist/engine-DPtLOUuj.js +1 -0
- package/dist/{exec-BC0MAnoA.js → exec-oCtz_dXO.js} +22 -5
- package/dist/exec-oCtz_dXO.js.map +1 -0
- package/dist/{gate-discovery-2ILpM2fi.js → gate-discovery-DE_KTX2p.js} +6 -6
- package/dist/{gate-discovery-2ILpM2fi.js.map → gate-discovery-DE_KTX2p.js.map} +1 -1
- package/dist/{get-copilot-usage-BZ6t2hFZ.js → get-copilot-usage-Dh9u7WeP.js} +2 -2
- package/dist/{get-copilot-usage-BZ6t2hFZ.js.map → get-copilot-usage-Dh9u7WeP.js.map} +1 -1
- package/dist/hooks.mjs +21 -4
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-DsK6VFs8.js → index-cmd-C4womtOS.js} +5 -5
- package/dist/{index-cmd-DsK6VFs8.js.map → index-cmd-C4womtOS.js.map} +1 -1
- package/dist/{internal-aic-status-CUZ7-trf.js → internal-aic-status-DSO2sR5u.js} +4 -4
- package/dist/{internal-aic-status-CUZ7-trf.js.map → internal-aic-status-DSO2sR5u.js.map} +1 -1
- package/dist/{internal-artifact-open-DRBg1PpV.js → internal-artifact-open-dlgqWieq.js} +2 -2
- package/dist/{internal-artifact-open-DRBg1PpV.js.map → internal-artifact-open-dlgqWieq.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-ZeS9u0A3.js → internal-fast-dispatch-guard-5nCNht5y.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-ZeS9u0A3.js.map → internal-fast-dispatch-guard-5nCNht5y.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-D6-Ees_6.js → internal-fast-dispatch-guard-DHm96Bj_.js} +1 -1
- package/dist/{internal-first-mate-guard-DsEEsLKJ.js → internal-first-mate-guard-Bb9Stjy-.js} +3 -3
- package/dist/{internal-first-mate-guard-DsEEsLKJ.js.map → internal-first-mate-guard-Bb9Stjy-.js.map} +1 -1
- package/dist/{internal-first-mate-guard-BijeVpi9.js → internal-first-mate-guard-D6HMd9Iz.js} +1 -1
- package/dist/{internal-max-dispatch-guard-4RLca1i5.js → internal-max-dispatch-guard-C8kq4WNV.js} +3 -3
- package/dist/{internal-max-dispatch-guard-4RLca1i5.js.map → internal-max-dispatch-guard-C8kq4WNV.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-DeEfWqfP.js → internal-max-dispatch-guard-CI17mrDJ.js} +1 -1
- package/dist/{internal-plan-review-bzqGNdtw.js → internal-plan-review-Bdga9wVP.js} +3 -3
- package/dist/{internal-plan-review-bzqGNdtw.js.map → internal-plan-review-Bdga9wVP.js.map} +1 -1
- package/dist/{internal-prompt-submit-ZBhH-SQ1.js → internal-prompt-submit-DKlHlcvK.js} +2 -2
- package/dist/{internal-prompt-submit-BZ2-CExM.js → internal-prompt-submit-Daswp8ro.js} +5 -5
- package/dist/{internal-prompt-submit-BZ2-CExM.js.map → internal-prompt-submit-Daswp8ro.js.map} +1 -1
- package/dist/{internal-rebrief-BIWbN7Sr.js → internal-rebrief-D8O1J-_J.js} +5 -5
- package/dist/{internal-rebrief-BIWbN7Sr.js.map → internal-rebrief-D8O1J-_J.js.map} +1 -1
- package/dist/{internal-session-bind-BL6hFRLO.js → internal-session-bind-0hQFrcWu.js} +2 -2
- package/dist/{internal-session-bind-BL6hFRLO.js.map → internal-session-bind-0hQFrcWu.js.map} +1 -1
- package/dist/{internal-stop-hook-cDF1MuJZ.js → internal-stop-hook-C3lLh-HY.js} +6 -6
- package/dist/{internal-stop-hook-cDF1MuJZ.js.map → internal-stop-hook-C3lLh-HY.js.map} +1 -1
- package/dist/{internal-stop-review-y8zjpK_3.js → internal-stop-review-Bnmzcqx5.js} +2 -2
- package/dist/{internal-stop-review-y8zjpK_3.js.map → internal-stop-review-Bnmzcqx5.js.map} +1 -1
- package/dist/{internal-worker-guard-DdyYBZR0.js → internal-worker-guard-LcPxDlbx.js} +2 -2
- package/dist/{internal-worker-guard-DdyYBZR0.js.map → internal-worker-guard-LcPxDlbx.js.map} +1 -1
- package/dist/{internal-workspace-header-BMKbO8yX.js → internal-workspace-header-BH53hBXO.js} +2 -2
- package/dist/{internal-workspace-header-BMKbO8yX.js.map → internal-workspace-header-BH53hBXO.js.map} +1 -1
- package/dist/{lifecycle-COZhARmE.js → lifecycle-BmoqtVj3.js} +2 -2
- package/dist/{lifecycle-COZhARmE.js.map → lifecycle-BmoqtVj3.js.map} +1 -1
- package/dist/lifecycle-CcNNfKbr.js +1 -0
- package/dist/lifecycle-CrImfxCd.js +1 -0
- package/dist/{lifecycle-BlC_kzNt.js → lifecycle-CwxOsp-U.js} +3 -3
- package/dist/{lifecycle-BlC_kzNt.js.map → lifecycle-CwxOsp-U.js.map} +1 -1
- package/dist/main.js +25 -25
- package/dist/{max-profile-contract-DbHwiLTx.js → max-profile-contract-CEn8hKb3.js} +60 -60
- package/dist/{max-profile-contract-DbHwiLTx.js.map → max-profile-contract-CEn8hKb3.js.map} +1 -1
- package/dist/{mcp-workspace-header-Bpa4BId8.js → mcp-workspace-header-lb7GV78v.js} +2 -2
- package/dist/{mcp-workspace-header-Bpa4BId8.js.map → mcp-workspace-header-lb7GV78v.js.map} +1 -1
- package/dist/{models-BDV-YLf2.js → models-BTCnhBCQ.js} +3 -3
- package/dist/{models-BDV-YLf2.js.map → models-BTCnhBCQ.js.map} +1 -1
- package/dist/{optional-DGAeyguL.js → optional-LUQJI6Vx.js} +216 -16
- package/dist/optional-LUQJI6Vx.js.map +1 -0
- package/dist/{orchestration-Bto5Nc1Y.js → orchestration-C_hyBL90.js} +3 -3
- package/dist/{orchestration-Bto5Nc1Y.js.map → orchestration-C_hyBL90.js.map} +1 -1
- package/dist/origin-9bOjyzvK.js +1 -0
- package/dist/{origin-BXtpcKP9.js → origin-B6GChVyp.js} +2 -2
- package/dist/{origin-BXtpcKP9.js.map → origin-B6GChVyp.js.map} +1 -1
- package/dist/{paths-DeFmYJhO.js → paths-CVXqt2tC.js} +3 -3
- package/dist/{paths-DeFmYJhO.js.map → paths-CVXqt2tC.js.map} +1 -1
- package/dist/paths-JIusmD6L.js +1 -0
- package/dist/{peer-mcp-personas-Dny0r5Am.js → peer-mcp-personas-Dgog_ZJ8.js} +54 -54
- package/dist/{peer-mcp-personas-Dny0r5Am.js.map → peer-mcp-personas-Dgog_ZJ8.js.map} +1 -1
- package/dist/{pi-DVud9eQn.js → pi-BZhnf1kx.js} +95 -35
- package/dist/pi-BZhnf1kx.js.map +1 -0
- package/dist/{pi-version-check-BeBB0Ny9.js → pi-version-check-BRt9XFLj.js} +4 -4
- package/dist/{pi-version-check-BeBB0Ny9.js.map → pi-version-check-BRt9XFLj.js.map} +1 -1
- package/dist/pi-version-check-SH1X9u4H.js +1 -0
- package/dist/{plan-review-hook-D_yyjOgO.js → plan-review-hook-Dx3suYmK.js} +4 -4
- package/dist/{plan-review-hook-D_yyjOgO.js.map → plan-review-hook-Dx3suYmK.js.map} +1 -1
- package/dist/{provision-BWtuDq_v.js → provision-A1YSravb.js} +6 -6
- package/dist/{provision-BWtuDq_v.js.map → provision-A1YSravb.js.map} +1 -1
- package/dist/{rerank-cross-encoder-BhjImuwG.js → rerank-cross-encoder-uqRu-LOe.js} +2 -2
- package/dist/{rerank-cross-encoder-BhjImuwG.js.map → rerank-cross-encoder-uqRu-LOe.js.map} +1 -1
- package/dist/{self-invocation-Dnq4iVD6.js → self-invocation-CayD3y72.js} +2 -2
- package/dist/{self-invocation-Dnq4iVD6.js.map → self-invocation-CayD3y72.js.map} +1 -1
- package/dist/{serve-B8Igr9Q0.js → serve-Cv3S3PFR.js} +17 -17
- package/dist/{serve-B8Igr9Q0.js.map → serve-Cv3S3PFR.js.map} +1 -1
- package/dist/{server-setup-byIhjgOb.js → server-setup--CYeBD-Z.js} +14 -14
- package/dist/{server-setup-byIhjgOb.js.map → server-setup--CYeBD-Z.js.map} +1 -1
- package/dist/{service-backend-BdhWVRSz.js → service-backend-EgwiO_K-.js} +6 -6
- package/dist/{service-backend-BdhWVRSz.js.map → service-backend-EgwiO_K-.js.map} +1 -1
- package/dist/{start-7CiQIl0r.js → start-CA0JsO56.js} +5 -5
- package/dist/{start-7CiQIl0r.js.map → start-CA0JsO56.js.map} +1 -1
- package/dist/{static-context-pack-BKFelEbM.js → static-context-pack-BIru_SKh.js} +142 -142
- package/dist/{static-context-pack-BKFelEbM.js.map → static-context-pack-BIru_SKh.js.map} +1 -1
- package/dist/{stop-gate-hook-DBOj0TqL.js → stop-gate-hook-Ba_RvZAj.js} +4 -4
- package/dist/{stop-gate-hook-DBOj0TqL.js.map → stop-gate-hook-Ba_RvZAj.js.map} +1 -1
- package/dist/{stop-gate-policy-Bp2wGh_W.js → stop-gate-policy-gW0a0hds.js} +3 -3
- package/dist/{stop-gate-policy-Bp2wGh_W.js.map → stop-gate-policy-gW0a0hds.js.map} +1 -1
- package/dist/{token-Ygd7D32L.js → token-BCzbNu8O.js} +3 -3
- package/dist/{token-Ygd7D32L.js.map → token-BCzbNu8O.js.map} +1 -1
- package/dist/{token-CKPOBdO0.js → token-CxKcs3I_.js} +2 -2
- package/dist/{token-CKPOBdO0.js.map → token-CxKcs3I_.js.map} +1 -1
- package/dist/{update-T1L7yFon.js → update-CM1yUCJR.js} +4 -4
- package/dist/{update-T1L7yFon.js.map → update-CM1yUCJR.js.map} +1 -1
- package/dist/update-Cpg-tbJG.js +1 -0
- package/dist/{update-fEgWTrIx.js → update-ZqCRVU0a.js} +4 -4
- package/dist/{update-fEgWTrIx.js.map → update-ZqCRVU0a.js.map} +1 -1
- package/dist/{worker-dispatch-DBWKTMda.js → worker-dispatch-DHZAfPO2.js} +2 -2
- package/dist/{worker-dispatch-DBWKTMda.js.map → worker-dispatch-DHZAfPO2.js.map} +1 -1
- package/dist/{workiq-D5b7xlbr.js → workiq-CRBVCUA4.js} +2 -2
- package/dist/{workiq-D5b7xlbr.js.map → workiq-CRBVCUA4.js.map} +1 -1
- package/dist/{workiq-tools-DdiQ2DOW.js → workiq-tools-BsoHfdYi.js} +1 -1
- package/package.json +1 -1
- package/dist/ado-tools-CsfbnY8x.js +0 -1
- package/dist/bluebird-client-BvoMTmEv.js +0 -1
- package/dist/claude-md-injection-DNMDcw1W.js.map +0 -1
- package/dist/engine-B6la_uIW.js +0 -1
- package/dist/exec-BC0MAnoA.js.map +0 -1
- package/dist/lifecycle-BOjgq9_l.js +0 -1
- package/dist/lifecycle-NQvr4flt.js +0 -1
- package/dist/optional-DGAeyguL.js.map +0 -1
- package/dist/origin-DbFUCiGp.js +0 -1
- package/dist/paths-CquOjytP.js +0 -1
- package/dist/pi-DVud9eQn.js.map +0 -1
- package/dist/pi-version-check-D5RvdLsG.js +0 -1
- package/dist/update-CB21YRKz.js +0 -1
package/README.md
CHANGED
|
@@ -196,6 +196,12 @@ declared in `package.json#peerDependencies` — it never crosses a major. The tw
|
|
|
196
196
|
switches are independent: `GH_ROUTER_NO_MANAGED_INSTALL=1` stops the self-updater but
|
|
197
197
|
still installs the optional payloads.
|
|
198
198
|
|
|
199
|
+
The range is resolved with `npm view <pkg>@<range>`, so the argument reaches npm as a
|
|
200
|
+
`^`-bearing spec. On Windows that argument travels through a quoted `cmd.exe`
|
|
201
|
+
envelope that must not caret-escape it (`docs/pi-launch.md`), and
|
|
202
|
+
`<APP_DIR>/optional/install-state.json` carries a schema version so a failed install's
|
|
203
|
+
backoff ladder cannot outlive a release that fixes the failure.
|
|
204
|
+
|
|
199
205
|
---
|
|
200
206
|
|
|
201
207
|
## Use with any OpenAI-compatible tool
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { xt as disposeAdoClients } from "./peer-mcp-personas-Dgog_ZJ8.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as PATHS } from "./paths-
|
|
2
|
-
import { f as resolveModel } from "./token-
|
|
1
|
+
import { t as PATHS } from "./paths-CVXqt2tC.js";
|
|
2
|
+
import { f as resolveModel } from "./token-CxKcs3I_.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs$1 from "node:fs/promises";
|
|
@@ -387,4 +387,4 @@ async function isPidAlive(pid) {
|
|
|
387
387
|
}
|
|
388
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 };
|
|
389
389
|
|
|
390
|
-
//# sourceMappingURL=aic-ledger-
|
|
390
|
+
//# sourceMappingURL=aic-ledger-Bz87EuHl.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aic-ledger-6GKI28nY.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,IA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AC,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-Bz87EuHl.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":";;;;;;;AA8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BAAqC;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-
|
|
1
|
+
import { t as buildSelfCommand } from "./self-invocation-CayD3y72.js";
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
// src/lib/aic-statusline-settings.ts
|
|
4
4
|
/**
|
|
@@ -137,4 +137,4 @@ async function writeBackupSidecar(settingsPath, previous) {
|
|
|
137
137
|
}
|
|
138
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 };
|
|
139
139
|
|
|
140
|
-
//# sourceMappingURL=aic-statusline-settings-
|
|
140
|
+
//# sourceMappingURL=aic-statusline-settings-dkVZbpRL.js.map
|
package/dist/{aic-statusline-settings-wLL1l_Z6.js.map → aic-statusline-settings-dkVZbpRL.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aic-statusline-settings-
|
|
1
|
+
{"version":3,"file":"aic-statusline-settings-dkVZbpRL.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 // Aud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oB,OAAO,GAAG;GAChC,MAAM,cAAc,QAAQ;GAK5B,MAAM,wBAAwB,cAAc;IAH1C,GAAG;IACH,YAAY;KAAE,MAAM;KAAW,SAAS;IAAc;GAEP,CAAC;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,15 +1,15 @@
|
|
|
1
|
-
import { p as writeRuntimeFileSecure, t as PATHS } from "./paths-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
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-BKFelEbM.js";
|
|
1
|
+
import { p as writeRuntimeFileSecure, t as PATHS } from "./paths-CVXqt2tC.js";
|
|
2
|
+
import { In as CONDENSED_OPERATING_SEQUENCE, Ln as DEFINITION_OF_GREATNESS, _r as LOCAL_CONSULT_REDACTION_LINE, a as buildAgentPrompt, cr as oneMContextDisabled, l as maxPersonasFor, lr as withOneMSuffix, mr as CHEAP_PROFILE_NATIVE_EFFORTS, n as MCP_GROUPS, pr as CHEAP_PROFILE_NATIVE_AGENT_NAMES, t as GROUP_META, u as personasFor } from "./peer-mcp-personas-Dgog_ZJ8.js";
|
|
3
|
+
import { E as MAX_COORDINATOR_PROMPT, O as maxNativeDescription, T as MAX_COORDINATOR_DESCRIPTION, a as MAX_PROFILE_NATIVE_AGENT_NAMES, i as MAX_PROFILE_MODELS, k as maxNativePrompt, o as MAX_PROFILE_NATIVE_EFFORTS, s as MAX_PROFILE_NATIVE_MODELS } from "./max-profile-contract-CEn8hKb3.js";
|
|
5
4
|
import { a as BALANCED_PROFILE_NATIVE_EFFORTS, i as BALANCED_PROFILE_NATIVE_AGENT_NAMES } from "./balanced-profile-contract-B6pSoWjm.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import "./
|
|
9
|
-
import {
|
|
10
|
-
import
|
|
11
|
-
import { a as
|
|
12
|
-
import {
|
|
5
|
+
import { E as LOCAL_PROFILE_NATIVE_MODELS, I as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, L as CHEAPEST_PROFILE_NATIVE_EFFORTS, T as LOCAL_PROFILE_NATIVE_AGENT_NAMES, _ as isBalancedFamily, b as isLocalFamily, v as isCheapestFamily } from "./static-context-pack-BIru_SKh.js";
|
|
6
|
+
import { d as renameWithRetry, n as GATHERING_SUBAGENT_CLAUSE, s as isUnderClaudeConfigMirrorRealpath } from "./claude-md-injection-BadtN0-I.js";
|
|
7
|
+
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";
|
|
8
|
+
import { A as MAX_BROWSE_LOW_ALIAS_ID, C as CHEAPEST_GENERAL_PURPOSE_ALIAS_ID, D as CHEAP_PLAN_ALIAS_ID, E as CHEAP_GENERAL_PURPOSE_ALIAS_ID, O as CHEAP_REVIEWER_ALIAS_ID, S as CHEAPEST_EXPLORE_ALIAS_ID, T as CHEAP_EXPLORE_ALIAS_ID, b as BALANCED_REVIEWER_ALIAS_ID, k as LUNA_SCOUT_ALIAS_ID, v as BALANCED_EXPLORE_ALIAS_ID, w as CHEAPEST_REVIEWER_ALIAS_ID, x as BROWSE_LOW_ALIAS_ID, y as BALANCED_GENERAL_PURPOSE_ALIAS_ID } from "./server-setup--CYeBD-Z.js";
|
|
9
|
+
import "./self-invocation-CayD3y72.js";
|
|
10
|
+
import { a as STRIPPED_AUTH_ROUTING_ENV_KEYS, n as buildCodexProviderConfigFlags } from "./provision-A1YSravb.js";
|
|
11
|
+
import { n as buildWorkspaceHeaderHelperCommand } from "./mcp-workspace-header-lb7GV78v.js";
|
|
12
|
+
import { a as dispatcherAgentName, c as dispatcherTools, n as activeDispatchModes, o as dispatcherDescription, s as dispatcherPrompt } from "./worker-dispatch-DHZAfPO2.js";
|
|
13
13
|
import consola from "consola";
|
|
14
14
|
import path from "node:path";
|
|
15
15
|
import { randomBytes } from "node:crypto";
|
|
@@ -433,16 +433,7 @@ function pinnedExploreDescription(explicit, is200K = false) {
|
|
|
433
433
|
}
|
|
434
434
|
function pinnedExplorePrompt(opts) {
|
|
435
435
|
const searchGuidance = pinnedSearchGuidance(opts.semanticAvailable, !opts.explicit, opts.bluebirdEnabled === true);
|
|
436
|
-
return `You are a codebase exploration specialist. Your mission is to map repository structure, discover implementation patterns, trace call chains, and locate the exact files, symbols, and declarations that are relevant to the request. This is read-only work. Do not modify files, do not propose diffs, and do not delegate to other agents. You cannot ask clarifying questions mid-run: ground every answer in repository evidence. If the request is ambiguous, explore the most probable interpretations and record the ambiguity in your report. Start broad, then converge. ${opts.explicit ? "Issue independent searches in parallel in one turn rather than one at a time, and " : ""}${searchGuidance} Confirm every claim at the source before you report it. Stop when further searching stops changing your answer. When you can name the exact files and lines a change would touch, you are done. Report what the repository contains, not what it ought to contain. Do not design a solution or recommend an approach. Return a self-contained result the lead can act on immediately without needing to re-run your discovery.
|
|
437
|
-
|
|
438
|
-
Return format:
|
|
439
|
-
Answer: a direct response to what was asked, in a few sentences.
|
|
440
|
-
Inventory: each relevant file and symbol as file:line, with a one-line description of its role.
|
|
441
|
-
Entry points: where control enters this area, as file:line.
|
|
442
|
-
Conventions in use: the patterns, idioms, error handling, and test style that any change here would be expected to follow, each with a file:line example.
|
|
443
|
-
Gaps and unknowns: what you could not confirm, and where you would look next.
|
|
444
|
-
|
|
445
|
-
` + (opts.is200K ? PROMPT_200K_NOTE : "") + readOnlyToolSteer(opts.semanticAvailable);
|
|
436
|
+
return `You are a codebase exploration specialist. Your mission is to map repository structure, discover implementation patterns, trace call chains, and locate the exact files, symbols, and declarations that are relevant to the request. This is read-only work. Do not modify files, do not propose diffs, and do not delegate to other agents. You cannot ask clarifying questions mid-run: ground every answer in repository evidence. If the request is ambiguous, explore the most probable interpretations and record the ambiguity in your report. Start broad, then converge. ${opts.explicit ? "Issue independent searches in parallel in one turn rather than one at a time, and " : ""}${searchGuidance} Confirm every claim at the source before you report it. Stop when further searching stops changing your answer. When you can name the exact files and lines a change would touch, you are done. ` + (opts.gatherSteer === true ? `${GATHERING_SUBAGENT_CLAUSE} ` : "") + "Report what the repository contains, not what it ought to contain. Do not design a solution or recommend an approach. Return a self-contained result the lead can act on immediately without needing to re-run your discovery.\n\nReturn format:\nAnswer: a direct response to what was asked, in a few sentences.\nInventory: each relevant file and symbol as file:line, with a one-line description of its role.\nEntry points: where control enters this area, as file:line.\nConventions in use: the patterns, idioms, error handling, and test style that any change here would be expected to follow, each with a file:line example.\nGaps and unknowns: what you could not confirm, and where you would look next.\n\n" + (opts.is200K ? PROMPT_200K_NOTE : "") + readOnlyToolSteer(opts.semanticAvailable);
|
|
446
437
|
}
|
|
447
438
|
const PLAN_DESC_HEAD = "Architecture and implementation planning specialist";
|
|
448
439
|
const PLAN_DESC_TAIL = " Returns a decision-complete, ordered implementation plan with runnable acceptance criteria. Never edits files.";
|
|
@@ -469,7 +460,7 @@ function pinnedGeneralPurposeDescription(explicit, isBalanced = false, is200K =
|
|
|
469
460
|
return (explicit ? isBalanced ? "Autonomous multi-step execution agent. Use proactively and FREELY for open-ended or mixed tasks combining investigation, tool workflows, and code changes where the approach emerges during work." + planClause + " " : "Autonomous multi-step execution agent. Use proactively for open-ended or mixed tasks combining investigation, tool workflows, and code changes where the approach emerges during work." + planClause + " " : "Autonomous multi-step execution agent for open-ended or mixed tasks combining investigation, tool workflows, and code changes where the approach emerges during work. ") + GENERAL_PURPOSE_DESC_TAIL + (is200K ? DESC_200K_NOTE : "");
|
|
470
461
|
}
|
|
471
462
|
function pinnedGeneralPurposePrompt(opts) {
|
|
472
|
-
return "You are an autonomous execution specialist for mixed, multi-step work. Your mission is to take an open-ended task from investigation through implementation to a verified end state within this turn. Keep going until the task is genuinely done. Do not stop at a diagnosis, a partial fix, or a plan when the request asked for a change. Ground discovery in repository truth. For low-risk ambiguities, choose the interpretation most consistent with the repository, proceed, and record it as an assumption in your report. For material intent gaps that would alter product behavior or security, surface concrete options and a recommendation to the lead. " + (opts?.planAgent === false ? "When the lead hands you a plan, follow its ordered steps and acceptance criteria; do not rediscover what the plan already settled — read the critical files it names, execute each step's done condition, and report any step whose premise proves wrong instead of silently replanning. " : "When a Plan handoff exists, follow its ordered steps and acceptance criteria; do not rediscover what the plan already settled — read the critical files it names, execute each step's done condition, and report any step whose premise proves wrong instead of silently replanning. ") + "Investigate before you act. Confirm your assumptions against the actual code rather than against the request's description of it. After every command, read the real output and let it decide the next step. When something fails, diagnose the specific cause before trying again. If repeated attempts fail for the same reason and no new information has emerged, stop retrying: re-examine the underlying assumption and take a different path. Escalate rather than expand. If the task turns out to require a change the lead did not sanction, complete the sanctioned part and report the rest as a recommendation. If the task collapses to pure discovery or a single settled edit, do that slice and report the remainder as a recommendation. Do not expand scope. Match the conventions, structure, and test style already present in the files you touch. The lead owns final integration. Verify before you report. Run the builds, linters, or test commands relevant to what you changed. Quote the command run, exit status, and concise decisive output verbatim; if output is long, summarize the middle and quote the pass/fail lines. Report your changes and test output directly to the caller. Post-integration review is owned by the lead. Return a self-contained result the lead can act on immediately.\n\nReturn format:\nOutcome: what is now true, and whether the task is complete.\nActions taken: what you did, in order.\nChanged files: each as file:line, with a one-line description of the change.\nVerification: the commands you ran, exit status, and decisive output.\nAssumptions: every interpretation you had to choose.\nRemaining items: anything deliberately not done, and why.\n\n" + (opts?.is200K ? PROMPT_200K_NOTE : "") + fileToolSteer("builds");
|
|
463
|
+
return "You are an autonomous execution specialist for mixed, multi-step work. Your mission is to take an open-ended task from investigation through implementation to a verified end state within this turn. Keep going until the task is genuinely done. Do not stop at a diagnosis, a partial fix, or a plan when the request asked for a change. Ground discovery in repository truth. For low-risk ambiguities, choose the interpretation most consistent with the repository, proceed, and record it as an assumption in your report. For material intent gaps that would alter product behavior or security, surface concrete options and a recommendation to the lead. " + (opts?.planAgent === false ? "When the lead hands you a plan, follow its ordered steps and acceptance criteria; do not rediscover what the plan already settled — read the critical files it names, execute each step's done condition, and report any step whose premise proves wrong instead of silently replanning. " : "When a Plan handoff exists, follow its ordered steps and acceptance criteria; do not rediscover what the plan already settled — read the critical files it names, execute each step's done condition, and report any step whose premise proves wrong instead of silently replanning. ") + "Investigate before you act. Confirm your assumptions against the actual code rather than against the request's description of it. After every command, read the real output and let it decide the next step. When something fails, diagnose the specific cause before trying again. If repeated attempts fail for the same reason and no new information has emerged, stop retrying: re-examine the underlying assumption and take a different path. Escalate rather than expand. If the task turns out to require a change the lead did not sanction, complete the sanctioned part and report the rest as a recommendation. If the task collapses to pure discovery or a single settled edit, do that slice and report the remainder as a recommendation. Do not expand scope. Match the conventions, structure, and test style already present in the files you touch. The lead owns final integration. Verify before you report. Run the builds, linters, or test commands relevant to what you changed. Quote the command run, exit status, and concise decisive output verbatim; if output is long, summarize the middle and quote the pass/fail lines. " + (opts?.gatherSteer === true ? `${GATHERING_SUBAGENT_CLAUSE} ` : "") + "Report your changes and test output directly to the caller. Post-integration review is owned by the lead. Return a self-contained result the lead can act on immediately.\n\nReturn format:\nOutcome: what is now true, and whether the task is complete.\nActions taken: what you did, in order.\nChanged files: each as file:line, with a one-line description of the change.\nVerification: the commands you ran, exit status, and decisive output.\nAssumptions: every interpretation you had to choose.\nRemaining items: anything deliberately not done, and why.\n\n" + (opts?.is200K ? PROMPT_200K_NOTE : "") + fileToolSteer("builds");
|
|
473
464
|
}
|
|
474
465
|
const REVIEWER_DESC_TAIL = "Runs builds/tests itself rather than assuming them. Returns SHIP / FIX / BLOCK with reproducible evidence. Never edits source.";
|
|
475
466
|
function pinnedReviewerDescription(explicit, isBalanced = false, is200K = false, advisorKind) {
|
|
@@ -514,7 +505,7 @@ const PROTEGE_APPENDICES = {
|
|
|
514
505
|
function pinnedReviewerPrompt(semanticAvailable = true, opts) {
|
|
515
506
|
const delegation = opts?.allowExploreDelegation === true ? "Do not modify source code. Scope first with search, then delegate: use code search (lexical, then semantic when available) and web search to narrow scope and rule out hypotheses before delegating — cheapest, always first. When search is insufficient, delegate targeted discovery to `Explore`: launch one or more `Explore` subagents in parallel with scoped evidence questions (call chains, config patterns, test conventions, boundary conditions) and let them return file:line conclusions; do not sweep the repository yourself. You may invoke only `Explore`; do not invoke any other subagent. You may run build, test, and read-only inspection commands; do not run commands that alter tracked source files or touch remote infrastructure (transient build cache or test runner side effects are expected). " : "Do not modify source code and do not delegate to other agents. You may run build, test, and read-only inspection commands; do not run commands that alter tracked source files or touch remote infrastructure (transient build cache or test runner side effects are expected). ";
|
|
516
507
|
const protege = opts?.advisorKind ? PROTEGE_APPENDICES[opts.advisorKind] : "";
|
|
517
|
-
return "You are an adversarial code reviewer. Your job is not to confirm that the change works. Your job is to find the conditions under which it does not. Think carefully about the plausible failure modes of this change before you start running commands, so that what you run is chosen to expose them. Read before you judge. Inspect the changed files and relevant surrounding context, callers of affected call sites, and tests that claim to cover the change, sized to the identified risks of the change. Then verify by execution. Run the builds, linters, or test suites relevant to what changed, and any command that would surface the specific failure you suspect. Verification means output you observed. Never state that something passes, compiles, or is covered unless you ran it and read the result; where you could not run something, say so explicitly rather than inferring the outcome. Probe deliberately: boundary and empty inputs, error and early-return paths, concurrency and ordering, resource acquisition and cleanup on the failure path, partial failure and retry, backward compatibility of any changed interface, handling of untrusted input, and whether the new tests would actually fail if the change were reverted. Judge against the bar the repository already holds itself to, not an abstract ideal. Do not soften a real finding, and do not manufacture findings to appear thorough. If the change is correct and verified, say so. " + delegation + protege + "Return a self-contained result the lead can act on immediately.\n\nReturn format. Line one must be exactly one of:\nVERDICT: SHIP\nVERDICT: FIX\nVERDICT: BLOCK\n\nSHIP means you found no blocking defect and your verification ran clean. FIX means the approach is sound but specific defects must be corrected. BLOCK means the approach itself is wrong, or verification could not be run at all.\n\nThen, using the repository's severity taxonomy:\nCritical: blocking defects (correctness, security, data loss). Each with file:line, the concrete scenario in which it fails, and how you confirmed it.\nImportant: non-blocking issues that should be fixed before shipping. Each with file:line and impact.\nSuggestion: non-blocking improvements or stylistic suggestions.\nEvidence: the commands you ran, exit status, and decisive output.\nUnverified surface: what you could not exercise, and why.\n\n" + (opts?.is200K ? PROMPT_200K_NOTE : "") + reviewerToolSteer(semanticAvailable);
|
|
508
|
+
return "You are an adversarial code reviewer. Your job is not to confirm that the change works. Your job is to find the conditions under which it does not. Think carefully about the plausible failure modes of this change before you start running commands, so that what you run is chosen to expose them. Read before you judge. Inspect the changed files and relevant surrounding context, callers of affected call sites, and tests that claim to cover the change, sized to the identified risks of the change. Then verify by execution. Run the builds, linters, or test suites relevant to what changed, and any command that would surface the specific failure you suspect. Verification means output you observed. Never state that something passes, compiles, or is covered unless you ran it and read the result; where you could not run something, say so explicitly rather than inferring the outcome. Probe deliberately: boundary and empty inputs, error and early-return paths, concurrency and ordering, resource acquisition and cleanup on the failure path, partial failure and retry, backward compatibility of any changed interface, handling of untrusted input, and whether the new tests would actually fail if the change were reverted. Judge against the bar the repository already holds itself to, not an abstract ideal. Do not soften a real finding, and do not manufacture findings to appear thorough. If the change is correct and verified, say so. " + delegation + protege + (opts?.gatherSteer === true ? `${GATHERING_SUBAGENT_CLAUSE} ` : "") + "Return a self-contained result the lead can act on immediately.\n\nReturn format. Line one must be exactly one of:\nVERDICT: SHIP\nVERDICT: FIX\nVERDICT: BLOCK\n\nSHIP means you found no blocking defect and your verification ran clean. FIX means the approach is sound but specific defects must be corrected. BLOCK means the approach itself is wrong, or verification could not be run at all.\n\nThen, using the repository's severity taxonomy:\nCritical: blocking defects (correctness, security, data loss). Each with file:line, the concrete scenario in which it fails, and how you confirmed it.\nImportant: non-blocking issues that should be fixed before shipping. Each with file:line and impact.\nSuggestion: non-blocking improvements or stylistic suggestions.\nEvidence: the commands you ran, exit status, and decisive output.\nUnverified surface: what you could not exercise, and why.\n\n" + (opts?.is200K ? PROMPT_200K_NOTE : "") + reviewerToolSteer(semanticAvailable);
|
|
518
509
|
}
|
|
519
510
|
/** Build the literal `-m fast` native roster. This is intentionally separate
|
|
520
511
|
* from the standard definitions: the names overlap, but their role bodies,
|
|
@@ -739,7 +730,8 @@ function buildCheapestProfileAgentDefinitions(opts) {
|
|
|
739
730
|
explicit: false,
|
|
740
731
|
semanticAvailable,
|
|
741
732
|
is200K: true,
|
|
742
|
-
bluebirdEnabled: opts.bluebirdEnabled
|
|
733
|
+
bluebirdEnabled: opts.bluebirdEnabled,
|
|
734
|
+
gatherSteer: true
|
|
743
735
|
}),
|
|
744
736
|
tools: readSearchTools,
|
|
745
737
|
model: exploreModel,
|
|
@@ -750,7 +742,8 @@ function buildCheapestProfileAgentDefinitions(opts) {
|
|
|
750
742
|
description: pinnedGeneralPurposeDescription(false, false, true, false),
|
|
751
743
|
prompt: pinnedGeneralPurposePrompt({
|
|
752
744
|
is200K: true,
|
|
753
|
-
planAgent: false
|
|
745
|
+
planAgent: false,
|
|
746
|
+
gatherSteer: true
|
|
754
747
|
}),
|
|
755
748
|
model: generalModel,
|
|
756
749
|
effort: effort("General-Purpose"),
|
|
@@ -760,7 +753,8 @@ function buildCheapestProfileAgentDefinitions(opts) {
|
|
|
760
753
|
description: pinnedReviewerDescription(false, false, true, advisorKind),
|
|
761
754
|
prompt: pinnedReviewerPrompt(semanticAvailable, {
|
|
762
755
|
is200K: true,
|
|
763
|
-
advisorKind
|
|
756
|
+
advisorKind,
|
|
757
|
+
gatherSteer: true
|
|
764
758
|
}),
|
|
765
759
|
model: reviewerModel,
|
|
766
760
|
effort: effort("reviewer"),
|
|
@@ -834,7 +828,8 @@ function buildLocalProfileAgentDefinitions(opts) {
|
|
|
834
828
|
explicit: false,
|
|
835
829
|
semanticAvailable,
|
|
836
830
|
is200K: true,
|
|
837
|
-
bluebirdEnabled: opts.bluebirdEnabled
|
|
831
|
+
bluebirdEnabled: opts.bluebirdEnabled,
|
|
832
|
+
gatherSteer: true
|
|
838
833
|
}),
|
|
839
834
|
tools: readSearchTools,
|
|
840
835
|
model: exploreModel,
|
|
@@ -845,7 +840,8 @@ function buildLocalProfileAgentDefinitions(opts) {
|
|
|
845
840
|
description: pinnedGeneralPurposeDescription(false, false, true, false),
|
|
846
841
|
prompt: pinnedGeneralPurposePrompt({
|
|
847
842
|
is200K: true,
|
|
848
|
-
planAgent: false
|
|
843
|
+
planAgent: false,
|
|
844
|
+
gatherSteer: true
|
|
849
845
|
}),
|
|
850
846
|
model: generalModel,
|
|
851
847
|
effort: effort("General-Purpose"),
|
|
@@ -855,7 +851,8 @@ function buildLocalProfileAgentDefinitions(opts) {
|
|
|
855
851
|
description: pinnedReviewerDescription(false, false, true, protegeAdvisor ? "copilot-served" : void 0),
|
|
856
852
|
prompt: pinnedReviewerPrompt(semanticAvailable, {
|
|
857
853
|
is200K: true,
|
|
858
|
-
advisorKind: protegeAdvisor ? "copilot-served" : void 0
|
|
854
|
+
advisorKind: protegeAdvisor ? "copilot-served" : void 0,
|
|
855
|
+
gatherSteer: true
|
|
859
856
|
}),
|
|
860
857
|
model: reviewerModel,
|
|
861
858
|
effort: effort("reviewer"),
|
|
@@ -3485,4 +3482,4 @@ async function injectAttributionSuppressionIntoSettingsFile(settingsPath) {
|
|
|
3485
3482
|
}
|
|
3486
3483
|
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 };
|
|
3487
3484
|
|
|
3488
|
-
//# sourceMappingURL=attribution-settings-
|
|
3485
|
+
//# sourceMappingURL=attribution-settings-BcPiSoZe.js.map
|