Files
thedotmack-claude-mem/plugin/scripts/transcript-watcher.cjs
Alex Newman edc5cf7d59 Ponytail audit (−10.4k lines) + worker-restart hardening + deterministic dependency closure (#3021)
* plan-10 Phase 1: ship deterministic plugin runtime dependency closure

Approach A — commit & ship plugin/bun.lock so the plugin's runtime
node_modules install is deterministic, fixing the recurring
`Cannot find module 'zod/v3'` (#2730).

- align generated plugin zod range to root (^4.4.3) in build-hooks.js
- new scripts/gen-plugin-lockfile.cjs generates plugin/bun.lock as a
  build artifact after build-hooks.js writes plugin/package.json
- track & ship plugin/bun.lock (.gitignore negation, .npmignore, files allowlist)
- install with `bun install --frozen-lockfile --ignore-scripts` at runtime

Refs #2783, #2730

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* plan-10 Phase 2: fail loud at install time on a broken dependency closure

Strengthen verifyCriticalModules to assert each dependency is actually
importable via require.resolve (not merely a directory), and assert the
worker-required zod subpaths resolve: zod/v3, zod/v4, zod/v4-mini.
A partial/stale install now fails `npx claude-mem install` immediately
instead of surfacing later as a Stop-hook `Cannot find module 'zod/v3'`.

Bin-only packages (e.g. tree-sitter-cli, which has no bare-name entry
point) fall back to resolving <dep>/package.json so a healthy install
isn't falsely rejected.

Adds tests/cli/verify-critical-modules.test.ts covering a missing zod/v3
subpath (throws), a complete zod (passes), and a bin-only dep (passes).

Refs #2783, #2730

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* plan-10 Phase 3: clean-room install + import smoke test (#2730 backstop)

Add scripts/smoke-clean-room.cjs and a `smoke:clean-room` npm script.
Against fresh temp dirs (never the repo's node_modules) it:
- copies plugin/, runs `bun install --frozen-lockfile --ignore-scripts`,
  asserts zod, zod/v3, zod/v4, zod/v4-mini resolve, and boots the bundled
  worker asserting no `Cannot find module` — the direct #2730 regression guard;
- `npm pack`s, installs the tarball into a second temp dir, and load-tests
  the published bin entrypoint, warning loudly on any declared main/exports
  target missing from the tarball (latent #2537 gap).

Exits non-zero naming the missing module on any failure; cleans up all
temp dirs and the tarball in a finally.

Refs #2783, #2730

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* plan-10 Phase 4: gate CI and publish on the clean-room dependency closure

- ci.yml: new `clean-room-deps` job (between build and the docker e2e job)
  runs a frozen-lockfile drift check on the committed plugin lockfile, then
  `npm run build` + `npm run smoke:clean-room`. The drift step catches a
  contributor who changed plugin deps without regenerating plugin/bun.lock.
- npm-publish.yml: add setup-bun and run `npm run smoke:clean-room` between
  build and `npm publish`, so a broken runtime closure cannot be published
  on a tag push (ci.yml does not run on tags). Secrets block untouched.

Refs #2783, #2730

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* plan-10: doc recluster note + Phase 0 execution slice for #2730

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* plans: backlog recluster (2026-06-04) — cross-cluster execution order + plan-13 doc

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* plan-10: gen-plugin-lockfile degrades gracefully when bun is absent

The Windows build CI job has no bun on PATH; regenerating the lockfile there
threw and failed the build. The committed plugin/bun.lock is already the
deterministic closure, so skip regeneration (non-fatal) when bun is missing
and a lockfile exists; fail loud only when neither is available.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: rebuild plugin artifacts after merging main (v13.5.1) + plan-10 work

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: rebuild plugin artifacts after merging main v13.5.5

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(deps): daily upgrade pass — agent SDK 0.3.172, better-auth 1.6.16, posthog-node 5.36.15, dompurify 3.4.9

- Bump @anthropic-ai/claude-agent-sdk 0.2.141 -> 0.3.172 (tsc + full test suite green)
- Remove deprecated @types/dompurify stub (dompurify ships its own types)
- Add overrides.tmp ^0.2.7 to clear GHSA-52f5-9888-hmc6 / GHSA-ph9p-34f9-6g65
  via np -> listr-input -> inquirer -> external-editor -> tmp chain
- npm audit: 0 vulnerabilities; npm outdated: clean
- package-lock.json is gitignored in this repo, so not committed

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* plan: worker-restart single-source-of-truth — 7-phase fix for restart races

Phased plan from the adversarially-verified diagnosis (wf_f07f3541-b05):
kill the cache mirror, single verified restart initiator, self-replacing
restart endpoint, unified spawn gate with lockfile, PID-file demotion,
test data-dir isolation, soak verification.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(restart): delete sync-script cache-mirror and HTTP restart trigger

Phase 1 of plans/2026-06-10-worker-restart-single-source-of-truth.md.
The installed-version cache mirror wrote version-N code into the
version-(N-1) cache dir, manufacturing permanent version disagreement;
the HTTP POST to /api/admin/restart raced the CLI restart that follows
it in build-and-sync. Both are deleted; the CLI worker:restart in the
marketplace copy is now the single restart initiator, and the sleep 1
between the two mechanisms is gone.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(restart): restart proves itself or exits 1

Phase 2 of plans/2026-06-10-worker-restart-single-source-of-truth.md.
worker-service restart now captures the old worker pid, waits for the
port with the same platform-scaled 15s budget as stop, spawns the
marketplace copy of worker-service.cjs when present, then polls
/api/health until the pid changes and the version matches this build's
baked __DEFAULT_PACKAGE_VERSION__ — success is printed to stdout,
deadline (platform-scaled 30s) exits 1 with the last observed health
payload and the spawned script path. The --daemon generic start-failure
path now exits 1 instead of masquerading as success; the three
duplicate-suppression exits remain 0.

New helper src/services/restart-verify.ts (worker-service.ts bootstraps
on import, so the helper lives in an import-safe module) with 8 tests
covering pid-flip success, stale pid, wrong version, unreachable
timeout, 503-degraded acceptance, and null-oldPid version-only
verification.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(restart): self-replacing worker — old worker spawns its successor

Phase 3 of plans/2026-06-10-worker-restart-single-source-of-truth.md.
/api/admin/restart was kill-only: hooks that POSTed it then raced the
dying worker with their own lazy-spawn (the observed recycle ping-pong).
Now the dying worker spawns its successor itself — after a re-entrancy-
guarded, deadline-bounded (platform-scaled 10s) graceful shutdown, and
only once its port is confirmed free; stop and signal shutdowns stay
kill-only. The hook recycle path waits for that successor via
/api/health polling (HOOK_READINESS_TIMEOUT_MS budget) and lazy-spawns
only as a fallback, with a warn-only version re-check so a hook never
recycles more than once per invocation.

Shutdown sequence lives in import-safe src/services/worker-shutdown.ts
(worker-service.ts bootstraps on import); registerSignalHandlers no
longer pre-sets isShuttingDown — the supervisor's shutdownInitiated
guard owns signal dedupe, and pre-setting would no-op the new entry
guard. 13 new tests cover re-entrancy, deadline expiry/rejection,
handoff ordering, kill-only reasons, successor-wait vs lazy-spawn
fallback, and pre-graceful bookkeeping failures.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(restart): one spawn gate; CLI restart defers to the self-replacing worker

Phase 4 of plans/2026-06-10-worker-restart-single-source-of-truth.md.
Three uncoordinated spawn paths (hook lazy-spawn, MCP worker-spawner,
CLI) with two different bun resolvers produced 3-launcher collisions
within a single second. Now a wx-flag lockfile (<DATA_DIR>/spawn.lock,
60s mtime staleness with re-stat-before-unlink, owner-checked release)
gates every external spawn: lock losers never fail — they skip the
spawn and wait for the winner's worker. resolveBunRuntime is deleted in
favor of ProcessManager's resolveWorkerRuntimePath (adds BUN_PATH,
~/.bun/bin, brew, which fallbacks), closing the kill-then-can't-respawn
path; mcp-server prefers the marketplace worker script so stale cache
dirs stop spawning stale workers.

Integration fix surfaced by live verification: the CLI restart raced
the Phase 3 self-replacement handoff (the successor re-binds the port
in ~200ms, so waitForPortFree always timed out and restart exited 1
while the restart had actually succeeded). The CLI now verifies the
worker's self-spawned successor directly, and only spawns — gate-
wrapped, after the port frees — as the fallback when no worker was
running, the shutdown POST was rejected, or no successor appeared. The
dying worker's handoff is intentionally ungated: it spawns only after
its own port closes, and hooks wait on it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(restart): demote the PID file — health and port are the liveness oracle

Phase 5 of plans/2026-06-10-worker-restart-single-source-of-truth.md.
The dying worker's shutdown cascade deleted the PID file
unconditionally as its final act, clobbering the successor's
freshly-written file; status then required portInUse AND pidInfo, so a
healthy worker reported as "not running". Now every PID-file deletion
is owner-guarded: the supervisor cascade deletes only its own pid
(removeOwnedPidFile), and the CLI stop/restart-fallback, the restart
handoff, and the daemon start-failure cleanup go through
removePidFileIfOwner (owner-or-dead — a live successor's file always
survives; corrupt files are left for the next boot's validator).

status sources from GET /api/health alone (pid, version, uptime,
workerPath; 503-degraded counts as running and now surfaces its queue
detail), with port-in-use-but-unreachable and not-running fallbacks —
all exit 0 as before. The --daemon duplicate gate checks the port
first (ground truth) and the PID file second (advisory, for the
freed-port-but-undeleted-file window); duplicate suppression stays
exit 0. writePidFile/touchPidFile remain — the file is diagnostics,
and the worker stays its only writer.

Also fixes combined-run test pollution: spawn-gate and worker-utils
timeout tests now eagerly import paths.js before setting a temp
CLAUDE_MEM_DATA_DIR, so the import-time DATA_DIR const can't freeze on
a deleted temp dir for suites loaded later in the same bun process.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: no test ever touches the real ~/.claude-mem again

Phase 6 of plans/2026-06-10-worker-restart-single-source-of-truth.md.
process-manager and graceful-shutdown tests wrote corrupt JSON and
sentinel PIDs (2147483647) into the real ~/.claude-mem/worker.pid and
drove the real supervisor.json cascade under a snapshot-restore that a
killed run would skip — that pollution contaminated production logs and
a prior diagnosis. Both files now set a temp CLAUDE_MEM_DATA_DIR at the
top of the file before dynamically importing the code under test (ESM
hoisting makes beforeEach too late), assert their paths landed outside
the real dir, and derive PID_FILE from the same frozen paths module the
code uses so test and code can never diverge under bun's shared module
cache. The snapshot-restore scaffolding is deleted; zero assertions
changed.

tests/preload.ts gains a tripwire: when CLAUDE_MEM_DATA_DIR is unset it
fills a per-run temp dir, so no test in any file can fall through to
the real data dir. Fallout made explicit: worker-spawn child processes
get an explicit temp dir; install-error-matrix restores rather than
deletes the env var; settings-defaults-manager pins the unset-env
default it was implicitly relying on.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(settings): bootstrap notices go to stderr, never stdout

CI on PR #2894 caught the latent bug: on the first boot in a fresh data
dir, SettingsDefaultsManager printed '[SETTINGS] Created settings file
with defaults: ...' to stdout before the start command's JSON hook
payload, corrupting the machine-readable contract every fresh install's
first hook invocation relies on. The Phase 6 per-run temp data dir made
the cold-dir case deterministic in CI, exposing it. Both informational
notices (creation, nested-schema migration) now use console.warn —
stderr — matching the function's existing failure-path idiom; two
regression tests pin stdout silence on both paths.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(restart): address PR #2894 review — dedupe script resolver, skip futile port wait

Both inline copies of the marketplace-first script-candidate list in
worker-service.ts (restart fallback + successor handoff injection) now
call the exported resolveWorkerScriptPath() ?? __filename, so the
candidate list lives in one place. verifyRestartedWorker's failure
result gains lastPollSawHealth; when the self-replacement handoff
verification timed out while a live (but unverifiable) worker was still
serving on the port, the CLI fallback now skips its port-free wait —
the port cannot free while that worker lives, so the wait only burned
its full platform-scaled budget before the same final verification ran
anyway.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(sdk): stale Claude CLI can no longer silently kill every observation

findClaudeExecutable validated candidates with --version only, so an
abandoned old install shadowing a current CLI in PATH (e.g. npm-global
2.0.42 next to the auto-updating native installer) passed validation,
then died at every Observer spawn: the SDK passes --permission-mode
dontAsk (hardened-options) which old CLIs reject with exit 1. Result:
healthy worker, zero observations, no visible error (#2782 family;
previously #1857/#2049/#1866/#2142 in the same class).

- Probe every candidate (which -a + known install paths) with
  `--permission-mode dontAsk --version`: one spawn proves both flag
  compatibility and version, no API call (~150ms)
- Prefer the newest capable version; PATH order only breaks ties
- Explicit CLAUDE_CODE_PATH still wins but fails loud with version and
  remedy when too old, instead of dying silently at spawn
- All-too-old throws an error naming each candidate, its version, and
  how to fix; resolution success logs at INFO with the chosen version
- Cache successful resolution 15 min (resolver runs per SDK query);
  never cache failure so a CLI update is picked up without restart
- SDK child keeps a 2KB stderr tail and includes it in the exit WARN,
  so "unknown option" deaths are diagnosable at default log level

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(audit): add ponytail audit master plan + SQLite removal companion

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(slice-0): remove commit-hash fabrication verification

Removes the commit-verification system whose second-system effects (greedy hex
regex false-positives + compensating scaffolding) cost more than the edge case
it caught. Deletes src/sdk/commit-verification.ts + its 2 tests, the
verify-before-persist block + stripFabricatedHashesFromSummary in
ResponseProcessor, and the now-dead fabricated_count/fabrication_* telemetry
in buffer.ts/scrub.ts/npx-cli telemetry.ts.

Consequence: PostHog Fabrication Rate tile goes dark (no other producer).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(slice-1): remove duplicate SQLite stack, test the shipping path

Two parallel SQLite systems lived in src/services/sqlite/. The worker only ever
used SessionStore (which runs its own inline migrations); the second stack —
ClaudeMemDatabase/MigrationRunner + a free-function CRUD API — was reachable only
from tests. This removes the dead duplicate and rewrites its tests against the
real SessionStore path.

Deleted: Database.ts, migrations/runner.ts, index.ts, SchemaRepair.ts, all 6 CRUD
barrels, transactions.ts, and the sessions/summaries/prompts/timeline/import
submodules (18 files). Trimmed the 5 survivor leaf functions to their single live
export. Removed dead SessionStore methods getSessionSummaryById (broken) and
storeObservationsAndMarkComplete (0 callers).

Replaced 9 old test files (coupled to the dead stack) with 7 focused
session-store-*.test.ts suites + a rewritten cleanup-v12_4_3 test, all exercising
the worker's real path.

Net ~-3,262 src lines. tsc clean; full suite 2253 pass / 0 fail; dead-reference
sweep zero. No production behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(slice-6): drop dead storage methods, dedupe EnvManager, stdlib swaps

Dead-code deletes (all zero-caller verified): sqlite ProjectsRepository.upsert +
getByRootPath, ServerSessionsRepository.getByMemorySessionId,
MemoryItemsRepository.getByLegacyObservationId, pg AgentEventsRepository.createMany
+ TeamsRepository.getMember; shared getWorkerSocketPath, createBackupFilename, and
the deprecated ENV_FILE_PATH const.

Refactors (behavior-preserving): EnvManager's three open-coded 5-key credential
blocks collapse to one CREDENTIAL_KEYS loop (whitelist semantics kept, no
Object.assign); parseEnvFile line-parser → util.parseEnv; fetchWithTimeout's manual
setTimeout race → AbortSignal.timeout (caller timeout-message contract preserved).

Net ~-106 lines. tsc clean; full suite 2253 pass / 0 fail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(slice-4): sweep dead/redundant code from src/server

Deletes (zero-caller verified): jobs/outbox.ts (canonical path is
IngestEventsService/EndSessionService) + its test; the src/server/mcp/ surface
(live MCP server is src/servers/mcp-server.ts) + its test; the always-inert
ServerBetaProviderRegistry/EventBroadcaster boundaries (no Active variant exists)
+ their /v1/info payload keys; the unused isServerClassified guard; dead option
sessionDebounceWindowMs (route + IngestEventsService).

Dedupe: hoist the 5 byte-identical auth helpers shared by auth.ts/postgres-auth.ts
into request-auth-helpers.ts; collapse resolveSummaryQueue/resolveEventQueue into
one resolveQueue(lane).

Kept (plan premise didn't verify): the ServerV1Routes runtime? option — a live
smoke test sets and asserts it. Disabled* boundary subclasses kept (real Active
counterparts chosen at runtime).

Net ~-570 source lines. tsc clean; full suite 2242 pass / 0 fail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(slice-7): dead-code sweep + dedup across services + npx-cli

Deletes (zero-caller verified, tests removed in lockstep): ProcessManager
getChildProcesses + parseElapsedTime (ps-reaper leftovers), ModeManager
getObservationConcepts/validateType/getTypeLabel, AgentFormatter
renderAgentFileHeader/renderAgentColumnKey/renderAgentContextIndex (return-[] inert,
HeaderRenderer arms collapsed to Human-only), asyncHandler export,
PriorMessages.userMessage (always ''), and 3 dead barrels (services/context,
services/server, services/server/Middleware).

Dedup: shared toError() helper (src/utils/to-error.ts) across 8 in-scope sites;
asMs hoisted to telemetry/common; spawnPlugin() folds 4 spawnHidden blocks;
countObserverSessionRows extracts the CleanupV12_4_3 count trio; IS_WINDOWS imported
from paths.ts (was redeclared 3x); detectOsVersion inlined to os.release().

Kept (plan premise didn't verify): bun-resolver's spawnSync (npx-cli runs under
Node — Bun.which would ReferenceError); context-generator.ts (a build entrypoint +
test mock seam) — barrel still removed; Middleware.ts consumer Server.ts repointed
to the real middleware.

Net ~-279 lines. tsc clean; full suite 2232 pass / 0 fail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(slice-5): delete orphans + dead UI/util code across cli/supervisor/ui

Orphan deletes (zero-caller verified): src/bin/ (import-xml-observations,
cleanup-duplicates — not wired to any entrypoint), src/adapters/ (abandoned parallel
impl; real adapters are src/cli/adapters/), core/schemas/context-pack.ts +
core/schemas/index.ts barrel. Companion tests removed in lockstep.

Dead functions: 7 cursor-utils helpers (kept the 6 live registry/context writers),
logger correlationId/sessionId/timing.

YAGNI trims: gemini-cli metadata block (never read), useStats collapsed to
fire-and-forget (+ dead Stats/WorkerStats/DatabaseStats types), useTheme
resolvedTheme, useContextPreview.refresh from the public result; env-sanitizer
ENV_PROXY_VARS folded into ENV_EXACT_MATCHES.

Dedup: useGitHubStars + formatNumber inlined into their single consumer
GitHubStarsButton (kept lowercase-k display — matches GitHub, Intl would uppercase);
waitForExit extracted in process-registry and shared with shutdown's reapSession
(placed low to avoid a circular import).

Net ~-1085 lines (incl. test deletions). tsc + viewer typecheck clean;
full suite 2181 pass / 0 fail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(slice-2a): integrations/sync dead exports + scoped Chroma cleanup

Dead-export deletes (zero-caller verified): syncContextToAgentsMd,
updateWindsurfContextForProject, handleWindsurfCommand, detectClaudeCode (+ orphaned
exec/promisify imports), getScriptExtension/detectPlatform, getVersionCheckAbsolutePath
(+ companion plugin-distribution test edit). ChromaSyncState flush/resetCache/dirty
(bump/replace persist eagerly, so dirty was always false).

Scoped to the Chroma write path only (SQLite/search/telemetry copies stay live):
dropped the created_at ISO field (kept created_at_epoch, the field actually read back)
and the discovery_tokens param/field from ChromaSync's local Stored interfaces + the
3 live call sites.

Stdlib/shrink: parseSemver/compareSemver → localeCompare numeric (ordering verified);
OpenClaw roots hoisted to one const; bootstrapWatermarks max-loop → Math.max;
Goose YAML builders collapsed to one withHeader flag.

Defers the 5-installer consolidation to a separate pass. Net ~-187 lines.
tsc clean; full suite 2181 pass / 0 fail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(slice-2b): delete dead fetchAndInjectOpenCodeContext

Orphaned when slice-2a removed syncContextToAgentsMd (its only caller chain).
Confirmed zero callers. Kept fetchRealContextFromWorker (live at :323).

Per feasibility analysis, the plan's 5-installer table-driven consolidation
(headline -2400) was descoped: the 5 installers write 5 different config schemas
and 4 different context formats with thin test coverage, so a 5->1 collapse would
relocate divergence into callbacks and risk untested IDE-config write paths for a
line-count-only win. Plan gate ('only if behavior genuinely identical') not met.

tsc clean; full suite 2181 pass / 0 fail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(slice-3): worker dead-code sweep + provider/search consolidation

Search pipeline: delete the unreachable half built speculatively (TimelineBuilder,
ResultFormatter instance methods [kept the one live static], search/filters/,
SearchStrategy.canHandle/name + BaseSearchStrategy, HybridSearchStrategy no-op
search(), dead SearchOrchestrator wrappers, ChromaQueryResult) + companion tests.
Dedup the 5 genuinely-identical chroma->recency->hydrate->FTS paths into one
hybridSemanticHydrate helper and the 3 timeline renderers into renderTimeline()
(search()/decisions()/changes()/howItWorks() left as-is — different shape).

Providers: extract OpenAICompatibleProvider base from the Gemini/OpenRouter twins,
preserving every per-provider divergence via flags/abstracts (truncation guard,
token estimation, empty-response handling, endpointClass, the Gemini-only RPM
throttle). Dedup parseRetryAfterMs into retry.ts.

http/agents/session: delete the IngestEventBus machinery + ingestPrompt, the
read-only POST /api/processing dup, FallbackErrorHandler.shouldFallbackToClaude,
RateLimitStore.getAll/clear, SessionCompletionHandler.completeByDbId,
SessionCleanupHelper, 3 dead agent types, and no-op empty-passthrough validateBody;
collapse the 6 CorpusRoutes 404 blocks into one helper.

Kept (false-dead, caller verified): SSEEventPayload (live via WorkerRef), RateLimitStore.get
(live via shouldAbortForQuota). Both adversarial reviews confirmed behavior preserved.

Net ~-2,640 lines. tsc clean; full suite 2080 pass / 0 fail; dead-ref sweep zero.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* build(plugin): regenerate distribution artifacts after ponytail audit

Rebuilds the worker/mcp/server-beta/transcript-watcher/context-generator bundles
and the viewer UI from the post-audit source (Slices 0-7).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(env): require Node >=20.12.0 to match util.parseEnv usage

EnvManager adopted stdlib util.parseEnv (added in Node 20.12.0) during
the ponytail audit, but engines.node still advertised >=20.0.0. On Node
20.0-20.11 parseEnv is undefined: loadClaudeMemEnv() silently returns {}
(credentials never load) and saveClaudeMemEnv() throws. Declare the real
floor in both the npm package and the generated plugin manifest (via its
generator in build-hooks.js so rebuilds stay consistent).

Greptile PR #3021 P1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 13:12:41 -07:00

29 lines
150 KiB
JavaScript
Executable File

#!/usr/bin/env bun
"use strict";var An=Object.create;var Yr=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var kn=Object.getOwnPropertyNames;var Rn=Object.getPrototypeOf,On=Object.prototype.hasOwnProperty;var Dn=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of kn(e))!On.call(t,i)&&i!==r&&Yr(t,i,{get:()=>e[i],enumerable:!(s=Cn(e,i))||s.enumerable});return t};var X=(t,e,r)=>(r=t!=null?An(Rn(t)):{},Dn(e||!t||!t.__esModule?Yr(r,"default",{value:t,enumerable:!0}):r,t));var ie=require("fs"),lr=require("os"),je=require("path");var _=require("path"),ar=require("os"),He=require("fs");var Xr=require("url");var se=require("fs"),Jr=require("path");var Pn=null;function rr(t){return(Pn??process.stderr.write.bind(process.stderr))(t)}var ot=null;function sr(t){rr(t)}function zr(t,e={}){ot&&ot.length>0&&(rr(ot.join("")),ot=[]),rr(t.endsWith(`
`)?t:`${t}
`),e.skipExit||process.exit(2)}var nr=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(nr||{}),ir=null,or=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=R.logsDir();(0,se.existsSync)(e)||(0,se.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Jr.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=R.settings();if((0,se.existsSync)(e)){let r=(0,se.readFileSync)(e,"utf-8"),i=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=nr[i]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let s=r;if(typeof r=="string")try{s=JSON.parse(r)}catch{s=r}if(e==="Bash"&&s.command)return`${e}(${s.command})`;if(s.file_path)return`${e}(${s.file_path})`;if(s.notebook_path)return`${e}(${s.notebook_path})`;if(e==="Glob"&&s.pattern)return`${e}(${s.pattern})`;if(e==="Grep"&&s.pattern)return`${e}(${s.pattern})`;if(s.url)return`${e}(${s.url})`;if(s.query)return`${e}(${s.query})`;if(e==="Task"){if(s.subagent_type)return`${e}(${s.subagent_type})`;if(s.description)return`${e}(${s.description})`}return e==="Skill"&&s.skill?`${e}(${s.skill})`:e==="LSP"&&s.operation?`${e}(${s.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${s}-${i} ${n}:${o}:${a}.${l}`}log(e,r,s,i,n){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=nr[e].padEnd(5),l=r.padEnd(6),c="";i?.correlationId?c=`[${i.correlationId}] `:i?.sessionId&&(c=`[session-${i.sessionId}] `);let u="";if(n!=null)if(n instanceof Error)u=this.getLevel()===0?`
${n.message}
${n.stack}`:` ${n.message}`;else if(this.getLevel()===0&&typeof n=="object")try{u=`
`+JSON.stringify(n,null,2)}catch{u=" "+this.formatData(n)}else u=" "+this.formatData(n);let h="";if(i){let{sessionId:f,memorySessionId:m,correlationId:g,...w}=i;Object.keys(w).length>0&&(h=` {${Object.entries(w).map(([E,y])=>`${E}=${y}`).join(", ")}}`)}let p=`[${o}] [${a}] [${l}] ${c}${s}${h}${u}`;if(this.logFilePath)try{(0,se.appendFileSync)(this.logFilePath,p+`
`,"utf8")}catch(f){sr(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
`)}else sr(p+`
`)}debug(e,r,s,i){this.log(0,e,r,s,i)}info(e,r,s,i){this.log(1,e,r,s,i)}warn(e,r,s,i){this.log(2,e,r,s,i)}setErrorSink(e){ir=e}error(e,r,s,i){this.log(3,e,r,s,i),this.routeErrorToSink(r,s,i)}routeErrorToSink(e,r,s){try{if(!ir||!(s instanceof Error))return;ir(s)}catch{}}dataIn(e,r,s,i){this.info(e,`\u2192 ${r}`,s,i)}dataOut(e,r,s,i){this.info(e,`\u2190 ${r}`,s,i)}success(e,r,s,i){this.info(e,`\u2713 ${r}`,s,i)}failure(e,r,s,i){this.error(e,`\u2717 ${r}`,s,i)}happyPathError(e,r,s,i,n=""){let c=((new Error().stack||"").split(`
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",h={...s,location:u};return this.warn(e,`[HAPPY-PATH] ${r}`,h,i),n}},d=new or;var jn={};function In(){return typeof __dirname<"u"?__dirname:(0,_.dirname)((0,Xr.fileURLToPath)(jn.url))}var Yl=In();function Oe(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,_.join)((0,ar.homedir)(),".claude-mem"),e=(0,_.join)(t,"settings.json");try{if((0,He.existsSync)(e)){let r=JSON.parse((0,He.readFileSync)(e,"utf-8")),s=r.env??r;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return t}var v=Oe(),at=process.env.CLAUDE_CONFIG_DIR||(0,_.join)((0,ar.homedir)(),".claude"),lt=(0,_.join)(at,"plugins","marketplaces","thedotmack"),xn=(0,_.join)(v,"archives"),Ln=(0,_.join)(v,"logs"),Nn=(0,_.join)(v,"trash"),Un=(0,_.join)(v,"backups"),Fn=(0,_.join)(v,"modes"),ct=(0,_.join)(v,"settings.json"),zl=(0,_.join)(v,"claude-mem.db"),Wn=(0,_.join)(v,"vector-db"),ut=(0,_.join)(v,"observer-sessions"),Hn=(0,_.basename)(ut),Jl=(0,_.join)(at,"settings.json"),Xl=(0,_.join)(at,"commands"),ql=(0,_.join)(at,"CLAUDE.md");var R={dataDir:()=>v,workerPid:()=>(0,_.join)(v,"worker.pid"),serverBetaPid:()=>(0,_.join)(v,".server-beta.pid"),serverBetaPort:()=>(0,_.join)(v,".server-beta.port"),serverBetaRuntime:()=>(0,_.join)(v,".server-beta.runtime.json"),settings:()=>(0,_.join)(v,"settings.json"),database:()=>(0,_.join)(v,"claude-mem.db"),chroma:()=>(0,_.join)(v,"chroma"),combinedCerts:()=>(0,_.join)(v,"combined_certs.pem"),transcriptsConfig:()=>(0,_.join)(v,"transcript-watch.json"),transcriptsState:()=>(0,_.join)(v,"transcript-watch-state.json"),corpora:()=>(0,_.join)(v,"corpora"),supervisorRegistry:()=>(0,_.join)(v,"supervisor.json"),envFile:()=>(0,_.join)(v,".env"),logsDir:()=>Ln,archives:()=>xn,trash:()=>Nn,backups:()=>Un,modes:()=>Fn,vectorDb:()=>Wn,observerSessions:()=>ut};var De=R.transcriptsConfig(),ht=R.transcriptsState();var $n={version:1,schemas:{},watches:[],stateFile:ht};function Bn(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let s=N(t.path).replace(/\\/g,"/"),i=(0,je.join)((0,lr.homedir)(),".codex","sessions").replace(/\\/g,"/");return s===`${i}/**/*.jsonl`}function qr(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name,r=t.name==="codex"&&(!e||e==="codex");return t.context?.mode==="agents"&&r&&Bn(t)}function N(t){return t&&(t.startsWith("~")?(0,je.join)((0,lr.homedir)(),t.slice(1)):t)}function $e(t=De){let e=N(t);if(!(0,ie.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=(0,ie.readFileSync)(e,"utf-8"),s=JSON.parse(r);if(!s.version||!s.watches)throw new Error(`Invalid transcript watch config: ${e}`);return s.stateFile||(s.stateFile=ht),s}function dt(t=De){let e=N(t),r=(0,je.dirname)(e);(0,ie.existsSync)(r)||(0,ie.mkdirSync)(r,{recursive:!0}),(0,ie.writeFileSync)(e,JSON.stringify($n,null,2))}var x=require("fs"),J=require("path");var Ps=require("node:url"),Le=require("node:path"),Us=require("node:url"),Q=require("fs"),qo=X(require("node:fs"),1),Se=require("node:fs/promises"),Ct=require("node:events"),yr=X(require("node:stream"),1),Fs=require("node:string_decoder"),ys=(t,e,r)=>{let s=t instanceof RegExp?Vr(t,r):t,i=e instanceof RegExp?Vr(e,r):e,n=s!==null&&i!=null&&Gn(s,i,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+s.length,n[1]),post:r.slice(n[1]+i.length)}},Vr=(t,e)=>{let r=e.match(t);return r?r[0]:null},Gn=(t,e,r)=>{let s,i,n,o,a,l=r.indexOf(t),c=r.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(t===e)return[l,c];for(s=[],n=r.length;u>=0&&!a;){if(u===l)s.push(u),l=r.indexOf(t,u+1);else if(s.length===1){let h=s.pop();h!==void 0&&(a=[h,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(e,u+1);u=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},_s="\0SLASH"+Math.random()+"\0",bs="\0OPEN"+Math.random()+"\0",Er="\0CLOSE"+Math.random()+"\0",vs="\0COMMA"+Math.random()+"\0",Ts="\0PERIOD"+Math.random()+"\0",Kn=new RegExp(_s,"g"),Yn=new RegExp(bs,"g"),zn=new RegExp(Er,"g"),Jn=new RegExp(vs,"g"),Xn=new RegExp(Ts,"g"),qn=/\\\\/g,Vn=/\\{/g,Qn=/\\}/g,Zn=/\\,/g,eo=/\\./g,to=1e5;function cr(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function ro(t){return t.replace(qn,_s).replace(Vn,bs).replace(Qn,Er).replace(Zn,vs).replace(eo,Ts)}function so(t){return t.replace(Kn,"\\").replace(Yn,"{").replace(zn,"}").replace(Jn,",").replace(Xn,".")}function Ms(t){if(!t)return[""];let e=[],r=ys("{","}",t);if(!r)return t.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=Ms(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function io(t,e={}){if(!t)return[];let{max:r=to}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),Xe(ro(t),r,!0).map(so)}function no(t){return"{"+t+"}"}function oo(t){return/^-?0\d/.test(t)}function ao(t,e){return t<=e}function lo(t,e){return t>=e}function Xe(t,e,r){let s=[],i=ys("{","}",t);if(!i)return[t];let n=i.pre,o=i.post.length?Xe(i.post,e,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<e;a++){let l=n+"{"+i.body+"}"+o[a];s.push(l)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),c=a||l,u=i.body.indexOf(",")>=0;if(!c&&!u)return i.post.match(/,(?!,).*\}/)?(t=i.pre+"{"+i.body+Er+i.post,Xe(t,e,!0)):[t];let h;if(c)h=i.body.split(/\.\./);else if(h=Ms(i.body),h.length===1&&h[0]!==void 0&&(h=Xe(h[0],e,!1).map(no),h.length===1))return o.map(f=>i.pre+h[0]+f);let p;if(c&&h[0]!==void 0&&h[1]!==void 0){let f=cr(h[0]),m=cr(h[1]),g=Math.max(h[0].length,h[1].length),w=h.length===3&&h[2]!==void 0?Math.abs(cr(h[2])):1,S=ao;m<f&&(w*=-1,S=lo);let E=h.some(oo);p=[];for(let y=f;S(y,m);y+=w){let b;if(l)b=String.fromCharCode(y),b==="\\"&&(b="");else if(b=String(y),E){let T=g-b.length;if(T>0){let pe=new Array(T+1).join("0");y<0?b="-"+pe+b.slice(1):b=pe+b}}p.push(b)}}else{p=[];for(let f=0;f<h.length;f++)p.push.apply(p,Xe(h[f],e,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&s.length<e;m++){let g=n+p[f]+o[m];(!r||c||g)&&s.push(g)}}return s}var vt=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},co={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Be=t=>t.replace(/[[\]\\-]/g,"\\$&"),uo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Qr=t=>t.join(""),ho=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,u=r,h="";e:for(;n<t.length;){let m=t.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){u=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(co))if(t.startsWith(g,n)){if(h)return["$.",!1,t.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue e}}if(l=!1,h){m>h?s.push(Be(h)+"-"+Be(m)):m===h&&s.push(Be(m)),h="",n++;continue}if(t.startsWith("-]",n+1)){s.push(Be(m+"-")),n+=2;continue}if(t.startsWith("-",n+1)){h=m,n+=2;continue}s.push(Be(m)),n++}if(u<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,t.length-r,!0];if(i.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let m=s[0].length===2?s[0].slice(-1):s[0];return[uo(m),!1,u-r,!1]}let p="["+(c?"^":"")+Qr(s)+"]",f="["+(c?"":"^")+Qr(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,u-r,!0]},xe=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!0}={})=>r?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),po=new Set(["!","?","+","*","@"]),Zr=t=>po.has(t),fo="(?!(?:^|/)\\.\\.?(?:$|/))",pt="(?!\\.)",mo=new Set(["[","."]),go=new Set(["..","."]),So=new Set("().*{}+?[]^$\\!"),Eo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),wr="[^/]",es=wr+"*?",ts=wr+"+?",As=class F{type;#e;#r;#n=!1;#i=[];#o;#y;#S;#u=!1;#a;#d;#h=!1;constructor(e,r,s={}){this.type=e,e&&(this.#r=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?s:this.#e.#a,this.#S=this.#e===this?[]:this.#e.#S,e==="!"&&!this.#e.#u&&this.#S.push(this),this.#y=this.#o?this.#o.#i.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#i)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#i.map(e=>String(e)).join("|")+")":this.#d=this.#i.map(e=>String(e)).join("")}#l(){if(this!==this.#e)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let e;for(;e=this.#S.pop();){if(e.type!=="!")continue;let r=e,s=r.#o;for(;s;){for(let i=r.#y+1;!s.type&&i<s.#i.length;i++)for(let n of e.#i){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(s.#i[i])}r=s,s=r.#o}}return this}push(...e){for(let r of e)if(r!==""){if(typeof r!="string"&&!(r instanceof F&&r.#o===this))throw new Error("invalid part: "+r);this.#i.push(r)}}toJSON(){let e=this.type===null?this.#i.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#i.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#u&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#y===0)return!0;let e=this.#o;for(let r=0;r<this.#y;r++){let s=e.#i[r];if(!(s instanceof F&&s.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#i.length:0;return this.#y===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let r=new F(this.type,e);for(let s of this.#i)r.copyIn(s);return r}static#s(e,r,s,i){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=s,m="";for(;f<e.length;){let g=e.charAt(f++);if(n||g==="\\"){n=!n,m+=g;continue}if(o){f===a+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(f===a+2&&l)&&(o=!1),m+=g;continue}else if(g==="["){o=!0,a=f,l=!1,m+=g;continue}if(!i.noext&&Zr(g)&&e.charAt(f)==="("){r.push(m),m="";let w=new F(g,r);f=F.#s(e,w,f,i),r.push(w);continue}m+=g}return r.push(m),f}let c=s+1,u=new F(null,r),h=[],p="";for(;c<e.length;){let f=e.charAt(c++);if(n||f==="\\"){n=!n,p+=f;continue}if(o){c===a+1?(f==="^"||f==="!")&&(l=!0):f==="]"&&!(c===a+2&&l)&&(o=!1),p+=f;continue}else if(f==="["){o=!0,a=c,l=!1,p+=f;continue}if(Zr(f)&&e.charAt(c)==="("){u.push(p),p="";let m=new F(f,u);u.push(m),c=F.#s(e,m,c,i);continue}if(f==="|"){u.push(p),p="",h.push(u),u=new F(null,r);continue}if(f===")")return p===""&&r.#i.length===0&&(r.#h=!0),u.push(p),p="",r.push(...h,u),c;p+=f}return r.type=null,r.#r=void 0,r.#i=[e.substring(s-1)],c}static fromGlob(e,r={}){let s=new F(null,void 0,r);return F.#s(e,s,0,r),s}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[r,s,i,n]=this.toRegExpSource();if(!(i||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;let o=(this.#a.nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${r}$`,o),{_src:r,_glob:e})}get options(){return this.#a}toRegExpSource(e){let r=e??!!this.#a.dot;if(this.#e===this&&this.#l(),!this.type){let l=this.isStart()&&this.isEnd()&&!this.#i.some(p=>typeof p!="string"),c=this.#i.map(p=>{let[f,m,g,w]=typeof p=="string"?F.#_(p,this.#r,l):p.toRegExpSource(e);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),u="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&go.has(this.#i[0]))){let p=mo,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!e&&p.has(c.charAt(0));u=f?fo:m?pt:""}let h="";return this.isEnd()&&this.#e.#u&&this.#o?.type==="!"&&(h="(?:$|\\/)"),[u+c+h,xe(c),this.#r=!!this.#r,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#p(r);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return this.#i=[l],this.type=null,this.#r=void 0,[l,xe(this.toString()),!1,!1]}let o=!s||e||r||!pt?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#h)a=(this.isStart()&&!r?pt:"")+ts;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!e?pt:"")+es+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,xe(n),this.#r=!!this.#r,this.#n]}#p(e){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=r.toRegExpSource(e);return this.#n=this.#n||o,s}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#_(e,r,s=!1){let i=!1,n="",o=!1,a=!1;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(i){i=!1,n+=(So.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(e)?ts:es,r=!0;continue}else a=!1;if(c==="\\"){l===e.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[u,h,p,f]=ho(e,l);if(p){n+=u,o=o||h,l+=p-1,r=r||f;continue}}if(c==="?"){n+=wr,r=!0;continue}n+=Eo(c)}return[n,xe(e),!!r,o]}},Cs=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!1}={})=>r?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&"),I=(t,e,r={})=>(vt(e),!r.nocomment&&e.charAt(0)==="#"?!1:new ge(e,r).match(t)),wo=/^\*+([^+@!?\*\[\(]*)$/,yo=t=>e=>!e.startsWith(".")&&e.endsWith(t),_o=t=>e=>e.endsWith(t),bo=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),vo=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),To=/^\*+\.\*+$/,Mo=t=>!t.startsWith(".")&&t.includes("."),Ao=t=>t!=="."&&t!==".."&&t.includes("."),Co=/^\.\*+$/,ko=t=>t!=="."&&t!==".."&&t.startsWith("."),Ro=/^\*+$/,Oo=t=>t.length!==0&&!t.startsWith("."),Do=t=>t.length!==0&&t!=="."&&t!=="..",Po=/^\?+([^+@!?\*\[\(]*)?$/,Io=([t,e=""])=>{let r=ks([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},xo=([t,e=""])=>{let r=Rs([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},Lo=([t,e=""])=>{let r=Rs([t]);return e?s=>r(s)&&s.endsWith(e):r},No=([t,e=""])=>{let r=ks([t]);return e?s=>r(s)&&s.endsWith(e):r},ks=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},Rs=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},Os=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",rs={win32:{sep:"\\"},posix:{sep:"/"}},Uo=Os==="win32"?rs.win32.sep:rs.posix.sep;I.sep=Uo;var P=Symbol("globstar **");I.GLOBSTAR=P;var Fo="[^/]",Wo=Fo+"*?",Ho="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",jo="(?:(?!(?:\\/|^)\\.).)*?",$o=(t,e={})=>r=>I(r,t,e);I.filter=$o;var W=(t,e={})=>Object.assign({},t,e),Bo=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return I;let e=I;return Object.assign((r,s,i={})=>e(r,s,W(t,i)),{Minimatch:class extends e.Minimatch{constructor(r,s={}){super(r,W(t,s))}static defaults(r){return e.defaults(W(t,r)).Minimatch}},AST:class extends e.AST{constructor(r,s,i={}){super(r,s,W(t,i))}static fromGlob(r,s={}){return e.AST.fromGlob(r,W(t,s))}},unescape:(r,s={})=>e.unescape(r,W(t,s)),escape:(r,s={})=>e.escape(r,W(t,s)),filter:(r,s={})=>e.filter(r,W(t,s)),defaults:r=>e.defaults(W(t,r)),makeRe:(r,s={})=>e.makeRe(r,W(t,s)),braceExpand:(r,s={})=>e.braceExpand(r,W(t,s)),match:(r,s,i={})=>e.match(r,s,W(t,i)),sep:e.sep,GLOBSTAR:P})};I.defaults=Bo;var Ds=(t,e={})=>(vt(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:io(t,{max:e.braceExpandMax}));I.braceExpand=Ds;var Go=(t,e={})=>new ge(t,e).makeRe();I.makeRe=Go;var Ko=(t,e,r={})=>{let s=new ge(e,r);return t=t.filter(i=>s.match(i)),s.options.nonull&&!t.length&&t.push(e),t};I.match=Ko;var ss=/[?*]|[+@!]\(.*?\)|\[|\]/,Yo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ge=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){vt(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Os,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let s=this.globParts.map((i,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=i[0]===""&&i[1]===""&&(i[2]==="?"||!ss.test(i[2]))&&!ss.test(i[3]),l=/^[a-z]:/i.test(i[0]);if(a)return[...i.slice(0,4),...i.slice(4).map(c=>this.parse(c))];if(l)return[i[0],...i.slice(1).map(c=>this.parse(c))]}return i.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let n=this.set[i];n[0]===""&&n[1]===""&&this.globParts[i][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let r=0;r<t.length;r++)for(let s=0;s<t[r].length;s++)t[r][s]==="**"&&(t[r][s]="*");let{optimizationLevel:e=1}=this.options;return e>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let r=-1;for(;(r=e.indexOf("**",r+1))!==-1;){let s=r;for(;e[s+1]==="**";)s++;s!==r&&e.splice(r,s-r)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((r,s)=>{let i=r[r.length-1];return s==="**"&&i==="**"?r:s===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(s),r)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let s=1;s<t.length-1;s++){let i=t[s];s===1&&i===""&&t[0]===""||(i==="."||i==="")&&(e=!0,t.splice(s,1),s--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(e=!0,t.pop())}let r=0;for(;(r=t.indexOf("..",r+1))!==-1;){let s=t[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(e=!0,t.splice(r-1,2),r-=2)}}while(e);return t.length===0?[""]:t}firstPhasePreProcess(t){let e=!1;do{e=!1;for(let r of t){let s=-1;for(;(s=r.indexOf("**",s+1))!==-1;){let n=s;for(;r[n+1]==="**";)n++;n>s&&r.splice(s+1,n-s);let o=r[s+1],a=r[s+2],l=r[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,r.splice(s,1);let c=r.slice(0);c[s]="**",t.push(c),s--}if(!this.preserveMultipleSlashes){for(let n=1;n<r.length-1;n++){let o=r[n];n===1&&o===""&&r[0]===""||(o==="."||o==="")&&(e=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(e=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let n=r[i-1];if(n&&n!=="."&&n!==".."&&n!=="**"){e=!0;let o=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...o),r.length===0&&r.push(""),i-=2}}}}while(e);return t}secondPhasePreProcess(t){for(let e=0;e<t.length-1;e++)for(let r=e+1;r<t.length;r++){let s=this.partsMatch(t[e],t[r],!this.preserveMultipleSlashes);if(s){t[e]=[],t[r]=s;break}}return t.filter(e=>e.length)}partsMatch(t,e,r=!1){let s=0,i=0,n=[],o="";for(;s<t.length&&i<e.length;)if(t[s]===e[i])n.push(o==="b"?e[i]:t[s]),s++,i++;else if(r&&t[s]==="**"&&e[i]===t[s+1])n.push(t[s]),s++;else if(r&&e[i]==="**"&&t[s]===e[i+1])n.push(e[i]),i++;else if(t[s]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(o==="b")return!1;o="a",n.push(t[s]),s++,i++}else if(e[i]==="*"&&t[s]&&(this.options.dot||!t[s].startsWith("."))&&t[s]!=="**"){if(o==="a")return!1;o="b",n.push(e[i]),s++,i++}else return!1;return t.length===e.length&&n}parseNegate(){if(this.nonegate)return;let t=this.pattern,e=!1,r=0;for(let s=0;s<t.length&&t.charAt(s)==="!";s++)e=!e,r++;r&&(this.pattern=t.slice(r)),this.negate=e}matchOne(t,e,r=!1){let s=this.options;if(this.isWindows){let m=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),g=!m&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),w=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),S=!w&&e[0]===""&&e[1]===""&&e[2]==="?"&&typeof e[3]=="string"&&/^[a-z]:$/i.test(e[3]),E=g?3:m?0:void 0,y=S?3:w?0:void 0;if(typeof E=="number"&&typeof y=="number"){let[b,T]=[t[E],e[y]];b.toLowerCase()===T.toLowerCase()&&(e[y]=b,y>E?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var n=0,o=0,a=t.length,l=e.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var c=e[o],u=t[n];if(this.debug(e,c,u),c===!1)return!1;if(c===P){this.debug("GLOBSTAR",[e,c,u]);var h=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(t[n]==="."||t[n]===".."||!s.dot&&t[n].charAt(0)===".")return!1;return!0}for(;h<a;){var f=t[h];if(this.debug(`
globstar while`,t,h,e,p,f),this.matchOne(t.slice(h),e.slice(p),r))return this.debug("globstar found match!",h,a,f),!0;if(f==="."||f===".."||!s.dot&&f.charAt(0)==="."){this.debug("dot detected!",t,h,e,p);break}this.debug("globstar swallow a segment, and continue"),h++}return!!(r&&(this.debug(`
>>> no match, partial?`,t,h,e,p),h===a))}let m;if(typeof c=="string"?(m=u===c,this.debug("string match",c,u,m)):(m=c.test(u),this.debug("pattern match",c,u,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&t[n]==="";throw new Error("wtf?")}braceExpand(){return Ds(this.pattern,this.options)}parse(t){vt(t);let e=this.options;if(t==="**")return P;if(t==="")return"";let r,s=null;(r=t.match(Ro))?s=e.dot?Do:Oo:(r=t.match(wo))?s=(e.nocase?e.dot?vo:bo:e.dot?_o:yo)(r[1]):(r=t.match(Po))?s=(e.nocase?e.dot?xo:Io:e.dot?Lo:No)(r):(r=t.match(To))?s=e.dot?Ao:Mo:(r=t.match(Co))&&(s=ko);let i=As.fromGlob(t,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,r=e.noglobstar?Wo:e.dot?Ho:jo,s=new Set(e.nocase?["i"]:[]),i=t.map(a=>{let l=a.map(u=>{if(u instanceof RegExp)for(let h of u.flags.split(""))s.add(h);return typeof u=="string"?Yo(u):u===P?P:u._src});l.forEach((u,h)=>{let p=l[h+1],f=l[h-1];u!==P||f===P||(f===void 0?p!==void 0&&p!==P?l[h+1]="(?:\\/|"+r+"\\/)?"+p:l[h]=r:p===void 0?l[h-1]=f+"(?:\\/|\\/"+r+")?":p!==P&&(l[h-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[h+1]=P))});let c=l.filter(u=>u!==P);if(this.partial&&c.length>=1){let u=[];for(let h=1;h<=c.length;h++)u.push(c.slice(0,h).join("/"));return"(?:"+u.join("|")+")"}return c.join("/")}).join("|"),[n,o]=t.length>1?["(?:",")"]:["",""];i="^"+n+i+o+"$",this.partial&&(i="^(?:\\/|"+n+i.slice(1,-1)+o+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let r=this.options;this.isWindows&&(t=t.split("\\").join("/"));let s=this.slashSplit(t);this.debug(this.pattern,"split",s);let i=this.set;this.debug(this.pattern,"set",i);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<i.length;o++){let a=i[o],l=s;if(r.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,e))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(t){return I.defaults(t).Minimatch}};I.AST=As;I.Minimatch=ge;I.escape=Cs;I.unescape=xe;var zo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Is=new Set,Sr=typeof process=="object"&&process?process:{},xs=(t,e,r,s)=>{typeof Sr.emitWarning=="function"?Sr.emitWarning(t,e,r,s):console.error(`[${r}] ${e}: ${t}`)},Tt=globalThis.AbortController,is=globalThis.AbortSignal;if(typeof Tt>"u"){is=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},Tt=class{constructor(){e()}signal=new is;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let s of this.signal._onabort)s(r);this.signal.onabort?.(r)}}};let t=Sr.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,xs("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var Jo=t=>!Is.has(t),me=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Ls=t=>me(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?_t:null:null,_t=class extends Array{constructor(t){super(t),this.fill(0)}},Xo=class qe{heap;length;static#e=!1;static create(e){let r=Ls(e);if(!r)return[];qe.#e=!0;let s=new qe(e,r);return qe.#e=!1,s}constructor(e,r){if(!qe.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},At=class Ns{#e;#r;#n;#i;#o;#y;#S;#u;get perf(){return this.#u}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#h;#l;#s;#p;#_;#w;#f;#k;#m;#T;#M;#g;#E;#b;#A;#t;#x;static unsafeExposeInternals(e){return{starts:e.#M,ttls:e.#g,autopurgeTimers:e.#E,sizes:e.#T,keyMap:e.#h,keyList:e.#l,valList:e.#s,next:e.#p,prev:e.#_,get head(){return e.#w},get tail(){return e.#f},free:e.#k,isBackgroundFetch:r=>e.#c(r),backgroundFetch:(r,s,i,n)=>e.#$(r,s,i,n),moveToTail:r=>e.#N(r),indexes:r=>e.#O(r),rindexes:r=>e.#D(r),isStale:r=>e.#v(r)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#d}get size(){return this.#a}get fetchMethod(){return this.#y}get memoMethod(){return this.#S}get dispose(){return this.#n}get onInsert(){return this.#i}get disposeAfter(){return this.#o}constructor(e){let{max:r=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:u,disposeAfter:h,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:pe,ignoreFetchAbort:Ce,perf:ke}=e;if(ke!==void 0&&typeof ke?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#u=ke??zo,r!==0&&!me(r))throw new TypeError("max option must be a nonnegative integer");let Re=r?Ls(r):Array;if(!Re)throw new Error("invalid max value: "+r);if(this.#e=r,this.#r=m,this.maxEntrySize=g||this.#r,this.sizeCalculation=w,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(E!==void 0&&typeof E!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=E,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#y=S,this.#A=!!S,this.#h=new Map,this.#l=new Array(r).fill(void 0),this.#s=new Array(r).fill(void 0),this.#p=new Re(r),this.#_=new Re(r),this.#w=0,this.#f=0,this.#k=Xo.create(r),this.#a=0,this.#d=0,typeof c=="function"&&(this.#n=c),typeof u=="function"&&(this.#i=u),typeof h=="function"?(this.#o=h,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#b=!!this.#n,this.#x=!!this.#i,this.#t=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!pe,this.ignoreFetchAbort=!!Ce,this.maxEntrySize!==0){if(this.#r!==0&&!me(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!me(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=me(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!me(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let tr="LRU_CACHE_UNBOUNDED";Jo(tr)&&(Is.add(tr),xs("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",tr,Ns))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#P(){let e=new _t(this.#e),r=new _t(this.#e);this.#g=e,this.#M=r;let s=this.ttlAutopurge?new Array(this.#e):void 0;this.#E=s,this.#F=(o,a,l=this.#u.now())=>{if(r[o]=a!==0?l:0,e[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let c=setTimeout(()=>{this.#v(o)&&this.#R(this.#l[o],"expire")},a+1);c.unref&&c.unref(),s[o]=c}},this.#C=o=>{r[o]=e[o]!==0?this.#u.now():0},this.#I=(o,a)=>{if(e[a]){let l=e[a],c=r[a];if(!l||!c)return;o.ttl=l,o.start=c,o.now=i||n();let u=o.now-c;o.remainingTTL=l-u}};let i=0,n=()=>{let o=this.#u.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#h.get(o);if(a===void 0)return 0;let l=e[a],c=r[a];if(!l||!c)return 1/0;let u=(i||n())-c;return l-u},this.#v=o=>{let a=r[o],l=e[o];return!!l&&!!a&&(i||n())-a>l}}#C=()=>{};#I=()=>{};#F=()=>{};#v=()=>!1;#G(){let e=new _t(this.#e);this.#d=0,this.#T=e,this.#U=r=>{this.#d-=e[r],e[r]=0},this.#W=(r,s,i,n)=>{if(this.#c(s))return 0;if(!me(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!me(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#L=(r,s,i)=>{if(e[r]=s,this.#r){let n=this.#r-e[r];for(;this.#d>n;)this.#j(!0)}this.#d+=e[r],i&&(i.entrySize=s,i.totalCalculatedSize=this.#d)}}#U=e=>{};#L=(e,r,s)=>{};#W=(e,r,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#f;!(!this.#H(r)||((e||!this.#v(r))&&(yield r),r===this.#w));)r=this.#_[r]}*#D({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#w;!(!this.#H(r)||((e||!this.#v(r))&&(yield r),r===this.#f));)r=this.#p[r]}#H(e){return e!==void 0&&this.#h.get(this.#l[e])===e}*entries(){for(let e of this.#O())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*rentries(){for(let e of this.#D())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*keys(){for(let e of this.#O()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*rkeys(){for(let e of this.#D()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*values(){for(let e of this.#O())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}*rvalues(){for(let e of this.#D())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&e(n,this.#l[s],this))return this.get(this.#l[s],r)}}forEach(e,r=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}rforEach(e,r=this){for(let s of this.#D()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}purgeStale(){let e=!1;for(let r of this.#D({allowStale:!0}))this.#v(r)&&(this.#R(this.#l[r],"expire"),e=!0);return e}info(e){let r=this.#h.get(e);if(r===void 0)return;let s=this.#s[r],i=this.#c(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#g&&this.#M){let o=this.#g[r],a=this.#M[r];if(o&&a){let l=o-(this.#u.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let e=[];for(let r of this.#O({allowStale:!0})){let s=this.#l[r],i=this.#s[r],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#g&&this.#M){o.ttl=this.#g[r];let a=this.#u.now()-this.#M[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),e.unshift([s,o])}return e}load(e){this.clear();for(let[r,s]of e){if(s.start){let i=Date.now()-s.start;s.start=this.#u.now()-i}this.set(r,s.value,s)}}set(e,r,s={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#W(e,r,s.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#R(e,"set"),this;let h=this.#a===0?void 0:this.#h.get(e);if(h===void 0)h=this.#a===0?this.#f:this.#k.length!==0?this.#k.pop():this.#a===this.#e?this.#j(!1):this.#a,this.#l[h]=e,this.#s[h]=r,this.#h.set(e,h),this.#p[this.#f]=h,this.#_[h]=this.#f,this.#f=h,this.#a++,this.#L(h,u,l),l&&(l.set="add"),c=!1,this.#x&&this.#i?.(r,e,"add");else{this.#N(h);let p=this.#s[h];if(r!==p){if(this.#A&&this.#c(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&!o&&(this.#b&&this.#n?.(f,e,"set"),this.#t&&this.#m?.push([f,e,"set"]))}else o||(this.#b&&this.#n?.(p,e,"set"),this.#t&&this.#m?.push([p,e,"set"]));if(this.#U(h),this.#L(h,u,l),this.#s[h]=r,l){l.set="replace";let f=p&&this.#c(p)?p.__staleWhileFetching:p;f!==void 0&&(l.oldValue=f)}}else l&&(l.set="update");this.#x&&this.onInsert?.(r,e,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(c||this.#F(h,i,n),l&&this.#I(l,h)),!o&&this.#t&&this.#m){let p=this.#m,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let e=this.#s[this.#w];if(this.#j(!0),this.#c(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#t&&this.#m){let e=this.#m,r;for(;r=e?.shift();)this.#o?.(...r)}}}#j(e){let r=this.#w,s=this.#l[r],i=this.#s[r];return this.#A&&this.#c(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(i,s,"evict"),this.#t&&this.#m?.push([i,s,"evict"])),this.#U(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),e&&(this.#l[r]=void 0,this.#s[r]=void 0,this.#k.push(r)),this.#a===1?(this.#w=this.#f=0,this.#k.length=0):this.#w=this.#p[r],this.#h.delete(s),this.#a--,r}has(e,r={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=r,n=this.#h.get(e);if(n!==void 0){let o=this.#s[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#v(n))i&&(i.has="stale",this.#I(i,n));else return s&&this.#C(n),i&&(i.has="hit",this.#I(i,n)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:s=this.allowStale}=r,i=this.#h.get(e);if(i===void 0||!s&&this.#v(i))return;let n=this.#s[i];return this.#c(n)?n.__staleWhileFetching:n}#$(e,r,s,i){let n=r===void 0?void 0:this.#s[r];if(this.#c(n))return n;let o=new Tt,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:i},c=(g,w=!1)=>{let{aborted:S}=o.signal,E=s.ignoreFetchAbort&&g!==void 0,y=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&g!==void 0);if(s.status&&(S&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,E&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),S&&!E&&!w)return h(o.signal.reason,y);let b=f,T=this.#s[r];return(T===f||E&&w&&T===void 0)&&(g===void 0?b.__staleWhileFetching!==void 0?this.#s[r]=b.__staleWhileFetching:this.#R(e,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(e,g,l.options))),g},u=g=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=g),h(g,!1)),h=(g,w)=>{let{aborted:S}=o.signal,E=S&&s.allowStaleOnFetchAbort,y=E||s.allowStaleOnFetchRejection,b=y||s.noDeleteOnFetchRejection,T=f;if(this.#s[r]===f&&(!b||!w&&T.__staleWhileFetching===void 0?this.#R(e,"fetch"):E||(this.#s[r]=T.__staleWhileFetching)),y)return s.status&&T.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),T.__staleWhileFetching;if(T.__returned===T)throw g},p=(g,w)=>{let S=this.#y?.(e,n,l);S&&S instanceof Promise&&S.then(E=>g(E===void 0?void 0:E),w),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(g(void 0),s.allowStaleOnFetchAbort&&(g=E=>c(E,!0)))})};s.status&&(s.status.fetchDispatched=!0);let f=new Promise(p).then(c,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(e,m,{...l.options,status:void 0}),r=this.#h.get(e)):this.#s[r]=m,m}#c(e){if(!this.#A)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Tt}async fetch(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:w=!1,status:S,signal:E}=r;if(!this.#A)return S&&(S.fetch="get"),this.get(e,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:S});let y={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},b=this.#h.get(e);if(b===void 0){S&&(S.fetch="miss");let T=this.#$(e,b,y,g);return T.__returned=T}else{let T=this.#s[b];if(this.#c(T)){let Re=s&&T.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Re&&(S.returnedStale=!0)),Re?T.__staleWhileFetching:T.__returned=T}let pe=this.#v(b);if(!w&&!pe)return S&&(S.fetch="hit"),this.#N(b),i&&this.#C(b),S&&this.#I(S,b),T;let Ce=this.#$(e,b,y,g),ke=Ce.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=pe?"stale":"refresh",ke&&pe&&(S.returnedStale=!0)),ke?Ce.__staleWhileFetching:Ce.__returned=Ce}}async forceFetch(e,r={}){let s=await this.fetch(e,r);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(e,r={}){let s=this.#S;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:n,...o}=r,a=this.get(e,o);if(!n&&a!==void 0)return a;let l=s(e,a,{options:o,context:i});return this.set(e,l,o),l}get(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#h.get(e);if(a!==void 0){let l=this.#s[a],c=this.#c(l);return o&&this.#I(o,a),this.#v(a)?(o&&(o.get="stale"),c?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?l.__staleWhileFetching:void 0):(n||this.#R(e,"expire"),o&&s&&(o.returnedStale=!0),s?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#N(a),i&&this.#C(a),l))}else o&&(o.get="miss")}#B(e,r){this.#_[r]=e,this.#p[e]=r}#N(e){e!==this.#f&&(e===this.#w?this.#w=this.#p[e]:this.#B(this.#_[e],this.#p[e]),this.#B(this.#f,e),this.#f=e)}delete(e){return this.#R(e,"delete")}#R(e,r){let s=!1;if(this.#a!==0){let i=this.#h.get(e);if(i!==void 0)if(this.#E?.[i]&&(clearTimeout(this.#E?.[i]),this.#E[i]=void 0),s=!0,this.#a===1)this.#K(r);else{this.#U(i);let n=this.#s[i];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(n,e,r),this.#t&&this.#m?.push([n,e,r])),this.#h.delete(e),this.#l[i]=void 0,this.#s[i]=void 0,i===this.#f)this.#f=this.#_[i];else if(i===this.#w)this.#w=this.#p[i];else{let o=this.#_[i];this.#p[o]=this.#p[i];let a=this.#p[i];this.#_[a]=this.#_[i]}this.#a--,this.#k.push(i)}}if(this.#t&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#K("delete")}#K(e){for(let r of this.#D({allowStale:!0})){let s=this.#s[r];if(this.#c(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#l[r];this.#b&&this.#n?.(s,i,e),this.#t&&this.#m?.push([s,i,e])}}if(this.#h.clear(),this.#s.fill(void 0),this.#l.fill(void 0),this.#g&&this.#M){this.#g.fill(0),this.#M.fill(0);for(let r of this.#E??[])r!==void 0&&clearTimeout(r);this.#E?.fill(void 0)}if(this.#T&&this.#T.fill(0),this.#w=0,this.#f=0,this.#k.length=0,this.#d=0,this.#a=0,this.#t&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},ns=typeof process=="object"&&process?process:{stdout:null,stderr:null},Vo=t=>!!t&&typeof t=="object"&&(t instanceof Mt||t instanceof yr.default||Qo(t)||Zo(t)),Qo=t=>!!t&&typeof t=="object"&&t instanceof Ct.EventEmitter&&typeof t.pipe=="function"&&t.pipe!==yr.default.Writable.prototype.pipe,Zo=t=>!!t&&typeof t=="object"&&t instanceof Ct.EventEmitter&&typeof t.write=="function"&&typeof t.end=="function",ne=Symbol("EOF"),oe=Symbol("maybeEmitEnd"),fe=Symbol("emittedEnd"),ft=Symbol("emittingEnd"),Ge=Symbol("emittedError"),mt=Symbol("closed"),os=Symbol("read"),gt=Symbol("flush"),as=Symbol("flushChunk"),G=Symbol("encoding"),Pe=Symbol("decoder"),A=Symbol("flowing"),Ke=Symbol("paused"),Ie=Symbol("resume"),C=Symbol("buffer"),D=Symbol("pipes"),k=Symbol("bufferLength"),ur=Symbol("bufferPush"),St=Symbol("bufferShift"),O=Symbol("objectMode"),M=Symbol("destroyed"),hr=Symbol("error"),dr=Symbol("emitData"),ls=Symbol("emitEnd"),pr=Symbol("emitEnd2"),q=Symbol("async"),fr=Symbol("abort"),Et=Symbol("aborted"),Ye=Symbol("signal"),ye=Symbol("dataListeners"),U=Symbol("discarded"),ze=t=>Promise.resolve().then(t),ea=t=>t(),ta=t=>t==="end"||t==="finish"||t==="prefinish",ra=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,sa=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Ws=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Ie](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},ia=class extends Ws{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=s=>this.dest.emit("error",s),t.on("error",this.proxyErrors)}},na=t=>!!t.objectMode,oa=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Mt=class extends Ct.EventEmitter{[A]=!1;[Ke]=!1;[D]=[];[C]=[];[O];[G];[q];[Pe];[ne]=!1;[fe]=!1;[ft]=!1;[mt]=!1;[Ge]=null;[k]=0;[M]=!1;[Ye];[Et]=!1;[ye]=0;[U]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");na(e)?(this[O]=!0,this[G]=null):oa(e)?(this[G]=e.encoding,this[O]=!1):(this[O]=!1,this[G]=null),this[q]=!!e.async,this[Pe]=this[G]?new Fs.StringDecoder(this[G]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[C]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[D]});let{signal:r}=e;r&&(this[Ye]=r,r.aborted?this[fr]():r.addEventListener("abort",()=>this[fr]()))}get bufferLength(){return this[k]}get encoding(){return this[G]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[O]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[q]}set async(t){this[q]=this[q]||!!t}[fr](){this[Et]=!0,this.emit("abort",this[Ye]?.reason),this.destroy(this[Ye]?.reason)}get aborted(){return this[Et]}set aborted(t){}write(t,e,r){if(this[Et])return!1;if(this[ne])throw new Error("write after end");if(this[M])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let s=this[q]?ze:ea;if(!this[O]&&!Buffer.isBuffer(t)){if(sa(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(ra(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[O]?(this[A]&&this[k]!==0&&this[gt](!0),this[A]?this.emit("data",t):this[ur](t),this[k]!==0&&this.emit("readable"),r&&s(r),this[A]):t.length?(typeof t=="string"&&!(e===this[G]&&!this[Pe]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[G]&&(t=this[Pe].write(t)),this[A]&&this[k]!==0&&this[gt](!0),this[A]?this.emit("data",t):this[ur](t),this[k]!==0&&this.emit("readable"),r&&s(r),this[A]):(this[k]!==0&&this.emit("readable"),r&&s(r),this[A])}read(t){if(this[M])return null;if(this[U]=!1,this[k]===0||t===0||t&&t>this[k])return this[oe](),null;this[O]&&(t=null),this[C].length>1&&!this[O]&&(this[C]=[this[G]?this[C].join(""):Buffer.concat(this[C],this[k])]);let e=this[os](t||null,this[C][0]);return this[oe](),e}[os](t,e){if(this[O])this[St]();else{let r=e;t===r.length||t===null?this[St]():typeof r=="string"?(this[C][0]=r.slice(t),e=r.slice(0,t),this[k]-=t):(this[C][0]=r.subarray(t),e=r.subarray(0,t),this[k]-=t)}return this.emit("data",e),!this[C].length&&!this[ne]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[ne]=!0,this.writable=!1,(this[A]||!this[Ke])&&this[oe](),this}[Ie](){this[M]||(!this[ye]&&!this[D].length&&(this[U]=!0),this[Ke]=!1,this[A]=!0,this.emit("resume"),this[C].length?this[gt]():this[ne]?this[oe]():this.emit("drain"))}resume(){return this[Ie]()}pause(){this[A]=!1,this[Ke]=!0,this[U]=!1}get destroyed(){return this[M]}get flowing(){return this[A]}get paused(){return this[Ke]}[ur](t){this[O]?this[k]+=1:this[k]+=t.length,this[C].push(t)}[St](){return this[O]?this[k]-=1:this[k]-=this[C][0].length,this[C].shift()}[gt](t=!1){do;while(this[as](this[St]())&&this[C].length);!t&&!this[C].length&&!this[ne]&&this.emit("drain")}[as](t){return this.emit("data",t),this[A]}pipe(t,e){if(this[M])return t;this[U]=!1;let r=this[fe];return e=e||{},t===ns.stdout||t===ns.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[D].push(e.proxyErrors?new ia(this,t,e):new Ws(this,t,e)),this[q]?ze(()=>this[Ie]()):this[Ie]()),t}unpipe(t){let e=this[D].find(r=>r.dest===t);e&&(this[D].length===1?(this[A]&&this[ye]===0&&(this[A]=!1),this[D]=[]):this[D].splice(this[D].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[U]=!1,this[ye]++,!this[D].length&&!this[A]&&this[Ie]();else if(t==="readable"&&this[k]!==0)super.emit("readable");else if(ta(t)&&this[fe])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ge]){let s=e;this[q]?ze(()=>s.call(this,this[Ge])):s.call(this,this[Ge])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[ye]=this.listeners("data").length,this[ye]===0&&!this[U]&&!this[D].length&&(this[A]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[ye]=0,!this[U]&&!this[D].length&&(this[A]=!1)),e}get emittedEnd(){return this[fe]}[oe](){!this[ft]&&!this[fe]&&!this[M]&&this[C].length===0&&this[ne]&&(this[ft]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[mt]&&this.emit("close"),this[ft]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==M&&this[M])return!1;if(t==="data")return!this[O]&&!r?!1:this[q]?(ze(()=>this[dr](r)),!0):this[dr](r);if(t==="end")return this[ls]();if(t==="close"){if(this[mt]=!0,!this[fe]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[Ge]=r,super.emit(hr,r);let i=!this[Ye]||this.listeners("error").length?super.emit("error",r):!1;return this[oe](),i}else if(t==="resume"){let i=super.emit("resume");return this[oe](),i}else if(t==="finish"||t==="prefinish"){let i=super.emit(t);return this.removeAllListeners(t),i}let s=super.emit(t,...e);return this[oe](),s}[dr](t){for(let r of this[D])r.dest.write(t)===!1&&this.pause();let e=this[U]?!1:super.emit("data",t);return this[oe](),e}[ls](){return this[fe]?!1:(this[fe]=!0,this.readable=!1,this[q]?(ze(()=>this[pr]()),!0):this[pr]())}[pr](){if(this[Pe]){let e=this[Pe].end();if(e){for(let r of this[D])r.dest.write(e);this[U]||super.emit("data",e)}}for(let e of this[D])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[O]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[O]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[O])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[G]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(M,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[U]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[ne])return e();let s,i,n=c=>{this.off("data",o),this.off("end",a),this.off(M,l),e(),i(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(M,l),this.pause(),s({value:c,done:!!this[ne]})},a=()=>{this.off("error",n),this.off("data",o),this.off(M,l),e(),s({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,u)=>{i=u,s=c,this.once(M,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[U]=!1;let t=!1,e=()=>(this.pause(),this.off(hr,e),this.off(M,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let s=this.read();return s===null?e():{done:!1,value:s}};return this.once("end",e),this.once(hr,e),this.once(M,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[M])return t?this.emit("error",t):this.emit(M),this;this[M]=!0,this[U]=!0,this[C].length=0,this[k]=0;let e=this;return typeof e.close=="function"&&!this[mt]&&e.close(),t?this.emit("error",t):this.emit(M),this}static get isStream(){return Vo}},aa=Q.realpathSync.native,Ve={lstatSync:Q.lstatSync,readdir:Q.readdir,readdirSync:Q.readdirSync,readlinkSync:Q.readlinkSync,realpathSync:aa,promises:{lstat:Se.lstat,readdir:Se.readdir,readlink:Se.readlink,realpath:Se.realpath}},Hs=t=>!t||t===Ve||t===qo?Ve:{...Ve,...t,promises:{...Ve.promises,...t.promises||{}}},js=/^\\\\\?\\([a-z]:)\\?$/i,la=t=>t.replace(/\//g,"\\").replace(js,"$1\\"),ca=/[\\\/]/,j=0,$s=1,Bs=2,V=4,Gs=6,Ks=8,_e=10,Ys=12,H=15,Je=~H,mr=16,cs=32,Qe=64,K=128,wt=256,bt=512,us=Qe|K|bt,ua=1023,gr=t=>t.isFile()?Ks:t.isDirectory()?V:t.isSymbolicLink()?_e:t.isCharacterDevice()?Bs:t.isBlockDevice()?Gs:t.isSocket()?Ys:t.isFIFO()?$s:j,hs=new At({max:2**12}),Ze=t=>{let e=hs.get(t);if(e)return e;let r=t.normalize("NFKD");return hs.set(t,r),r},ds=new At({max:2**12}),yt=t=>{let e=ds.get(t);if(e)return e;let r=Ze(t.toLowerCase());return ds.set(t,r),r},ps=class extends At{constructor(){super({max:256})}},ha=class extends At{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},zs=Symbol("PathScurry setAsCwd"),L=class{name;root;roots;parent;nocase;isCWD=!1;#e;#r;get dev(){return this.#r}#n;get mode(){return this.#n}#i;get nlink(){return this.#i}#o;get uid(){return this.#o}#y;get gid(){return this.#y}#S;get rdev(){return this.#S}#u;get blksize(){return this.#u}#a;get ino(){return this.#a}#d;get size(){return this.#d}#h;get blocks(){return this.#h}#l;get atimeMs(){return this.#l}#s;get mtimeMs(){return this.#s}#p;get ctimeMs(){return this.#p}#_;get birthtimeMs(){return this.#_}#w;get atime(){return this.#w}#f;get mtime(){return this.#f}#k;get ctime(){return this.#k}#m;get birthtime(){return this.#m}#T;#M;#g;#E;#b;#A;#t;#x;#P;#C;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=j,r,s,i,n,o){this.name=t,this.#T=i?yt(t):Ze(t),this.#t=e&ua,this.nocase=i,this.roots=s,this.root=r||this,this.#x=n,this.#g=o.fullpath,this.#b=o.relative,this.#A=o.relativePosix,this.parent=o.parent,this.parent?this.#e=this.parent.#e:this.#e=Hs(o.fs)}depth(){return this.#M!==void 0?this.#M:this.parent?this.#M=this.parent.depth()+1:this.#M=0}childrenCache(){return this.#x}resolve(t){if(!t)return this;let e=this.getRootString(t),r=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#I(r):this.#I(r)}#I(t){let e=this;for(let r of t)e=e.child(r);return e}children(){let t=this.#x.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#x.set(this,e),this.#t&=~mr,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let r=this.children(),s=this.nocase?yt(t):Ze(t);for(let a of r)if(a.#T===s)return a;let i=this.parent?this.sep:"",n=this.#g?this.#g+i+t:void 0,o=this.newChild(t,j,{...e,parent:this,fullpath:n});return this.canReaddir()||(o.#t|=K),r.push(o),o}relative(){if(this.isCWD)return"";if(this.#b!==void 0)return this.#b;let t=this.name,e=this.parent;if(!e)return this.#b=this.name;let r=e.relative();return r+(!r||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#A!==void 0)return this.#A;let t=this.name,e=this.parent;if(!e)return this.#A=this.fullpathPosix();let r=e.relativePosix();return r+(!r||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let r=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=r}fullpathPosix(){if(this.#E!==void 0)return this.#E;if(this.sep==="/")return this.#E=this.fullpath();if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(s)?this.#E=`//?/${s}`:this.#E=s}let t=this.parent,e=t.fullpathPosix(),r=e+(!e||!t.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#t&H)===j}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#t&H)===Ks}isDirectory(){return(this.#t&H)===V}isCharacterDevice(){return(this.#t&H)===Bs}isBlockDevice(){return(this.#t&H)===Gs}isFIFO(){return(this.#t&H)===$s}isSocket(){return(this.#t&H)===Ys}isSymbolicLink(){return(this.#t&_e)===_e}lstatCached(){return this.#t&cs?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#C}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let t=this.#t&H;return!(t!==j&&t!==_e||this.#t&wt||this.#t&K)}calledReaddir(){return!!(this.#t&mr)}isENOENT(){return!!(this.#t&K)}isNamed(t){return this.nocase?this.#T===yt(t):this.#T===Ze(t)}async readlink(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(e);if(r)return this.#P=r}catch(e){this.#D(e.code);return}}readlinkSync(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(e);if(r)return this.#P=r}catch(e){this.#D(e.code);return}}#F(t){this.#t|=mr;for(let e=t.provisional;e<t.length;e++){let r=t[e];r&&r.#v()}}#v(){this.#t&K||(this.#t=(this.#t|K)&Je,this.#G())}#G(){let t=this.children();t.provisional=0;for(let e of t)e.#v()}#U(){this.#t|=bt,this.#L()}#L(){if(this.#t&Qe)return;let t=this.#t;(t&H)===V&&(t&=Je),this.#t=t|Qe,this.#G()}#W(t=""){t==="ENOTDIR"||t==="EPERM"?this.#L():t==="ENOENT"?this.#v():this.children().provisional=0}#O(t=""){t==="ENOTDIR"?this.parent.#L():t==="ENOENT"&&this.#v()}#D(t=""){let e=this.#t;e|=wt,t==="ENOENT"&&(e|=K),(t==="EINVAL"||t==="UNKNOWN")&&(e&=Je),this.#t=e,t==="ENOTDIR"&&this.parent&&this.parent.#L()}#H(t,e){return this.#$(t,e)||this.#j(t,e)}#j(t,e){let r=gr(t),s=this.newChild(t.name,r,{parent:this}),i=s.#t&H;return i!==V&&i!==_e&&i!==j&&(s.#t|=Qe),e.unshift(s),e.provisional++,s}#$(t,e){for(let r=e.provisional;r<e.length;r++){let s=e[r];if((this.nocase?yt(t.name):Ze(t.name))===s.#T)return this.#c(t,s,r,e)}}#c(t,e,r,s){let i=e.name;return e.#t=e.#t&Je|gr(t),i!==t.name&&(e.name=t.name),r!==s.provisional&&(r===s.length-1?s.pop():s.splice(r,1),s.unshift(e)),s.provisional++,e}async lstat(){if((this.#t&K)===0)try{return this.#B(await this.#e.promises.lstat(this.fullpath())),this}catch(t){this.#O(t.code)}}lstatSync(){if((this.#t&K)===0)try{return this.#B(this.#e.lstatSync(this.fullpath())),this}catch(t){this.#O(t.code)}}#B(t){let{atime:e,atimeMs:r,birthtime:s,birthtimeMs:i,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:u,ino:h,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=t;this.#w=e,this.#l=r,this.#m=s,this.#_=i,this.#u=n,this.#h=o,this.#k=a,this.#p=l,this.#r=c,this.#y=u,this.#a=h,this.#n=p,this.#f=f,this.#s=m,this.#i=g,this.#S=w,this.#d=S,this.#o=E;let y=gr(t);this.#t=this.#t&Je|y|cs,y!==j&&y!==V&&y!==_e&&(this.#t|=Qe)}#N=[];#R=!1;#K(t){this.#R=!1;let e=this.#N.slice();this.#N.length=0,e.forEach(r=>r(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);e?t(null,i):queueMicrotask(()=>t(null,i));return}if(this.#N.push(t),this.#R)return;this.#R=!0;let s=this.fullpath();this.#e.readdir(s,{withFileTypes:!0},(i,n)=>{if(i)this.#W(i.code),r.provisional=0;else{for(let o of n)this.#H(o,r);this.#F(r)}this.#K(r.slice(0,r.provisional))})}#Y;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#Y)await this.#Y;else{let r=()=>{};this.#Y=new Promise(s=>r=s);try{for(let s of await this.#e.promises.readdir(e,{withFileTypes:!0}))this.#H(s,t);this.#F(t)}catch(s){this.#W(s.code),t.provisional=0}this.#Y=void 0,r()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let r of this.#e.readdirSync(e,{withFileTypes:!0}))this.#H(r,t);this.#F(t)}catch(r){this.#W(r.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#t&us)return!1;let t=H&this.#t;return t===j||t===V||t===_e}shouldWalk(t,e){return(this.#t&V)===V&&!(this.#t&us)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#C)return this.#C;if(!((bt|wt|K)&this.#t))try{let t=await this.#e.promises.realpath(this.fullpath());return this.#C=this.resolve(t)}catch{this.#U()}}realpathSync(){if(this.#C)return this.#C;if(!((bt|wt|K)&this.#t))try{let t=this.#e.realpathSync(this.fullpath());return this.#C=this.resolve(t)}catch{this.#U()}}[zs](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),r=[],s=this;for(;s&&s.parent;)e.add(s),s.#b=r.join(this.sep),s.#A=r.join("/"),s=s.parent,r.push("..");for(s=t;s&&s.parent&&!e.has(s);)s.#b=void 0,s.#A=void 0,s=s.parent}},Js=class Xs extends L{sep="\\";splitSep=ca;constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}newChild(e,r=j,s={}){return new Xs(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return Le.win32.parse(e).root}getRoot(e){if(e=la(e.toUpperCase()),e===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(e,r))return this.roots[e]=s;return this.roots[e]=new _r(e,this).root}sameRoot(e,r=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(js,"$1\\"),e===r}},qs=class Vs extends L{splitSep="/";sep="/";constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,r=j,s={}){return new Vs(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Qs=class{root;rootPath;roots;cwd;#e;#r;#n;nocase;#i;constructor(t=process.cwd(),e,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=Ve}={}){this.#i=Hs(n),(t instanceof URL||t.startsWith("file://"))&&(t=(0,Us.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#e=new ps,this.#r=new ps,this.#n=new ha(i);let a=o.substring(this.rootPath.length).split(r);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,u=e.sep,h=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(u),relativePosix:new Array(m).fill("..").join("/"),fullpath:h+=(p?"":u)+f}),p=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#e.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpath();return this.#e.set(e,s),s}resolvePosix(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#r.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpathPosix();return this.#r.set(e,s),s}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r}=e;if(t.canReaddir()){let s=await t.readdir();return r?s:s.map(i=>i.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0}=e;return t.canReaddir()?r?t.readdirSync():t.readdirSync().map(s=>s.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.readlink();return e?r:r?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.readlinkSync();return e?r:r?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.realpath();return e?r:r?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.realpathSync();return e?r:r?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set,l=(u,h)=>{a.add(u),u.readdirCB((p,f)=>{if(p)return h(p);let m=f.length;if(!m)return h();let g=()=>{--m===0&&h()};for(let w of f)(!i||i(w))&&o.push(r?w:w.fullpath()),s&&w.isSymbolicLink()?w.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,n)?l(S,g):g()):w.shouldWalk(a,n)?l(w,g):g()},!0)},c=t;return new Promise((u,h)=>{l(c,p=>{if(p)return h(p);u(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let u of c){(!i||i(u))&&o.push(r?u:u.fullpath());let h=u;if(u.isSymbolicLink()){if(!(s&&(h=u.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(a,n)&&a.add(h)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e;(!i||i(t))&&(yield r?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let c of l){(!i||i(c))&&(yield r?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(s&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(o,n)&&o.add(u)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new Mt({objectMode:!0});(!i||i(t))&&o.write(r?t:t.fullpath());let a=new Set,l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=(g,w,S=!1)=>{if(g)return o.emit("error",g);if(s&&!S){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(b=>b?.isUnknown()?b.lstat():b));if(E.length){Promise.all(E).then(()=>f(null,w,!0));return}}for(let E of w)E&&(!i||i(E))&&(o.write(r?E:E.fullpath())||(h=!0));c--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,n)&&l.push(y)}h&&!o.flowing?o.once("drain",u):m||u()},m=!0;p.readdirCB(f,!0),m=!1}};return u(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new Mt({objectMode:!0}),a=new Set;(!i||i(t))&&o.write(r?t:t.fullpath());let l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=p.readdirSync();for(let m of f)(!i||i(m))&&(o.write(r?m:m.fullpath())||(h=!0));c--;for(let m of f){let g=m;if(m.isSymbolicLink()){if(!(s&&(g=m.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(a,n)&&l.push(g)}}h&&!o.flowing&&o.once("drain",u)};return u(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[zs](e)}},_r=class extends Qs{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,Le.win32,"\\",{...e,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(t){return Le.win32.parse(t).root.toUpperCase()}newRoot(t){return new Js(this.rootPath,V,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},br=class extends Qs{sep="/";constructor(t=process.cwd(),e={}){let{nocase:r=!1}=e;super(t,Le.posix,"/",{...e,nocase:r}),this.nocase=r}parseRootPath(t){return"/"}newRoot(t){return new qs(this.rootPath,V,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Zs=class extends br{constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,{...e,nocase:r})}},ec=process.platform==="win32"?Js:qs,da=process.platform==="win32"?_r:process.platform==="darwin"?Zs:br,pa=t=>t.length>=1,fa=t=>t.length>=1,ma=Symbol.for("nodejs.util.inspect.custom"),ei=class ti{#e;#r;#n;length;#i;#o;#y;#S;#u;#a;#d=!0;constructor(e,r,s,i){if(!pa(e))throw new TypeError("empty pattern list");if(!fa(r))throw new TypeError("empty glob list");if(r.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#e,[u,h,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[u,h,p,f,""].join("/");this.#e=[g,...c],this.#r=[w,...m],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#e,[a,...l]=this.#r;o[0]===""&&(o.shift(),l.shift());let c=n+"/",u=a+"/";this.#e=[c,...o],this.#r=[u,...l],this.length=this.#e.length}}}[ma](){return"Pattern <"+this.#r.slice(this.#n).join("/")+">"}pattern(){return this.#e[this.#n]}isString(){return typeof this.#e[this.#n]=="string"}isGlobstar(){return this.#e[this.#n]===P}isRegExp(){return this.#e[this.#n]instanceof RegExp}globString(){return this.#y=this.#y||(this.#n===0?this.isAbsolute()?this.#r[0]+this.#r.slice(1).join("/"):this.#r.join("/"):this.#r.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new ti(this.#e,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#u=this.#u,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#u!==void 0?this.#u:this.#u=this.#i==="win32"&&this.#n===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#S!==void 0?this.#S:this.#S=this.#i==="win32"&&this.#n===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#n===0?e:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},ga=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",fs=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:r,noext:s,noglobstar:i,platform:n=ga}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:e,nocase:r,noext:s,noglobstar:i,optimizationLevel:2,platform:n,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new ge(t,this.mmopts);for(let r=0;r<e.set.length;r++){let s=e.set[r],i=e.globParts[r];if(!s||!i)throw new Error("invalid pattern object");for(;s[0]==="."&&i[0]===".";)s.shift(),i.shift();let n=new ei(s,i,0,this.platform),o=new ge(n.globString(),this.mmopts),a=i[i.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(t){let e=t.fullpath(),r=`${e}/`,s=t.relative()||".",i=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(i))return!0;for(let n of this.absolute)if(n.match(e)||n.match(r))return!0;return!1}childrenIgnored(t){let e=t.fullpath()+"/",r=(t.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(e))return!0;return!1}},Sa=class ri{store;constructor(e=new Map){this.store=e}copy(){return new ri(new Map(this.store))}hasWalked(e,r){return this.store.get(e.fullpath())?.has(r.globString())}storeWalked(e,r){let s=e.fullpath(),i=this.store.get(s);i?i.add(r.globString()):this.store.set(s,new Set([r.globString()]))}},Ea=class{store=new Map;add(t,e,r){let s=(e?2:0)|(r?1:0),i=this.store.get(t);this.store.set(t,i===void 0?s:s&i)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}},wa=class{store=new Map;add(t,e){if(!t.canReaddir())return;let r=this.store.get(t);r?r.find(s=>s.globString()===e.globString())||r.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},ms=class si{hasWalkedCache;matches=new Ea;subwalks=new wa;patterns;follow;dot;opts;constructor(e,r){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=r?r.copy():new Sa}processPatterns(e,r){this.patterns=r;let s=r.map(i=>[e,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let h=n.rest();if(h)n=h;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,u=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,u=!0;if(l=n.pattern(),c=n.rest(),u){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let h=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,h);continue}else if(l===P){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let h=c?.pattern(),p=c?.rest();if(!c||(h===""||h===".")&&!p)this.matches.add(i,a,h===""||h===".");else if(h===".."){let f=i.parent||i;p?this.hasWalkedCache.hasWalked(f,p)||this.subwalks.add(f,p):this.matches.add(f,a,!0)}}else l instanceof RegExp&&this.subwalks.add(i,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new si(this.opts,this.hasWalkedCache)}filterEntries(e,r){let s=this.subwalks.get(e),i=this.child();for(let n of r)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===P?i.testGlobstar(n,o,c,a):l instanceof RegExp?i.testRegExp(n,l,c,a):i.testString(n,l,c,a)}return i}testGlobstar(e,r,s,i){if((this.dot||!e.name.startsWith("."))&&(r.hasMore()||this.matches.add(e,i,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,r):e.isSymbolicLink()&&(s&&r.checkFollowGlobstar()?this.subwalks.add(e,s):r.markFollowGlobstar()&&this.subwalks.add(e,r)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(e,n,s.rest(),i);else if(n===".."){let o=e.parent||e;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(e,n,s.rest(),i)}}testRegExp(e,r,s,i){r.test(e.name)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}testString(e,r,s,i){e.isNamed(r)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}},ya=(t,e)=>typeof t=="string"?new fs([t],e):Array.isArray(t)?new fs(t,e):t,ii=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#r;#n;signal;maxDepth;includeChildMatches;constructor(t,e,r){if(this.patterns=t,this.path=e,this.opts=r,this.#n=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#r=ya(r.ignore??[],r),!this.includeChildMatches&&typeof this.#r.add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#i(t){return this.seen.has(t)||!!this.#r?.ignored?.(t)}#o(t){return!!this.#r?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#e.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#e.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||await t.realpath(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#i(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||t.realpathSync(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,e)}matchFinish(t,e){if(this.#i(t))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${t.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let s=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(r){let i=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?t.relativePosix():t.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(t,e,r){let s=await this.matchCheck(t,r);s&&this.matchFinish(s,e)}matchSync(t,e,r){let s=this.matchCheckSync(t,r);s&&this.matchFinish(s,e)}walkCB(t,e,r){this.signal?.aborted&&r(),this.walkCB2(t,e,new ms(this.opts),r)}walkCB2(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,r,n):o.readdirCB((l,c)=>this.walkCB3(o,c,r,n),!0)}n()}walkCB3(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let[o,a]of r.subwalks.entries())i++,this.walkCB2(o,a,r.child(),n);n()}walkCBSync(t,e,r){this.signal?.aborted&&r(),this.walkCB2Sync(t,e,new ms(this.opts),r)}walkCB2Sync(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirSync();this.walkCB3Sync(o,a,r,n)}n()}walkCB3Sync(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let[o,a]of r.subwalks.entries())i++,this.walkCB2Sync(o,a,r.child(),n);n()}},gs=class extends ii{matches=new Set;constructor(t,e,r){super(t,e,r)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Ss=class extends ii{results;constructor(t,e,r){super(t,e,r),this.results=new Mt({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},_a=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",be=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,Ps.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||_a,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?_r:e.platform==="darwin"?Zs:e.platform?br:da;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(a=>new ge(a,s)),[n,o]=i.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new ei(a,c,0,this.platform)})}async walk(){return[...await new gs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new gs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Ss(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Ss(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},ba=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let r of t)if(new ge(r,e).hasMagic())return!0;return!1};function kt(t,e={}){return new be(t,e).streamSync()}function ni(t,e={}){return new be(t,e).stream()}function et(t,e={}){return new be(t,e).walkSync()}async function Es(t,e={}){return new be(t,e).walk()}function Rt(t,e={}){return new be(t,e).iterateSync()}function oi(t,e={}){return new be(t,e).iterate()}var va=kt,Ta=Object.assign(ni,{sync:kt}),Ma=Rt,Aa=Object.assign(oi,{sync:Rt}),Ca=Object.assign(et,{stream:kt,iterate:Rt}),ws=Object.assign(Es,{glob:Es,globSync:et,sync:Ca,globStream:ni,stream:Ta,globStreamSync:kt,streamSync:va,globIterate:oi,iterate:Aa,globIterateSync:Rt,iterateSync:Ma,Glob:be,hasMagic:ba,escape:Cs,unescape:xe});ws.glob=ws;var ae=require("fs"),ai=require("path");function li(t){try{if(!(0,ae.existsSync)(t))return{offsets:{}};let e=(0,ae.readFileSync)(t,"utf-8"),r=JSON.parse(e);return r.offsets?r:{offsets:{}}}catch(e){return d.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:t,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function ci(t,e){try{let r=(0,ai.dirname)(t);(0,ae.existsSync)(r)||(0,ae.mkdirSync)(r,{recursive:!0}),(0,ae.writeFileSync)(t,JSON.stringify(e,null,2))}catch(r){d.warn("TRANSCRIPT","Failed to save watch state",{statePath:t,error:r instanceof Error?r.message:String(r)})}}var nt=X(require("path"),1);var Fe=X(require("path"),1),Y=require("fs");var ui=require("node:child_process");function Ot(t,e,r){return(0,ui.spawn)(t,e??[],{windowsHide:!0,...r})}var $={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},Ee={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3};function le(t){return process.platform==="win32"?Math.round(t*$.WINDOWS_MULTIPLIER):t}var Z=require("fs"),tt=require("path"),vr=require("os");var ee=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(le($.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,tt.join)((0,vr.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,tt.join)((0,vr.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(r[s]=process.env[s]);return r}static loadFromFile(e,r=!0){try{if(!(0,Z.existsSync)(e)){let a=this.getAllDefaults();try{let l=(0,tt.dirname)(e);(0,Z.existsSync)(l)||(0,Z.mkdirSync)(l,{recursive:!0}),(0,Z.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let s=(0,Z.readFileSync)(e,"utf-8"),i=JSON.parse(s.replace(/^\uFEFF/,"")),n=i;if(i.env&&typeof i.env=="object"){n=i.env;try{(0,Z.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let o={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))n[a]!==void 0&&(o[a]=n[a]);return r?this.applyEnvOverrides(o):o}catch(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();return r?this.applyEnvOverrides(i):i}}};var Dt=null;function ce(){return Dt!==null||(Dt=ee.loadFromFile(ct)),Dt}var ve=require("fs");var kr=require("child_process");var te=require("fs"),Ar=X(require("path"),1);var ka=["CLAUDECODE_","CLAUDE_CODE_"],Ra=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),Oa=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Pt(t=process.env){let e={};for(let[r,s]of Object.entries(t))if(s!==void 0){if(Oa.has(r)){e[r]=s;continue}Ra.has(r)||ka.some(i=>r.startsWith(i))||(e[r]=s)}return e}var Da=5e3,Pa=1e3,Ia=R.supervisorRegistry();function ue(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(d.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return d.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function It(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(s=>!ue(s.pid)))return;await new Promise(s=>setTimeout(s,100))}}var xa=5e3,hi=new Map;function La(t){let e=hi.get(t);if(e&&Date.now()-e.capturedAtMs<xa)return e.token;let r=null;try{let s=(0,kr.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Pt(process.env),LC_ALL:"C",LANG:"C"}});if(s.status===0){let i=s.stdout.trim();r=i.length>0?i:null}}catch(s){d.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:s instanceof Error?s.message:String(s)}),r=null}return hi.set(t,{token:r,capturedAtMs:Date.now()}),r}function di(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,te.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return La(t);try{let e=(0,kr.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Pt(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Rr(t){if(!t||!ue(t.pid))return!1;if(!t.startToken)return!0;let e=di(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||d.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var Cr=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Ia){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,te.mkdirSync)(Ar.default.dirname(this.registryPath),{recursive:!0}),!(0,te.existsSync)(this.registryPath)){this.persist();return}try{let s=JSON.parse((0,te.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,n]of Object.entries(s))this.entries.set(i,n)}catch(r){r instanceof Error?d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,s){this.initialize(),this.entries.set(e,r),s&&this.runtimeProcesses.set(e,s),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&Mr()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let s=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(s)?0:s)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(s=>s.sessionId!==void 0&&String(s.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[s,i]of this.entries)ue(i.pid)||(this.entries.delete(s),this.runtimeProcesses.delete(s),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let s=0;s<r;s+=1)Mr();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let s=typeof e=="number"?e:Number(e)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:s,pids:r.map(o=>o.pid)});let i=r.filter(o=>ue(o.pid));for(let o of i)try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},a):d.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(a)})}await It(i,Da);let n=i.filter(o=>ue(o.pid));for(let o of n){d.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:s});try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},a):d.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(a)})}}if(n.length>0){let o=Date.now()+Pa;for(;Date.now()<o&&n.filter(l=>ue(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of r)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of r)o.type==="sdk"&&Mr();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:s,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,te.mkdirSync)(Ar.default.dirname(this.registryPath),{recursive:!0}),(0,te.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Tr=null;function xt(){return Tr||(Tr=new Cr),Tr}var Na=[];function Mr(){let t=Na.shift();t&&t()}var fi=require("child_process"),Ne=require("fs"),mi=require("util");var Ua=(0,mi.promisify)(fi.execFile),Fa=R.workerPid();async function gi(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Fa,s=t.registry.getAll(),i=[...s].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!ue(o.pid)){t.registry.unregister(o.id);continue}try{await pi(o,"SIGTERM")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await It(i,5e3);let n=i.filter(o=>ue(o.pid));for(let o of n)try{await pi(o,"SIGKILL")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await It(n,1e3);for(let o of i)t.registry.unregister(o.id);for(let o of s.filter(a=>a.pid===e))t.registry.unregister(o.id);Wa(r,e),t.registry.pruneDeadEntries()}function Wa(t,e){if(!(0,Ne.existsSync)(t))return;let r=null;try{let s=JSON.parse((0,Ne.readFileSync)(t,"utf-8"));r=typeof s.pid=="number"?s.pid:null}catch(s){d.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:s instanceof Error?s.message:String(s)});return}if(r!==e){d.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:r,currentPid:e});return}try{(0,Ne.rmSync)(t,{force:!0})}catch(s){s instanceof Error?d.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},s):d.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(s)})}}async function pi(t,e){let{pid:r,pgid:s}=t;if(process.platform!=="win32"){if(typeof s=="number")try{process.kill(-s,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await Ha();if(i){await new Promise((o,a)=>{i(r,e,l=>{if(!l){o();return}if(l.code==="ESRCH"){o();return}a(l)})});return}let n=["/PID",String(r),"/T"];e==="SIGKILL"&&n.push("/F"),await Ua("taskkill",n,{timeout:$.POWERSHELL_COMMAND,windowsHide:!0})}async function Ha(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return d.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var Si=3e4,Ue=null;function ja(){let e=xt().pruneDeadEntries();e>0&&d.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Ei(){Ue===null&&(Ue=setInterval(ja,Si),Ue.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:Si}))}function wi(){Ue!==null&&(clearInterval(Ue),Ue=null,d.debug("SYSTEM","Health checker stopped"))}var $a=R.workerPid(),Or=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Lt({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Ei()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async s=>{if(this.shutdownInitiated){d.warn("SYSTEM",`Received ${s} but shutdown already in progress`);return}this.shutdownInitiated=!0,d.info("SYSTEM",`Received ${s}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?d.error("SYSTEM","Error during shutdown",{},i):d.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(n){n instanceof Error?d.debug("SYSTEM","Supervisor shutdown fallback failed",{},n):d.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(n)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{d.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}wi(),this.stopPromise=gi({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,s){this.registry.register(e,r,s)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},eu=new Or(xt());function Lt(t={}){let e=t.pidFilePath??$a;if(!(0,ve.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ve.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,ve.rmSync)(e,{force:!0}),"invalid"}return Rr(r)&&r?((t.logAlive??!0)&&d.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(d.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ve.rmSync)(e,{force:!0}),"stale")}var Dr=require("path"),Ut=require("fs"),_i=require("crypto");var Nt=require("fs");function yi(t,e){if(!(0,Nt.existsSync)(t))return e;try{return JSON.parse((0,Nt.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var bi="telemetry.json";function Ba(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Ga(t,e){if(Ba(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function vi(t,e){return Ga(t,e).enabled}function Ka(){return(0,Dr.join)(Oe(),bi)}function Pr(){try{let t=yi(Ka(),null);return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}catch{return null}}function Ya(t){let e=Oe();(0,Ut.mkdirSync)(e,{recursive:!0}),(0,Ut.writeFileSync)((0,Dr.join)(e,bi),JSON.stringify(t,null,2)+`
`)}function Ti(){let t=Pr();if(t?.installId)return t.installId;let e=(0,_i.randomUUID)();return Ya({installId:e,decidedAt:""}),e}var za=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens"]),Mi=200;function Ai(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!za.has(r))continue;let s=t[r];typeof s=="string"?e[r]=s.length>Mi?s.slice(0,Mi):s:(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(e[r]=s)}}catch{}return e}var Ir=X(require("os"),1),Ja="13.7.0",Xa="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",qa="https://us.i.posthog.com";function Ci(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Xa}function ki(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||qa}var Va=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function Ri(t){let e={};for(let r of Va)t[r]!==void 0&&(e[r]=t[r]);return e}function Qa(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Ir.default.release().toLowerCase().includes("microsoft")}catch{return!1}}function Oi(){return{version:Ja,os:process.platform,os_version:Ir.default.release(),is_wsl:Qa(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Za=2e3;async function Di(t,e,r){try{if(!vi(process.env,Pr()))return;let s=Ai({...Oi(),...e??{}});if(r?.person?s.$set=Ri(s):s.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:s})+`
`);return}let i=Ci();if(!i)return;let n=new AbortController,o=setTimeout(()=>n.abort(),Za);try{await fetch(`${ki()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i,event:t,distinct_id:Ti(),properties:s}),signal:n.signal})}finally{clearTimeout(o)}}catch{}}var Te=X(require("path"),1),Ii=require("os"),re=require("fs"),Lr=require("child_process");var yu=R.dataDir(),_u=R.workerPid();function Pi(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function tl(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,s;try{s=(0,Lr.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(n){return n instanceof Error?d.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},n):d.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(n))),null}return s.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)||null}var xr;function xi(t={}){let e=Object.keys(t).length===0;if(e&&xr!==void 0)return xr;let r=rl(t);return e&&r!==null&&(xr=r),r}function rl(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Pi(r))return r;let s=t.env??process.env,i=t.homeDirectory??(0,Ii.homedir)(),n=t.pathExists??re.existsSync,o=t.lookupInPath??tl,a=e==="win32"?[s.BUN,s.BUN_PATH,Te.default.join(i,".bun","bin","bun.exe"),Te.default.join(i,".bun","bin","bun"),s.USERPROFILE?Te.default.join(s.USERPROFILE,".bun","bin","bun.exe"):void 0,s.LOCALAPPDATA?Te.default.join(s.LOCALAPPDATA,"bun","bun.exe"):void 0,s.LOCALAPPDATA?Te.default.join(s.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[s.BUN,s.BUN_PATH,Te.default.join(i,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of a){let c=l?.trim();if(c&&(Pi(c)&&n(c)||c.toLowerCase()==="bun"))return c}return o("bun",e)}var Li=X(require("path"),1);var Ni=require("fs");async function sl(t,e,r="GET"){let s=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}function il(){try{let t=Li.default.join(lt,"package.json");return JSON.parse((0,Ni.readFileSync)(t,"utf-8")).version}catch(t){if(t instanceof Error){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return d.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}throw t}}async function nl(t){try{let e=await sl(t,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return d.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Ui(t){let e=il(),r=await nl(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}var Ft=require("path"),B=require("fs");var ol=6e4;function Fi(){return(0,Ft.join)(Oe(),"spawn.lock")}function Wi(){let t=Fi(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,B.mkdirSync)((0,Ft.dirname)(t),{recursive:!0}),(0,B.writeFileSync)(t,e,{flag:"wx"}),!0}catch(s){if(s?.code!=="EEXIST")return!0;if(r>0)return!1;let n;try{n=(0,B.statSync)(t).mtimeMs}catch{continue}if(Date.now()-n<=ol)return!1;let o;try{o=(0,B.statSync)(t).mtimeMs}catch{continue}if(o!==n)return!1;try{(0,B.unlinkSync)(t)}catch{return!1}}return!1}function Hi(){let t=Fi();try{if(JSON.parse((0,B.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,B.unlinkSync)(t)}catch{}}function Wr(t,e,r){let s=process.env[t];if(s){let i=parseInt(s,10);if(Number.isFinite(i)&&i>=r.min&&i<=r.max)return i;d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max})}return e}var Gt=Wr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",le($.HEALTH_CHECK),{min:500,max:3e5}),Ju=Wr("CLAUDE_MEM_API_TIMEOUT_MS",le($.API_REQUEST),{min:500,max:3e5}),Ki=Wr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",le($.HOOK_READINESS_WAIT),{min:0,max:3e5}),al={min:500,max:3e5};async function Hr(t,e={},r){try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(s){throw s instanceof DOMException&&s.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):s}}var Wt=null,Ht=null,jt=null,$t=null;function ll(){return Fe.default.join(ee.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function jr(){return jt!==null||(jt=ee.loadFromFile(ll())),jt}function ji(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function cl(t,e,r){let s=process.env[t];if(s!==void 0){let o=ji(s,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max}),e)}let i=jr()[t],n=ji(i,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:i,min:r.min,max:r.max}),e)}function Yi(){if(Wt!==null)return Wt;let t=jr();return Wt=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Wt}function ul(){return Ht!==null||(Ht=jr().CLAUDE_MEM_WORKER_HOST),Ht}function hl(){return $t!==null||($t=cl("CLAUDE_MEM_API_TIMEOUT_MS",le($.API_REQUEST),al)),$t}function dl(t){return`http://${ul()}:${Yi()}${t}`}function he(t,e={}){let r=e.method??"GET",s=e.timeoutMs??hl(),i=dl(t),n={method:r};return e.headers&&(n.headers=e.headers),e.body&&(n.body=e.body),s>0?Hr(i,n,s):fetch(i,n)}async function pl(){return(await he("/api/health",{timeoutMs:Gt})).ok}async function $i(){return(await he("/api/readiness",{timeoutMs:Gt})).ok}function fl(){let t=[Fe.default.join(lt,"plugin","scripts","worker-service.cjs"),Fe.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,Y.existsSync)(e))return e;return null}async function ml(t){let e=t.backoffMs;for(let r=1;r<=t.attempts;r++){if(await Ji())return!0;r<t.attempts&&(await new Promise(s=>setTimeout(s,e)),e*=2)}return!1}async function Nr(t=Ki){if(t<=0)try{return await $i()}catch{return!1}let e=Date.now();for(;Date.now()-e<t;){try{if(await $i())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=t-(Date.now()-e);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function zi(){try{let e=await(await he("/api/health",{timeoutMs:Gt})).json();return typeof e.version=="string"?e.version:null}catch{return null}}async function gl(t,e=Ki){let r=Date.now();for(;Date.now()-r<e;){if(await zi()===t)return!0;let i=e-(Date.now()-r);if(i<=0)break;await new Promise(n=>setTimeout(n,Math.min(500,i)))}return!1}async function Ur(t){let e=await zi();e!==null&&e!==t&&d.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:t,workerVersion:e})}async function Ji(){let t;try{t=await pl()}catch(r){return d.debug("SYSTEM","Worker health check threw",{error:r instanceof Error?r.message:String(r)}),!1}if(!t)return!1;let e=Lt({logAlive:!1});return e==="missing"||e==="alive"}async function Kt(){let t=null;if(await Ji()){let{matches:n,pluginVersion:o,workerVersion:a}=await Ui(Yi());if(o!=="unknown"&&(t=o),n)return await Nr()?(t!==null&&await Ur(t),!0):(d.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);d.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:o,workerVersion:a});try{if(await he("/api/admin/restart",{method:"POST",timeoutMs:Gt}),await gl(o))return await Nr()?(t!==null&&await Ur(t),!0):(d.warn("SYSTEM","Recycled worker appeared but did not become ready; skipping hook API call"),!1);d.warn("SYSTEM","No successor worker appeared after recycle; falling through to lazy-spawn",{pluginVersion:o,workerVersion:a})}catch(l){d.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{error:l instanceof Error?l.message:String(l)})}}let e=xi(),r=fl();if(!e)return d.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!r)return d.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let s=Wi();try{if(s){d.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:e,scriptPath:r});try{Ot(e,[r,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(o){return o instanceof Error?d.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:e,scriptPath:r},o):d.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:e,scriptPath:r,error:String(o)}),!1}}else d.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await ml({attempts:6,backoffMs:500}))return d.warn("SYSTEM",s?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{s&&Hi()}return await Nr()?(t!==null&&await Ur(t),!0):(d.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Bt=null;async function Sl(){return Bt!==null||(Bt=await Kt()),Bt}var El=3;function Xi(){return Fe.default.join(v,"state")}function qi(){return Fe.default.join(Xi(),"hook-failures.json")}function Vi(){try{let t=(0,Y.readFileSync)(qi(),"utf-8"),e=JSON.parse(t);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function Qi(t){let e=Xi(),r=qi(),s=`${r}.tmp`;try{(0,Y.existsSync)(e)||(0,Y.mkdirSync)(e,{recursive:!0}),(0,Y.writeFileSync)(s,JSON.stringify(t),"utf-8"),(0,Y.renameSync)(s,r)}catch(i){d.debug("SYSTEM","Failed to persist hook-failure counter",{error:i instanceof Error?i.message:String(i)})}}function wl(){try{let e=ce().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return El}var Bi=null;async function yl(){let e={consecutiveFailures:Vi().consecutiveFailures+1,lastFailureAt:Date.now()};Qi(e);let r=wl();return e.consecutiveFailures>=r&&(e.consecutiveFailures===r&&await Di("hook_failed",{...Bi!==null?{hook_type:Bi}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),zr(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Gi(){Vi().consecutiveFailures!==0&&Qi({consecutiveFailures:0,lastFailureAt:0})}var Fr=Symbol.for("claude-mem/worker-fallback");function rt(t){return typeof t=="object"&&t!==null&&t[Fr]===!0}async function st(t,e,r,s={}){if(!await Sl())return await yl(),{continue:!0,reason:"worker_unreachable",[Fr]:!0};let n={method:e};r!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(r)),s.timeoutMs!==void 0&&(n.timeoutMs=s.timeoutMs);let o=await he(t,n);if(!o.ok){let l=await o.text().catch(()=>"");if(Gi(),o.status===429||o.status>=500)return d.warn("SYSTEM",`Worker API ${e} ${t} returned ${o.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${o.status}`,[Fr]:!0};let c=l;try{c=JSON.parse(l)}catch{}return c}Gi();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var en=require("os"),tn=X(require("path"),1),rn=require("child_process");var zt=require("fs"),Yt=X(require("path"),1);var it={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Zi(t){let e=Yt.default.join(t,".git"),r;try{r=(0,zt.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),it}if(!r.isFile())return it;let s;try{s=(0,zt.readFileSync)(e,"utf-8").trim()}catch(u){return d.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),it}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return it;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return it;let a=o[1],l=Yt.default.basename(t),c=Yt.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function sn(t){return t==="~"||t.startsWith("~/")?t.replace(/^~/,(0,en.homedir)()):t}function _l(t){try{return(0,rn.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function bl(t){if(!t||t.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=sn(t),s=_l(e)??e,i=tn.default.basename(s);if(i===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let l=`drive-${o[1].toUpperCase()}`;return d.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:l}),l}}return d.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return i}function Me(t){let e=bl(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=sn(t),s=Zi(r);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${e}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var Ae=require("path");var nn=require("os"),on=require("path");function vl(t){let e=t.startsWith("~")?(0,nn.homedir)()+t.slice(1):t;e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Jt(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),s=(0,on.basename)(r),i=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of i)try{let o=vl(n);if(o.test(r)||o.test(s))return!0}catch(o){d.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:n,error:o instanceof Error?o.message:String(o)});continue}return!1}function Tl(t,e){let r=(0,Ae.normalize)(t),s=(0,Ae.normalize)(e);if(r===s)return!0;let i=(0,Ae.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,Ae.isAbsolute)(i)}function Xt(t){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!t)return!0;if(Tl(t,ut))return!1;let e=ce();return!Jt(t,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var an="claude";function Ml(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function we(t){if(!t)return an;let e=Ml(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:an}var un=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],ln=new RegExp(`<(${un.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var cn=100;function Al(t){let e=Object.fromEntries(un.map(i=>[i,0]));ln.lastIndex=0;let r=0,s=t.replace(ln,(i,n)=>(e[n]=(e[n]??0)+1,r+=1,""));return r>cn&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:cn,contentLength:t.length}),{stripped:s.trim(),counts:e}}function $r(t){return Al(t).stripped}var Cl=["task-notification"],kl=new RegExp(`^\\s*<(${Cl.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Rl=256*1024;function hn(t){return!t||t.length>Rl?!1:kl.test(t)}var Ol=le($.API_REQUEST),de=class extends Error{kind;status;cause;constructor(e,r,s={}){super(r),this.name="ServerBetaClientError",this.kind=e,this.status=s.status??null,this.cause=s.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},qt=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Dl(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Ol}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),s=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,r)}async endSession(e){if(!e.sessionId)throw new de("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new de("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,s=e.kind??"manual",i=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:s,type:s,narrative:r,...i?{title:i}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,s){if(!this.apiKey||!this.apiKey.trim())throw new de("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let i=`${this.baseUrl}${r}`,n={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};s!==void 0&&(n.body=JSON.stringify(s));let o;try{o=await Hr(i,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),u=/timed out|timeout/i.test(c);throw new de(u?"timeout":"transport",`Server beta ${e} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new de("http_error",`Server beta ${e} ${r} returned ${o.status}: ${Pl(l,200)}`,{status:o.status})}let a=await o.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(l){throw new de("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:l})}}};function dn(t){return t instanceof de}function Dl(t){return t.replace(/\/+$/,"")}function Pl(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Il(){return(ce().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function xl(){let t=ce(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),s=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return d.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return d.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!s)return d.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new qt(i),projectId:s,serverBaseUrl:e}}function pn(){if(Il()!=="server-beta")return{runtime:"worker"};let t=xl();return t||{runtime:"worker"}}function fn(t,e){d.warn("HOOK",`[server-beta-fallback] reason=${t}`,e??{})}var mn={async execute(t){let{sessionId:e,prompt:r}=t,s=t.cwd??process.cwd();if(!e)return d.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};if(!Xt(s))return d.info("HOOK","Project excluded from tracking",{cwd:s}),{continue:!0,suppressOutput:!0};if(r&&hn(r))return d.debug("HOOK","session-init: skipping internal protocol payload",{preview:r.slice(0,80)}),{continue:!0,suppressOutput:!0};let i=!r||!r.trim()?"[media prompt]":r,n=Me(s).primary,o=we(t.platform),a=pn();if(a.runtime==="server-beta")try{return await a.client.startSession({projectId:a.projectId,externalSessionId:e,contentSessionId:e,agentId:t.agentId??null,agentType:t.agentType??null,platformSource:o,metadata:{project:n,prompt:i}}),d.info("HOOK","session-init: server-beta session started",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(dn(m)&&m.isFallbackEligible())fn(m.kind,{status:m.status,message:m.message,route:"/v1/sessions/start"});else return d.error("HOOK","Server beta session-start failed (non-recoverable)",{error:m instanceof Error?m.message:String(m)}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:n});let l=await st("/api/sessions/init","POST",{contentSessionId:e,project:n,prompt:i,platformSource:o});if(rt(l))return{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};if(typeof l?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};let c=l.sessionDbId,u=l.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:c,promptNumber:u,skipped:l.skipped,contextInjected:l.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${u} | sessionDbId=${c}`),l.skipped&&l.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | skipped=true | reason=private`,{sessionId:c}),{continue:!0,suppressOutput:!0};let h=ce(),p=String(h.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",f="";if(p&&i&&i.length>=20&&i!=="[media prompt]"){let m=h.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await st("/api/context/semantic","POST",{q:i,project:n,limit:m});!rt(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:c,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | project=${n}`,{sessionId:c}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var gn={async execute(t){let{sessionId:e,cwd:r,filePath:s,edits:i}=t,n=we(t.platform);if(!s)throw new Error("fileEditHandler requires filePath");if(d.dataIn("HOOK",`FileEdit: ${s}`,{editCount:i?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${s}`);if(!Xt(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};let o=await st("/api/sessions/observations","POST",{contentSessionId:e,platformSource:n,tool_name:"write_file",tool_input:{filePath:s,edits:i},tool_response:{success:!0},cwd:r});return rt(o)?{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:s}),{continue:!0,suppressOutput:!0})}};var z=require("fs"),Vt=require("path");var Jh=R.settings();function Sn(t,e){let r="<claude-mem-context>",s="</claude-mem-context>";if(!t)return`${r}
${e}
${s}`;let i=t.indexOf(r),n=t.indexOf(s);return i!==-1&&n!==-1?t.substring(0,i)+`${r}
${e}
${s}`+t.substring(n+s.length):t+`
${r}
${e}
${s}`}function En(t,e){if(!t)return;let r=(0,Vt.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let s=(0,Vt.dirname)(t);(0,z.existsSync)(s)||(0,z.mkdirSync)(s,{recursive:!0});let i="";(0,z.existsSync)(t)&&(i=(0,z.readFileSync)(t,"utf-8"));let n=`# Memory Context
${e}`,o=Sn(i,n),a=`${t}.tmp`;try{(0,z.writeFileSync)(a,o),(0,z.renameSync)(a,t)}catch(l){d.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},l instanceof Error?l:new Error(String(l)))}}function Ll(t){let e=t.trim().replace(/^\$\.?/,"");if(!e)return[];let r=[],s=e.split(".");for(let i of s){let n=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=n.exec(i))!==null;)o[1]?r.push(o[1]):o[2]&&r.push(parseInt(o[2],10))}return r}function Br(t,e){if(!e)return;let r=Ll(e),s=t;for(let i of r){if(s==null)return;s=s[i]}return s}function wn(t){return t==null||t===""}function yn(t,e){if(t.startsWith("$watch.")){let r=t.slice(7);return e.watch[r]}if(t.startsWith("$schema.")){let r=t.slice(8);return e.schema[r]}if(t.startsWith("$session.")){let r=t.slice(9);return e.session?e.session[r]:void 0}if(t==="$cwd")return e.watch.workspace;if(t==="$project")return e.watch.project}function We(t,e,r){if(t!==void 0){if(typeof t=="string"){let s=yn(t,r);return s!==void 0?s:Br(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let s of t.coalesce){let i=We(s,e,r);if(!wn(i))return i}if(t.path){let s=yn(t.path,r);if(s!==void 0)return s;let i=Br(e,t.path);if(!wn(i))return i}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function _n(t,e,r){let s={};if(!t)return s;for(let[i,n]of Object.entries(t))s[i]=We(n,e,r);return s}function bn(t,e,r){if(!e)return!0;let s=e.path||r.eventTypePath||"type",i=s?Br(t,s):void 0,n=i==null||i==="";if(e.exists!==void 0&&(e.exists&&n||!e.exists&&!n)||e.equals!==void 0&&i!==e.equals||e.not_equals!==void 0&&i===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(i)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(i)||e.contains!==void 0&&(typeof i!="string"||!i.includes(e.contains))||e.not_contains!==void 0&&typeof i=="string"&&i.includes(e.not_contains))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(i??"")))return!1}catch(o){return d.debug("WORKER","Invalid regex in match rule",{regex:e.regex},o instanceof Error?o:void 0),!1}return!0}var Qt=class{static checkUserPromptPrivacy(e,r,s,i,n,o){let a=e.getUserPrompt(r,s);return a===null?(d.warn("HOOK",`${i}: no user_prompts row for prompt #${s} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:n,contentSessionId:r,promptNumber:s,...o}),{allow:!0,prompt:""}):a.trim()===""?(d.debug("HOOK",`Skipping ${i} - user prompt was entirely private`,{sessionId:n,promptNumber:s,...o}),{allow:!1,reason:"private"}):{allow:!0,prompt:a}}};var vn=null;function Nl(){if(!vn)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return vn}async function Tn(t){let{sessionManager:e,dbManager:r,eventBroadcaster:s,ensureGeneratorRunning:i}=Nl(),n=we(t.platformSource),o=typeof t.cwd=="string"?t.cwd:"",a=o.trim()?Me(o).primary:"",l=ee.loadFromFile(ct);if(o&&Jt(o,l.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(new Set(l.CLAUDE_MEM_SKIP_TOOLS.split(",").map(S=>S.trim()).filter(Boolean)).has(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(t.toolName)&&t.toolInput&&typeof t.toolInput=="object"){let S=t.toolInput,E=S.file_path||S.notebook_path;if(E&&E.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let h=r.getSessionStore(),p,f;try{p=h.createSDKSession(t.contentSessionId,a,"",void 0,n),f=h.getPromptNumberFromUserPrompts(t.contentSessionId)}catch(S){let E=S instanceof Error?S.message:String(S);return d.error("INGEST","Observation session resolution failed",{contentSessionId:t.contentSessionId,toolName:t.toolName},S instanceof Error?S:new Error(E)),{ok:!1,reason:E,status:500}}if(!Qt.checkUserPromptPrivacy(h,t.contentSessionId,f,"observation",p,{tool_name:t.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let g=t.toolInput!==void 0?$r(JSON.stringify(t.toolInput)):"{}",w=t.toolResponse!==void 0?$r(JSON.stringify(t.toolResponse)):"{}";return await e.queueObservation(p,{tool_name:t.toolName,tool_input:g,tool_response:w,prompt_number:f,cwd:o||(d.error("INGEST","Missing cwd when ingesting observation",{sessionId:p,toolName:t.toolName}),""),agentId:typeof t.agentId=="string"?t.agentId:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,toolUseId:typeof t.toolUseId=="string"?t.toolUseId:void 0}),await i?.(p,"observation"),s.broadcastObservationQueued(p),{ok:!0,sessionDbId:p}}var Zt=class{sessions=new Map;async processEntry(e,r,s,i){for(let n of s.events)bn(e,n.match,s)&&await this.handleEvent(e,r,s,n,i??void 0)}getSessionKey(e,r){return`${e.name}:${r}`}getOrCreateSession(e,r){let s=this.getSessionKey(e,r),i=this.sessions.get(s);return i||(i={sessionId:r,platformSource:we(e.name)},this.sessions.set(s,i)),i}resolveSessionId(e,r,s,i,n){let o={watch:r,schema:s},a=i.fields?.sessionId??(s.sessionIdPath?{path:s.sessionIdPath}:void 0),l=We(a,e,o);return typeof l=="string"&&l.trim()?l:typeof l=="number"?String(l):n&&n.trim()?n:null}resolveCwd(e,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.cwd??(s.cwdPath?{path:s.cwdPath}:void 0),l=We(a,e,o);return typeof l=="string"&&l.trim()?l:r.workspace?r.workspace:n.cwd}resolveProject(e,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.project??(s.projectPath?{path:s.projectPath}:void 0),l=We(a,e,o);return typeof l=="string"&&l.trim()?l:r.project?r.project:n.cwd?Me(n.cwd).primary:n.project}async handleEvent(e,r,s,i,n){let o=this.resolveSessionId(e,r,s,i,n);if(!o){d.debug("TRANSCRIPT","Skipping event without sessionId",{event:i.name,watch:r.name});return}let a=this.getOrCreateSession(r,o),l=this.resolveCwd(e,r,s,i,a);l&&(a.cwd=l);let c=this.resolveProject(e,r,s,i,a);c&&(a.project=c);let u=_n(i.fields,e,{watch:r,schema:s,session:a});switch(i.action){case"session_context":this.applySessionContext(a,u);break;case"session_init":await this.handleSessionInit(a,u),r.context?.updateOn?.includes("session_start")&&await this.updateContext(a,r);break;case"user_message":typeof u.message=="string"&&(a.lastUserMessage=u.message),typeof u.prompt=="string"&&(a.lastUserMessage=u.prompt);break;case"assistant_message":typeof u.message=="string"&&(a.lastAssistantMessage=u.message);break;case"tool_use":await this.handleToolUse(a,u);break;case"tool_result":await this.handleToolResult(a,u);break;case"observation":await this.sendObservation(a,u);break;case"file_edit":await this.sendFileEdit(a,u);break;case"session_end":await this.handleSessionEnd(a,r);break;default:break}}applySessionContext(e,r){let s=typeof r.cwd=="string"?r.cwd:void 0,i=typeof r.project=="string"?r.project:void 0;s&&(e.cwd=s),i&&(e.project=i)}async handleSessionInit(e,r){let s=typeof r.prompt=="string"?r.prompt:"",i=e.cwd??process.cwd();s&&(e.lastUserMessage=s),await mn.execute({sessionId:e.sessionId,cwd:i,prompt:s,platform:e.platformSource})}async handleToolUse(e,r){let s=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,n=this.maybeParseJson(r.toolInput),o=this.maybeParseJson(r.toolResponse);if(i==="apply_patch"&&typeof n=="string"){let a=this.parseApplyPatchFiles(n);for(let l of a)await this.sendFileEdit(e,{filePath:l,edits:[{type:"apply_patch",patch:n}]})}i&&o!==void 0?await this.sendObservation(e,{toolName:i,toolInput:n,toolResponse:o,toolUseId:s}):i&&s&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(s,{toolName:i,toolInput:n}))}async handleToolResult(e,r){let s=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,n=this.maybeParseJson(r.toolResponse),o=this.maybeParseJson(r.toolInput);if(s&&e.pendingTools){let a=e.pendingTools.get(s);a&&(i||(i=a.toolName),o===void 0&&(o=a.toolInput),e.pendingTools.delete(s))}i?await this.sendObservation(e,{toolName:i,toolInput:o,toolResponse:n,toolUseId:s}):d.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:s})}async sendObservation(e,r){let s=typeof r.toolName=="string"?r.toolName:void 0;if(!s)return;let i=await Tn({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:s,toolInput:this.maybeParseJson(r.toolInput),toolResponse:this.maybeParseJson(r.toolResponse),platformSource:e.platformSource,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0});if(!i.ok)throw new Error(`ingestObservation failed: ${i.reason}`)}async sendFileEdit(e,r){let s=typeof r.filePath=="string"?r.filePath:void 0;s&&await gn.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:s,edits:Array.isArray(r.edits)?r.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let r=e.trim();if(!r||!(r.startsWith("{")||r.startsWith("[")))return e;try{return JSON.parse(r)}catch(s){return d.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:r.slice(0,120)},s instanceof Error?s:void 0),e}}parseApplyPatchFiles(e){let r=[],s=e.split(`
`);for(let i of s){let n=i.trim();if(n.startsWith("*** Update File: "))r.push(n.replace("*** Update File: ","").trim());else if(n.startsWith("*** Add File: "))r.push(n.replace("*** Add File: ","").trim());else if(n.startsWith("*** Delete File: "))r.push(n.replace("*** Delete File: ","").trim());else if(n.startsWith("*** Move to: "))r.push(n.replace("*** Move to: ","").trim());else if(n.startsWith("+++ ")){let o=n.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&r.push(o)}}return Array.from(new Set(r))}async handleSessionEnd(e,r){await this.queueSummary(e),await this.updateContext(e,r),e.pendingTools?.clear();let s=this.getSessionKey(r,e.sessionId);this.sessions.delete(s)}async queueSummary(e){if(!await Kt())return;let s=e.lastAssistantMessage??"",i=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:s,platformSource:e.platformSource});try{await he("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:i})}catch(n){d.warn("TRANSCRIPT","Summary request failed",{error:n instanceof Error?n.message:String(n)})}}async updateContext(e,r){if(!r.context||r.context.mode!=="agents"||qr(r)||!await Kt())return;let i=e.cwd??r.workspace;if(!i)return;let o=Me(i).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}`,l=N(r.context.path??`${i}/AGENTS.md`),c=nt.default.resolve(l),u=[nt.default.resolve(i),nt.default.resolve(v)];if(!u.some(m=>c.startsWith(m+nt.default.sep)||c===m)){d.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:r.context.path,resolved:c,allowedRoots:u});return}let p;try{p=await he(a)}catch(m){d.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:m instanceof Error?m.message:String(m)});return}if(!p.ok)return;let f=(await p.text()).trim();f&&(En(l,f),d.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:l,watch:r.name}))}};var Gr=class{constructor(e,r,s,i){this.filePath=e;this.onLine=s;this.onOffset=i;this.tailState={offset:r,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,x.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,x.existsSync)(this.filePath))return;let e=0;try{e=(0,x.statSync)(this.filePath).size}catch(o){d.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}if(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let r=(0,x.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),s="";for await(let o of r)s+=o;this.tailState.offset=e,this.onOffset(this.tailState.offset);let n=(this.tailState.partial+s).split(`
`);this.tailState.partial=n.pop()??"";for(let o of n){let a=o.trim();a&&await this.onLine(a)}}},er=class{constructor(e,r){this.config=e;this.statePath=r;this.state=li(r)}config;statePath;processor=new Zt;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let r=this.resolveSchema(e);if(!r){d.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let s=N(e.path),i=this.resolveWatchFiles(s);for(let o of i)await this.addTailer(o,e,r);let n=this.deepestNonGlobAncestor(s);if(!n||!(0,x.existsSync)(n)){d.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:n});return}try{let o=(0,x.watch)(n,{recursive:!0,persistent:!0},(a,l)=>{if(!l)return;let c=(0,J.resolve)(n,l).replace(/\\/g,"/"),u=this.tailers.get(c);if(u){u.poke();return}let h=this.resolveWatchFiles(s);for(let p of h)this.tailers.has(p)||this.addTailer(p,e,r)});this.rootWatchers.push(o),d.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:n})}catch(o){d.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:n},o instanceof Error?o:void 0)}}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,x.existsSync)(e))try{return(0,x.statSync)(e).isDirectory()?e:(0,J.resolve)(e,"..")}catch{return(0,J.resolve)(e,"..")}return e}let r=e.split(/[/\\]/),s=[];for(let i of r){if(/[*?[\]{}()]/.test(i))break;s.push(i)}return s.length===0||s.length===1&&s[0]===""?"":s.join(J.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return et(this.normalizeGlobPattern(e),{nodir:!0,absolute:!0});if((0,x.existsSync)(e))try{if((0,x.statSync)(e).isDirectory()){let s=(0,J.join)(e,"**","*.jsonl");return et(this.normalizeGlobPattern(s),{nodir:!0,absolute:!0})}return[e]}catch(r){return d.debug("WORKER","Failed to stat watch path",{path:e},r instanceof Error?r:void 0),[]}return[]}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,s){if(this.tailers.has(e))return;let i=this.extractSessionIdFromPath(e),n=this.state.offsets[e]??0;if(n===0&&r.startAtEnd)try{n=(0,x.statSync)(e).size}catch(a){d.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},a instanceof Error?a:void 0),n=0}let o=new Gr(e,n,async a=>{await this.handleLine(a,r,s,e,i)},a=>{this.state.offsets[e]=a,ci(this.statePath,this.state)});o.start(),this.tailers.set(e,o),d.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:s.name})}async handleLine(e,r,s,i,n){try{let o=JSON.parse(e);await this.processor.processEntry(o,r,s,n??void 0)}catch(o){o instanceof Error?d.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,J.basename)(i)},o):d.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,J.basename)(i),error:String(o)})}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};function Kr(t,e){let r=t.indexOf(e);return r===-1?null:t[r+1]??null}async function Mn(t,e){switch(t){case"init":{let r=Kr(e,"--config")??De;return dt(r),console.log(`Created sample config: ${N(r)}`),0}case"watch":{let r=Kr(e,"--config")??De,s;try{s=$e(r)}catch(a){if(a instanceof Error&&a.message.includes("not found"))dt(r),console.log(`Created sample config: ${N(r)}`),s=$e(r);else throw a}let i=N(s.stateFile??ht),n=new er(s,i);await n.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let o=()=>{n.stop(),process.exit(0)};return process.on("SIGINT",o),process.on("SIGTERM",o),await new Promise(()=>{})}case"validate":{let r=Kr(e,"--config")??De;try{$e(r)}catch(s){if(s instanceof Error&&s.message.includes("not found"))dt(r),console.log(`Created sample config: ${N(r)}`),$e(r);else throw s}return console.log(`Config OK: ${N(r)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Ul=process.argv[2],Fl=process.argv.slice(3);Mn(Ul,Fl).then(t=>{process.exit(t)}).catch(t=>{console.error(t),process.exit(1)});