github-router 0.3.380 → 0.3.382

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/ado-tools-CNEWS1kF.js +1 -0
  2. package/dist/{attribution-settings-BJ1fjX7V.js → attribution-settings-BhQmS2u9.js} +23 -26
  3. package/dist/{attribution-settings-BJ1fjX7V.js.map → attribution-settings-BhQmS2u9.js.map} +1 -1
  4. package/dist/browser-ext/manifest.json +1 -1
  5. package/dist/{claude-BWwkOMi3.js → claude-B9Mw8x0M.js} +12 -12
  6. package/dist/{claude-BWwkOMi3.js.map → claude-B9Mw8x0M.js.map} +1 -1
  7. package/dist/{claude-md-injection-DNMDcw1W.js → claude-md-injection-DiokMV4p.js} +16 -7
  8. package/dist/claude-md-injection-DiokMV4p.js.map +1 -0
  9. package/dist/{codex-C6ix3BaY.js → codex-DiybqRAO.js} +5 -5
  10. package/dist/{codex-C6ix3BaY.js.map → codex-DiybqRAO.js.map} +1 -1
  11. package/dist/engine-DCR1lSsw.js +1 -0
  12. package/dist/{gate-discovery-2ILpM2fi.js → gate-discovery-DCdds1gg.js} +2 -2
  13. package/dist/{gate-discovery-2ILpM2fi.js.map → gate-discovery-DCdds1gg.js.map} +1 -1
  14. package/dist/{internal-max-dispatch-guard-DeEfWqfP.js → internal-max-dispatch-guard-CXaZ5TTR.js} +1 -1
  15. package/dist/{internal-max-dispatch-guard-4RLca1i5.js → internal-max-dispatch-guard-sjBGijoa.js} +2 -2
  16. package/dist/{internal-max-dispatch-guard-4RLca1i5.js.map → internal-max-dispatch-guard-sjBGijoa.js.map} +1 -1
  17. package/dist/{internal-prompt-submit-BZ2-CExM.js → internal-prompt-submit-C_QigwLP.js} +2 -2
  18. package/dist/{internal-prompt-submit-BZ2-CExM.js.map → internal-prompt-submit-C_QigwLP.js.map} +1 -1
  19. package/dist/{internal-prompt-submit-ZBhH-SQ1.js → internal-prompt-submit-DBmCOUfy.js} +2 -2
  20. package/dist/{internal-rebrief-BIWbN7Sr.js → internal-rebrief-CjaEXHIo.js} +3 -3
  21. package/dist/{internal-rebrief-BIWbN7Sr.js.map → internal-rebrief-CjaEXHIo.js.map} +1 -1
  22. package/dist/{internal-stop-hook-cDF1MuJZ.js → internal-stop-hook-CcXuDASI.js} +2 -2
  23. package/dist/{internal-stop-hook-cDF1MuJZ.js.map → internal-stop-hook-CcXuDASI.js.map} +1 -1
  24. package/dist/main.js +9 -9
  25. package/dist/{max-profile-contract-DbHwiLTx.js → max-profile-contract-CEn8hKb3.js} +60 -60
  26. package/dist/{max-profile-contract-DbHwiLTx.js.map → max-profile-contract-CEn8hKb3.js.map} +1 -1
  27. package/dist/{peer-mcp-personas-Dny0r5Am.js → peer-mcp-personas-Ckbn70c5.js} +40 -40
  28. package/dist/{peer-mcp-personas-Dny0r5Am.js.map → peer-mcp-personas-Ckbn70c5.js.map} +1 -1
  29. package/dist/{pi-YhoA26wi.js → pi-D9IbxlSj.js} +88 -180
  30. package/dist/pi-D9IbxlSj.js.map +1 -0
  31. package/dist/{provision-BWtuDq_v.js → provision-BY5pXtSG.js} +2 -2
  32. package/dist/{provision-BWtuDq_v.js.map → provision-BY5pXtSG.js.map} +1 -1
  33. package/dist/{serve-DrHAX2Bh.js → serve-DPPh7goh.js} +7 -7
  34. package/dist/{serve-DrHAX2Bh.js.map → serve-DPPh7goh.js.map} +1 -1
  35. package/dist/{server-setup-DLwejgVA.js → server-setup-CVMUKERN.js} +703 -9
  36. package/dist/server-setup-CVMUKERN.js.map +1 -0
  37. package/dist/{start-DvV3Lbwy.js → start-B7z2Mg2B.js} +3 -3
  38. package/dist/{start-DvV3Lbwy.js.map → start-B7z2Mg2B.js.map} +1 -1
  39. package/dist/{static-context-pack-BKFelEbM.js → static-context-pack-DdQpWwQN.js} +140 -140
  40. package/dist/{static-context-pack-BKFelEbM.js.map → static-context-pack-DdQpWwQN.js.map} +1 -1
  41. package/dist/{workiq-tools-DdiQ2DOW.js → workiq-tools-3K9WKiQ2.js} +1 -1
  42. package/package.json +1 -1
  43. package/dist/ado-tools-CsfbnY8x.js +0 -1
  44. package/dist/claude-md-injection-DNMDcw1W.js.map +0 -1
  45. package/dist/engine-B6la_uIW.js +0 -1
  46. package/dist/pi-YhoA26wi.js.map +0 -1
  47. package/dist/server-setup-DLwejgVA.js.map +0 -1
