github-router 0.3.379 → 0.3.381
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 +62 -0
- package/dist/ado-tools-CsfbnY8x.js +1 -0
- package/dist/{aic-ledger-CeSXqTEE.js → aic-ledger-6GKI28nY.js} +3 -3
- package/dist/{aic-ledger-CeSXqTEE.js.map → aic-ledger-6GKI28nY.js.map} +1 -1
- package/dist/{aic-statusline-settings-BKveu679.js → aic-statusline-settings-wLL1l_Z6.js} +2 -2
- package/dist/{aic-statusline-settings-BKveu679.js.map → aic-statusline-settings-wLL1l_Z6.js.map} +1 -1
- package/dist/atomic-file-Dif1kLKM.js +198 -0
- package/dist/atomic-file-Dif1kLKM.js.map +1 -0
- package/dist/{attribution-settings-BWYL2b8N.js → attribution-settings-BEwSkdhK.js} +10 -10
- package/dist/{attribution-settings-BWYL2b8N.js.map → attribution-settings-BEwSkdhK.js.map} +1 -1
- package/dist/{auth-BZHpTtfF.js → auth-5TKcQbbH.js} +3 -3
- package/dist/{auth-BZHpTtfF.js.map → auth-5TKcQbbH.js.map} +1 -1
- package/dist/bin.js +1479 -0
- package/dist/bin.js.map +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-BlIWDuV2.js → check-usage-DM39fdel.js} +4 -4
- package/dist/{check-usage-BlIWDuV2.js.map → check-usage-DM39fdel.js.map} +1 -1
- package/dist/{claude-CSuIdaLV.js → claude-CkrhHkPQ.js} +26 -25
- package/dist/{claude-CSuIdaLV.js.map → claude-CkrhHkPQ.js.map} +1 -1
- package/dist/{claude-md-injection-Biq_Xhve.js → claude-md-injection-DNMDcw1W.js} +15 -24
- package/dist/claude-md-injection-DNMDcw1W.js.map +1 -0
- package/dist/{codex-BG0pfud9.js → codex-50GzveCD.js} +8 -7
- package/dist/{codex-BG0pfud9.js.map → codex-50GzveCD.js.map} +1 -1
- package/dist/{copilot-discount-UXC6NQbN.js → copilot-discount-DM98PuAF.js} +2 -2
- package/dist/{copilot-discount-UXC6NQbN.js.map → copilot-discount-DM98PuAF.js.map} +1 -1
- package/dist/{debug-1HUHCWFl.js → debug-Df0Kuzi3.js} +2 -2
- package/dist/{debug-1HUHCWFl.js.map → debug-Df0Kuzi3.js.map} +1 -1
- package/dist/diagnostics-cXjCT_JQ.js +12 -0
- package/dist/diagnostics-cXjCT_JQ.js.map +1 -0
- package/dist/engine-B6la_uIW.js +1 -0
- package/dist/{gate-discovery-DjH9YXoN.js → gate-discovery-2ILpM2fi.js} +5 -5
- package/dist/{gate-discovery-DjH9YXoN.js.map → gate-discovery-2ILpM2fi.js.map} +1 -1
- package/dist/{get-copilot-usage-CKg42gSH.js → get-copilot-usage-BZ6t2hFZ.js} +2 -2
- package/dist/{get-copilot-usage-CKg42gSH.js.map → get-copilot-usage-BZ6t2hFZ.js.map} +1 -1
- package/dist/hooks.mjs +13 -0
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-sKwchRJz.js → index-cmd-DsK6VFs8.js} +4 -4
- package/dist/{index-cmd-sKwchRJz.js.map → index-cmd-DsK6VFs8.js.map} +1 -1
- package/dist/{internal-aic-status-B_hEeM37.js → internal-aic-status-CUZ7-trf.js} +3 -3
- package/dist/{internal-aic-status-B_hEeM37.js.map → internal-aic-status-CUZ7-trf.js.map} +1 -1
- package/dist/{internal-artifact-open-DbHjipxU.js → internal-artifact-open-DRBg1PpV.js} +2 -2
- package/dist/{internal-artifact-open-DbHjipxU.js.map → internal-artifact-open-DRBg1PpV.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-DMzqs-r8.js → internal-fast-dispatch-guard-D6-Ees_6.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js → internal-fast-dispatch-guard-ZeS9u0A3.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js.map → internal-fast-dispatch-guard-ZeS9u0A3.js.map} +1 -1
- package/dist/{internal-first-mate-guard-BxPDUsV3.js → internal-first-mate-guard-BijeVpi9.js} +1 -1
- package/dist/{internal-first-mate-guard-4Yro9xNM.js → internal-first-mate-guard-DsEEsLKJ.js} +3 -3
- package/dist/{internal-first-mate-guard-4Yro9xNM.js.map → internal-first-mate-guard-DsEEsLKJ.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-0teaxIc1.js → internal-max-dispatch-guard-4RLca1i5.js} +2 -2
- package/dist/{internal-max-dispatch-guard-0teaxIc1.js.map → internal-max-dispatch-guard-4RLca1i5.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-5LSaHN_y.js → internal-max-dispatch-guard-DeEfWqfP.js} +1 -1
- package/dist/{internal-plan-review-BfHLeszV.js → internal-plan-review-bzqGNdtw.js} +3 -3
- package/dist/{internal-plan-review-BfHLeszV.js.map → internal-plan-review-bzqGNdtw.js.map} +1 -1
- package/dist/{internal-prompt-submit-BixNLmM3.js → internal-prompt-submit-BZ2-CExM.js} +4 -4
- package/dist/{internal-prompt-submit-BixNLmM3.js.map → internal-prompt-submit-BZ2-CExM.js.map} +1 -1
- package/dist/{internal-prompt-submit-Ou8xtRXj.js → internal-prompt-submit-ZBhH-SQ1.js} +2 -2
- package/dist/{internal-rebrief-BBGM0PMv.js → internal-rebrief-BIWbN7Sr.js} +4 -4
- package/dist/{internal-rebrief-BBGM0PMv.js.map → internal-rebrief-BIWbN7Sr.js.map} +1 -1
- package/dist/{internal-session-bind-pN1V11Mn.js → internal-session-bind-BL6hFRLO.js} +2 -2
- package/dist/{internal-session-bind-pN1V11Mn.js.map → internal-session-bind-BL6hFRLO.js.map} +1 -1
- package/dist/{internal-stop-hook-DO9Iiaes.js → internal-stop-hook-cDF1MuJZ.js} +5 -5
- package/dist/{internal-stop-hook-DO9Iiaes.js.map → internal-stop-hook-cDF1MuJZ.js.map} +1 -1
- package/dist/{internal-stop-review-BWp-4XWW.js → internal-stop-review-y8zjpK_3.js} +2 -2
- package/dist/{internal-stop-review-BWp-4XWW.js.map → internal-stop-review-y8zjpK_3.js.map} +1 -1
- package/dist/{internal-worker-guard-C9OZPgzu.js → internal-worker-guard-DdyYBZR0.js} +2 -2
- package/dist/{internal-worker-guard-C9OZPgzu.js.map → internal-worker-guard-DdyYBZR0.js.map} +1 -1
- package/dist/{internal-workspace-header-B4TXFBLU.js → internal-workspace-header-BMKbO8yX.js} +2 -2
- package/dist/{internal-workspace-header-B4TXFBLU.js.map → internal-workspace-header-BMKbO8yX.js.map} +1 -1
- package/dist/lib/tree-sitter-pool/worker.js +268 -21
- package/dist/lifecycle-BOjgq9_l.js +1 -0
- package/dist/{lifecycle-vjHAFCaY.js → lifecycle-BlC_kzNt.js} +2 -2
- package/dist/{lifecycle-vjHAFCaY.js.map → lifecycle-BlC_kzNt.js.map} +1 -1
- package/dist/{lifecycle-Dh9y8OF1.js → lifecycle-COZhARmE.js} +2 -2
- package/dist/{lifecycle-Dh9y8OF1.js.map → lifecycle-COZhARmE.js.map} +1 -1
- package/dist/lifecycle-NQvr4flt.js +1 -0
- package/dist/main.js +39 -24
- package/dist/main.js.map +1 -1
- package/dist/{mcp-workspace-header-C5-dOWNa.js → mcp-workspace-header-Bpa4BId8.js} +2 -2
- package/dist/{mcp-workspace-header-C5-dOWNa.js.map → mcp-workspace-header-Bpa4BId8.js.map} +1 -1
- package/dist/{models-B6nH1sS6.js → models-BDV-YLf2.js} +3 -3
- package/dist/{models-B6nH1sS6.js.map → models-BDV-YLf2.js.map} +1 -1
- package/dist/npm-env-H60tX76c.js +130 -0
- package/dist/npm-env-H60tX76c.js.map +1 -0
- package/dist/optional-DGAeyguL.js +586 -0
- package/dist/optional-DGAeyguL.js.map +1 -0
- package/dist/{orchestration-B93jxrWI.js → orchestration-Bto5Nc1Y.js} +2 -2
- package/dist/{orchestration-B93jxrWI.js.map → orchestration-Bto5Nc1Y.js.map} +1 -1
- package/dist/origin-BXtpcKP9.js +382 -0
- package/dist/origin-BXtpcKP9.js.map +1 -0
- package/dist/origin-DbFUCiGp.js +1 -0
- package/dist/paths-CquOjytP.js +1 -0
- package/dist/paths-DK_b2ihK.js +176 -0
- package/dist/paths-DK_b2ihK.js.map +1 -0
- package/dist/{paths-CVEO8jEH.js → paths-DeFmYJhO.js} +16 -3
- package/dist/paths-DeFmYJhO.js.map +1 -0
- package/dist/{peer-mcp-personas-OWsSm6To.js → peer-mcp-personas-Dny0r5Am.js} +14 -14
- package/dist/{peer-mcp-personas-OWsSm6To.js.map → peer-mcp-personas-Dny0r5Am.js.map} +1 -1
- package/dist/{pi-DmeBxzIo.js → pi-DVud9eQn.js} +386 -243
- package/dist/pi-DVud9eQn.js.map +1 -0
- package/dist/{pi-foreign-artifacts-DZ4tioyO.js → pi-foreign-artifacts-CNt6wQ1P.js} +2 -2
- package/dist/{pi-foreign-artifacts-DZ4tioyO.js.map → pi-foreign-artifacts-CNt6wQ1P.js.map} +1 -1
- package/dist/pi-memory-bridge-BxmCIIbk.js +618 -0
- package/dist/pi-memory-bridge-BxmCIIbk.js.map +1 -0
- package/dist/pi-memory-bridge-D5A0h_Kf.js +1 -0
- package/dist/pi-version-check-BeBB0Ny9.js +551 -0
- package/dist/pi-version-check-BeBB0Ny9.js.map +1 -0
- package/dist/pi-version-check-D5RvdLsG.js +1 -0
- package/dist/{plan-review-hook-MhjK92wq.js → plan-review-hook-D_yyjOgO.js} +3 -3
- package/dist/{plan-review-hook-MhjK92wq.js.map → plan-review-hook-D_yyjOgO.js.map} +1 -1
- package/dist/{provision-DPL8aGe2.js → provision-BWtuDq_v.js} +30 -36
- package/dist/provision-BWtuDq_v.js.map +1 -0
- package/dist/rerank-cross-encoder-BhjImuwG.js +192 -0
- package/dist/rerank-cross-encoder-BhjImuwG.js.map +1 -0
- package/dist/{self-invocation-DMUnXVGT.js → self-invocation-Dnq4iVD6.js} +4 -31
- package/dist/{self-invocation-DMUnXVGT.js.map → self-invocation-Dnq4iVD6.js.map} +1 -1
- package/dist/{serve-zbQKfx1E.js → serve-B8Igr9Q0.js} +15 -14
- package/dist/{serve-zbQKfx1E.js.map → serve-B8Igr9Q0.js.map} +1 -1
- package/dist/{server-setup-ClZdV33Q.js → server-setup-byIhjgOb.js} +708 -640
- package/dist/server-setup-byIhjgOb.js.map +1 -0
- package/dist/{service-backend-Cdgz6WPx.js → service-backend-BdhWVRSz.js} +17 -62
- package/dist/service-backend-BdhWVRSz.js.map +1 -0
- package/dist/{start-mnedD5cH.js → start-7CiQIl0r.js} +5 -4
- package/dist/{start-mnedD5cH.js.map → start-7CiQIl0r.js.map} +1 -1
- package/dist/{static-context-pack-CtnBwHSd.js → static-context-pack-BKFelEbM.js} +3 -3
- package/dist/{static-context-pack-CtnBwHSd.js.map → static-context-pack-BKFelEbM.js.map} +1 -1
- package/dist/{stop-gate-hook-CBVLD8iB.js → stop-gate-hook-DBOj0TqL.js} +3 -3
- package/dist/{stop-gate-hook-CBVLD8iB.js.map → stop-gate-hook-DBOj0TqL.js.map} +1 -1
- package/dist/{stop-gate-policy-BehNiNix.js → stop-gate-policy-Bp2wGh_W.js} +2 -2
- package/dist/{stop-gate-policy-BehNiNix.js.map → stop-gate-policy-Bp2wGh_W.js.map} +1 -1
- package/dist/{token-CPzYxU4Y.js → token-CKPOBdO0.js} +23 -88
- package/dist/{token-CPzYxU4Y.js.map → token-CKPOBdO0.js.map} +1 -1
- package/dist/{token-DHEkiO4g.js → token-Ygd7D32L.js} +3 -3
- package/dist/{token-DHEkiO4g.js.map → token-Ygd7D32L.js.map} +1 -1
- package/dist/update-CB21YRKz.js +1 -0
- package/dist/update-T1L7yFon.js +1548 -0
- package/dist/update-T1L7yFon.js.map +1 -0
- package/dist/update-fEgWTrIx.js +214 -0
- package/dist/update-fEgWTrIx.js.map +1 -0
- package/dist/update-lock-BeS_WmC8.js +1 -0
- package/dist/update-lock-BmXx6QaR.js +171 -0
- package/dist/update-lock-BmXx6QaR.js.map +1 -0
- package/dist/volatile-root-DQNNvQ7Z.js +50 -0
- package/dist/volatile-root-DQNNvQ7Z.js.map +1 -0
- package/dist/{worker-dispatch-C7RtNOXv.js → worker-dispatch-DBWKTMda.js} +2 -2
- package/dist/{worker-dispatch-C7RtNOXv.js.map → worker-dispatch-DBWKTMda.js.map} +1 -1
- package/dist/{workiq-CQauEAMc.js → workiq-D5b7xlbr.js} +2 -2
- package/dist/{workiq-CQauEAMc.js.map → workiq-D5b7xlbr.js.map} +1 -1
- package/dist/{workiq-tools-DL6rC4bP.js → workiq-tools-DdiQ2DOW.js} +1 -1
- package/package.json +16 -4
- package/dist/ado-tools-CRkyU51J.js +0 -1
- package/dist/claude-md-injection-Biq_Xhve.js.map +0 -1
- package/dist/engine-V46un8Xl.js +0 -1
- package/dist/lifecycle-BENRuuX6.js +0 -1
- package/dist/lifecycle-Dli9vGI2.js +0 -1
- package/dist/paths-Be9_ujQ3.js +0 -1
- package/dist/paths-CVEO8jEH.js.map +0 -1
- package/dist/pi-DmeBxzIo.js.map +0 -1
- package/dist/pi-memory-bridge-Bp9AnYw9.js +0 -1
- package/dist/pi-memory-bridge-CICIdDVP.js +0 -413
- package/dist/pi-memory-bridge-CICIdDVP.js.map +0 -1
- package/dist/provision-DPL8aGe2.js.map +0 -1
- package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
- package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
- package/dist/server-setup-ClZdV33Q.js.map +0 -1
- package/dist/service-backend-Cdgz6WPx.js.map +0 -1
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import { i as ensurePaths, t as PATHS } from "./paths-CVEO8jEH.js";
|
|
1
|
+
import { i as ensurePaths, t as PATHS } from "./paths-DeFmYJhO.js";
|
|
3
2
|
import { t as state } from "./state-CCGDJ43X.js";
|
|
4
|
-
import {
|
|
3
|
+
import { i as writeFileAtomic } from "./atomic-file-Dif1kLKM.js";
|
|
4
|
+
import { C as copilotHeaders, S as copilotBaseUrl, c as cacheVSCodeVersion, f as resolveModel, i as tryRefreshAndRetry, l as filterBetaHeader, n as setupGitHubAgentToken, o as cacheCopilotVersion, p as sleep, r as setupGitHubToken, s as cacheModels, t as setupCopilotToken, u as isNullish, v as HTTPError, y as forwardError } from "./token-CKPOBdO0.js";
|
|
5
5
|
import { r as fetchWithTransientRetry } from "./upstream-retry-VNR-bCuT.js";
|
|
6
|
-
import { t as getCopilotUsage } from "./get-copilot-usage-
|
|
7
|
-
import { a as parseBoolEnv,
|
|
8
|
-
import {
|
|
6
|
+
import { t as getCopilotUsage } from "./get-copilot-usage-BZ6t2hFZ.js";
|
|
7
|
+
import { a as parseBoolEnv, i as killManagedTree, s as resolveExecutable } from "./exec-BC0MAnoA.js";
|
|
8
|
+
import { l as resolvePiRegistry } from "./pi-version-check-BeBB0Ny9.js";
|
|
9
9
|
import { c as FAST_PROFILE_MODELS, l as FAST_PROFILE_NATIVE_AGENT_NAMES, r as FAST_PROFILE_ADVISOR_MODEL } from "./fast-profile-contract-BLnKg0Ay.js";
|
|
10
|
-
import { $ as buildAnthropicErrorEvent, An as parseJsonOrDiagnose, B as FAST_ADVISOR_TOOL_INSTRUCTIONS, Cn as assembleResponsesPayload, Ct as ADO_DEFAULT_TOOLSETS, D as toolbeltEnabled, Dn as createChatCompletions, En as createResponses, Et as agentToolsEnabled, F as ADVISOR_TOOL_INSTRUCTIONS, Fn as normalizeKustoClusterUri, G as isAdvisorRequested, H as LOCAL_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, I as CHEAPEST_ADVISOR_TOOL_INSTRUCTIONS, J as resolveCuratedAdvisorModel, K as resolveAdvisorEffort, L as CHEAPEST_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, N as searchWeb, On as MAX_RESPONSE_BODY_BYTES, P as ADVISOR_INTERNAL_TOOL_NAME, Pn as normalizeCloudAgentEnvironment, Q as repairRejectedThinkingHistory, R as CHEAPLOCAL_ADVISOR_TOOL_INSTRUCTIONS, Rn as assertCopilotModelAllowed, St as provisionAdoTools, Tn as resolveMcpToolTimeoutMs, U as buildAdvisorStream, V as LOCAL_ADVISOR_TOOL_INSTRUCTIONS, W as injectAdvisorTool, X as rememberThinkingHistoryRepair, Y as formatThinkingRepairDecline, Yn as BUDGET_SMALL_FAST_SLUG, Z as repairKnownThinkingHistory, _n as LAUNCH_BOUND_TOKEN_PREFIX, _t as provisionWorkiqTools, at as EFFORT_ORDER, cn as shimDefaultsToXhigh, cr as classifyMessagesRoute, ct as clampEffort, dn as getTokenizerFromModel, dr as withOneMSuffix, dt as normalizeAnthropicUsageInPlace, er as UPSTREAM_FETCH_TIMEOUT_MS, et as buildOpenAIErrorEvent, fr as withOneMSuffixForLead, ft as handleMcpDelete, gn as createMessages, hn as countTokens, hr as CHEAP_PROFILE_NATIVE_AGENT_NAMES, i as assertMcpToolSurfaceConsistent, it as relayAnthropicStream, jn as normalizeOpenAIUsage, kn as readResponseBodyCapped, ln as getTextTokenCount, lr as catalogAdvertises1M, lt as anthropicUsageNormalizeDisabled, mn as localSessionId, mr as CHEAP_PROFILE_MODELS, nr as generateRandomPort, nt as logStreamError, or as upstreamAllowH2, ot as UNKNOWN_EFFORT_ANCHOR, pn as localBaseUrl, pr as CHEAP_PROFILE_ADVISOR_CLIENT_MODEL, pt as handleMcpPost, q as resolveAdvisorModel, qn as toolbeltPathOverride, rr as isBudgetClaudeLead, rt as readIteratorWithTimeout, sr as upstreamMaxConnections, st as bucketEffort, tr as UPSTREAM_INACTIVITY_TIMEOUT_MS, tt as isControllerClosedError, un as getTokenCount, ur as oneMContextDisabled, ut as createAnthropicUsageRewriteTransform, vn as findLaunchBySecret, vr as CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS, wn as warnOnTokenPriceDrift, wt as normalizeAdoToolsets, xn as rememberLaunchSessionId, z as CHEAPLOCAL_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, zn as effectiveLocalProfile } from "./peer-mcp-personas-
|
|
11
|
-
import { C as localContractFor, I as CHEAPEST_PROFILE_MODELS, L as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, O as LOCAL_PROFILE_TIER_MODELS, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, g as displayModelName, j as CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL, p as cheapestContractFor, v as isCheapestFamily, x as isPinnedLaunchProfile } from "./static-context-pack-
|
|
10
|
+
import { $ as buildAnthropicErrorEvent, An as parseJsonOrDiagnose, B as FAST_ADVISOR_TOOL_INSTRUCTIONS, Cn as assembleResponsesPayload, Ct as ADO_DEFAULT_TOOLSETS, D as toolbeltEnabled, Dn as createChatCompletions, En as createResponses, Et as agentToolsEnabled, F as ADVISOR_TOOL_INSTRUCTIONS, Fn as normalizeKustoClusterUri, G as isAdvisorRequested, H as LOCAL_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, I as CHEAPEST_ADVISOR_TOOL_INSTRUCTIONS, J as resolveCuratedAdvisorModel, K as resolveAdvisorEffort, L as CHEAPEST_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, N as searchWeb, On as MAX_RESPONSE_BODY_BYTES, P as ADVISOR_INTERNAL_TOOL_NAME, Pn as normalizeCloudAgentEnvironment, Q as repairRejectedThinkingHistory, R as CHEAPLOCAL_ADVISOR_TOOL_INSTRUCTIONS, Rn as assertCopilotModelAllowed, St as provisionAdoTools, Tn as resolveMcpToolTimeoutMs, U as buildAdvisorStream, V as LOCAL_ADVISOR_TOOL_INSTRUCTIONS, W as injectAdvisorTool, X as rememberThinkingHistoryRepair, Y as formatThinkingRepairDecline, Yn as BUDGET_SMALL_FAST_SLUG, Z as repairKnownThinkingHistory, _n as LAUNCH_BOUND_TOKEN_PREFIX, _t as provisionWorkiqTools, at as EFFORT_ORDER, cn as shimDefaultsToXhigh, cr as classifyMessagesRoute, ct as clampEffort, dn as getTokenizerFromModel, dr as withOneMSuffix, dt as normalizeAnthropicUsageInPlace, er as UPSTREAM_FETCH_TIMEOUT_MS, et as buildOpenAIErrorEvent, fr as withOneMSuffixForLead, ft as handleMcpDelete, gn as createMessages, hn as countTokens, hr as CHEAP_PROFILE_NATIVE_AGENT_NAMES, i as assertMcpToolSurfaceConsistent, it as relayAnthropicStream, jn as normalizeOpenAIUsage, kn as readResponseBodyCapped, ln as getTextTokenCount, lr as catalogAdvertises1M, lt as anthropicUsageNormalizeDisabled, mn as localSessionId, mr as CHEAP_PROFILE_MODELS, nr as generateRandomPort, nt as logStreamError, or as upstreamAllowH2, ot as UNKNOWN_EFFORT_ANCHOR, pn as localBaseUrl, pr as CHEAP_PROFILE_ADVISOR_CLIENT_MODEL, pt as handleMcpPost, q as resolveAdvisorModel, qn as toolbeltPathOverride, rr as isBudgetClaudeLead, rt as readIteratorWithTimeout, sr as upstreamMaxConnections, st as bucketEffort, tr as UPSTREAM_INACTIVITY_TIMEOUT_MS, tt as isControllerClosedError, un as getTokenCount, ur as oneMContextDisabled, ut as createAnthropicUsageRewriteTransform, vn as findLaunchBySecret, vr as CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS, wn as warnOnTokenPriceDrift, wt as normalizeAdoToolsets, xn as rememberLaunchSessionId, z as CHEAPLOCAL_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, zn as effectiveLocalProfile } from "./peer-mcp-personas-Dny0r5Am.js";
|
|
11
|
+
import { C as localContractFor, I as CHEAPEST_PROFILE_MODELS, L as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, O as LOCAL_PROFILE_TIER_MODELS, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, g as displayModelName, j as CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL, p as cheapestContractFor, v as isCheapestFamily, x as isPinnedLaunchProfile } from "./static-context-pack-BKFelEbM.js";
|
|
12
12
|
import { i as BALANCED_PROFILE_NATIVE_AGENT_NAMES, r as BALANCED_PROFILE_MODELS } from "./balanced-profile-contract-B6pSoWjm.js";
|
|
13
13
|
import { A as normalizeTrailingOneMSuffix, a as MAX_PROFILE_NATIVE_AGENT_NAMES, d as maxAdvisorPinIsValid, h as maxOpusModel, i as MAX_PROFILE_MODELS, j as stripTrailingOneMSuffix, k as fastEndpointForModel, l as maxAdvisorEffortForModel, n as MAX_PROFILE_ALLOWED_LEAD_MODEL_IDS, t as MAX_PROFILE_ADVISOR_INSTRUCTIONS, u as maxAdvisorModelFromPin, y as validateMaxProfilePrerequisites } from "./max-profile-contract-DbHwiLTx.js";
|
|
14
14
|
import { f as getAzureRepoFromGit } from "./bluebird-client-BasIdv5J.js";
|
|
15
|
-
import {
|
|
15
|
+
import { I as provisionTreeSitterAssets } from "./service-backend-BdhWVRSz.js";
|
|
16
|
+
import { a as extractAndRecordPricedAic, g as nanoAiuToCredits, h as formatAic, i as extractAndRecordAic, l as recordAic, m as extractCopilotUsage, p as copilotUsageToWire, u as recordZeroCostRequest } from "./aic-ledger-6GKI28nY.js";
|
|
16
17
|
import consola from "consola";
|
|
17
18
|
import fs, { existsSync } from "node:fs";
|
|
18
19
|
import path from "node:path";
|
|
@@ -28,353 +29,6 @@ import { createBodyTooLargeError, limitRequestBody } from "srvx/body-limit";
|
|
|
28
29
|
import { getProxyForUrl } from "proxy-from-env";
|
|
29
30
|
import { Hono } from "hono";
|
|
30
31
|
import { cors } from "hono/cors";
|
|
31
|
-
// src/lib/claude-version-check.ts
|
|
32
|
-
const NPM_PACKAGE$1 = "@anthropic-ai/claude-code";
|
|
33
|
-
const THROTTLE_HOURS$2 = 1;
|
|
34
|
-
const NPM_VIEW_TIMEOUT_MS$2 = 5e3;
|
|
35
|
-
const CLAUDE_VERSION_TIMEOUT_MS = 3e3;
|
|
36
|
-
const NPM_INSTALL_TIMEOUT_MS$1 = 12e4;
|
|
37
|
-
/** Path to the throttle cache. Created on demand. */
|
|
38
|
-
function cacheFilePath$2() {
|
|
39
|
-
return path.join(os.homedir(), ".local", "share", "github-router", "last-update-check");
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Read the throttle cache. Returns null on missing/corrupt file —
|
|
43
|
-
* triggers a fresh check.
|
|
44
|
-
*/
|
|
45
|
-
async function readCache$2() {
|
|
46
|
-
try {
|
|
47
|
-
const raw = await fs$1.readFile(cacheFilePath$2(), "utf8");
|
|
48
|
-
const parsed = JSON.parse(raw);
|
|
49
|
-
if (typeof parsed.checkedAt !== "string" || parsed.installedVersion !== null && typeof parsed.installedVersion !== "string" || parsed.latestVersion !== null && typeof parsed.latestVersion !== "string") return null;
|
|
50
|
-
return parsed;
|
|
51
|
-
} catch {
|
|
52
|
-
return null;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
async function writeCache$2(cache) {
|
|
56
|
-
try {
|
|
57
|
-
await fs$1.mkdir(path.dirname(cacheFilePath$2()), { recursive: true });
|
|
58
|
-
await fs$1.writeFile(cacheFilePath$2(), JSON.stringify(cache), { mode: 384 });
|
|
59
|
-
} catch (err) {
|
|
60
|
-
consola.debug("Failed to write claude version-check cache:", err);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
/** Check if it's been more than THROTTLE_HOURS since the last check. */
|
|
64
|
-
function shouldCheckNow$2(cache) {
|
|
65
|
-
if (!cache) return true;
|
|
66
|
-
const lastCheck = new Date(cache.checkedAt).getTime();
|
|
67
|
-
if (Number.isNaN(lastCheck)) return true;
|
|
68
|
-
return (Date.now() - lastCheck) / 1e3 / 3600 >= THROTTLE_HOURS$2;
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Read the installed `claude` version. Returns null if claude is not
|
|
72
|
-
* on PATH or the version probe fails (e.g. older versions that don't
|
|
73
|
-
* support `--version` cleanly).
|
|
74
|
-
*
|
|
75
|
-
* Windows-safe: `claude` is a `.cmd` shim that `execFile` cannot launch
|
|
76
|
-
* directly. We resolve it to an absolute path (excluding the cwd, so a
|
|
77
|
-
* planted `claude.cmd` in an untrusted repo can't run) and invoke it
|
|
78
|
-
* through the shared exec helper.
|
|
79
|
-
*/
|
|
80
|
-
async function getInstalledVersion() {
|
|
81
|
-
const claudePath = resolveExecutable("claude");
|
|
82
|
-
if (!claudePath) return null;
|
|
83
|
-
try {
|
|
84
|
-
const { stdout, code } = await runCommandCapture([claudePath, "--version"], { timeoutMs: CLAUDE_VERSION_TIMEOUT_MS });
|
|
85
|
-
if (code !== 0) return null;
|
|
86
|
-
const match = stdout.match(/(\d+\.\d+\.\d+)/);
|
|
87
|
-
return match ? match[1] : null;
|
|
88
|
-
} catch {
|
|
89
|
-
return null;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Fetch the latest version of @anthropic-ai/claude-code from the npm
|
|
94
|
-
* registry. Returns null on network failure / npm unavailable.
|
|
95
|
-
*
|
|
96
|
-
* Windows-safe: `npm` is `npm.cmd`; resolved to an absolute path
|
|
97
|
-
* (excluding cwd) before invocation.
|
|
98
|
-
*/
|
|
99
|
-
async function getLatestVersion$1() {
|
|
100
|
-
const npmPath = resolveExecutable("npm");
|
|
101
|
-
if (!npmPath) return null;
|
|
102
|
-
try {
|
|
103
|
-
const { stdout, code } = await runCommandCapture([
|
|
104
|
-
npmPath,
|
|
105
|
-
"view",
|
|
106
|
-
NPM_PACKAGE$1,
|
|
107
|
-
"version",
|
|
108
|
-
"--silent"
|
|
109
|
-
], { timeoutMs: NPM_VIEW_TIMEOUT_MS$2 });
|
|
110
|
-
if (code !== 0) return null;
|
|
111
|
-
const v = stdout.trim();
|
|
112
|
-
return /^\d+\.\d+\.\d+/.test(v) ? v : null;
|
|
113
|
-
} catch {
|
|
114
|
-
return null;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* Compare two semver-shaped strings (only the leading X.Y.Z, no
|
|
119
|
-
* pre-release / metadata handling — sufficient for npm-published
|
|
120
|
-
* stable releases). Returns true if `latest` is strictly higher than
|
|
121
|
-
* `installed`.
|
|
122
|
-
*/
|
|
123
|
-
function isNewer(installed, latest) {
|
|
124
|
-
if (!installed || !latest) return false;
|
|
125
|
-
const a = installed.split(".").map((n) => parseInt(n, 10));
|
|
126
|
-
const b = latest.split(".").map((n) => parseInt(n, 10));
|
|
127
|
-
for (let i = 0; i < 3; i++) {
|
|
128
|
-
const av = a[i] ?? 0;
|
|
129
|
-
const bv = b[i] ?? 0;
|
|
130
|
-
if (av < bv) return true;
|
|
131
|
-
if (av > bv) return false;
|
|
132
|
-
}
|
|
133
|
-
return false;
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* Run a version check (subject to throttle). Side-effect: updates the
|
|
137
|
-
* throttle cache. Returns the comparison result.
|
|
138
|
-
*/
|
|
139
|
-
async function checkClaudeVersion(opts = {}) {
|
|
140
|
-
if (opts.noCheck) return {
|
|
141
|
-
installed: false,
|
|
142
|
-
installedVersion: null,
|
|
143
|
-
latestVersion: null,
|
|
144
|
-
needsUpdate: false,
|
|
145
|
-
skipped: true,
|
|
146
|
-
skipReason: "disabled"
|
|
147
|
-
};
|
|
148
|
-
const cache = await readCache$2();
|
|
149
|
-
if (!opts.force && !shouldCheckNow$2(cache)) return {
|
|
150
|
-
installed: cache?.installedVersion !== null,
|
|
151
|
-
installedVersion: cache?.installedVersion ?? null,
|
|
152
|
-
latestVersion: cache?.latestVersion ?? null,
|
|
153
|
-
needsUpdate: isNewer(cache?.installedVersion ?? null, cache?.latestVersion ?? null),
|
|
154
|
-
skipped: true,
|
|
155
|
-
skipReason: "throttled"
|
|
156
|
-
};
|
|
157
|
-
const installedVersion = await getInstalledVersion();
|
|
158
|
-
if (installedVersion === null) return {
|
|
159
|
-
installed: false,
|
|
160
|
-
installedVersion: null,
|
|
161
|
-
latestVersion: null,
|
|
162
|
-
needsUpdate: false,
|
|
163
|
-
skipped: true,
|
|
164
|
-
skipReason: "no-claude"
|
|
165
|
-
};
|
|
166
|
-
const latestVersion = await getLatestVersion$1();
|
|
167
|
-
await writeCache$2({
|
|
168
|
-
checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
169
|
-
installedVersion,
|
|
170
|
-
latestVersion
|
|
171
|
-
});
|
|
172
|
-
if (latestVersion === null) return {
|
|
173
|
-
installed: true,
|
|
174
|
-
installedVersion,
|
|
175
|
-
latestVersion: null,
|
|
176
|
-
needsUpdate: false,
|
|
177
|
-
skipped: true,
|
|
178
|
-
skipReason: "no-npm"
|
|
179
|
-
};
|
|
180
|
-
return {
|
|
181
|
-
installed: true,
|
|
182
|
-
installedVersion,
|
|
183
|
-
latestVersion,
|
|
184
|
-
needsUpdate: isNewer(installedVersion, latestVersion),
|
|
185
|
-
skipped: false
|
|
186
|
-
};
|
|
187
|
-
}
|
|
188
|
-
/**
|
|
189
|
-
* Heuristic: did `claude update` fail because the subcommand does not
|
|
190
|
-
* exist (a build predating `claude update`), as opposed to a transient
|
|
191
|
-
* update error? We only npm-fall-back on this specific signal — falling
|
|
192
|
-
* back on any failure would install a conflicting npm copy on
|
|
193
|
-
* native-installer machines.
|
|
194
|
-
*
|
|
195
|
-
* Matches the usage/Commander-style "unknown command" messages CLIs emit
|
|
196
|
-
* for an unrecognized subcommand. Deliberately narrow.
|
|
197
|
-
*/
|
|
198
|
-
function looksLikeUnknownUpdateCommand(output) {
|
|
199
|
-
return /unknown command|unknown subcommand|unrecognized (sub)?command|invalid command|command not found|is not a (known|valid) command/i.test(output);
|
|
200
|
-
}
|
|
201
|
-
async function updateClaude(latestVersion, deps = {}) {
|
|
202
|
-
const _resolve = deps.resolveExecutable ?? resolveExecutable;
|
|
203
|
-
const _capture = deps.runCommandCapture ?? runCommandCapture;
|
|
204
|
-
const _void = deps.runCommandVoid ?? runCommandVoid;
|
|
205
|
-
const _lock = deps.withInstallLock ?? withInstallLock;
|
|
206
|
-
const claudePath = _resolve("claude");
|
|
207
|
-
if (!claudePath) throw new Error("claude not found on PATH");
|
|
208
|
-
if (!await _lock("claude-update.lock", async () => {
|
|
209
|
-
consola.info(`Updating Claude Code to ${latestVersion} via \`claude update\`...`);
|
|
210
|
-
const { code, stdout, stderr } = await _capture([claudePath, "update"], { timeoutMs: NPM_INSTALL_TIMEOUT_MS$1 });
|
|
211
|
-
const combined = `${stdout}${stderr}`;
|
|
212
|
-
const trimmed = combined.trim();
|
|
213
|
-
if (trimmed) process.stdout.write(trimmed.endsWith("\n") ? trimmed : `${trimmed}\n`);
|
|
214
|
-
if (code === 0) {
|
|
215
|
-
consola.success(`Claude Code updated to ${latestVersion}`);
|
|
216
|
-
return;
|
|
217
|
-
}
|
|
218
|
-
if (!looksLikeUnknownUpdateCommand(combined)) throw new Error(`\`claude update\` exited with code ${code}`);
|
|
219
|
-
const npmPath = _resolve("npm");
|
|
220
|
-
if (!npmPath) throw new Error(`this Claude Code build predates \`claude update\` and npm is not on PATH; update manually: npm install -g ${NPM_PACKAGE$1}@latest`);
|
|
221
|
-
consola.warn(`This Claude Code build predates \`claude update\`; falling back to \`npm install -g ${NPM_PACKAGE$1}@latest\`.`);
|
|
222
|
-
const { code: npmCode, stderr: npmStderr } = await _void([
|
|
223
|
-
npmPath,
|
|
224
|
-
"install",
|
|
225
|
-
"-g",
|
|
226
|
-
`${NPM_PACKAGE$1}@latest`,
|
|
227
|
-
"--silent"
|
|
228
|
-
], { timeoutMs: NPM_INSTALL_TIMEOUT_MS$1 });
|
|
229
|
-
if (npmCode !== 0) throw new Error(`npm install failed: ${npmStderr.trim() || `exit ${npmCode}`}`);
|
|
230
|
-
consola.success(`${NPM_PACKAGE$1} updated to ${latestVersion}`);
|
|
231
|
-
})) consola.debug("Claude Code update already in progress in another process; skipping.");
|
|
232
|
-
}
|
|
233
|
-
// src/lib/self-update.ts
|
|
234
|
-
/**
|
|
235
|
-
* Self-update for the `github-router` proxy.
|
|
236
|
-
*
|
|
237
|
-
* The proxy is a *running* process, so updating its own global install
|
|
238
|
-
* in place (`npm install -g github-router@latest`) deletes/overwrites
|
|
239
|
-
* files the OS holds open — on Windows that fails deterministically
|
|
240
|
-
* (EPERM/EBUSY) and can corrupt the install. So we never install in
|
|
241
|
-
* place: when a newer version exists we spawn a **detached updater that
|
|
242
|
-
* waits for this process to exit**, then installs. The update takes
|
|
243
|
-
* effect on the next launch — no re-exec, no restart prompt.
|
|
244
|
-
*
|
|
245
|
-
* Best-effort throughout: every failure is swallowed to debug/warn and
|
|
246
|
-
* never blocks startup. The startup probe is bounded and the install is
|
|
247
|
-
* off the critical path (detached), so even a blackholed network can't
|
|
248
|
-
* delay the proxy from serving.
|
|
249
|
-
*/
|
|
250
|
-
const NPM_PACKAGE = "github-router";
|
|
251
|
-
const THROTTLE_HOURS$1 = 1;
|
|
252
|
-
const NPM_VIEW_TIMEOUT_MS$1 = 5e3;
|
|
253
|
-
function cacheFilePath$1() {
|
|
254
|
-
return path.join(os.homedir(), ".local", "share", "github-router", "last-self-update-check");
|
|
255
|
-
}
|
|
256
|
-
async function readCache$1() {
|
|
257
|
-
try {
|
|
258
|
-
const parsed = JSON.parse(await fs$1.readFile(cacheFilePath$1(), "utf8"));
|
|
259
|
-
if (typeof parsed.checkedAt !== "string") return null;
|
|
260
|
-
return parsed;
|
|
261
|
-
} catch {
|
|
262
|
-
return null;
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
async function writeCache$1(cache) {
|
|
266
|
-
try {
|
|
267
|
-
await fs$1.mkdir(path.dirname(cacheFilePath$1()), { recursive: true });
|
|
268
|
-
await fs$1.writeFile(cacheFilePath$1(), JSON.stringify(cache), { mode: 384 });
|
|
269
|
-
} catch (err) {
|
|
270
|
-
consola.debug("Failed to write self-update cache:", err);
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
function shouldCheckNow$1(cache) {
|
|
274
|
-
if (!cache) return true;
|
|
275
|
-
const last = new Date(cache.checkedAt).getTime();
|
|
276
|
-
if (Number.isNaN(last)) return true;
|
|
277
|
-
return (Date.now() - last) / 1e3 / 3600 >= THROTTLE_HOURS$1;
|
|
278
|
-
}
|
|
279
|
-
async function getLatestVersion(npmPath) {
|
|
280
|
-
try {
|
|
281
|
-
const { stdout, code } = await runCommandCapture([
|
|
282
|
-
npmPath,
|
|
283
|
-
"view",
|
|
284
|
-
NPM_PACKAGE,
|
|
285
|
-
"version",
|
|
286
|
-
"--silent"
|
|
287
|
-
], { timeoutMs: NPM_VIEW_TIMEOUT_MS$1 });
|
|
288
|
-
if (code !== 0) return null;
|
|
289
|
-
const v = stdout.trim();
|
|
290
|
-
return /^\d+\.\d+\.\d+/.test(v) ? v : null;
|
|
291
|
-
} catch {
|
|
292
|
-
return null;
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
/**
|
|
296
|
-
* Spawn a detached process that waits for THIS proxy (pid) to exit,
|
|
297
|
-
* then runs `npm install -g <spec>`. Fully detached and unref'd so it
|
|
298
|
-
* outlives the proxy; output discarded.
|
|
299
|
-
*
|
|
300
|
-
* The waiter is a tiny inline Node script (Node is guaranteed present —
|
|
301
|
-
* the proxy runs on it) that polls `process.kill(pid, 0)` until the
|
|
302
|
-
* parent is gone, then execs npm. This avoids the Windows file-lock by
|
|
303
|
-
* never touching the global install while the proxy holds it open.
|
|
304
|
-
*
|
|
305
|
-
* Shared by the proxy self-update (`github-router@latest`) and the Pi
|
|
306
|
-
* background refresh (`@earendil-works/pi-coding-agent@<version>`):
|
|
307
|
-
* both must update a global install without delaying startup, holding
|
|
308
|
-
* shutdown, or racing each other (callers hold `withInstallLock`
|
|
309
|
-
* before queueing).
|
|
310
|
-
*/
|
|
311
|
-
function queueDetachedGlobalInstall(npmPath, spec, extraArgs = []) {
|
|
312
|
-
const parentPid = process.pid;
|
|
313
|
-
const installArgs = [
|
|
314
|
-
"install",
|
|
315
|
-
"-g",
|
|
316
|
-
spec,
|
|
317
|
-
...extraArgs
|
|
318
|
-
];
|
|
319
|
-
const waiter = `
|
|
320
|
-
const pid = ${parentPid};
|
|
321
|
-
const { spawn } = require("node:child_process");
|
|
322
|
-
function alive() { try { process.kill(pid, 0); return true } catch { return false } }
|
|
323
|
-
const timer = setInterval(() => {
|
|
324
|
-
if (alive()) return;
|
|
325
|
-
clearInterval(timer);
|
|
326
|
-
const args = [...${JSON.stringify(installArgs)}, "--silent"];
|
|
327
|
-
const isWin = process.platform === "win32";
|
|
328
|
-
const child = spawn(${JSON.stringify(npmPath)}, args, {
|
|
329
|
-
stdio: "ignore", windowsHide: true, shell: isWin, detached: !isWin,
|
|
330
|
-
});
|
|
331
|
-
child.on("error", () => process.exit(0));
|
|
332
|
-
child.on("exit", () => process.exit(0));
|
|
333
|
-
// Safety: never hang forever.
|
|
334
|
-
setTimeout(() => process.exit(0), 180000).unref();
|
|
335
|
-
}, 500);
|
|
336
|
-
// Safety cap on the wait itself (e.g. extremely long sessions still
|
|
337
|
-
// eventually give up rather than leak the waiter).
|
|
338
|
-
setTimeout(() => { clearInterval(timer); process.exit(0); }, 24 * 3600 * 1000).unref();
|
|
339
|
-
`.trim();
|
|
340
|
-
spawn(process.execPath, ["-e", waiter], {
|
|
341
|
-
detached: true,
|
|
342
|
-
stdio: "ignore",
|
|
343
|
-
windowsHide: true
|
|
344
|
-
}).unref();
|
|
345
|
-
}
|
|
346
|
-
function spawnDetachedUpdater(npmPath) {
|
|
347
|
-
queueDetachedGlobalInstall(npmPath, `${NPM_PACKAGE}@latest`);
|
|
348
|
-
}
|
|
349
|
-
/**
|
|
350
|
-
* Probe npm for a newer `github-router` and, if found, queue a detached
|
|
351
|
-
* post-exit update. Returns quickly; never throws. Call AFTER the
|
|
352
|
-
* server is listening so the bounded probe can't delay binding.
|
|
353
|
-
*/
|
|
354
|
-
async function runSelfUpdate(opts) {
|
|
355
|
-
if (!opts.selfUpdate) return;
|
|
356
|
-
if (parseBoolEnv(process.env.GH_ROUTER_NO_SELF_UPDATE) === true) return;
|
|
357
|
-
try {
|
|
358
|
-
const cache = await readCache$1();
|
|
359
|
-
if (!opts.force && !shouldCheckNow$1(cache)) return;
|
|
360
|
-
const installed = getPackageVersion();
|
|
361
|
-
if (installed === "unknown") return;
|
|
362
|
-
const npmPath = resolveExecutable("npm");
|
|
363
|
-
if (!npmPath) return;
|
|
364
|
-
const latest = await getLatestVersion(npmPath);
|
|
365
|
-
await writeCache$1({
|
|
366
|
-
checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
367
|
-
installedVersion: installed,
|
|
368
|
-
latestVersion: latest
|
|
369
|
-
});
|
|
370
|
-
if (!latest || !isNewer(installed, latest)) return;
|
|
371
|
-
if (await withInstallLock("self-update.lock", async () => {
|
|
372
|
-
spawnDetachedUpdater(npmPath);
|
|
373
|
-
})) consola.info(`github-router ${installed} → ${latest} update queued; it takes effect on the next launch.`);
|
|
374
|
-
} catch (err) {
|
|
375
|
-
consola.debug("Self-update check failed:", err);
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
32
|
// src/lib/launch-profile.ts
|
|
379
33
|
const STANDARD_PROFILE = Object.freeze({
|
|
380
34
|
id: "standard",
|
|
@@ -2779,9 +2433,693 @@ function deriveAutoCompactWindowTokens(maxPromptTokens, maxOutputTokens) {
|
|
|
2779
2433
|
const window = assumedClientWindowTokens + CLIENT_THRESHOLD_RESERVE_TOKENS;
|
|
2780
2434
|
return Math.min(ENV_WINDOW_MAX_TOKENS, Math.max(ENV_WINDOW_MIN_TOKENS, window));
|
|
2781
2435
|
}
|
|
2436
|
+
// src/lib/pi-package-cache.ts
|
|
2437
|
+
/**
|
|
2438
|
+
* Durable npm-package cache for Pi launches, shared by LINK, never by copy.
|
|
2439
|
+
*
|
|
2440
|
+
* Pi installs the mirror's `packages[]` into `<agentDir>/npm` on every boot,
|
|
2441
|
+
* and the agent dir is a fresh per-launch mirror (`pi-agent-<pid>-<rand>`) —
|
|
2442
|
+
* so without a cache every launch pays a full registry install (~5s + `added
|
|
2443
|
+
* N packages` noise that bypasses `npm_config_loglevel=error`). Pi skips the
|
|
2444
|
+
* install when the package dir already exists and the installed version
|
|
2445
|
+
* satisfies the configured range — and unpinned `npm:name` specs match ANY
|
|
2446
|
+
* installed version — so pointing `<mirror>/npm` at a durable tree makes
|
|
2447
|
+
* repeat launches install nothing: faster AND silent.
|
|
2448
|
+
*
|
|
2449
|
+
* Copies were the original design and the bug. Pre-seeding a mirror with
|
|
2450
|
+
* `fs.cp` measured 27 s (88 MB / 14.6k files) and saving it back 32 s, while
|
|
2451
|
+
* the launcher arms a 5 s shutdown fail-safe (`setTimeout(exit, 5000)`) around
|
|
2452
|
+
* `onShutdown`. Every save was therefore killed mid-`fs.cp`, leaving a
|
|
2453
|
+
* truncated entry with a FRESH mtime; the next launch trusted that mtime,
|
|
2454
|
+
* copied the truncated tree, Pi found its `packages[]` missing and reinstalled
|
|
2455
|
+
* them, and the loop never ended (observed: an entry whose `node_modules`
|
|
2456
|
+
* held 7 directories and a lockfile naming 269, so Pi saw "already installed"
|
|
2457
|
+
* for nothing it needed and reinstalled everything, every launch). A directory
|
|
2458
|
+
* link
|
|
2459
|
+
* (`junction` on Windows, works without elevation) is O(1) in both directions
|
|
2460
|
+
* and needs no shutdown work at all: Pi installs into the durable entry
|
|
2461
|
+
* directly, so the entry is always exactly what a launch left there.
|
|
2462
|
+
*
|
|
2463
|
+
* The invariant that makes a shared tree safe — `<mirror>/npm` is linked ONLY
|
|
2464
|
+
* to an entry that is (a) newly created and empty, (b) verified complete, or
|
|
2465
|
+
* (c) complete against the configured package set but still awaiting packages.
|
|
2466
|
+
* Never to a stale entry, and never to one known to be internally inconsistent
|
|
2467
|
+
* that could not be retired. Every other path leaves `<mirror>/npm` absent, so
|
|
2468
|
+
* Pi installs into the per-launch tree exactly as it did before the cache
|
|
2469
|
+
* existed. Two consequences worth knowing:
|
|
2470
|
+
*
|
|
2471
|
+
* - nothing destructive ever runs on the shutdown path. Seed validates, so a
|
|
2472
|
+
* shutdown could only rediscover what the next seed finds on its own; the
|
|
2473
|
+
* 32 s copy this replaces was cut short by the 5 s fail-safe every single
|
|
2474
|
+
* time, and an `rm -rf` of the same tree would be the same bug with a new
|
|
2475
|
+
* verb (5-30 s on Windows with Defender, and it fails partially).
|
|
2476
|
+
* - a tree we must discard is renamed aside first and deleted on the side, so
|
|
2477
|
+
* the launch never waits for the delete and never loses a recoverable tree.
|
|
2478
|
+
*
|
|
2479
|
+
* Keyed by the exact package set (sorted spec fingerprints), so flag
|
|
2480
|
+
* combinations (`--helpers`/`--ui`/`--search`/`--browse`) each get their own
|
|
2481
|
+
* entry and can never cross-contaminate. Entries older than the max age are a
|
|
2482
|
+
* miss AND are retired — a linked stale tree would let Pi skip the install, so
|
|
2483
|
+
* the cache could never refresh — and the launch that missed installs into the
|
|
2484
|
+
* new (empty) entry, which is what makes the following launch a hit. Opt out
|
|
2485
|
+
* entirely with `GH_ROUTER_PI_NO_PACKAGE_CACHE=1`.
|
|
2486
|
+
*
|
|
2487
|
+
* Max age defaults to 24h, not the original 7d. Pi resolves an unpinned
|
|
2488
|
+
* `npm:name` spec to whatever is already installed, so the max age IS the
|
|
2489
|
+
* worst-case staleness of every extension the user runs — a week of it meant a
|
|
2490
|
+
* fix published upstream on Monday was still missing the following Sunday.
|
|
2491
|
+
* A day bounds the lag without making the cache pointless: the npm install it
|
|
2492
|
+
* avoids takes ~5s, so one refresh per day is paid back by every other launch
|
|
2493
|
+
* that day. Override with `GH_ROUTER_PI_PACKAGE_CACHE_HOURS`.
|
|
2494
|
+
*/
|
|
2495
|
+
const PI_PACKAGE_CACHE_MAX_AGE_MS = 864e5;
|
|
2496
|
+
/** Rename target prefix for a retired `node_modules`. */
|
|
2497
|
+
const TRASH_PREFIX = ".trash-";
|
|
2498
|
+
/**
|
|
2499
|
+
* Marker file recording that the entry's tree passed a full validation, so the
|
|
2500
|
+
* O(N) walk (269 keys: 7 ms warm here, 1-3 s against a cold or AV-scanned
|
|
2501
|
+
* directory) does not run on every boot. Lives beside `npm/`, not inside it, so
|
|
2502
|
+
* writing it cannot disturb `npm/`'s mtime — the freshness clock below.
|
|
2503
|
+
*/
|
|
2504
|
+
const STAMP_NAME = ".pi-cache-ok";
|
|
2505
|
+
const STAMP_SCHEMA_VERSION = 1;
|
|
2506
|
+
/** Bound on concurrent `stat`s during validation (269 keys traded 41 ms → 7 ms). */
|
|
2507
|
+
const VALIDATION_CONCURRENCY = 32;
|
|
2508
|
+
/** Bounded retries for the off-path delete of a retired tree (Windows sharing). */
|
|
2509
|
+
const RETIRE_DELETE_OPTS = {
|
|
2510
|
+
recursive: true,
|
|
2511
|
+
force: true,
|
|
2512
|
+
maxRetries: 10,
|
|
2513
|
+
retryDelay: 100
|
|
2514
|
+
};
|
|
2515
|
+
/**
|
|
2516
|
+
* Effective max age. Read per call rather than at module load so a test (or a
|
|
2517
|
+
* long-lived process re-reading config) can change the env and observe it, and
|
|
2518
|
+
* so a malformed value degrades to the default instead of `NaN` day math —
|
|
2519
|
+
* `Date.now() - mtime > NaN` is always false, which would make every entry
|
|
2520
|
+
* eternally fresh.
|
|
2521
|
+
*/
|
|
2522
|
+
function piPackageCacheMaxAgeMs() {
|
|
2523
|
+
const raw = (process.env["GH_ROUTER_PI_PACKAGE_CACHE_HOURS"] ?? "").trim();
|
|
2524
|
+
if (!raw) return PI_PACKAGE_CACHE_MAX_AGE_MS;
|
|
2525
|
+
const hours = Number(raw);
|
|
2526
|
+
if (!Number.isFinite(hours) || hours <= 0) return PI_PACKAGE_CACHE_MAX_AGE_MS;
|
|
2527
|
+
return hours * 3600 * 1e3;
|
|
2528
|
+
}
|
|
2529
|
+
/**
|
|
2530
|
+
* Whether the cache may be used at all (env opt-out honoured per call, same
|
|
2531
|
+
* reason as the max age above). `pi-paths` reads this too, to decide whether
|
|
2532
|
+
* `<mirror>/npm` is the launcher's to own, so the two must agree.
|
|
2533
|
+
*/
|
|
2534
|
+
function piPackageCacheEnabled(env = process.env) {
|
|
2535
|
+
return env.GH_ROUTER_PI_NO_PACKAGE_CACHE !== "1";
|
|
2536
|
+
}
|
|
2537
|
+
/** Stable fingerprint of one `packages[]` entry (order-independent). */
|
|
2538
|
+
function piPackageSpecFingerprint(entry) {
|
|
2539
|
+
if (typeof entry === "string") return entry;
|
|
2540
|
+
const join = (v) => [...v ?? []].sort().join(",");
|
|
2541
|
+
return [
|
|
2542
|
+
entry.source,
|
|
2543
|
+
`ext:${join(entry.extensions)}`,
|
|
2544
|
+
`skills:${join(entry.skills)}`,
|
|
2545
|
+
`prompts:${join(entry.prompts)}`,
|
|
2546
|
+
`themes:${join(entry.themes)}`
|
|
2547
|
+
].join("::");
|
|
2548
|
+
}
|
|
2549
|
+
/** Order-independent cache key for a launch's full `packages[]` slice. */
|
|
2550
|
+
function piPackageCacheKey(packages) {
|
|
2551
|
+
const specs = packages.map(piPackageSpecFingerprint).sort();
|
|
2552
|
+
return createHash("sha256").update(specs.join("\n")).digest("hex").slice(0, 16);
|
|
2553
|
+
}
|
|
2554
|
+
function piPackageCacheDir(key) {
|
|
2555
|
+
return path.join(PATHS.APP_DIR, "pi-packages", key);
|
|
2556
|
+
}
|
|
2557
|
+
/**
|
|
2558
|
+
* Package NAME a `packages[]` entry asks npm for, or null when the entry is not
|
|
2559
|
+
* an npm spec at all (`local:`, `git:`, `https:`, a bare path). `npm:@scope/pkg`
|
|
2560
|
+
* keeps its scope; `npm:foo@^1.2.3` loses only the version — the cut is at the
|
|
2561
|
+
* last `@` that comes after the last `/`, which is what makes a scoped name
|
|
2562
|
+
* survive intact.
|
|
2563
|
+
*/
|
|
2564
|
+
function npmPackageName(entry) {
|
|
2565
|
+
const source = typeof entry === "string" ? entry : entry.source;
|
|
2566
|
+
if (!source.startsWith("npm:")) return null;
|
|
2567
|
+
const rest = source.slice(4).trim();
|
|
2568
|
+
const at = rest.lastIndexOf("@");
|
|
2569
|
+
const name = (at > rest.lastIndexOf("/") ? rest.slice(0, at) : rest).trim();
|
|
2570
|
+
return name === "" ? null : name;
|
|
2571
|
+
}
|
|
2572
|
+
/**
|
|
2573
|
+
* The package names a cache entry MUST contain to count as complete, sorted and
|
|
2574
|
+
* de-duplicated. Derived from the launch's own `packages[]`, never from the
|
|
2575
|
+
* entry's lockfile: npm rewrites `.package-lock.json` after every individual
|
|
2576
|
+
* `npm install`, and Pi installs one package at a time, so a lock listing 1 of
|
|
2577
|
+
* 5 packages is a normal intermediate state. Trusting the lock alone would call
|
|
2578
|
+
* a half-installed tree complete — a milder rerun of the bug this file exists
|
|
2579
|
+
* to prevent. Non-npm entries are skipped: they are not resolvable by name
|
|
2580
|
+
* here and must never make an entry permanently invalid.
|
|
2581
|
+
*/
|
|
2582
|
+
function requiredPackageNames(packages) {
|
|
2583
|
+
const names = /* @__PURE__ */ new Set();
|
|
2584
|
+
for (const entry of packages) {
|
|
2585
|
+
const name = npmPackageName(entry);
|
|
2586
|
+
if (name !== null) names.add(name);
|
|
2587
|
+
}
|
|
2588
|
+
return [...names].sort();
|
|
2589
|
+
}
|
|
2590
|
+
function npmDirOf(root) {
|
|
2591
|
+
return path.join(root, "npm");
|
|
2592
|
+
}
|
|
2593
|
+
async function mtimeMsOf(dir) {
|
|
2594
|
+
try {
|
|
2595
|
+
return (await fs$1.stat(dir)).mtimeMs;
|
|
2596
|
+
} catch {
|
|
2597
|
+
return null;
|
|
2598
|
+
}
|
|
2599
|
+
}
|
|
2600
|
+
/** Case-fold on win32 only: junctions reached through a mapped drive differ in case. */
|
|
2601
|
+
function samePathText(a, b) {
|
|
2602
|
+
return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
2603
|
+
}
|
|
2604
|
+
/**
|
|
2605
|
+
* Do two paths name the same filesystem object? Both sides go through
|
|
2606
|
+
* `realpath`, so a link compared against its target matches. A path that does
|
|
2607
|
+
* not resolve is never "the same" — a dangling link is exactly the case that
|
|
2608
|
+
* must be rejected rather than adopted.
|
|
2609
|
+
*/
|
|
2610
|
+
async function samePath(a, b) {
|
|
2611
|
+
const [left, right] = await Promise.all([fs$1.realpath(a).catch(() => null), fs$1.realpath(b).catch(() => null)]);
|
|
2612
|
+
if (left === null || right === null) return false;
|
|
2613
|
+
return samePathText(left, right);
|
|
2614
|
+
}
|
|
2615
|
+
/**
|
|
2616
|
+
* Stats fanned out with a hard cap, returning the items whose probe said no (or
|
|
2617
|
+
* threw — an unreadable path and a missing one are the same verdict here).
|
|
2618
|
+
* Order of the result follows completion, so callers sort before printing.
|
|
2619
|
+
*/
|
|
2620
|
+
async function missingOf(items, probe) {
|
|
2621
|
+
const missing = [];
|
|
2622
|
+
let cursor = 0;
|
|
2623
|
+
const worker = async () => {
|
|
2624
|
+
while (cursor < items.length) {
|
|
2625
|
+
const item = items[cursor++];
|
|
2626
|
+
try {
|
|
2627
|
+
if (await probe(item)) continue;
|
|
2628
|
+
} catch {}
|
|
2629
|
+
missing.push(item);
|
|
2630
|
+
}
|
|
2631
|
+
};
|
|
2632
|
+
await Promise.all(Array.from({ length: Math.min(VALIDATION_CONCURRENCY, items.length) }, worker));
|
|
2633
|
+
return missing;
|
|
2634
|
+
}
|
|
2635
|
+
/** `packages` keys npm wrote into the hidden lockfile, minus the prefix itself. */
|
|
2636
|
+
function lockPackageKeys(parsed) {
|
|
2637
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
2638
|
+
const packagesField = parsed.packages;
|
|
2639
|
+
if (typeof packagesField !== "object" || packagesField === null) return null;
|
|
2640
|
+
return Object.keys(packagesField).filter((key) => key.length > 0);
|
|
2641
|
+
}
|
|
2642
|
+
/**
|
|
2643
|
+
* Is this entry a complete tree for the given package names?
|
|
2644
|
+
*
|
|
2645
|
+
* Two parts, in order, because the failure modes mean opposite things:
|
|
2646
|
+
*
|
|
2647
|
+
* A. Every configured npm package must have
|
|
2648
|
+
* `<entry>/npm/node_modules/<name>/package.json`. A shortfall means "not
|
|
2649
|
+
* installed yet" — another launch may be mid-install, or Pi simply has not
|
|
2650
|
+
* reached that package — so it is a miss the launch can finish, NOT
|
|
2651
|
+
* corruption to destroy.
|
|
2652
|
+
* B. Only then is `.package-lock.json` worth reading, as the record of what
|
|
2653
|
+
* npm wrote for those packages: every key it lists must exist on disk. A
|
|
2654
|
+
* lock that outruns its tree is npm interrupted mid-write (7 dirs against
|
|
2655
|
+
* a 269-key lock), and that entry is worthless.
|
|
2656
|
+
*
|
|
2657
|
+
* A missing or unparseable lock is UNVERIFIED, not invalid: `package-lock=false`
|
|
2658
|
+
* in a user `.npmrc` means the hidden lock is never written at all, and calling
|
|
2659
|
+
* that invalid would wipe an 88 MB tree at every boot forever. Part B only ever
|
|
2660
|
+
* applies to a lock that exists.
|
|
2661
|
+
*/
|
|
2662
|
+
async function validateCacheEntry(entryNpm, requiredNames) {
|
|
2663
|
+
const nodeModules = path.join(entryNpm, "node_modules");
|
|
2664
|
+
const missingPackages = await missingOf(requiredNames, async (name) => {
|
|
2665
|
+
return (await fs$1.stat(path.join(nodeModules, name, "package.json"))).isFile();
|
|
2666
|
+
});
|
|
2667
|
+
if (missingPackages.length > 0) {
|
|
2668
|
+
const sorted = [...missingPackages].sort();
|
|
2669
|
+
const shown = sorted.slice(0, 5).join(", ");
|
|
2670
|
+
const more = sorted.length > 5 ? ", …" : "";
|
|
2671
|
+
return {
|
|
2672
|
+
ok: false,
|
|
2673
|
+
part: "packages",
|
|
2674
|
+
reason: `cached tree is missing ${sorted.length} of ${requiredNames.length} configured packages (${shown}${more})`
|
|
2675
|
+
};
|
|
2676
|
+
}
|
|
2677
|
+
let lockKeys;
|
|
2678
|
+
try {
|
|
2679
|
+
lockKeys = lockPackageKeys(JSON.parse(await fs$1.readFile(path.join(nodeModules, ".package-lock.json"), "utf8")));
|
|
2680
|
+
} catch {
|
|
2681
|
+
lockKeys = null;
|
|
2682
|
+
}
|
|
2683
|
+
if (lockKeys === null) return {
|
|
2684
|
+
ok: true,
|
|
2685
|
+
packages: requiredNames.length,
|
|
2686
|
+
entries: 0,
|
|
2687
|
+
lock: "absent"
|
|
2688
|
+
};
|
|
2689
|
+
const missingEntries = await missingOf(lockKeys, async (key) => {
|
|
2690
|
+
await fs$1.stat(path.join(entryNpm, key));
|
|
2691
|
+
return true;
|
|
2692
|
+
});
|
|
2693
|
+
if (missingEntries.length > 0) return {
|
|
2694
|
+
ok: false,
|
|
2695
|
+
part: "lockfile",
|
|
2696
|
+
reason: `cached tree is missing ${missingEntries.length} lockfile entries`
|
|
2697
|
+
};
|
|
2698
|
+
return {
|
|
2699
|
+
ok: true,
|
|
2700
|
+
packages: requiredNames.length,
|
|
2701
|
+
entries: lockKeys.length,
|
|
2702
|
+
lock: "checked"
|
|
2703
|
+
};
|
|
2704
|
+
}
|
|
2705
|
+
function stampPath(entry) {
|
|
2706
|
+
return path.join(entry, STAMP_NAME);
|
|
2707
|
+
}
|
|
2708
|
+
/**
|
|
2709
|
+
* Grace on the stamp's mtime comparison, absorbing the difference between
|
|
2710
|
+
* `Date.now()` and the filesystem's timestamp rounding. Five milliseconds is
|
|
2711
|
+
* far below any real modification, and a change landing inside it is
|
|
2712
|
+
* indistinguishable from the stamp write itself.
|
|
2713
|
+
*/
|
|
2714
|
+
const STAMP_MTIME_TOLERANCE_MS = 5;
|
|
2715
|
+
/**
|
|
2716
|
+
* Is there a stamp that lets this boot skip the walk? Every condition is a way
|
|
2717
|
+
* the claim could be wrong: schema, key, package set and max-age window must
|
|
2718
|
+
* all match, and the tree must not have been touched since the stamp was
|
|
2719
|
+
* written (`node_modules`'s mtime is the cheap proxy — deleting a package dir
|
|
2720
|
+
* or rewriting a lockfile bumps it). That last check is what stops a stamp from
|
|
2721
|
+
* vouching for a tree that changed after validation, which is the only way a
|
|
2722
|
+
* stale stamp could reintroduce the half-tree this file exists to prevent. One
|
|
2723
|
+
* `stat` covers both the "still exists" and "still untouched" halves.
|
|
2724
|
+
*/
|
|
2725
|
+
async function stampIsFresh(entry, entryNpm, key, names) {
|
|
2726
|
+
let stamp;
|
|
2727
|
+
try {
|
|
2728
|
+
const parsed = JSON.parse(await fs$1.readFile(stampPath(entry), "utf8"));
|
|
2729
|
+
if (typeof parsed !== "object" || parsed === null) return false;
|
|
2730
|
+
stamp = parsed;
|
|
2731
|
+
} catch {
|
|
2732
|
+
return false;
|
|
2733
|
+
}
|
|
2734
|
+
if (stamp.schemaVersion !== STAMP_SCHEMA_VERSION) return false;
|
|
2735
|
+
if (stamp.key !== key) return false;
|
|
2736
|
+
if (!Array.isArray(stamp.packages) || stamp.packages.length !== names.length) return false;
|
|
2737
|
+
if (!stamp.packages.every((name, index) => name === names[index])) return false;
|
|
2738
|
+
if (typeof stamp.entries !== "number") return false;
|
|
2739
|
+
if (typeof stamp.validatedAt !== "string") return false;
|
|
2740
|
+
const validatedAt = Date.parse(stamp.validatedAt);
|
|
2741
|
+
if (!Number.isFinite(validatedAt)) return false;
|
|
2742
|
+
if (Date.now() - validatedAt > piPackageCacheMaxAgeMs()) return false;
|
|
2743
|
+
const nodeModulesMtime = await mtimeMsOf(path.join(entryNpm, "node_modules"));
|
|
2744
|
+
if (nodeModulesMtime === null) return false;
|
|
2745
|
+
return nodeModulesMtime <= validatedAt + STAMP_MTIME_TOLERANCE_MS;
|
|
2746
|
+
}
|
|
2747
|
+
/** Record a passed validation. Best-effort — an unwritable stamp only costs a scan. */
|
|
2748
|
+
async function writeStamp(entry, key, names, entries) {
|
|
2749
|
+
const stamp = {
|
|
2750
|
+
schemaVersion: STAMP_SCHEMA_VERSION,
|
|
2751
|
+
key,
|
|
2752
|
+
packages: [...names],
|
|
2753
|
+
entries,
|
|
2754
|
+
validatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2755
|
+
};
|
|
2756
|
+
try {
|
|
2757
|
+
await writeFileAtomic(stampPath(entry), `${JSON.stringify(stamp)}\n`, { mode: 384 });
|
|
2758
|
+
} catch (err) {
|
|
2759
|
+
consola.debug("Pi package cache: could not write the validation stamp:", err);
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
/**
|
|
2763
|
+
* Drop the stamp. Called before every destructive step so a wipe can never
|
|
2764
|
+
* leave a stamp claiming the wiped tree is fine; the next launch then re-walks
|
|
2765
|
+
* and re-stamps honestly.
|
|
2766
|
+
*/
|
|
2767
|
+
async function dropStamp(entry) {
|
|
2768
|
+
try {
|
|
2769
|
+
await fs$1.rm(stampPath(entry), { force: true });
|
|
2770
|
+
} catch (err) {
|
|
2771
|
+
consola.debug("Pi package cache: could not drop the validation stamp:", err);
|
|
2772
|
+
}
|
|
2773
|
+
}
|
|
2774
|
+
/**
|
|
2775
|
+
* Is another LIVE launch using this entry? Returns its PID, else null.
|
|
2776
|
+
*
|
|
2777
|
+
* Load-bearing now that the tree is shared: deleting a target leaves every
|
|
2778
|
+
* junction to it dangling (verified — junctions do not error when their target
|
|
2779
|
+
* disappears), and `mkdir` does not recreate the target, so Pi's own install
|
|
2780
|
+
* then fails at boot with ENOENT instead of falling back to a cold cache.
|
|
2781
|
+
*
|
|
2782
|
+
* Deliberately not a cross-process lock. A lock would serialise launches and
|
|
2783
|
+
* make the second one pay a full install anyway, for a case that only arises
|
|
2784
|
+
* when an entry is stale or corrupt while a session still runs from it. This
|
|
2785
|
+
* guard is conservative in the safe direction (an unreadable PID counts as
|
|
2786
|
+
* alive, and PID reuse can only cost one launch its shared tree), needs no
|
|
2787
|
+
* clock skew or hostname logic, and cannot deadlock.
|
|
2788
|
+
*/
|
|
2789
|
+
async function entryInUseByOtherLaunch(entryNpm) {
|
|
2790
|
+
const target = await fs$1.realpath(entryNpm).catch(() => null);
|
|
2791
|
+
if (target === null) return null;
|
|
2792
|
+
const mirrorsRoot = path.join(PATHS.APP_DIR, "pi-mirrors");
|
|
2793
|
+
let mirrors;
|
|
2794
|
+
try {
|
|
2795
|
+
mirrors = await fs$1.readdir(mirrorsRoot);
|
|
2796
|
+
} catch {
|
|
2797
|
+
return null;
|
|
2798
|
+
}
|
|
2799
|
+
for (const name of mirrors) {
|
|
2800
|
+
const match = /^pi-agent-(\d+)-[0-9a-f]+$/.exec(name);
|
|
2801
|
+
if (!match) continue;
|
|
2802
|
+
const pid = Number.parseInt(match[1], 10);
|
|
2803
|
+
if (!Number.isFinite(pid) || pid === process.pid) continue;
|
|
2804
|
+
const link = path.join(mirrorsRoot, name, "npm");
|
|
2805
|
+
try {
|
|
2806
|
+
if (!(await fs$1.lstat(link)).isSymbolicLink()) continue;
|
|
2807
|
+
} catch {
|
|
2808
|
+
continue;
|
|
2809
|
+
}
|
|
2810
|
+
const resolved = await fs$1.realpath(link).catch(() => null);
|
|
2811
|
+
if (resolved === null || !samePathText(resolved, target)) continue;
|
|
2812
|
+
if (isPidAlive(pid)) return pid;
|
|
2813
|
+
}
|
|
2814
|
+
return null;
|
|
2815
|
+
}
|
|
2816
|
+
/**
|
|
2817
|
+
* Only `ESRCH` (and the `ENOENT` some platforms report for a vanished pid) mean
|
|
2818
|
+
* "gone". `EPERM` from another user's process and `EINVAL` both mean the
|
|
2819
|
+
* process is there and we may not signal it — counting those as dead would
|
|
2820
|
+
* delete a tree out from under a live session.
|
|
2821
|
+
*/
|
|
2822
|
+
function isPidAlive(pid) {
|
|
2823
|
+
try {
|
|
2824
|
+
process.kill(pid, 0);
|
|
2825
|
+
return true;
|
|
2826
|
+
} catch (err) {
|
|
2827
|
+
const code = err.code;
|
|
2828
|
+
return code !== "ESRCH" && code !== "ENOENT";
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
/**
|
|
2832
|
+
* Move an entry's `node_modules` out of the way without waiting on a delete.
|
|
2833
|
+
*
|
|
2834
|
+
* `rm -rf` of this tree is what a shutdown copy used to be followed by, and on
|
|
2835
|
+
* Windows with Defender it takes 5-30 s and fails partially, which would put the
|
|
2836
|
+
* same overrun on the launch path. A rename is atomic or it does nothing:
|
|
2837
|
+
* measured here, it fails with EPERM when a child file is held open, so the
|
|
2838
|
+
* fallback is an in-place delete — but the common case (nothing holding it) is
|
|
2839
|
+
* instant and the tree stays recoverable until the off-path delete lands.
|
|
2840
|
+
*
|
|
2841
|
+
* A fresh empty `node_modules` is always recreated so npm has a prefix, and the
|
|
2842
|
+
* stamp is always dropped. `<entry>` itself is never removed.
|
|
2843
|
+
*/
|
|
2844
|
+
async function retireEntryTree(entry, entryNpm) {
|
|
2845
|
+
const nodeModules = path.join(entryNpm, "node_modules");
|
|
2846
|
+
await dropStamp(entry);
|
|
2847
|
+
const trash = path.join(entryNpm, `${TRASH_PREFIX}${Date.now()}-${randomBytes(4).toString("hex")}`);
|
|
2848
|
+
let renamed = false;
|
|
2849
|
+
try {
|
|
2850
|
+
await fs$1.rename(nodeModules, trash);
|
|
2851
|
+
renamed = true;
|
|
2852
|
+
} catch (err) {
|
|
2853
|
+
consola.debug("Pi package cache: could not move the tree aside, deleting in place:", err);
|
|
2854
|
+
}
|
|
2855
|
+
if (!renamed) try {
|
|
2856
|
+
await fs$1.rm(nodeModules, RETIRE_DELETE_OPTS);
|
|
2857
|
+
} catch (err) {
|
|
2858
|
+
consola.debug("Pi package cache: in-place delete did not finish:", err);
|
|
2859
|
+
}
|
|
2860
|
+
try {
|
|
2861
|
+
await fs$1.mkdir(nodeModules, { recursive: true });
|
|
2862
|
+
} catch (err) {
|
|
2863
|
+
consola.debug("Pi package cache: could not recreate node_modules:", err);
|
|
2864
|
+
return;
|
|
2865
|
+
}
|
|
2866
|
+
if (!renamed) return;
|
|
2867
|
+
fs$1.rm(trash, RETIRE_DELETE_OPTS).catch((err) => {
|
|
2868
|
+
consola.debug("Pi package cache: retired tree will be collected later:", err);
|
|
2869
|
+
});
|
|
2870
|
+
}
|
|
2871
|
+
/**
|
|
2872
|
+
* Forget npm's own bookkeeping at the entry root, used when the tree is retired
|
|
2873
|
+
* for staleness: a root lockfile still describing the retired tree would let
|
|
2874
|
+
* the next install resolve the OLD versions, which is the opposite of what a
|
|
2875
|
+
* stale retirement is for. Cheap (two small files), and only when the tree is
|
|
2876
|
+
* already being thrown away.
|
|
2877
|
+
*/
|
|
2878
|
+
async function forgetEntryManifests(entryNpm) {
|
|
2879
|
+
await Promise.all(["package.json", "package-lock.json"].map((name) => fs$1.rm(path.join(entryNpm, name), { force: true }).catch(() => void 0)));
|
|
2880
|
+
}
|
|
2881
|
+
/**
|
|
2882
|
+
* Collect trees retired in past launches. Best-effort, never awaited by the
|
|
2883
|
+
* caller: junk older than an hour is deleted in the background, and whatever
|
|
2884
|
+
* refuses to go is retried on the next boot.
|
|
2885
|
+
*/
|
|
2886
|
+
function collectRetiredTrees(entryNpm) {
|
|
2887
|
+
(async () => {
|
|
2888
|
+
let names;
|
|
2889
|
+
try {
|
|
2890
|
+
names = await fs$1.readdir(entryNpm);
|
|
2891
|
+
} catch {
|
|
2892
|
+
return;
|
|
2893
|
+
}
|
|
2894
|
+
await Promise.all(names.filter((name) => name.startsWith(TRASH_PREFIX)).map(async (name) => {
|
|
2895
|
+
const dir = path.join(entryNpm, name);
|
|
2896
|
+
try {
|
|
2897
|
+
const stat = await fs$1.stat(dir);
|
|
2898
|
+
if (Date.now() - stat.mtimeMs < 36e5) return;
|
|
2899
|
+
await fs$1.rm(dir, RETIRE_DELETE_OPTS);
|
|
2900
|
+
} catch (err) {
|
|
2901
|
+
consola.debug(`Pi package cache: retired tree ${name} not collected yet:`, err);
|
|
2902
|
+
}
|
|
2903
|
+
}));
|
|
2904
|
+
})().catch((err) => {
|
|
2905
|
+
consola.debug("Pi package cache: trash collection skipped:", err);
|
|
2906
|
+
});
|
|
2907
|
+
}
|
|
2908
|
+
/** Remove whatever sits at the mirror's npm path, link or real dir. */
|
|
2909
|
+
async function clearMirrorNpm(mirrorNpm) {
|
|
2910
|
+
try {
|
|
2911
|
+
if ((await fs$1.lstat(mirrorNpm)).isSymbolicLink()) await fs$1.unlink(mirrorNpm);
|
|
2912
|
+
else await fs$1.rm(mirrorNpm, {
|
|
2913
|
+
recursive: true,
|
|
2914
|
+
force: true
|
|
2915
|
+
});
|
|
2916
|
+
} catch (err) {
|
|
2917
|
+
if (err.code !== "ENOENT") consola.debug("Pi package cache: could not clear the mirror's npm path:", err);
|
|
2918
|
+
}
|
|
2919
|
+
}
|
|
2920
|
+
/**
|
|
2921
|
+
* Is `<mirror>/npm` already the link we would plant? Checked before every
|
|
2922
|
+
* link and before every clear, so a second call in the same launch reuses the
|
|
2923
|
+
* link instead of unlinking and recreating it (churn, and a window in which
|
|
2924
|
+
* the mirror has no npm root at all).
|
|
2925
|
+
*/
|
|
2926
|
+
async function linkIsCorrect(mirrorNpm, entryNpm) {
|
|
2927
|
+
try {
|
|
2928
|
+
if (!(await fs$1.lstat(mirrorNpm)).isSymbolicLink()) return false;
|
|
2929
|
+
} catch {
|
|
2930
|
+
return false;
|
|
2931
|
+
}
|
|
2932
|
+
return samePath(mirrorNpm, entryNpm);
|
|
2933
|
+
}
|
|
2934
|
+
/**
|
|
2935
|
+
* Make sure nothing but our link sits at `<mirror>/npm`.
|
|
2936
|
+
*
|
|
2937
|
+
* This path is inside the per-launch mirror, which this module owns: it is
|
|
2938
|
+
* created by `ensurePiAgentMirror`, swept by PID on the next launch, and never
|
|
2939
|
+
* holds a user file (the user's own `npm` tree is deliberately not mirrored —
|
|
2940
|
+
* see `SKIP` in `pi-paths`). So a real dir or file here is either a tree a
|
|
2941
|
+
* previous launch installed into after a fallback, or debris from an earlier
|
|
2942
|
+
* call in this process, and replacing it is safe.
|
|
2943
|
+
*/
|
|
2944
|
+
async function prepareMirrorNpm(mirrorNpm, entryNpm) {
|
|
2945
|
+
try {
|
|
2946
|
+
await fs$1.lstat(mirrorNpm);
|
|
2947
|
+
} catch {
|
|
2948
|
+
return;
|
|
2949
|
+
}
|
|
2950
|
+
if (await linkIsCorrect(mirrorNpm, entryNpm)) return;
|
|
2951
|
+
await clearMirrorNpm(mirrorNpm);
|
|
2952
|
+
}
|
|
2953
|
+
const SYMLINK_FALLBACK_REASON = "symlink unavailable; this launch installs into its own tree";
|
|
2954
|
+
const LINK_MISMATCH_REASON = "symlink does not resolve to the cache entry; this launch installs into its own tree";
|
|
2955
|
+
/**
|
|
2956
|
+
* Plant `<mirror>/npm` -> `<entry>/npm` and prove it stuck.
|
|
2957
|
+
*
|
|
2958
|
+
* The link is the whole mechanism, so its failure must degrade, never fail: an
|
|
2959
|
+
* EPERM (no junction privilege), an EACCES, or a filesystem that refuses
|
|
2960
|
+
* symlinks means this launch installs into its own tree exactly as it did
|
|
2961
|
+
* before the cache existed. The `realpath` check afterwards is the only defence
|
|
2962
|
+
* against a link we did not plant (a stale one, or one pre-created at that
|
|
2963
|
+
* path) being adopted as if it were the cache.
|
|
2964
|
+
*/
|
|
2965
|
+
async function linkEntry(entryNpm, mirrorNpm) {
|
|
2966
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2967
|
+
if (await linkIsCorrect(mirrorNpm, entryNpm)) return { ok: true };
|
|
2968
|
+
try {
|
|
2969
|
+
await fs$1.symlink(entryNpm, mirrorNpm, process.platform === "win32" ? "junction" : "dir");
|
|
2970
|
+
break;
|
|
2971
|
+
} catch (err) {
|
|
2972
|
+
if (attempt === 1) {
|
|
2973
|
+
consola.debug("Pi package cache: symlink unavailable:", err);
|
|
2974
|
+
await fs$1.rm(mirrorNpm, {
|
|
2975
|
+
recursive: true,
|
|
2976
|
+
force: true
|
|
2977
|
+
}).catch(() => void 0);
|
|
2978
|
+
return {
|
|
2979
|
+
ok: false,
|
|
2980
|
+
reason: SYMLINK_FALLBACK_REASON
|
|
2981
|
+
};
|
|
2982
|
+
}
|
|
2983
|
+
await clearMirrorNpm(mirrorNpm);
|
|
2984
|
+
}
|
|
2985
|
+
}
|
|
2986
|
+
if (!await samePath(mirrorNpm, entryNpm)) {
|
|
2987
|
+
consola.debug(`Pi package cache: ${mirrorNpm} does not resolve to ${entryNpm}; unlinking it.`);
|
|
2988
|
+
await fs$1.unlink(mirrorNpm).catch(() => void 0);
|
|
2989
|
+
return {
|
|
2990
|
+
ok: false,
|
|
2991
|
+
reason: LINK_MISMATCH_REASON
|
|
2992
|
+
};
|
|
2993
|
+
}
|
|
2994
|
+
return { ok: true };
|
|
2995
|
+
}
|
|
2996
|
+
function seedResult(mirrorNpm, hit, reason) {
|
|
2997
|
+
return {
|
|
2998
|
+
hit,
|
|
2999
|
+
npmRoot: mirrorNpm,
|
|
3000
|
+
reason
|
|
3001
|
+
};
|
|
3002
|
+
}
|
|
3003
|
+
/**
|
|
3004
|
+
* Point `<mirror>/npm` at the durable entry for this package set, verifying it
|
|
3005
|
+
* first. Never copies a tree (that is what the 5 s shutdown budget used to
|
|
3006
|
+
* truncate), never deletes on the launch path without renaming aside first, and
|
|
3007
|
+
* never throws: a cache that cannot be set up leaves the mirror with no `npm`
|
|
3008
|
+
* at all, so this launch installs into its own tree.
|
|
3009
|
+
*/
|
|
3010
|
+
async function seedPiPackageCache(mirrorDir, packages) {
|
|
3011
|
+
const mirrorNpm = npmDirOf(mirrorDir);
|
|
3012
|
+
if (!piPackageCacheEnabled()) return seedResult(mirrorNpm, false, "cache disabled");
|
|
3013
|
+
const key = piPackageCacheKey(packages);
|
|
3014
|
+
const entry = piPackageCacheDir(key);
|
|
3015
|
+
const entryNpm = npmDirOf(entry);
|
|
3016
|
+
const names = requiredPackageNames(packages);
|
|
3017
|
+
const maxAge = piPackageCacheMaxAgeMs();
|
|
3018
|
+
try {
|
|
3019
|
+
await fs$1.mkdir(mirrorDir, { recursive: true });
|
|
3020
|
+
collectRetiredTrees(entryNpm);
|
|
3021
|
+
await prepareMirrorNpm(mirrorNpm, entryNpm);
|
|
3022
|
+
const inUseReason = (pid) => {
|
|
3023
|
+
consola.debug(`Pi package cache ${key}: entry is in use by launch ${pid}; leaving it alone.`);
|
|
3024
|
+
return seedResult(mirrorNpm, false, `cache entry is in use by launch ${pid}; this launch installs into its own tree`);
|
|
3025
|
+
};
|
|
3026
|
+
const mtime = await mtimeMsOf(entryNpm);
|
|
3027
|
+
if (mtime !== null && Date.now() - mtime > maxAge) {
|
|
3028
|
+
const holder = await entryInUseByOtherLaunch(entryNpm);
|
|
3029
|
+
if (holder !== null) {
|
|
3030
|
+
await clearMirrorNpm(mirrorNpm);
|
|
3031
|
+
return inUseReason(holder);
|
|
3032
|
+
}
|
|
3033
|
+
const stale = `cached tree was stale (${Math.floor((Date.now() - mtime) / 36e5)}h old, max ${Math.round(maxAge / 36e5)}h)`;
|
|
3034
|
+
consola.debug(`Pi package cache ${key}: ${stale}; retiring it and refilling from the registry.`);
|
|
3035
|
+
await retireEntryTree(entry, entryNpm);
|
|
3036
|
+
await forgetEntryManifests(entryNpm);
|
|
3037
|
+
const link = await linkEntry(entryNpm, mirrorNpm);
|
|
3038
|
+
return seedResult(mirrorNpm, false, link.ok ? stale : link.reason);
|
|
3039
|
+
}
|
|
3040
|
+
if (mtime === null) {
|
|
3041
|
+
await fs$1.mkdir(entryNpm, { recursive: true });
|
|
3042
|
+
await dropStamp(entry);
|
|
3043
|
+
const link = await linkEntry(entryNpm, mirrorNpm);
|
|
3044
|
+
return seedResult(mirrorNpm, false, link.ok ? "no cached tree for this package set" : link.reason);
|
|
3045
|
+
}
|
|
3046
|
+
if (await stampIsFresh(entry, entryNpm, key, names)) {
|
|
3047
|
+
const link = await linkEntry(entryNpm, mirrorNpm);
|
|
3048
|
+
return seedResult(mirrorNpm, link.ok, link.ok ? `cached tree verified (${names.length} packages, stamp)` : link.reason);
|
|
3049
|
+
}
|
|
3050
|
+
const verdict = await validateCacheEntry(entryNpm, names);
|
|
3051
|
+
if (!verdict.ok) {
|
|
3052
|
+
consola.debug(`Pi package cache ${key}: ${verdict.reason}`);
|
|
3053
|
+
await dropStamp(entry);
|
|
3054
|
+
if (verdict.part === "lockfile") {
|
|
3055
|
+
const holder = await entryInUseByOtherLaunch(entryNpm);
|
|
3056
|
+
if (holder !== null) {
|
|
3057
|
+
await clearMirrorNpm(mirrorNpm);
|
|
3058
|
+
return inUseReason(holder);
|
|
3059
|
+
}
|
|
3060
|
+
await retireEntryTree(entry, entryNpm);
|
|
3061
|
+
}
|
|
3062
|
+
const link = await linkEntry(entryNpm, mirrorNpm);
|
|
3063
|
+
return seedResult(mirrorNpm, false, link.ok ? verdict.reason : link.reason);
|
|
3064
|
+
}
|
|
3065
|
+
await writeStamp(entry, key, names, verdict.entries);
|
|
3066
|
+
const detail = verdict.lock === "absent" ? "no lockfile" : "full scan";
|
|
3067
|
+
const link = await linkEntry(entryNpm, mirrorNpm);
|
|
3068
|
+
return seedResult(mirrorNpm, link.ok, link.ok ? `cached tree verified (${verdict.packages} packages, ${detail})` : link.reason);
|
|
3069
|
+
} catch (err) {
|
|
3070
|
+
consola.debug("Pi package cache seed skipped:", err);
|
|
3071
|
+
return seedResult(mirrorNpm, false, "cache setup failed; this launch installs into its own tree");
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3074
|
+
/**
|
|
3075
|
+
* Sweep cache entries whose `npm/` tree is older than the max age. Best-effort,
|
|
3076
|
+
* never throws. Runs opportunistically at boot — and skips entries another live
|
|
3077
|
+
* launch is installing into, for the dangling-link reason spelled out on
|
|
3078
|
+
* `entryInUseByOtherLaunch`.
|
|
3079
|
+
*/
|
|
3080
|
+
async function sweepStalePiPackageCaches() {
|
|
3081
|
+
if (!piPackageCacheEnabled()) return;
|
|
3082
|
+
const root = path.join(PATHS.APP_DIR, "pi-packages");
|
|
3083
|
+
let entries;
|
|
3084
|
+
try {
|
|
3085
|
+
entries = await fs$1.readdir(root);
|
|
3086
|
+
} catch {
|
|
3087
|
+
return;
|
|
3088
|
+
}
|
|
3089
|
+
await Promise.all(entries.map(async (entry) => {
|
|
3090
|
+
const entryDir = path.join(root, entry);
|
|
3091
|
+
const npmDir = npmDirOf(entryDir);
|
|
3092
|
+
try {
|
|
3093
|
+
const holder = await entryInUseByOtherLaunch(npmDir);
|
|
3094
|
+
if (holder !== null) {
|
|
3095
|
+
consola.debug(`Pi package cache sweep: skipping ${entry}, in use by launch ${holder}.`);
|
|
3096
|
+
return;
|
|
3097
|
+
}
|
|
3098
|
+
const mtime = await mtimeMsOf(npmDir);
|
|
3099
|
+
if (mtime === null || Date.now() - mtime > piPackageCacheMaxAgeMs()) await fs$1.rm(entryDir, {
|
|
3100
|
+
recursive: true,
|
|
3101
|
+
force: true
|
|
3102
|
+
});
|
|
3103
|
+
} catch (err) {
|
|
3104
|
+
consola.debug(`Pi package cache sweep: skipping ${entry}:`, err);
|
|
3105
|
+
}
|
|
3106
|
+
}));
|
|
3107
|
+
}
|
|
2782
3108
|
// src/lib/pi-paths.ts
|
|
3109
|
+
/**
|
|
3110
|
+
* The app-data root, taken from the ONE resolver in `paths.ts`.
|
|
3111
|
+
*
|
|
3112
|
+
* This module used to carry its own `os.homedir()/"..."/github-router` copy,
|
|
3113
|
+
* which silently ignored `GH_ROUTER_APP_DIR`. That was survivable while
|
|
3114
|
+
* everything here was per-launch scratch, but the package cache made it a
|
|
3115
|
+
* correctness bug: `piPackageCacheDir` honours the override and lands under
|
|
3116
|
+
* `<override>/pi-packages`, while mirrors stayed under `~/.local/share`, so
|
|
3117
|
+
* the cache's in-use scan looked for other launches in a directory nothing
|
|
3118
|
+
* writes to and could never see one. Two resolvers for one directory is the
|
|
3119
|
+
* bug; `paths.ts` documents the same hazard for the managed install.
|
|
3120
|
+
*/
|
|
2783
3121
|
function appDir() {
|
|
2784
|
-
return
|
|
3122
|
+
return PATHS.APP_DIR;
|
|
2785
3123
|
}
|
|
2786
3124
|
/** Where the user's real Pi agent dir lives (`PI_CODING_AGENT_DIR` wins). */
|
|
2787
3125
|
function userPiAgentDir() {
|
|
@@ -2830,6 +3168,13 @@ function piSessionsDir() {
|
|
|
2830
3168
|
* Copy failures of individual user files are debug-logged and skipped —
|
|
2831
3169
|
* a corrupt user file must not strand the launch. Throws only when the
|
|
2832
3170
|
* mirror directory itself cannot be created.
|
|
3171
|
+
*
|
|
3172
|
+
* `npm/` is the one entry this copy does NOT own when the package cache is
|
|
3173
|
+
* on: `seedPiPackageCache` replaces `<mirror>/npm` with a link into the
|
|
3174
|
+
* durable cache, so copying the user's own `npm` tree there first would be a
|
|
3175
|
+
* full 27 s copy (88 MB / 14.6k files, measured) of a tree deleted moments
|
|
3176
|
+
* later. With the cache disabled the copy stays, because nothing else would
|
|
3177
|
+
* populate that path.
|
|
2833
3178
|
*/
|
|
2834
3179
|
async function ensurePiAgentMirror() {
|
|
2835
3180
|
const mirror = piMirrorDir();
|
|
@@ -2843,11 +3188,13 @@ async function ensurePiAgentMirror() {
|
|
|
2843
3188
|
return mirror;
|
|
2844
3189
|
}
|
|
2845
3190
|
const keepUserExtensions = process.env.GH_ROUTER_PI_KEEP_USER_EXTENSIONS === "1";
|
|
3191
|
+
const cacheOwnsNpm = piPackageCacheEnabled();
|
|
2846
3192
|
const SKIP = /* @__PURE__ */ new Set([
|
|
2847
3193
|
"auth.json",
|
|
2848
3194
|
"sessions",
|
|
2849
3195
|
"models-store.json",
|
|
2850
|
-
...keepUserExtensions ? [] : ["extensions"]
|
|
3196
|
+
...keepUserExtensions ? [] : ["extensions"],
|
|
3197
|
+
...cacheOwnsNpm ? ["npm"] : []
|
|
2851
3198
|
]);
|
|
2852
3199
|
await Promise.all(entries.filter((e) => !SKIP.has(e)).map(async (entry) => {
|
|
2853
3200
|
try {
|
|
@@ -2905,285 +3252,6 @@ async function sweepStalePiAgentMirrors() {
|
|
|
2905
3252
|
}
|
|
2906
3253
|
}));
|
|
2907
3254
|
}
|
|
2908
|
-
// src/lib/pi-version-check.ts
|
|
2909
|
-
const PI_NPM_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
2910
|
-
/**
|
|
2911
|
-
* Minimum Pi version the `pi` launcher supports.
|
|
2912
|
-
*
|
|
2913
|
-
* The floor is pinned to the first release whose `before_agent_start` event
|
|
2914
|
-
* carries the `messageType` discriminator (present at 1.3.0, absent at 1.1.0).
|
|
2915
|
-
* The generated extension's prompt hook stands down for non-user events using
|
|
2916
|
-
* that field, and without it the hook would fire on subagent and system turns
|
|
2917
|
-
* the user never typed, which is a wrong brief rather than a missing one.
|
|
2918
|
-
* Below-floor Pi hard-exits at the launcher (`src/pi.ts`), but only where the
|
|
2919
|
-
* gate actually runs: the install probe, the background refresh, and this floor
|
|
2920
|
-
* check all sit inside `--update-check` (default on), so `--no-update-check`
|
|
2921
|
-
* (documented for offline/CI) skips the floor as well. That path is still
|
|
2922
|
-
* fail-closed rather than silently wrong: the generated extension's own shape
|
|
2923
|
-
* probe sees the missing `messageType`, warns once with the fix, and injects
|
|
2924
|
-
* nothing.
|
|
2925
|
-
*/
|
|
2926
|
-
const PI_MIN_VERSION = "1.3.0";
|
|
2927
|
-
/**
|
|
2928
|
-
* Registry used for the PI PACKAGE ONLY.
|
|
2929
|
-
*
|
|
2930
|
-
* Pi must come from a registry that actually carries it. A corporate npm mirror
|
|
2931
|
-
* can lag npmjs far enough that its `latest` sits below `PI_MIN_VERSION`, and
|
|
2932
|
-
* the launcher then fail-closes on an upgrade command the user cannot satisfy
|
|
2933
|
-
* (their `npm install -g` resolves through the same lagging mirror). Pointing
|
|
2934
|
-
* the Pi probe and install at npmjs by default keeps the floor reachable;
|
|
2935
|
-
* `GH_ROUTER_NPM_REGISTRY` overrides it for a mirror that does carry the
|
|
2936
|
-
* package. Everything else this repo installs still resolves through the user's
|
|
2937
|
-
* configured registry.
|
|
2938
|
-
*/
|
|
2939
|
-
const PI_DEFAULT_REGISTRY = "https://registry.npmjs.org/";
|
|
2940
|
-
/**
|
|
2941
|
-
* Resolve the registry for Pi package operations. Accepts `GH_ROUTER_NPM_REGISTRY`
|
|
2942
|
-
* when it is an http(s) URL and falls back to `PI_DEFAULT_REGISTRY` with a
|
|
2943
|
-
* warning otherwise, so a typo degrades to the working default rather than
|
|
2944
|
-
* bricking the launcher.
|
|
2945
|
-
*/
|
|
2946
|
-
function resolvePiRegistry() {
|
|
2947
|
-
const raw = process.env.GH_ROUTER_NPM_REGISTRY?.trim();
|
|
2948
|
-
if (!raw) return PI_DEFAULT_REGISTRY;
|
|
2949
|
-
if (!/^https?:\/\//i.test(raw)) {
|
|
2950
|
-
consola.warn(`Ignoring GH_ROUTER_NPM_REGISTRY=${JSON.stringify(raw)}: expected an http(s) URL. Using ${PI_DEFAULT_REGISTRY}.`);
|
|
2951
|
-
return PI_DEFAULT_REGISTRY;
|
|
2952
|
-
}
|
|
2953
|
-
return raw.endsWith("/") ? raw : `${raw}/`;
|
|
2954
|
-
}
|
|
2955
|
-
/** `npm` args that pin an operation to the resolved Pi registry. */
|
|
2956
|
-
function piRegistryArgs(registry = resolvePiRegistry()) {
|
|
2957
|
-
return [`--registry=${registry}`];
|
|
2958
|
-
}
|
|
2959
|
-
const THROTTLE_HOURS = 1;
|
|
2960
|
-
const NPM_VIEW_TIMEOUT_MS = 5e3;
|
|
2961
|
-
const PI_VERSION_TIMEOUT_MS = 3e3;
|
|
2962
|
-
const NPM_INSTALL_TIMEOUT_MS = 3e5;
|
|
2963
|
-
/** Path to the throttle cache. Created on demand. Separate file from the Claude check. */
|
|
2964
|
-
function cacheFilePath() {
|
|
2965
|
-
return path.join(os.homedir(), ".local", "share", "github-router", "last-pi-update-check");
|
|
2966
|
-
}
|
|
2967
|
-
async function readCache() {
|
|
2968
|
-
try {
|
|
2969
|
-
const raw = await fs$1.readFile(cacheFilePath(), "utf8");
|
|
2970
|
-
const parsed = JSON.parse(raw);
|
|
2971
|
-
if (typeof parsed.checkedAt !== "string" || parsed.installedVersion !== null && typeof parsed.installedVersion !== "string" || parsed.latestVersion !== null && typeof parsed.latestVersion !== "string") return null;
|
|
2972
|
-
return parsed;
|
|
2973
|
-
} catch {
|
|
2974
|
-
return null;
|
|
2975
|
-
}
|
|
2976
|
-
}
|
|
2977
|
-
async function writeCache(cache) {
|
|
2978
|
-
try {
|
|
2979
|
-
await fs$1.mkdir(path.dirname(cacheFilePath()), { recursive: true });
|
|
2980
|
-
await fs$1.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 384 });
|
|
2981
|
-
} catch (err) {
|
|
2982
|
-
consola.debug("Failed to write pi version-check cache:", err);
|
|
2983
|
-
}
|
|
2984
|
-
}
|
|
2985
|
-
function shouldCheckNow(cache) {
|
|
2986
|
-
if (!cache) return true;
|
|
2987
|
-
const lastCheck = new Date(cache.checkedAt).getTime();
|
|
2988
|
-
if (Number.isNaN(lastCheck)) return true;
|
|
2989
|
-
return (Date.now() - lastCheck) / 1e3 / 3600 >= THROTTLE_HOURS;
|
|
2990
|
-
}
|
|
2991
|
-
/**
|
|
2992
|
-
* Read the installed `pi` version. Returns null if pi is not on PATH
|
|
2993
|
-
* or the version probe fails.
|
|
2994
|
-
*
|
|
2995
|
-
* Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path
|
|
2996
|
-
* (excluding the cwd) before invocation via the shared exec helper.
|
|
2997
|
-
*/
|
|
2998
|
-
async function getInstalledPiVersion() {
|
|
2999
|
-
const piPath = resolveExecutable("pi");
|
|
3000
|
-
if (!piPath) return null;
|
|
3001
|
-
try {
|
|
3002
|
-
const { stdout, code } = await runCommandCapture([piPath, "--version"], { timeoutMs: PI_VERSION_TIMEOUT_MS });
|
|
3003
|
-
if (code !== 0) return null;
|
|
3004
|
-
const match = stdout.match(/(\d+\.\d+\.\d+)/);
|
|
3005
|
-
return match ? match[1] : null;
|
|
3006
|
-
} catch {
|
|
3007
|
-
return null;
|
|
3008
|
-
}
|
|
3009
|
-
}
|
|
3010
|
-
/** Fetch the latest Pi version from npm. Null on network/npm failure. */
|
|
3011
|
-
async function getLatestPiVersion() {
|
|
3012
|
-
const npmPath = resolveExecutable("npm");
|
|
3013
|
-
if (!npmPath) return null;
|
|
3014
|
-
try {
|
|
3015
|
-
const { stdout, code } = await runCommandCapture([
|
|
3016
|
-
npmPath,
|
|
3017
|
-
"view",
|
|
3018
|
-
PI_NPM_PACKAGE,
|
|
3019
|
-
"version",
|
|
3020
|
-
"--silent",
|
|
3021
|
-
...piRegistryArgs()
|
|
3022
|
-
], { timeoutMs: NPM_VIEW_TIMEOUT_MS });
|
|
3023
|
-
if (code !== 0) return null;
|
|
3024
|
-
const v = stdout.trim();
|
|
3025
|
-
return /^\d+\.\d+\.\d+/.test(v) ? v : null;
|
|
3026
|
-
} catch {
|
|
3027
|
-
return null;
|
|
3028
|
-
}
|
|
3029
|
-
}
|
|
3030
|
-
/**
|
|
3031
|
-
* Compare two semver-shaped strings (leading X.Y.Z only). True when
|
|
3032
|
-
* `latest` is strictly higher than `installed`.
|
|
3033
|
-
*/
|
|
3034
|
-
function isPiNewer(installed, latest) {
|
|
3035
|
-
if (!installed || !latest) return false;
|
|
3036
|
-
const a = installed.split(".").map((n) => parseInt(n, 10));
|
|
3037
|
-
const b = latest.split(".").map((n) => parseInt(n, 10));
|
|
3038
|
-
for (let i = 0; i < 3; i++) {
|
|
3039
|
-
const av = a[i] ?? 0;
|
|
3040
|
-
const bv = b[i] ?? 0;
|
|
3041
|
-
if (av < bv) return true;
|
|
3042
|
-
if (av > bv) return false;
|
|
3043
|
-
}
|
|
3044
|
-
return false;
|
|
3045
|
-
}
|
|
3046
|
-
/** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */
|
|
3047
|
-
function meetsPiMinVersion(version) {
|
|
3048
|
-
if (!version) return false;
|
|
3049
|
-
return !isPiNewer(version, PI_MIN_VERSION);
|
|
3050
|
-
}
|
|
3051
|
-
/** Run a version check (subject to throttle). Side-effect: updates the cache. */
|
|
3052
|
-
async function checkPiVersion(opts = {}) {
|
|
3053
|
-
if (opts.noCheck) return {
|
|
3054
|
-
installed: false,
|
|
3055
|
-
installedVersion: null,
|
|
3056
|
-
latestVersion: null,
|
|
3057
|
-
needsUpdate: false,
|
|
3058
|
-
needsMinUpgrade: false,
|
|
3059
|
-
skipped: true,
|
|
3060
|
-
skipReason: "disabled"
|
|
3061
|
-
};
|
|
3062
|
-
const cache = await readCache();
|
|
3063
|
-
if (!opts.force && !shouldCheckNow(cache)) {
|
|
3064
|
-
const installedVersion = cache?.installedVersion ?? null;
|
|
3065
|
-
const latestVersion = cache?.latestVersion ?? null;
|
|
3066
|
-
return {
|
|
3067
|
-
installed: installedVersion !== null,
|
|
3068
|
-
installedVersion,
|
|
3069
|
-
latestVersion,
|
|
3070
|
-
needsUpdate: isPiNewer(installedVersion, latestVersion),
|
|
3071
|
-
needsMinUpgrade: !meetsPiMinVersion(installedVersion),
|
|
3072
|
-
skipped: true,
|
|
3073
|
-
skipReason: "throttled"
|
|
3074
|
-
};
|
|
3075
|
-
}
|
|
3076
|
-
const installedVersion = await getInstalledPiVersion();
|
|
3077
|
-
if (installedVersion === null) return {
|
|
3078
|
-
installed: false,
|
|
3079
|
-
installedVersion: null,
|
|
3080
|
-
latestVersion: null,
|
|
3081
|
-
needsUpdate: false,
|
|
3082
|
-
needsMinUpgrade: true,
|
|
3083
|
-
skipped: true,
|
|
3084
|
-
skipReason: "no-pi"
|
|
3085
|
-
};
|
|
3086
|
-
const latestVersion = await getLatestPiVersion();
|
|
3087
|
-
await writeCache({
|
|
3088
|
-
checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3089
|
-
installedVersion,
|
|
3090
|
-
latestVersion
|
|
3091
|
-
});
|
|
3092
|
-
if (latestVersion === null) return {
|
|
3093
|
-
installed: true,
|
|
3094
|
-
installedVersion,
|
|
3095
|
-
latestVersion: null,
|
|
3096
|
-
needsUpdate: false,
|
|
3097
|
-
needsMinUpgrade: !meetsPiMinVersion(installedVersion),
|
|
3098
|
-
skipped: true,
|
|
3099
|
-
skipReason: "no-npm"
|
|
3100
|
-
};
|
|
3101
|
-
return {
|
|
3102
|
-
installed: true,
|
|
3103
|
-
installedVersion,
|
|
3104
|
-
latestVersion,
|
|
3105
|
-
needsUpdate: isPiNewer(installedVersion, latestVersion),
|
|
3106
|
-
needsMinUpgrade: !meetsPiMinVersion(installedVersion),
|
|
3107
|
-
skipped: false
|
|
3108
|
-
};
|
|
3109
|
-
}
|
|
3110
|
-
/**
|
|
3111
|
-
* Install (or upgrade) Pi from npm under the cross-process install lock.
|
|
3112
|
-
* Returns `true` when this call performed the install, `false` when
|
|
3113
|
-
* another process holds the lock (caller skips — its install will land
|
|
3114
|
-
* for a later launch). Best-effort: throws on failure; callers fall
|
|
3115
|
-
* back to the installed version with a visible warning rather than
|
|
3116
|
-
* stranding the launch.
|
|
3117
|
-
*/
|
|
3118
|
-
function updatePi(version, opts = {}) {
|
|
3119
|
-
const npmPath = resolveExecutable("npm");
|
|
3120
|
-
if (!npmPath) throw new Error("npm not found on PATH; cannot install Pi automatically");
|
|
3121
|
-
return withInstallLock("pi-install.lock", async () => {
|
|
3122
|
-
const registry = resolvePiRegistry();
|
|
3123
|
-
consola.info(`Installing ${PI_NPM_PACKAGE}@${version} from ${registry}...`);
|
|
3124
|
-
await runCommandVoid([
|
|
3125
|
-
npmPath,
|
|
3126
|
-
"install",
|
|
3127
|
-
"-g",
|
|
3128
|
-
`${PI_NPM_PACKAGE}@${version}`,
|
|
3129
|
-
...piRegistryArgs(registry)
|
|
3130
|
-
], {
|
|
3131
|
-
timeoutMs: NPM_INSTALL_TIMEOUT_MS,
|
|
3132
|
-
signal: opts.signal
|
|
3133
|
-
});
|
|
3134
|
-
});
|
|
3135
|
-
}
|
|
3136
|
-
/**
|
|
3137
|
-
* Blocking fresh install for when Pi is absent entirely. Installs
|
|
3138
|
-
* `@latest`, then force re-checks; throws when Pi still is not on PATH
|
|
3139
|
-
* (caller exits with the install command). Only used when there is no
|
|
3140
|
-
* usable Pi at all — the healthy path never blocks on npm.
|
|
3141
|
-
*/
|
|
3142
|
-
async function ensurePiInstalled(opts = {}) {
|
|
3143
|
-
const acquired = await updatePi("latest", opts);
|
|
3144
|
-
const retry = await checkPiVersion({ force: true });
|
|
3145
|
-
if (retry.installed && retry.installedVersion) return retry.installedVersion;
|
|
3146
|
-
throw new Error(acquired ? "install did not place pi on PATH" : "another Pi install is already running; retry in a moment");
|
|
3147
|
-
}
|
|
3148
|
-
/**
|
|
3149
|
-
* Fire-and-forget freshness refresh for a healthy Pi install. Never
|
|
3150
|
-
* blocks launch and never throws: on the throttled schedule it probes
|
|
3151
|
-
* npm for a newer Pi and, when one exists, queues a DETACHED post-exit
|
|
3152
|
-
* install (same pattern as the proxy self-update) so neither startup
|
|
3153
|
-
* nor the running session nor shutdown ever waits on npm. The
|
|
3154
|
-
* cross-process install lock serializes against concurrent launches;
|
|
3155
|
-
* every failure degrades to a debug log.
|
|
3156
|
-
*
|
|
3157
|
-
* Deliberately never touches a below-floor install: the floor is
|
|
3158
|
-
* enforced foreground by the launcher (fail-closed), and a background
|
|
3159
|
-
* task must not change what the running session validated.
|
|
3160
|
-
*/
|
|
3161
|
-
function refreshPiInBackground(opts) {
|
|
3162
|
-
if (!opts.autoUpdate) return;
|
|
3163
|
-
(async () => {
|
|
3164
|
-
try {
|
|
3165
|
-
if (!shouldCheckNow(await readCache())) return;
|
|
3166
|
-
const installedVersion = await getInstalledPiVersion();
|
|
3167
|
-
if (!meetsPiMinVersion(installedVersion)) return;
|
|
3168
|
-
const npmPath = resolveExecutable("npm");
|
|
3169
|
-
const latestVersion = await getLatestPiVersion();
|
|
3170
|
-
await writeCache({
|
|
3171
|
-
checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3172
|
-
installedVersion,
|
|
3173
|
-
latestVersion
|
|
3174
|
-
});
|
|
3175
|
-
if (!npmPath) return;
|
|
3176
|
-
if (!latestVersion || !isPiNewer(installedVersion, latestVersion)) return;
|
|
3177
|
-
if (await withInstallLock("pi-install.lock", async () => {
|
|
3178
|
-
queueDetachedGlobalInstall(npmPath, `@earendil-works/pi-coding-agent@${latestVersion}`, piRegistryArgs());
|
|
3179
|
-
})) consola.info(`Pi ${installedVersion} → ${latestVersion} update queued; it takes effect on the next launch.`);
|
|
3180
|
-
} catch (err) {
|
|
3181
|
-
consola.debug("Background Pi refresh failed:", err);
|
|
3182
|
-
}
|
|
3183
|
-
})().catch((err) => {
|
|
3184
|
-
consola.debug("Background Pi refresh failed:", err);
|
|
3185
|
-
});
|
|
3186
|
-
}
|
|
3187
3255
|
// src/lib/proxy.ts
|
|
3188
3256
|
let socketCounter = 0;
|
|
3189
3257
|
/**
|
|
@@ -3535,7 +3603,7 @@ function collectToolFieldKeys(body) {
|
|
|
3535
3603
|
}
|
|
3536
3604
|
// package.json
|
|
3537
3605
|
var name = "github-router";
|
|
3538
|
-
var version = "0.3.
|
|
3606
|
+
var version = "0.3.381";
|
|
3539
3607
|
// src/lib/approval.ts
|
|
3540
3608
|
const awaitApproval = async () => {
|
|
3541
3609
|
if (!await consola.prompt(`Accept incoming request?`, { type: "confirm" })) throw new HTTPError("Request rejected by user", Response.json({ message: "Request rejected by user" }, { status: 403 }));
|
|
@@ -9533,6 +9601,6 @@ function getPiLaunchEnvVars(mirrorDir) {
|
|
|
9533
9601
|
if (toolbeltEnabled()) Object.assign(vars, toolbeltPathOverride(process.env, PATHS.TOOLBELT_BIN_DIR));
|
|
9534
9602
|
return vars;
|
|
9535
9603
|
}
|
|
9536
|
-
export {
|
|
9604
|
+
export { MAX_BROWSE_LOW_ALIAS_ID as A, validateCheap1mProfilePrerequisites as B, CHEAPEST_GENERAL_PURPOSE_ALIAS_ID as C, CHEAP_PLAN_ALIAS_ID as D, CHEAP_GENERAL_PURPOSE_ALIAS_ID as E, formatFastPrerequisiteFailure as F, validateMaxProfileLaunch as G, validateCheapestProfilePrerequisites as H, formatLocalPrerequisiteFailure as I, profileDescriptor as L, formatCheap1mPrerequisiteFailure as M, formatCheapPrerequisiteFailure as N, CHEAP_REVIEWER_ALIAS_ID as O, formatCheapestPrerequisiteFailure as P, resolveLaunchProfile as R, CHEAPEST_EXPLORE_ALIAS_ID as S, CHEAP_EXPLORE_ALIAS_ID as T, validateFastProfilePrerequisites as U, validateCheapProfilePrerequisites as V, validateLocalProfilePrerequisites as W, enableFileLogging as _, setupAndServe as a, BALANCED_REVIEWER_ALIAS_ID as b, ensurePiAgentMirror as c, seedPiPackageCache as d, sweepStalePiPackageCaches as f, listModelsForEndpoint as g, injectModelPickerSettingsFile as h, parseSharedArgs as i, formatBalancedPrerequisiteFailure as j, LUNA_SCOUT_ALIAS_ID as k, removeOwnPiAgentMirror as l, stopKeepAwake as m, getCodexEnvVars as n, sharedServerArgs as o, startKeepAwake as p, getPiLaunchEnvVars as r, LAUNCH_SECRET_HEADER as s, getClaudeCodeEnvVars as t, sweepStalePiAgentMirrors as u, BALANCED_EXPLORE_ALIAS_ID as v, CHEAPEST_REVIEWER_ALIAS_ID as w, BROWSE_LOW_ALIAS_ID as x, BALANCED_GENERAL_PURPOSE_ALIAS_ID as y, validateBalancedProfilePrerequisites as z };
|
|
9537
9605
|
|
|
9538
|
-
//# sourceMappingURL=server-setup-
|
|
9606
|
+
//# sourceMappingURL=server-setup-byIhjgOb.js.map
|