@@ -1,15 +1,16 @@
1
1
  import { i as ensurePaths, t as PATHS } from "./paths-DeFmYJhO.js";
2
2
  import { t as state } from "./state-CCGDJ43X.js";
3
+ import { i as writeFileAtomic } from "./atomic-file-Dif1kLKM.js";
3
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";
4
5
  import { r as fetchWithTransientRetry } from "./upstream-retry-VNR-bCuT.js";
5
6
  import { t as getCopilotUsage } from "./get-copilot-usage-BZ6t2hFZ.js";
6
7
  import { a as parseBoolEnv, i as killManagedTree, s as resolveExecutable } from "./exec-BC0MAnoA.js";
7
8
  import { l as resolvePiRegistry } from "./pi-version-check-BeBB0Ny9.js";
8
- 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";
9
- 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";
10
- 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";
9
+ import { $ as buildAnthropicErrorEvent, $n as UPSTREAM_INACTIVITY_TIMEOUT_MS, 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, Gn as toolbeltPathOverride, 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, Qn as UPSTREAM_FETCH_TIMEOUT_MS, 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, Z as repairKnownThinkingHistory, _n as LAUNCH_BOUND_TOKEN_PREFIX, _t as provisionWorkiqTools, ar as upstreamMaxConnections, at as EFFORT_ORDER, cn as shimDefaultsToXhigh, cr as oneMContextDisabled, ct as clampEffort, dn as getTokenizerFromModel, dr as CHEAP_PROFILE_ADVISOR_CLIENT_MODEL, dt as normalizeAnthropicUsageInPlace, er as generateRandomPort, et as buildOpenAIErrorEvent, fr as CHEAP_PROFILE_MODELS, ft as handleMcpDelete, gn as createMessages, gr as CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS, hn as countTokens, i as assertMcpToolSurfaceConsistent, ir as upstreamAllowH2, it as relayAnthropicStream, jn as normalizeOpenAIUsage, kn as readResponseBodyCapped, ln as getTextTokenCount, lr as withOneMSuffix, lt as anthropicUsageNormalizeDisabled, mn as localSessionId, nt as logStreamError, or as classifyMessagesRoute, ot as UNKNOWN_EFFORT_ANCHOR, pn as localBaseUrl, pr as CHEAP_PROFILE_NATIVE_AGENT_NAMES, pt as handleMcpPost, q as resolveAdvisorModel, qn as BUDGET_SMALL_FAST_SLUG, rt as readIteratorWithTimeout, sr as catalogAdvertises1M, st as bucketEffort, tr as isBudgetClaudeLead, tt as isControllerClosedError, un as getTokenCount, ur as withOneMSuffixForLead, ut as createAnthropicUsageRewriteTransform, vn as findLaunchBySecret, wn as warnOnTokenPriceDrift, wt as normalizeAdoToolsets, xn as rememberLaunchSessionId, z as CHEAPLOCAL_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS, zn as effectiveLocalProfile } from "./peer-mcp-personas-Ckbn70c5.js";
10
+ import { C as stripTrailingOneMSuffix, S as normalizeTrailingOneMSuffix, a as MAX_PROFILE_NATIVE_AGENT_NAMES, d as maxAdvisorPinIsValid, h as maxOpusModel, i as MAX_PROFILE_MODELS, l as maxAdvisorEffortForModel, n as MAX_PROFILE_ALLOWED_LEAD_MODEL_IDS, t as MAX_PROFILE_ADVISOR_INSTRUCTIONS, u as maxAdvisorModelFromPin, x as fastEndpointForModel, y as validateMaxProfilePrerequisites } from "./max-profile-contract-CEn8hKb3.js";
11
11
  import { i as BALANCED_PROFILE_NATIVE_AGENT_NAMES, r as BALANCED_PROFILE_MODELS } from "./balanced-profile-contract-B6pSoWjm.js";
12
- 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";
12
+ import { A as CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL, C as localContractFor, D as LOCAL_PROFILE_TIER_MODELS, F as CHEAPEST_PROFILE_MODELS, I as CHEAPEST_PROFILE_NATIVE_AGENT_NAMES, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, g as displayModelName, p as cheapestContractFor, v as isCheapestFamily, x as isPinnedLaunchProfile } from "./static-context-pack-DdQpWwQN.js";
13
+ 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";
13
14
  import { f as getAzureRepoFromGit } from "./bluebird-client-BasIdv5J.js";
14
15
  import { I as provisionTreeSitterAssets } from "./service-backend-BdhWVRSz.js";
15
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";
@@ -2432,9 +2433,693 @@ function deriveAutoCompactWindowTokens(maxPromptTokens, maxOutputTokens) {
2432
2433
  const window = assumedClientWindowTokens + CLIENT_THRESHOLD_RESERVE_TOKENS;
2433
2434
  return Math.min(ENV_WINDOW_MAX_TOKENS, Math.max(ENV_WINDOW_MIN_TOKENS, window));
2434
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
+ }
2435
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
+ */
2436
3121
  function appDir() {
2437
- return path.join(os.homedir(), ".local", "share", "github-router");
3122
+ return PATHS.APP_DIR;
2438
3123
  }
2439
3124
  /** Where the user's real Pi agent dir lives (`PI_CODING_AGENT_DIR` wins). */
2440
3125
  function userPiAgentDir() {
@@ -2483,6 +3168,13 @@ function piSessionsDir() {
2483
3168
  * Copy failures of individual user files are debug-logged and skipped —
2484
3169
  * a corrupt user file must not strand the launch. Throws only when the
2485
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.
2486
3178
  */
2487
3179
  async function ensurePiAgentMirror() {
2488
3180
  const mirror = piMirrorDir();
@@ -2496,11 +3188,13 @@ async function ensurePiAgentMirror() {
2496
3188
  return mirror;
2497
3189
  }
2498
3190
  const keepUserExtensions = process.env.GH_ROUTER_PI_KEEP_USER_EXTENSIONS === "1";
3191
+ const cacheOwnsNpm = piPackageCacheEnabled();
2499
3192
  const SKIP = /* @__PURE__ */ new Set([
2500
3193
  "auth.json",
2501
3194
  "sessions",
2502
3195
  "models-store.json",
2503
- ...keepUserExtensions ? [] : ["extensions"]
3196
+ ...keepUserExtensions ? [] : ["extensions"],
3197
+ ...cacheOwnsNpm ? ["npm"] : []
2504
3198
  ]);
2505
3199
  await Promise.all(entries.filter((e) => !SKIP.has(e)).map(async (entry) => {
2506
3200
  try {
@@ -2909,7 +3603,7 @@ function collectToolFieldKeys(body) {
2909
3603
  }
2910
3604
  // package.json
2911
3605
  var name = "github-router";
2912
- var version = "0.3.380";
3606
+ var version = "0.3.382";
2913
3607
  // src/lib/approval.ts
2914
3608
  const awaitApproval = async () => {
2915
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 }));
@@ -8907,6 +9601,6 @@ function getPiLaunchEnvVars(mirrorDir) {
8907
9601
  if (toolbeltEnabled()) Object.assign(vars, toolbeltPathOverride(process.env, PATHS.TOOLBELT_BIN_DIR));
8908
9602
  return vars;
8909
9603
  }
8910
- export { formatCheap1mPrerequisiteFailure as A, validateCheapestProfilePrerequisites as B, CHEAP_EXPLORE_ALIAS_ID as C, LUNA_SCOUT_ALIAS_ID as D, CHEAP_REVIEWER_ALIAS_ID as E, profileDescriptor as F, validateLocalProfilePrerequisites as H, resolveLaunchProfile as I, validateBalancedProfilePrerequisites as L, formatCheapestPrerequisiteFailure as M, formatFastPrerequisiteFailure as N, MAX_BROWSE_LOW_ALIAS_ID as O, formatLocalPrerequisiteFailure as P, validateCheap1mProfilePrerequisites as R, CHEAPEST_REVIEWER_ALIAS_ID as S, CHEAP_PLAN_ALIAS_ID as T, validateMaxProfileLaunch as U, validateFastProfilePrerequisites as V, BALANCED_GENERAL_PURPOSE_ALIAS_ID as _, setupAndServe as a, CHEAPEST_EXPLORE_ALIAS_ID as b, ensurePiAgentMirror as c, startKeepAwake as d, stopKeepAwake as f, BALANCED_EXPLORE_ALIAS_ID as g, enableFileLogging as h, parseSharedArgs as i, formatCheapPrerequisiteFailure as j, formatBalancedPrerequisiteFailure as k, removeOwnPiAgentMirror as l, listModelsForEndpoint as m, getCodexEnvVars as n, sharedServerArgs as o, injectModelPickerSettingsFile as p, getPiLaunchEnvVars as r, LAUNCH_SECRET_HEADER as s, getClaudeCodeEnvVars as t, sweepStalePiAgentMirrors as u, BALANCED_REVIEWER_ALIAS_ID as v, CHEAP_GENERAL_PURPOSE_ALIAS_ID as w, CHEAPEST_GENERAL_PURPOSE_ALIAS_ID as x, BROWSE_LOW_ALIAS_ID as y, validateCheapProfilePrerequisites as z };
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 };
8911
9605
 
8912
- //# sourceMappingURL=server-setup-DLwejgVA.js.map
9606
+ //# sourceMappingURL=server-setup-CVMUKERN.js.map