sidekick-shared 0.27.3 → 0.27.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,27 @@ All notable changes to sidekick-shared will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.27.5] - 2026-09-23
9
+
10
+ ### Added
11
+
12
+ - `collectSessionPromptHistory()` (`sidekick-shared/node` and the package root, not the browser entry) returns every human prompt of each matching Claude Code or Codex session, grouped by session.
13
+ - **Consistency.** Sessions are read from the start with the scanners of `collectPromptHistory()`, so text, fail-closed scope, first-call model and usage, and ordinals are identical.
14
+ - **Selection.** `sessionIds`, `since` (file modification time only; returned sessions are whole), and `limit` (most recent sessions with prompts).
15
+ - **Session fields.** `startedAt`, `lastActivityAt`, `cwds`, `gitBranches`, `models`, and completeness (`complete`, `truncated`, `droppedPrompts`, `excludedRecords`).
16
+ - **Opt-in content.** `include.replies` adds the agent's last text for each prompt's turn (for Codex, `task_complete.last_agent_message` first). `include.signals` adds `interrupt`, `toolRejected` (Claude only, with the typed rejection reason in full), `toolError` (tool name plus error text cut to 1024 characters), `compaction`, `apiError`, and `rollback`, each with the ordinal of the prompt it followed.
17
+ - **Scope.** Replies and signals that follow an out-of-scope prompt are dropped.
18
+ - **Bounds.** `maxSessions`, `maxSessionBytes` (default 256 MiB), `maxTotalBytes` (default 256 MiB), `maxRecordBytes`, `deadlineMs`, and `signal`. A session that `maxSessions`, `maxTotalBytes`, `deadlineMs`, or `signal` interrupts, or that changes while it is read, is listed in `unread`, never returned partially; a session over `maxSessionBytes` is returned with `truncated: true`.
19
+ - New exported types: `CollectSessionPromptHistoryOptions`, `PromptHistorySession`, `PromptHistorySessionPrompt`, `PromptHistorySessionRef`, `PromptHistoryReply`, `PromptHistorySignal`, `PromptHistorySignalKind`, `SessionPromptHistoryBound`, `SessionPromptHistoryBounds`, `SessionPromptHistoryInclude`, `SessionPromptHistoryResult`, and `SessionPromptHistoryStats`.
20
+
21
+ ## [0.27.4] - 2026-09-23
22
+
23
+ ### Added
24
+
25
+ - `sidekick-shared/node` exports `createSessionProviders()`, the `CreateSessionProvidersOptions` / `CreateSessionProvidersResult` types, `SYNTHETIC_MODEL`, and the `ProviderId` / `SessionProviderBase` / `SessionProviderDiagnostic` types, re-exported from their own modules. `collectUsageEvents()` callers no longer need the package root, a CommonJS barrel that bundlers cannot tree-shake (about 420 KB minified saved in one esbuild consumer). Root exports are unchanged.
26
+ - `CollectUsageEventsOptions.signal` (optional `AbortSignal`): `collectUsageEvents()` checks it before listing sessions and between sessions, and rejects with the signal's reason (`AbortError` by default). Only fully read sessions are cached. Without a signal nothing changes; counting, pricing, and the cache format (`USAGE_CACHE_VERSION` 2) are the same.
27
+ - A packaging test walks every relative `require` reachable from `dist/node.js` and fails if it reaches `dist/index.js`.
28
+
8
29
  ## [0.27.3] - 2026-09-23
9
30
 
10
31
  ### Fixed
package/README.md CHANGED
@@ -9,6 +9,8 @@ Types, parsers, providers, readers, formatters, aggregation, search, reporting,
9
9
 
10
10
  ## Recent additions
11
11
 
12
+ - **0.27.5: whole-session prompt history** — `collectSessionPromptHistory()` (root and Node) returns every human prompt of each matching Claude Code or Codex session, grouped by session and read from the start with the `collectPromptHistory()` scanners, so text, scope, model and usage, and ordinals are identical. Select with `sessionIds`, `since` (file mtime), or `limit`; each session carries `startedAt` / `lastActivityAt`, `cwds`, `gitBranches`, `models`, and `complete` / `truncated` / `droppedPrompts` / `excludedRecords`. `include.replies` adds the agent's last text for each prompt, and `include.signals` adds `interrupt`, `toolRejected`, `toolError`, `compaction`, `apiError`, and `rollback` signals. Sessions that `maxSessions`, `maxTotalBytes`, the deadline, or an abort cut off are listed in `unread` instead of being returned partially.
13
+ - **0.27.4: usage events from the Node entry** — `sidekick-shared/node` now exports `createSessionProviders()`, `SYNTHETIC_MODEL`, and the `ProviderId` / `SessionProviderBase` / `SessionProviderDiagnostic` / `CreateSessionProviders*` types, so `collectUsageEvents()` callers never import the package root (a CommonJS barrel that bundlers cannot tree-shake). `collectUsageEvents()` accepts an optional `signal` that stops the collection before listing and between sessions.
12
14
  - **0.27.3: honest session totals** — Claude Code split lines are counted once: `ClaudeUsageDeduper` keeps a `message.id`'s first usage, strips identical repeats, and turns streamed growth into a `usageKind: 'correction'` delta that `EventAggregator` adds to tokens and cost without counting another call. `resolveCodexCallUsage()` drops duplicate Codex `token_count` events. `collectSessionTokenTotals()` (root and Node) returns `mainThread`, per-`subagents`, `subagentTotal`, and `combined` in the `summarizeTokens()` vocabulary, and `formatTokenBreakdown()` renders one line whose parts add up to the headline. `TokenSummary` gains `reasoning` / `billedOutsideBuckets`, and `SubagentStats` from every provider now carries cache, reasoning, and total tokens. The session dumps and `HtmlReportOptions` accept `subagents`, `readSessionReportInputs()` returns them, `collectUsageEvents()` reads Claude Code subagent transcripts, and `USAGE_CACHE_VERSION` 2 re-reads caches built with the old counting.
13
15
  - **0.27.2: streamed prompt history** — `collectPromptHistory()` reads session logs of any size in bounded, resumable passes instead of skipping files over `maxFileBytes`: every call keeps what it read, the cursor (`version: 3`) continues where each file stopped, and a pending prompt keeps its answer state so a far-away answer still settles it. Adds `maxRecordBytes` and `maxEntries` bounds, `hasMore`, permanently skipped records in `exclusions`, and rewrite detection.
14
16
  - **0.27.1: late prompt metadata** — `collectPromptHistory()` returns a prompt again, with the same provider, sessionId, ordinal, timestamp, and text, when its first answering call is written after an earlier collection, and entries gain `metadataStatus` (`pending` / `provisional` / `final`). The cursor becomes `version: 2`, keeps a replay offset and metadata digest for the one open prompt per file (no prompt text), and still accepts 0.27.0 cursors.
@@ -130,17 +132,17 @@ returns the platform default that both overrides bypass.
130
132
 
131
133
  `sidekick-shared` ships three public entry points plus a few convenience subpaths. Pick the one that matches your runtime. As of 0.25.0 every documented subpath declares explicit `types` / `import` / `require` / `default` export conditions and resolves under Vite and TypeScript's legacy `moduleResolution: node` without consumer-side aliases.
132
134
 
133
- | Path | Runtime | What it exposes |
134
- | ------------------------------ | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
135
- | `sidekick-shared` | Node (CLI, extension host) | Full public API (readers, providers, parsers, pricing, …). |
136
- | `sidekick-shared/browser` | **Browser / webview** | Pure helpers: usage normalization/pricing, token estimation, transcript and assistant-turn projection, model/context math, `parseMcpToolName()`. |
137
- | `sidekick-shared/node` | Node only | LiteLLM pricing and context-window hydration, public provider service status (`fetchProviderServiceStatus()`), observed context-window persistence, recent-session/transcript reads, human prompt history (`collectPromptHistory()`), session previews (`listSessionPreviews()` / `readSessionPreview()` plus the bounded-concurrency `listSessionPreviewsAsync()` / `readSessionPreviewAsync()`), Codex history/rollout lookup (`readCodexHistory()`, `findCodexRolloutFile()`), and resilient observed-session collection (`fs` + providers). |
138
- | `sidekick-shared/phrases` | Any runtime | Phrase arrays + `getRandomPhrase()`. |
139
- | `sidekick-shared/modelContext` | Any runtime | Direct access to the context-window module. |
140
- | `sidekick-shared/modelInfo` | Any runtime | Direct access to model parsing and cost math. |
141
- | `sidekick-shared/formatting` | Any runtime | Direct access to pure token and duration display helpers. |
142
- | `sidekick-shared/schemas` | Any runtime | Pure Zod boundary schemas (session events, assistant turns, observed-session V1, quota, account status, account management, quota history, the `state.json` contract) — fs-free, no Node builtins. |
143
- | `sidekick-shared/statusline` | Node only | Cache-only statusline surface: account status + quota snapshot readers and writers, `formatStatusline()`, burn-rate estimates, quota freshness helpers, `parseClaudeStatuslinePayload()` / `quotaFromStatuslinePayload()`, and `readStateFile()` / `writeStateFile()`. |
135
+ | Path | Runtime | What it exposes |
136
+ | ------------------------------ | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
137
+ | `sidekick-shared` | Node (CLI, extension host) | Full public API (readers, providers, parsers, pricing, …). |
138
+ | `sidekick-shared/browser` | **Browser / webview** | Pure helpers: usage normalization/pricing, token estimation, transcript and assistant-turn projection, model/context math, `parseMcpToolName()`. |
139
+ | `sidekick-shared/node` | Node only | LiteLLM pricing and context-window hydration, public provider service status (`fetchProviderServiceStatus()`), observed context-window persistence, recent-session/transcript reads, human prompt history (`collectPromptHistory()`, and whole sessions with `collectSessionPromptHistory()`), usage events from session logs (`collectUsageEvents()` with `createSessionProviders()` and `SYNTHETIC_MODEL`), session previews (`listSessionPreviews()` / `readSessionPreview()` plus the bounded-concurrency `listSessionPreviewsAsync()` / `readSessionPreviewAsync()`), Codex history/rollout lookup (`readCodexHistory()`, `findCodexRolloutFile()`), and resilient observed-session collection (`fs` + providers). |
140
+ | `sidekick-shared/phrases` | Any runtime | Phrase arrays + `getRandomPhrase()`. |
141
+ | `sidekick-shared/modelContext` | Any runtime | Direct access to the context-window module. |
142
+ | `sidekick-shared/modelInfo` | Any runtime | Direct access to model parsing and cost math. |
143
+ | `sidekick-shared/formatting` | Any runtime | Direct access to pure token and duration display helpers. |
144
+ | `sidekick-shared/schemas` | Any runtime | Pure Zod boundary schemas (session events, assistant turns, observed-session V1, quota, account status, account management, quota history, the `state.json` contract) — fs-free, no Node builtins. |
145
+ | `sidekick-shared/statusline` | Node only | Cache-only statusline surface: account status + quota snapshot readers and writers, `formatStatusline()`, burn-rate estimates, quota freshness helpers, `parseClaudeStatuslinePayload()` / `quotaFromStatuslinePayload()`, and `readStateFile()` / `writeStateFile()`. |
144
146
 
145
147
  ### Browser / webview runtimes
146
148
 
@@ -359,6 +361,51 @@ for (const exclusion of result.exclusions) console.warn('record left out', exclu
359
361
  - **Permanent exclusions are reported.** A record over `maxRecordBytes` is skipped as it streams past without being buffered, even when it is still being written, and a complete line that is not JSON is skipped. Each is counted (`stats.recordsOverSizeLimit`, `stats.recordsMalformed`) and listed in `exclusions` with its byte offset. A prompt inside such a record is lost and does not consume an ordinal. A file that shrank or whose first 4 KiB changed is treated as rewritten: it is read again from the start with fresh ordinals and counted in `stats.sessionsRewritten`.
360
362
  - **Cursor versions.** Output is `version: 3`. Cursors from 0.27.0 (`version: 1`) and 0.27.1 (`version: 2`) are accepted: each file is re-verified once, and a 0.27.1 pending prompt is replayed from its line in resumable passes, so it now settles even when its answer is far away. Files 0.27.1 skipped for size were never in its cursor and are read in full on the first call. Metadata that 0.27.1 already gave up on (a pending replay that exceeded `maxFileBytes`) was not saved and cannot be recovered, and a 0.27.0 cursor still cannot recover prompts it returned without metadata.
361
363
 
364
+ ### Collect whole sessions of prompts
365
+
366
+ `collectSessionPromptHistory()` (Node-only) returns every human prompt of each matching session, grouped by session, for consumers that classify a session as a whole. It reads each session from the start with the same scanners as `collectPromptHistory()`, so text, scope, model and usage, and ordinals are identical. The replies and interaction signals that the prompt filter leaves out are opt-in.
367
+
368
+ ```typescript
369
+ import { collectSessionPromptHistory } from 'sidekick-shared/node';
370
+
371
+ const result = await collectSessionPromptHistory({
372
+ workspacePaths: ['/Users/me/code/app'], // plus git worktree siblings
373
+ providers: ['claude-code', 'codex'], // default: both
374
+ since: new Date('2026-09-01'), // sessions whose file changed since then, returned whole
375
+ // sessionIds: ['…'], // or exact session ids
376
+ // limit: 20, // most recent sessions with prompts
377
+ include: { signals: true, replies: true }, // default: prompts only
378
+ bounds: {
379
+ maxSessions: 1000,
380
+ maxSessionBytes: 256 << 20,
381
+ maxTotalBytes: 256 << 20,
382
+ deadlineMs: 60_000,
383
+ },
384
+ });
385
+
386
+ for (const session of result.sessions) {
387
+ // { provider, sessionId, startedAt, lastActivityAt, cwds, gitBranches, models,
388
+ // prompts: [{ ordinal, timestamp, text, cwd, gitBranch?, model?, usage?, metadataStatus, reply? }],
389
+ // signals?: [{ kind, timestamp, afterOrdinal, tool?, text?, textTruncated? }],
390
+ // complete, truncated, droppedPrompts, excludedRecords }
391
+ }
392
+ if (result.unread.length > 0) {
393
+ // A bound stopped the call, or a session changed while it was read:
394
+ // pass these back as `sessionIds` to continue.
395
+ }
396
+ ```
397
+
398
+ - **Whole sessions, no cursor.** Every call reads each session from its first line and never resumes one mid-file. `since` selects files by modification time and never drops older prompts from a returned session. A long-lived consumer can use the `collectPromptHistory()` cursor to learn which sessions changed, then fetch those sessions whole by `sessionIds`.
399
+ - **Bounds.** `maxSessions`, `maxTotalBytes`, the deadline, and an abort stop the call. Any session they interrupt is listed in `unread` rather than returned partially, and `boundsHit` names the bound. A session that changed while it was being read is also listed in `unread`, with no `boundsHit` entry. A session longer than `maxSessionBytes` is returned with `truncated: true`, and `boundsHit` includes `maxSessionBytes`; keep `maxSessionBytes` at or below `maxTotalBytes`, or a session larger than `maxTotalBytes` is never read. A record over `maxRecordBytes` (default 16 MiB) is skipped and counted in `excludedRecords`.
400
+ - **Completeness.** `complete` is false when the session was truncated, when `droppedPrompts` > 0 (prompts out of scope or without a timestamp, visible as gaps in `ordinal`), or when `excludedRecords` > 0 (oversized or malformed records).
401
+ - **Replies** (`include.replies`): the agent's last text for the prompt's turn. For Claude Code this is the last assistant message with text before the next prompt, with split records joined. For Codex it is `task_complete.last_agent_message`, falling back to the last agent message.
402
+ - **Signals** (`include.signals`), in log order, each with the ordinal of the prompt it followed (`afterOrdinal`, -1 before the first):
403
+ - `interrupt`: Claude `[Request interrupted by user…]`, or Codex `turn_aborted`.
404
+ - `toolRejected`: Claude only. Carries the rejection reason the person typed, in full. A rejection without a reason and the interrupt Claude Code writes after it count as one signal.
405
+ - `toolError`: a failed tool call, with the tool name and the error text cut to 1024 characters (`textTruncated`).
406
+ - `compaction`, `apiError` (including Codex usage-limit errors), and `rollback` (Codex `thread_rolled_back`).
407
+ - **Scope fails closed.** Sessions with no prompt inside the roots are omitted. Replies and signals that follow an out-of-scope prompt are dropped.
408
+
362
409
  For an already-open incremental Codex rollout, keep one `CodexRolloutParser` per stream and pass each parsed `SessionEvent[]` batch to `projectSessionTranscript()` (or append the events to an existing projection). This preserves parser state for paired tool calls, model context, and cumulative token deltas; consumers should not convert raw `response_item` rows themselves.
363
410
 
364
411
  ### Locate provider-native session files
@@ -481,6 +528,27 @@ const { providers, diagnostics } = createSessionProviders({
481
528
  Repeated identical degradations are coalesced, so the diagnostic stream stays
482
529
  bounded across long-lived polling and subscription cycles.
483
530
 
531
+ ### Collect usage events from the Node entry
532
+
533
+ Everything `collectUsageEvents()` needs is exported from `sidekick-shared/node`,
534
+ which never loads the package root, so bundlers keep only what you use:
535
+
536
+ ```typescript
537
+ import { collectUsageEvents, createSessionProviders, SYNTHETIC_MODEL } from 'sidekick-shared/node';
538
+
539
+ const { providers } = createSessionProviders({ providerIds: ['claude-code', 'codex'] });
540
+ const { events } = await collectUsageEvents({
541
+ providers,
542
+ since: '2026-09-01',
543
+ workspacePath: '/path/to/repo',
544
+ signal: AbortSignal.timeout(30_000), // optional: stop before listing and between sessions
545
+ });
546
+ const priced = events.filter((event) => event.model !== SYNTHETIC_MODEL);
547
+ ```
548
+
549
+ On abort the promise rejects with the signal's reason (an `AbortError` by
550
+ default); sessions read before the abort keep their cache entries.
551
+
484
552
  ### Detect the active session provider
485
553
 
486
554
  For a single-provider surface, auto-detect and construct just one:
package/dist/index.d.ts CHANGED
@@ -12,6 +12,9 @@ export type { TranscriptFidelity, TranscriptSourceProvenance, CanonicalTranscrip
12
12
  export { listRecentSessions, readSessionTranscript } from './sessionTranscripts';
13
13
  export { collectPromptHistory } from './promptHistory';
14
14
  export type { CollectPromptHistoryOptions, PromptHistoryAnswerState, PromptHistoryBound, PromptHistoryBounds, PromptHistoryCursor, PromptHistoryCursorSession, PromptHistoryEntry, PromptHistoryExclusion, PromptHistoryMetadataStatus, PromptHistoryPendingPrompt, PromptHistoryProvider, PromptHistoryResult, PromptHistoryResumeState, PromptHistoryStats, PromptHistoryUsage, } from './promptHistory';
15
+ export { collectSessionPromptHistory } from './sessionPromptHistory';
16
+ export type { CollectSessionPromptHistoryOptions, PromptHistorySession, PromptHistorySessionPrompt, PromptHistorySessionRef, SessionPromptHistoryBound, SessionPromptHistoryBounds, SessionPromptHistoryInclude, SessionPromptHistoryResult, SessionPromptHistoryStats, } from './sessionPromptHistory';
17
+ export type { PromptHistoryReply, PromptHistorySignal, PromptHistorySignalKind, } from './sessionPromptSignals';
15
18
  export { HUMAN_CLAUDE_ENTRYPOINTS, HUMAN_CODEX_SOURCES, humanPromptText, isHumanPrompt, } from './humanPrompt';
16
19
  export type { HumanPromptProvider } from './humanPrompt';
17
20
  export { computeSessionFileStats, firstUserPrompt, providerContextSizeFn, readSessionFileStats, } from './sessionStats';
package/dist/index.js CHANGED
@@ -3,17 +3,17 @@
3
3
  * Public API for sidekick-shared.
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.importSessionHistory = exports.ACTIVE_SESSION_MTIME_THRESHOLD_MS = exports.sessionSummaryFromStats = exports.removeSessionSummary = exports.markFileImported = exports.isFileImported = exports.applySessionSummary = exports.pruneUsageCache = exports.getUsageCacheDir = exports.collectUsageEvents = exports.USAGE_CACHE_VERSION = exports.MAX_USAGE_CACHE_FILES = exports.findActiveBillingBlock = exports.computeBillingBlocks = exports.BILLING_BLOCK_DURATION_MS = exports.writeStateFile = exports.readStateFile = exports.quotaToStateFile = exports.getStateFilePath = exports.billingBlockToStateFile = exports.STATE_FILE_SCHEMA_VERSION = exports.STATE_FILE_NAME = exports.sessionFingerprintParts = exports.fingerprintString = exports.readSessionReportInputs = exports.readSessionFileStats = exports.providerContextSizeFn = exports.firstUserPrompt = exports.computeSessionFileStats = exports.isHumanPrompt = exports.humanPromptText = exports.HUMAN_CODEX_SOURCES = exports.HUMAN_CLAUDE_ENTRYPOINTS = exports.collectPromptHistory = exports.readSessionTranscript = exports.listRecentSessions = exports.projectSessionTranscript = exports.estimateSerializedTokens = exports.estimateTextTokens = exports.TOKEN_TOTAL_LABEL = exports.TOKEN_SUBAGENTS_LABEL = exports.TOKEN_SESSION_TOTAL_LABEL = exports.TOKEN_MAIN_THREAD_LABEL = exports.TOKEN_CONTEXT_LABEL = exports.sumTokenTotals = exports.summarizeTokens = exports.formatTokenBreakdown = exports.calculateNormalizedUsageCost = exports.extractNormalizedUsage = exports.normalizeProviderUsage = void 0;
7
- exports.updateJsonStoreAtomicSync = exports.updateJsonStoreAtomic = exports.atomicWriteFileSync = exports.atomicWriteJsonSync = exports.atomicWriteJson = exports.readClaudeCodePlanFiles = exports.getPlanAnalytics = exports.writePlans = exports.getLatestPlan = exports.readPlans = exports.readLatestHandoff = exports.readHistory = exports.readNotes = exports.readDecisions = exports.readTasks = exports.migrateLegacyProjectStores = exports.resolveProjectIdentity = exports.getProjectSlugRaw = exports.getProjectSlug = exports.encodeWorkspacePath = exports.getGlobalDataPath = exports.getProjectDataPath = exports.setConfigDir = exports.getDefaultConfigDir = exports.getConfigDirOverride = exports.getConfigDir = exports.CONFIG_DIR_ENV_VAR = exports.MAX_PLANS_PER_PROJECT = exports.PLAN_SCHEMA_VERSION = exports.createEmptyDataStore = exports.createEmptyTokenTotals = exports.HISTORICAL_SESSION_RETENTION_LIMIT = exports.HISTORICAL_DATA_SCHEMA_VERSION = exports.STALENESS_THRESHOLDS = exports.IMPORTANCE_DECAY_FACTORS = exports.KNOWLEDGE_NOTE_SCHEMA_VERSION = exports.DECISION_LOG_SCHEMA_VERSION = exports.normalizeTaskStatus = exports.TASK_PERSISTENCE_SCHEMA_VERSION = exports.isAggregateCodexLimit = exports.splitWatchedPath = exports.DirectoryListingCache = exports.fileFingerprintParts = exports.fileFingerprint = exports.observedSessionSourceFromProvider = exports.ObservedSessionCollector = exports.weekKey = exports.usageBucketKey = exports.summarizeUsageRows = exports.bucketUsage = void 0;
8
- exports.detectSessionActivity = exports.classifySessionActivity = exports.subagentTokenTotals = exports.scanSessionSubagents = exports.readMainThreadTokenTotals = exports.combineSessionTokenTotals = exports.collectSessionTokenTotals = exports.addUsageToSubagent = exports.normalizeClaudeUsage = exports.dedupedRawClaudeUsage = exports.SYNTHETIC_MODEL = exports.ClaudeUsageDeduper = exports.readAgentMeta = exports.extractTaskInfo = exports.scanSubagentDir = exports.resolveCodexCallUsage = exports.normalizeCodexToolInput = exports.normalizeCodexToolName = exports.extractPatchFilePaths = exports.CodexRolloutParser = exports.parseDbPartData = exports.parseDbMessageData = exports.convertOpenCodeMessage = exports.detectPlanModeFromText = exports.normalizeToolInput = exports.normalizeToolName = exports.TRUNCATION_PATTERNS = exports.JsonlParser = exports.walkRolloutFilesAsync = exports.walkRolloutFiles = exports.findCodexRolloutFile = exports.CodexProvider = exports.getOpenCodeDataDir = exports.OpenCodeProvider = exports.ClaudeCodeProvider = exports.getAllDetectedProviders = exports.detectProvider = exports._resetProviderDetectionCache = exports.getObservedActivityReason = exports.derivePendingUserRequestV1 = exports.createProviderSessionAdapterV1 = exports.createSessionProviders = exports.SESSION_PROVIDER_IDS = exports.renderHandoffUrlTemplate = exports.addNote = exports.decisionFingerprint = exports.addDecision = exports.completeTask = exports.addTask = exports.withFileLockSync = void 0;
9
- exports.createJsonlTail = exports.toFollowEvents = exports.resolveSessionPath = exports.createWatcher = exports.parseChangelog = exports.extractProposedPlanShared = exports.parsePlanMarkdownShared = exports.PlanExtractor = exports.segmentAssistantTurn = exports.reasoningSummary = exports.isAssistantTurnSubagentTool = exports.extractTurnSubagents = exports.assistantTurnEventsFromSessionEvents = exports.readSessionContextSnapshot = exports.createSessionContextProjector = exports.calculateSessionContextPressure = exports.buildSessionContextSnapshot = exports.composeContext = exports.FilterEngine = exports.searchSessions = exports.CodexDatabase = exports.OpenCodeDatabase = exports.discoverDebugLogs = exports.collapseDuplicates = exports.filterByLevel = exports.parseDebugLog = exports.readSessionPreviewAsync = exports.readSessionPreview = exports.listSessionPreviewsAsync = exports.listSessionPreviews = exports.readCodexHistory = exports.parseMcpToolName = exports.scanSubagentTraces = exports.findAllSessionsWithWorktrees = exports.discoverWorktreeSiblings = exports.resolveWorktreeMainRepo = exports.getAllClaudeProjectFolders = exports.decodeEncodedPath = exports.getMostRecentlyActiveSessionDir = exports.findSubdirectorySessionDirs = exports.findSessionFilesWithStats = exports.findSessionsInDirectory = exports.findAllClaudeSessions = exports.findActiveClaudeSession = exports.discoverSessionDirectory = exports.getClaudeSessionDirectory = exports.encodeClaudeWorkspacePath = exports.SESSION_ACTIVITY_STALENESS_MS = exports.SESSION_ACTIVITY_GRACE_PERIOD_MS = exports.refreshSessionActivityState = void 0;
10
- exports.parseTranscriptFromEvents = exports.parseTranscript = exports.generateHtmlReport = exports.formatCompactionLedger = exports.calculateCompactionLedger = exports.describeCostProvenance = exports.classifyCostProvenance = exports.calculateCodeImpact = exports.scoreSessionQuality = exports.calculateQualityTrend = exports.PatternExtractor = exports.HeatmapTracker = exports.FrequencyTracker = exports.readErrorHistory = exports.getTopFailingTools = exports.appendErrorHistory = exports.MAX_ERROR_HISTORY_SESSIONS = exports.ERROR_HISTORY_SCHEMA_VERSION = exports.getSnapshotPath = exports.MAX_SNAPSHOT_FILES = exports.pruneSnapshots = exports.isSnapshotValid = exports.deleteSnapshot = exports.loadSnapshot = exports.saveSnapshot = exports.SessionMonitor = exports.parseTodoDependencies = exports.EventAggregator = exports.getRandomPhrase = exports.PHRASE_CATEGORIES = exports.ALL_PHRASES = exports.HIGHLIGHT_CSS = exports.clearHighlightCache = exports.highlightEvent = exports.formatSessionJson = exports.formatSessionMarkdown = exports.formatSessionText = exports.classifyNoise = exports.shouldMergeWithPrevious = exports.classifyFollowEvent = exports.classifyMessage = exports.getSoftNoiseReason = exports.isHardNoiseFollowEvent = exports.isHardNoise = exports.formatToolSummary = exports.parseLocalDateKey = exports.formatTokenCount = exports.formatLocalDateKey = exports.formatDurationMs = exports.addLocalDays = void 0;
11
- exports.syncLiveAccountState = exports.getLastSwitchPath = exports.readLastSwitch = exports.resolveClaudeLoginCommand = exports.listAllAccounts = exports.getLastSwitch = exports.undoLastSwitch = exports.switchAccountAsync = exports.switchAccount = exports.spawnAccountLogin = exports.finalizeAccountLoginAsync = exports.finalizeAccountLogin = exports.getAccountLoginStatusAsync = exports.getAccountLoginStatus = exports.beginAccountLogin = exports.isMultiAccountEnabled = exports.resolveActiveClaudeAccount = exports.getActiveAccount = exports.listAccounts = exports.removeAccount = exports.reconcileClaudeAuthState = exports.applyActiveClaudeToLiveHome = exports.resolveActiveClaudeHome = exports.cleanupAbandonedClaudeLogins = exports.syncClaudeLiveState = exports.switchToAccountAsync = exports.switchToAccount = exports.addCurrentAccount = exports.readActiveClaudeAccount = exports.writeAccountRegistry = exports.readAccountRegistry = exports.ensureDefaultAccounts = exports.codexIdentitiesMatch = exports.readCodexAccessTokenExpiry = exports.readCodexLastRefresh = exports.readCodexAuthIdentity = exports.parseCodexAuthJson = exports.CLAUDE_REFRESH_TOKEN_LIFETIME_ESTIMATE_MS = exports.CLAUDE_ACCESS_TOKEN_LIFETIME_MS = exports.resolveClaudeRefreshExpiry = exports.isNewerClaudeCredential = exports.claudeCredentialFreshness = exports.parseClaudeCredentialBlob = exports.readClaudeMaxAccessTokenSync = exports.readClaudeMaxCredentialsRaw = exports.readClaudeMaxCredentials = exports.deleteStoredCredentials = exports.writeActiveCredentials = exports.readActiveCredentials = exports.openInBrowser = void 0;
12
- exports.prepareCodexAccount = exports.getCodexExecutionEnv = exports.resolveSidekickCodexHome = exports.resolveActiveCodexAccount = exports.getActiveCodexAccount = exports.listCodexAccounts = exports.getSystemCodexHome = exports.getCodexMonitoringHomes = exports.getCodexProfileHome = exports.getCodexProfilesDir = exports.readLiveClaudeIdentity = exports.readClaudeProfileIdentity = exports.isClaudeProfileAuthenticated = exports.CLAUDE_SECURESTORAGE_CONFIG_DIR_ENV = exports.buildClaudeChildEnv = exports.claudeKeychainAccountName = exports.claudeKeychainService = exports.claudeKeychainSuffix = exports.getClaudeConfigPath = exports.getDefaultClaudeHome = exports.getLiveClaudeHome = exports.getClaudeProfileHome = exports.getClaudeProfilesDir = exports.onAccountsChanged = exports.getActiveAccountStatus = exports.ACCOUNT_PROVIDER_IDS = exports.removeSavedAccountProfile = exports.replaceSavedAccountProfiles = exports.setActiveSavedAccount = exports.upsertSavedAccountProfile = exports.getActiveSavedAccount = exports.listSavedAccountProfiles = exports.writeSavedAccountRegistry = exports.readSavedAccountRegistry = exports.getAccountsDir = exports.ACCOUNT_CONSUMER_REACHABILITY = exports.describeAccountConsumer = exports.detectRunningAccountConsumersSync = exports.detectRunningAccountConsumers = exports.findRunningProcessesSync = exports.findRunningProcesses = exports.keepAliveCommand = exports.refreshInactiveAccounts = exports.getAccountLaunchEnv = exports.getHealthSidecarPath = exports.readHealthSidecar = exports.listAccountsWithHealth = exports.getAccountHealth = exports.cleanupAbandonedLogins = exports.syncLiveAccountStateSync = void 0;
13
- exports.readZaiCredentials = exports.quotaStateFromZaiQuotaLimitPayload = exports.fetchZaiQuotaFromApi = exports.CodexQuotaWatcher = exports.resolveCodexQuotaFromLocalSources = exports.resolveCodexQuota = exports.readLatestCodexQuotaFromRollouts = exports.quotaFromCodexRateLimits = exports.fetchCodexQuotaFromApi = exports.fetchCodexResetCreditsFromApi = exports.getWorkspaceIdFromPath = exports.pruneQuotaHistory = exports.readQuotaHistoryDailyBuckets = exports.readQuotaHistoryRange = exports.appendQuotaHistorySample = exports.quotaFromStatuslinePayload = exports.parseClaudeStatuslinePayload = exports.evaluateQuotaThresholds = exports.describeQuotaThresholdAlert = exports.DEFAULT_QUOTA_THRESHOLDS = exports.QUOTA_FRESH_MAX_AGE_MS = exports.QUOTA_AGING_MAX_AGE_MS = exports.formatQuotaAge = exports.classifyQuotaFreshness = exports.resolveQuota = exports.writeQuotaSnapshot = exports.readQuotaSnapshot = exports.QuotaPoller = exports.describeQuotaFailure = exports.withQuotaProjections = exports.projectQuotaWindow = exports.fetchQuota = exports.SEVEN_DAY_WINDOW_MS = exports.QUOTA_PROVIDER_IDS = exports.FIVE_HOUR_WINDOW_MS = exports.AutoSwitchController = exports.decideAutoSwitch = exports.DEFAULT_AUTO_SWITCH_CONFIG = exports.removeLauncher = exports.writeLauncher = exports.CODEX_KEYRING_FIX_HINT = exports.getCodexCredentialStoreMode = exports.cleanupAbandonedCodexLogins = exports.syncCodexLiveState = exports.removeCodexAccount = exports.switchToCodexAccountAsync = exports.switchToCodexAccount = exports.finalizeCodexAccountAsync = exports.finalizeCodexAccount = exports.prepareCodexAccountAsync = void 0;
14
- exports.ToolCallTracker = exports.extractToolCalls = exports.extractToolCall = exports.extractErrorMessage = exports.categorizeError = exports.gatherAssetsForCwd = exports.codexSessions = exports.readCodexAssets = exports.claudeSessions = exports.readClaudeAssets = exports.extractCommands = exports.extractFilePaths = exports.extractUrls = exports.extractTokenUsage = exports.getObservedContextWindowPath = exports.recordObservedContextWindow = exports.loadObservedContextWindows = exports.LITELLM_CATALOG_URL = exports.normalizeLiteLlmContextWindows = exports.normalizeLiteLlmCatalog = exports.hydratePricingCatalog = exports.RESOLVED_MODEL_CATALOG_SCHEMA_VERSION = exports.resolveModelAlias = exports.registerModelAlias = exports.importResolvedModelCatalog = exports.exportResolvedModelCatalog = exports.MODEL_PROVIDER_IDS = exports.formatCost = exports.sortModelIds = exports.compareModelIds = exports.getModelDisplayInfo = exports.shortModelName = exports.mergeCostSources = exports.calculateCostWithProvenance = exports.calculateCostWithPricing = exports.calculateCost = exports.getModelInfo = exports.resolveModelPricing = exports.getModelPricing = exports.parseModelId = exports.DEFAULT_CONTEXT_WINDOW = exports.resolveModelContextWindow = exports.getModelContextWindowSize = exports.selectStatuslineAccount = exports.formatStatusline = exports.estimateTimeToQuota = exports.BurnRateCalculator = exports.RUNTIME_QUOTA_PROVIDER_IDS = exports.MultiProviderQuotaService = exports.resolveZaiQuota = void 0;
15
- exports.runDoctor = exports.getSessionDiagnostics = exports.formatHealthReport = exports.toLegacyProviderStatus = exports.fetchOpenAIStatus = exports.fetchProviderStatus = exports.assistantTurnToolRefSchema = exports.assistantTurnToolGroupStepSchema = exports.assistantTurnTimelineItemSchema = exports.assistantTurnSubagentStatusSchema = exports.assistantTurnSubagentSchema = exports.assistantTurnReasoningTimelineItemSchema = exports.assistantTurnProjectionSchema = exports.assistantTurnProcessStepSchema = exports.assistantTurnProcessSchema = exports.assistantTurnNarrationStepSchema = exports.assistantTurnEventTypeSchema = exports.assistantTurnEventSchema = exports.listAllAccountsResultSchema = exports.savedAccountProfileSchema = exports.accountEntrySchema = exports.accountLoginStatusSchema = exports.beginAccountLoginResultSchema = exports.accountManagerResultSchema = exports.accountProviderIdSchema = exports.activeAccountStatusSchema = exports.activeProviderAccountStatusSchema = exports.quotaHistoryDailyBucketSchema = exports.quotaHistorySampleSchema = exports.quotaHistoryRuntimeProviderSchema = exports.providerQuotaMapSchema = exports.zaiProviderQuotaStateSchema = exports.codexProviderQuotaStateSchema = exports.claudeProviderQuotaStateSchema = exports.providerQuotaStateSchema = exports.runtimeQuotaProviderSchema = exports.quotaFailureDescriptorSchema = exports.peakHoursStateSchema = exports.codexResetCreditsSnapshotSchema = exports.codexResetCreditSchema = exports.quotaSourceSchema = exports.quotaProviderIdSchema = exports.quotaFailureKindSchema = exports.quotaStateSchema = exports.quotaWindowSchema = exports.extractSessionEvents = exports.permissionModeSchema = exports.sessionEventSchema = exports.sessionMessageSchema = exports.messageUsageSchema = void 0;
16
- exports.fetchProviderServiceStatus = exports.diagnoseProviderFailure = exports.mergeFailingToolWindows = exports.failingToolTrend = exports.FAILING_TOOL_TREND_ARROWS = exports.scopePeakHoursToSessionProvider = exports.PEAK_HOURS_DESCRIPTION = exports.PEAK_HOURS_CACHE_MS = exports.isClaudeCodeSessionProvider = exports.getScheduledPeakHoursState = exports.fetchPeakHoursStatus = exports.DEFAULT_PEAK_HOURS_TIMEOUT_MS = exports.createPeakHoursNotApplicableState = exports._resetPeakHoursCache = void 0;
6
+ exports.ACTIVE_SESSION_MTIME_THRESHOLD_MS = exports.sessionSummaryFromStats = exports.removeSessionSummary = exports.markFileImported = exports.isFileImported = exports.applySessionSummary = exports.pruneUsageCache = exports.getUsageCacheDir = exports.collectUsageEvents = exports.USAGE_CACHE_VERSION = exports.MAX_USAGE_CACHE_FILES = exports.findActiveBillingBlock = exports.computeBillingBlocks = exports.BILLING_BLOCK_DURATION_MS = exports.writeStateFile = exports.readStateFile = exports.quotaToStateFile = exports.getStateFilePath = exports.billingBlockToStateFile = exports.STATE_FILE_SCHEMA_VERSION = exports.STATE_FILE_NAME = exports.sessionFingerprintParts = exports.fingerprintString = exports.readSessionReportInputs = exports.readSessionFileStats = exports.providerContextSizeFn = exports.firstUserPrompt = exports.computeSessionFileStats = exports.isHumanPrompt = exports.humanPromptText = exports.HUMAN_CODEX_SOURCES = exports.HUMAN_CLAUDE_ENTRYPOINTS = exports.collectSessionPromptHistory = exports.collectPromptHistory = exports.readSessionTranscript = exports.listRecentSessions = exports.projectSessionTranscript = exports.estimateSerializedTokens = exports.estimateTextTokens = exports.TOKEN_TOTAL_LABEL = exports.TOKEN_SUBAGENTS_LABEL = exports.TOKEN_SESSION_TOTAL_LABEL = exports.TOKEN_MAIN_THREAD_LABEL = exports.TOKEN_CONTEXT_LABEL = exports.sumTokenTotals = exports.summarizeTokens = exports.formatTokenBreakdown = exports.calculateNormalizedUsageCost = exports.extractNormalizedUsage = exports.normalizeProviderUsage = void 0;
7
+ exports.updateJsonStoreAtomic = exports.atomicWriteFileSync = exports.atomicWriteJsonSync = exports.atomicWriteJson = exports.readClaudeCodePlanFiles = exports.getPlanAnalytics = exports.writePlans = exports.getLatestPlan = exports.readPlans = exports.readLatestHandoff = exports.readHistory = exports.readNotes = exports.readDecisions = exports.readTasks = exports.migrateLegacyProjectStores = exports.resolveProjectIdentity = exports.getProjectSlugRaw = exports.getProjectSlug = exports.encodeWorkspacePath = exports.getGlobalDataPath = exports.getProjectDataPath = exports.setConfigDir = exports.getDefaultConfigDir = exports.getConfigDirOverride = exports.getConfigDir = exports.CONFIG_DIR_ENV_VAR = exports.MAX_PLANS_PER_PROJECT = exports.PLAN_SCHEMA_VERSION = exports.createEmptyDataStore = exports.createEmptyTokenTotals = exports.HISTORICAL_SESSION_RETENTION_LIMIT = exports.HISTORICAL_DATA_SCHEMA_VERSION = exports.STALENESS_THRESHOLDS = exports.IMPORTANCE_DECAY_FACTORS = exports.KNOWLEDGE_NOTE_SCHEMA_VERSION = exports.DECISION_LOG_SCHEMA_VERSION = exports.normalizeTaskStatus = exports.TASK_PERSISTENCE_SCHEMA_VERSION = exports.isAggregateCodexLimit = exports.splitWatchedPath = exports.DirectoryListingCache = exports.fileFingerprintParts = exports.fileFingerprint = exports.observedSessionSourceFromProvider = exports.ObservedSessionCollector = exports.weekKey = exports.usageBucketKey = exports.summarizeUsageRows = exports.bucketUsage = exports.importSessionHistory = void 0;
8
+ exports.classifySessionActivity = exports.subagentTokenTotals = exports.scanSessionSubagents = exports.readMainThreadTokenTotals = exports.combineSessionTokenTotals = exports.collectSessionTokenTotals = exports.addUsageToSubagent = exports.normalizeClaudeUsage = exports.dedupedRawClaudeUsage = exports.SYNTHETIC_MODEL = exports.ClaudeUsageDeduper = exports.readAgentMeta = exports.extractTaskInfo = exports.scanSubagentDir = exports.resolveCodexCallUsage = exports.normalizeCodexToolInput = exports.normalizeCodexToolName = exports.extractPatchFilePaths = exports.CodexRolloutParser = exports.parseDbPartData = exports.parseDbMessageData = exports.convertOpenCodeMessage = exports.detectPlanModeFromText = exports.normalizeToolInput = exports.normalizeToolName = exports.TRUNCATION_PATTERNS = exports.JsonlParser = exports.walkRolloutFilesAsync = exports.walkRolloutFiles = exports.findCodexRolloutFile = exports.CodexProvider = exports.getOpenCodeDataDir = exports.OpenCodeProvider = exports.ClaudeCodeProvider = exports.getAllDetectedProviders = exports.detectProvider = exports._resetProviderDetectionCache = exports.getObservedActivityReason = exports.derivePendingUserRequestV1 = exports.createProviderSessionAdapterV1 = exports.createSessionProviders = exports.SESSION_PROVIDER_IDS = exports.renderHandoffUrlTemplate = exports.addNote = exports.decisionFingerprint = exports.addDecision = exports.completeTask = exports.addTask = exports.withFileLockSync = exports.updateJsonStoreAtomicSync = void 0;
9
+ exports.toFollowEvents = exports.resolveSessionPath = exports.createWatcher = exports.parseChangelog = exports.extractProposedPlanShared = exports.parsePlanMarkdownShared = exports.PlanExtractor = exports.segmentAssistantTurn = exports.reasoningSummary = exports.isAssistantTurnSubagentTool = exports.extractTurnSubagents = exports.assistantTurnEventsFromSessionEvents = exports.readSessionContextSnapshot = exports.createSessionContextProjector = exports.calculateSessionContextPressure = exports.buildSessionContextSnapshot = exports.composeContext = exports.FilterEngine = exports.searchSessions = exports.CodexDatabase = exports.OpenCodeDatabase = exports.discoverDebugLogs = exports.collapseDuplicates = exports.filterByLevel = exports.parseDebugLog = exports.readSessionPreviewAsync = exports.readSessionPreview = exports.listSessionPreviewsAsync = exports.listSessionPreviews = exports.readCodexHistory = exports.parseMcpToolName = exports.scanSubagentTraces = exports.findAllSessionsWithWorktrees = exports.discoverWorktreeSiblings = exports.resolveWorktreeMainRepo = exports.getAllClaudeProjectFolders = exports.decodeEncodedPath = exports.getMostRecentlyActiveSessionDir = exports.findSubdirectorySessionDirs = exports.findSessionFilesWithStats = exports.findSessionsInDirectory = exports.findAllClaudeSessions = exports.findActiveClaudeSession = exports.discoverSessionDirectory = exports.getClaudeSessionDirectory = exports.encodeClaudeWorkspacePath = exports.SESSION_ACTIVITY_STALENESS_MS = exports.SESSION_ACTIVITY_GRACE_PERIOD_MS = exports.refreshSessionActivityState = exports.detectSessionActivity = void 0;
10
+ exports.parseTranscript = exports.generateHtmlReport = exports.formatCompactionLedger = exports.calculateCompactionLedger = exports.describeCostProvenance = exports.classifyCostProvenance = exports.calculateCodeImpact = exports.scoreSessionQuality = exports.calculateQualityTrend = exports.PatternExtractor = exports.HeatmapTracker = exports.FrequencyTracker = exports.readErrorHistory = exports.getTopFailingTools = exports.appendErrorHistory = exports.MAX_ERROR_HISTORY_SESSIONS = exports.ERROR_HISTORY_SCHEMA_VERSION = exports.getSnapshotPath = exports.MAX_SNAPSHOT_FILES = exports.pruneSnapshots = exports.isSnapshotValid = exports.deleteSnapshot = exports.loadSnapshot = exports.saveSnapshot = exports.SessionMonitor = exports.parseTodoDependencies = exports.EventAggregator = exports.getRandomPhrase = exports.PHRASE_CATEGORIES = exports.ALL_PHRASES = exports.HIGHLIGHT_CSS = exports.clearHighlightCache = exports.highlightEvent = exports.formatSessionJson = exports.formatSessionMarkdown = exports.formatSessionText = exports.classifyNoise = exports.shouldMergeWithPrevious = exports.classifyFollowEvent = exports.classifyMessage = exports.getSoftNoiseReason = exports.isHardNoiseFollowEvent = exports.isHardNoise = exports.formatToolSummary = exports.parseLocalDateKey = exports.formatTokenCount = exports.formatLocalDateKey = exports.formatDurationMs = exports.addLocalDays = exports.createJsonlTail = void 0;
11
+ exports.getLastSwitchPath = exports.readLastSwitch = exports.resolveClaudeLoginCommand = exports.listAllAccounts = exports.getLastSwitch = exports.undoLastSwitch = exports.switchAccountAsync = exports.switchAccount = exports.spawnAccountLogin = exports.finalizeAccountLoginAsync = exports.finalizeAccountLogin = exports.getAccountLoginStatusAsync = exports.getAccountLoginStatus = exports.beginAccountLogin = exports.isMultiAccountEnabled = exports.resolveActiveClaudeAccount = exports.getActiveAccount = exports.listAccounts = exports.removeAccount = exports.reconcileClaudeAuthState = exports.applyActiveClaudeToLiveHome = exports.resolveActiveClaudeHome = exports.cleanupAbandonedClaudeLogins = exports.syncClaudeLiveState = exports.switchToAccountAsync = exports.switchToAccount = exports.addCurrentAccount = exports.readActiveClaudeAccount = exports.writeAccountRegistry = exports.readAccountRegistry = exports.ensureDefaultAccounts = exports.codexIdentitiesMatch = exports.readCodexAccessTokenExpiry = exports.readCodexLastRefresh = exports.readCodexAuthIdentity = exports.parseCodexAuthJson = exports.CLAUDE_REFRESH_TOKEN_LIFETIME_ESTIMATE_MS = exports.CLAUDE_ACCESS_TOKEN_LIFETIME_MS = exports.resolveClaudeRefreshExpiry = exports.isNewerClaudeCredential = exports.claudeCredentialFreshness = exports.parseClaudeCredentialBlob = exports.readClaudeMaxAccessTokenSync = exports.readClaudeMaxCredentialsRaw = exports.readClaudeMaxCredentials = exports.deleteStoredCredentials = exports.writeActiveCredentials = exports.readActiveCredentials = exports.openInBrowser = exports.parseTranscriptFromEvents = void 0;
12
+ exports.getCodexExecutionEnv = exports.resolveSidekickCodexHome = exports.resolveActiveCodexAccount = exports.getActiveCodexAccount = exports.listCodexAccounts = exports.getSystemCodexHome = exports.getCodexMonitoringHomes = exports.getCodexProfileHome = exports.getCodexProfilesDir = exports.readLiveClaudeIdentity = exports.readClaudeProfileIdentity = exports.isClaudeProfileAuthenticated = exports.CLAUDE_SECURESTORAGE_CONFIG_DIR_ENV = exports.buildClaudeChildEnv = exports.claudeKeychainAccountName = exports.claudeKeychainService = exports.claudeKeychainSuffix = exports.getClaudeConfigPath = exports.getDefaultClaudeHome = exports.getLiveClaudeHome = exports.getClaudeProfileHome = exports.getClaudeProfilesDir = exports.onAccountsChanged = exports.getActiveAccountStatus = exports.ACCOUNT_PROVIDER_IDS = exports.removeSavedAccountProfile = exports.replaceSavedAccountProfiles = exports.setActiveSavedAccount = exports.upsertSavedAccountProfile = exports.getActiveSavedAccount = exports.listSavedAccountProfiles = exports.writeSavedAccountRegistry = exports.readSavedAccountRegistry = exports.getAccountsDir = exports.ACCOUNT_CONSUMER_REACHABILITY = exports.describeAccountConsumer = exports.detectRunningAccountConsumersSync = exports.detectRunningAccountConsumers = exports.findRunningProcessesSync = exports.findRunningProcesses = exports.keepAliveCommand = exports.refreshInactiveAccounts = exports.getAccountLaunchEnv = exports.getHealthSidecarPath = exports.readHealthSidecar = exports.listAccountsWithHealth = exports.getAccountHealth = exports.cleanupAbandonedLogins = exports.syncLiveAccountStateSync = exports.syncLiveAccountState = void 0;
13
+ exports.quotaStateFromZaiQuotaLimitPayload = exports.fetchZaiQuotaFromApi = exports.CodexQuotaWatcher = exports.resolveCodexQuotaFromLocalSources = exports.resolveCodexQuota = exports.readLatestCodexQuotaFromRollouts = exports.quotaFromCodexRateLimits = exports.fetchCodexQuotaFromApi = exports.fetchCodexResetCreditsFromApi = exports.getWorkspaceIdFromPath = exports.pruneQuotaHistory = exports.readQuotaHistoryDailyBuckets = exports.readQuotaHistoryRange = exports.appendQuotaHistorySample = exports.quotaFromStatuslinePayload = exports.parseClaudeStatuslinePayload = exports.evaluateQuotaThresholds = exports.describeQuotaThresholdAlert = exports.DEFAULT_QUOTA_THRESHOLDS = exports.QUOTA_FRESH_MAX_AGE_MS = exports.QUOTA_AGING_MAX_AGE_MS = exports.formatQuotaAge = exports.classifyQuotaFreshness = exports.resolveQuota = exports.writeQuotaSnapshot = exports.readQuotaSnapshot = exports.QuotaPoller = exports.describeQuotaFailure = exports.withQuotaProjections = exports.projectQuotaWindow = exports.fetchQuota = exports.SEVEN_DAY_WINDOW_MS = exports.QUOTA_PROVIDER_IDS = exports.FIVE_HOUR_WINDOW_MS = exports.AutoSwitchController = exports.decideAutoSwitch = exports.DEFAULT_AUTO_SWITCH_CONFIG = exports.removeLauncher = exports.writeLauncher = exports.CODEX_KEYRING_FIX_HINT = exports.getCodexCredentialStoreMode = exports.cleanupAbandonedCodexLogins = exports.syncCodexLiveState = exports.removeCodexAccount = exports.switchToCodexAccountAsync = exports.switchToCodexAccount = exports.finalizeCodexAccountAsync = exports.finalizeCodexAccount = exports.prepareCodexAccountAsync = exports.prepareCodexAccount = void 0;
14
+ exports.extractToolCalls = exports.extractToolCall = exports.extractErrorMessage = exports.categorizeError = exports.gatherAssetsForCwd = exports.codexSessions = exports.readCodexAssets = exports.claudeSessions = exports.readClaudeAssets = exports.extractCommands = exports.extractFilePaths = exports.extractUrls = exports.extractTokenUsage = exports.getObservedContextWindowPath = exports.recordObservedContextWindow = exports.loadObservedContextWindows = exports.LITELLM_CATALOG_URL = exports.normalizeLiteLlmContextWindows = exports.normalizeLiteLlmCatalog = exports.hydratePricingCatalog = exports.RESOLVED_MODEL_CATALOG_SCHEMA_VERSION = exports.resolveModelAlias = exports.registerModelAlias = exports.importResolvedModelCatalog = exports.exportResolvedModelCatalog = exports.MODEL_PROVIDER_IDS = exports.formatCost = exports.sortModelIds = exports.compareModelIds = exports.getModelDisplayInfo = exports.shortModelName = exports.mergeCostSources = exports.calculateCostWithProvenance = exports.calculateCostWithPricing = exports.calculateCost = exports.getModelInfo = exports.resolveModelPricing = exports.getModelPricing = exports.parseModelId = exports.DEFAULT_CONTEXT_WINDOW = exports.resolveModelContextWindow = exports.getModelContextWindowSize = exports.selectStatuslineAccount = exports.formatStatusline = exports.estimateTimeToQuota = exports.BurnRateCalculator = exports.RUNTIME_QUOTA_PROVIDER_IDS = exports.MultiProviderQuotaService = exports.resolveZaiQuota = exports.readZaiCredentials = void 0;
15
+ exports.getSessionDiagnostics = exports.formatHealthReport = exports.toLegacyProviderStatus = exports.fetchOpenAIStatus = exports.fetchProviderStatus = exports.assistantTurnToolRefSchema = exports.assistantTurnToolGroupStepSchema = exports.assistantTurnTimelineItemSchema = exports.assistantTurnSubagentStatusSchema = exports.assistantTurnSubagentSchema = exports.assistantTurnReasoningTimelineItemSchema = exports.assistantTurnProjectionSchema = exports.assistantTurnProcessStepSchema = exports.assistantTurnProcessSchema = exports.assistantTurnNarrationStepSchema = exports.assistantTurnEventTypeSchema = exports.assistantTurnEventSchema = exports.listAllAccountsResultSchema = exports.savedAccountProfileSchema = exports.accountEntrySchema = exports.accountLoginStatusSchema = exports.beginAccountLoginResultSchema = exports.accountManagerResultSchema = exports.accountProviderIdSchema = exports.activeAccountStatusSchema = exports.activeProviderAccountStatusSchema = exports.quotaHistoryDailyBucketSchema = exports.quotaHistorySampleSchema = exports.quotaHistoryRuntimeProviderSchema = exports.providerQuotaMapSchema = exports.zaiProviderQuotaStateSchema = exports.codexProviderQuotaStateSchema = exports.claudeProviderQuotaStateSchema = exports.providerQuotaStateSchema = exports.runtimeQuotaProviderSchema = exports.quotaFailureDescriptorSchema = exports.peakHoursStateSchema = exports.codexResetCreditsSnapshotSchema = exports.codexResetCreditSchema = exports.quotaSourceSchema = exports.quotaProviderIdSchema = exports.quotaFailureKindSchema = exports.quotaStateSchema = exports.quotaWindowSchema = exports.extractSessionEvents = exports.permissionModeSchema = exports.sessionEventSchema = exports.sessionMessageSchema = exports.messageUsageSchema = exports.ToolCallTracker = void 0;
16
+ exports.fetchProviderServiceStatus = exports.diagnoseProviderFailure = exports.mergeFailingToolWindows = exports.failingToolTrend = exports.FAILING_TOOL_TREND_ARROWS = exports.scopePeakHoursToSessionProvider = exports.PEAK_HOURS_DESCRIPTION = exports.PEAK_HOURS_CACHE_MS = exports.isClaudeCodeSessionProvider = exports.getScheduledPeakHoursState = exports.fetchPeakHoursStatus = exports.DEFAULT_PEAK_HOURS_TIMEOUT_MS = exports.createPeakHoursNotApplicableState = exports._resetPeakHoursCache = exports.runDoctor = void 0;
17
17
  var usageNormalization_1 = require("./usageNormalization");
18
18
  Object.defineProperty(exports, "normalizeProviderUsage", { enumerable: true, get: function () { return usageNormalization_1.normalizeProviderUsage; } });
19
19
  Object.defineProperty(exports, "extractNormalizedUsage", { enumerable: true, get: function () { return usageNormalization_1.extractNormalizedUsage; } });
@@ -37,6 +37,8 @@ Object.defineProperty(exports, "listRecentSessions", { enumerable: true, get: fu
37
37
  Object.defineProperty(exports, "readSessionTranscript", { enumerable: true, get: function () { return sessionTranscripts_1.readSessionTranscript; } });
38
38
  var promptHistory_1 = require("./promptHistory");
39
39
  Object.defineProperty(exports, "collectPromptHistory", { enumerable: true, get: function () { return promptHistory_1.collectPromptHistory; } });
40
+ var sessionPromptHistory_1 = require("./sessionPromptHistory");
41
+ Object.defineProperty(exports, "collectSessionPromptHistory", { enumerable: true, get: function () { return sessionPromptHistory_1.collectSessionPromptHistory; } });
40
42
  var humanPrompt_1 = require("./humanPrompt");
41
43
  Object.defineProperty(exports, "HUMAN_CLAUDE_ENTRYPOINTS", { enumerable: true, get: function () { return humanPrompt_1.HUMAN_CLAUDE_ENTRYPOINTS; } });
42
44
  Object.defineProperty(exports, "HUMAN_CODEX_SOURCES", { enumerable: true, get: function () { return humanPrompt_1.HUMAN_CODEX_SOURCES; } });
package/dist/node.d.ts CHANGED
@@ -12,6 +12,9 @@ export type { ObservedContextWindowOptions, ObservedContextWindowStore, } from '
12
12
  export { listRecentSessions, readSessionTranscript } from './sessionTranscripts';
13
13
  export { collectPromptHistory } from './promptHistory';
14
14
  export type { CollectPromptHistoryOptions, PromptHistoryAnswerState, PromptHistoryBound, PromptHistoryBounds, PromptHistoryCursor, PromptHistoryCursorSession, PromptHistoryEntry, PromptHistoryExclusion, PromptHistoryMetadataStatus, PromptHistoryPendingPrompt, PromptHistoryProvider, PromptHistoryResult, PromptHistoryResumeState, PromptHistoryStats, PromptHistoryUsage, } from './promptHistory';
15
+ export { collectSessionPromptHistory } from './sessionPromptHistory';
16
+ export type { CollectSessionPromptHistoryOptions, PromptHistorySession, PromptHistorySessionPrompt, PromptHistorySessionRef, SessionPromptHistoryBound, SessionPromptHistoryBounds, SessionPromptHistoryInclude, SessionPromptHistoryResult, SessionPromptHistoryStats, } from './sessionPromptHistory';
17
+ export type { PromptHistoryReply, PromptHistorySignal, PromptHistorySignalKind, } from './sessionPromptSignals';
15
18
  export { HUMAN_CLAUDE_ENTRYPOINTS, HUMAN_CODEX_SOURCES, humanPromptText, isHumanPrompt, } from './humanPrompt';
16
19
  export type { HumanPromptProvider } from './humanPrompt';
17
20
  export { computeSessionFileStats, firstUserPrompt, providerContextSizeFn, readSessionFileStats, } from './sessionStats';
@@ -46,6 +49,9 @@ export { ObservedSessionCollector, observedSessionSourceFromProvider, fileFinger
46
49
  export type { KnownObservedSessionFingerprint, ObservedSessionChange, ObservedSessionChangeBatch, ObservedSessionChangeType, ObservedSessionReference, ObservedSessionFingerprintParts, ObservedSessionSourceSubscribeOptions, ObservedSessionSubscribeOptions, ObservedSessionCollectionSource, ProviderObservedSessionCollectionSource, ObservedSessionDiagnosticKind, ObservedSessionDiagnosticPhase, ObservedSessionDiagnosticSeverity, ObservedSessionDiagnostic, ObservedSessionCollection, ObservedSessionCollectorOptions, ObservedSessionCollectOptions, ObservedSessionDiscoverOptions, ObservedSessionDiscoveryStats, ObservedSessionDiscoveryTrigger, ObservedSessionSourceSignal, ObservedSessionSourceListener, ObservedSessionResolution, } from './observedSessionCollector';
47
50
  export { DirectoryListingCache, splitWatchedPath } from './providers/directoryListingCache';
48
51
  export type { CachedDirectoryListing, CachedFileStat, DirectoryListingCacheOptions, DirectoryListingCounters, ListDirectoryOptions, } from './providers/directoryListingCache';
49
- export type { ListSessionFilesOptions, SessionEnumerationCounters, WatchedSessionFile, } from './providers/types';
52
+ export type { ListSessionFilesOptions, ProviderId, SessionEnumerationCounters, SessionProviderBase, SessionProviderDiagnostic, WatchedSessionFile, } from './providers/types';
53
+ export { createSessionProviders } from './providers/factory';
54
+ export type { CreateSessionProvidersOptions, CreateSessionProvidersResult, } from './providers/factory';
55
+ export { SYNTHETIC_MODEL } from './usage/claudeUsageDedupe';
50
56
  export type { ProviderServiceSeverity, ProviderServiceComponent, ProviderServiceIncident, ProviderServiceStatusFailureReason, ObservedProviderServiceStatus, UnavailableProviderServiceStatus, ProviderServiceStatus, FetchProviderServiceStatusOptions, } from './providerServiceStatusTypes';
51
57
  export { fetchProviderServiceStatus } from './providerServiceStatus';
package/dist/node.js CHANGED
@@ -7,8 +7,8 @@
7
7
  * for browser bundles — use `sidekick-shared/browser` there.
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.summarizeUsageRows = exports.bucketUsage = exports.importSessionHistory = exports.ACTIVE_SESSION_MTIME_THRESHOLD_MS = exports.sessionSummaryFromStats = exports.removeSessionSummary = exports.markFileImported = exports.isFileImported = exports.applySessionSummary = exports.subagentTokenTotals = exports.scanSessionSubagents = exports.readMainThreadTokenTotals = exports.combineSessionTokenTotals = exports.collectSessionTokenTotals = exports.pruneUsageCache = exports.getUsageCacheDir = exports.collectUsageEvents = exports.USAGE_CACHE_VERSION = exports.MAX_USAGE_CACHE_FILES = exports.findActiveBillingBlock = exports.computeBillingBlocks = exports.BILLING_BLOCK_DURATION_MS = exports.writeStateFile = exports.readStateFile = exports.quotaToStateFile = exports.getStateFilePath = exports.billingBlockToStateFile = exports.STATE_FILE_SCHEMA_VERSION = exports.STATE_FILE_NAME = exports.sessionFingerprintParts = exports.fingerprintString = exports.readSessionReportInputs = exports.readSessionFileStats = exports.providerContextSizeFn = exports.firstUserPrompt = exports.computeSessionFileStats = exports.isHumanPrompt = exports.humanPromptText = exports.HUMAN_CODEX_SOURCES = exports.HUMAN_CLAUDE_ENTRYPOINTS = exports.collectPromptHistory = exports.readSessionTranscript = exports.listRecentSessions = exports.getObservedContextWindowPath = exports.recordObservedContextWindow = exports.loadObservedContextWindows = exports.LITELLM_CATALOG_URL = exports.normalizeLiteLlmContextWindows = exports.normalizeLiteLlmCatalog = exports.hydratePricingCatalog = void 0;
11
- exports.fetchProviderServiceStatus = exports.splitWatchedPath = exports.DirectoryListingCache = exports.fileFingerprintParts = exports.fileFingerprint = exports.observedSessionSourceFromProvider = exports.ObservedSessionCollector = exports.readSessionPreviewAsync = exports.readSessionPreview = exports.listSessionPreviewsAsync = exports.listSessionPreviews = exports.readCodexHistory = exports.walkRolloutFilesAsync = exports.walkRolloutFiles = exports.findCodexRolloutFile = exports.weekKey = exports.usageBucketKey = void 0;
10
+ exports.bucketUsage = exports.importSessionHistory = exports.ACTIVE_SESSION_MTIME_THRESHOLD_MS = exports.sessionSummaryFromStats = exports.removeSessionSummary = exports.markFileImported = exports.isFileImported = exports.applySessionSummary = exports.subagentTokenTotals = exports.scanSessionSubagents = exports.readMainThreadTokenTotals = exports.combineSessionTokenTotals = exports.collectSessionTokenTotals = exports.pruneUsageCache = exports.getUsageCacheDir = exports.collectUsageEvents = exports.USAGE_CACHE_VERSION = exports.MAX_USAGE_CACHE_FILES = exports.findActiveBillingBlock = exports.computeBillingBlocks = exports.BILLING_BLOCK_DURATION_MS = exports.writeStateFile = exports.readStateFile = exports.quotaToStateFile = exports.getStateFilePath = exports.billingBlockToStateFile = exports.STATE_FILE_SCHEMA_VERSION = exports.STATE_FILE_NAME = exports.sessionFingerprintParts = exports.fingerprintString = exports.readSessionReportInputs = exports.readSessionFileStats = exports.providerContextSizeFn = exports.firstUserPrompt = exports.computeSessionFileStats = exports.isHumanPrompt = exports.humanPromptText = exports.HUMAN_CODEX_SOURCES = exports.HUMAN_CLAUDE_ENTRYPOINTS = exports.collectSessionPromptHistory = exports.collectPromptHistory = exports.readSessionTranscript = exports.listRecentSessions = exports.getObservedContextWindowPath = exports.recordObservedContextWindow = exports.loadObservedContextWindows = exports.LITELLM_CATALOG_URL = exports.normalizeLiteLlmContextWindows = exports.normalizeLiteLlmCatalog = exports.hydratePricingCatalog = void 0;
11
+ exports.fetchProviderServiceStatus = exports.SYNTHETIC_MODEL = exports.createSessionProviders = exports.splitWatchedPath = exports.DirectoryListingCache = exports.fileFingerprintParts = exports.fileFingerprint = exports.observedSessionSourceFromProvider = exports.ObservedSessionCollector = exports.readSessionPreviewAsync = exports.readSessionPreview = exports.listSessionPreviewsAsync = exports.listSessionPreviews = exports.readCodexHistory = exports.walkRolloutFilesAsync = exports.walkRolloutFiles = exports.findCodexRolloutFile = exports.weekKey = exports.usageBucketKey = exports.summarizeUsageRows = void 0;
12
12
  var pricingCatalog_1 = require("./pricingCatalog");
13
13
  Object.defineProperty(exports, "hydratePricingCatalog", { enumerable: true, get: function () { return pricingCatalog_1.hydratePricingCatalog; } });
14
14
  Object.defineProperty(exports, "normalizeLiteLlmCatalog", { enumerable: true, get: function () { return pricingCatalog_1.normalizeLiteLlmCatalog; } });
@@ -23,6 +23,8 @@ Object.defineProperty(exports, "listRecentSessions", { enumerable: true, get: fu
23
23
  Object.defineProperty(exports, "readSessionTranscript", { enumerable: true, get: function () { return sessionTranscripts_1.readSessionTranscript; } });
24
24
  var promptHistory_1 = require("./promptHistory");
25
25
  Object.defineProperty(exports, "collectPromptHistory", { enumerable: true, get: function () { return promptHistory_1.collectPromptHistory; } });
26
+ var sessionPromptHistory_1 = require("./sessionPromptHistory");
27
+ Object.defineProperty(exports, "collectSessionPromptHistory", { enumerable: true, get: function () { return sessionPromptHistory_1.collectSessionPromptHistory; } });
26
28
  var humanPrompt_1 = require("./humanPrompt");
27
29
  Object.defineProperty(exports, "HUMAN_CLAUDE_ENTRYPOINTS", { enumerable: true, get: function () { return humanPrompt_1.HUMAN_CLAUDE_ENTRYPOINTS; } });
28
30
  Object.defineProperty(exports, "HUMAN_CODEX_SOURCES", { enumerable: true, get: function () { return humanPrompt_1.HUMAN_CODEX_SOURCES; } });
@@ -96,5 +98,9 @@ Object.defineProperty(exports, "fileFingerprintParts", { enumerable: true, get:
96
98
  var directoryListingCache_1 = require("./providers/directoryListingCache");
97
99
  Object.defineProperty(exports, "DirectoryListingCache", { enumerable: true, get: function () { return directoryListingCache_1.DirectoryListingCache; } });
98
100
  Object.defineProperty(exports, "splitWatchedPath", { enumerable: true, get: function () { return directoryListingCache_1.splitWatchedPath; } });
101
+ var factory_1 = require("./providers/factory");
102
+ Object.defineProperty(exports, "createSessionProviders", { enumerable: true, get: function () { return factory_1.createSessionProviders; } });
103
+ var claudeUsageDedupe_1 = require("./usage/claudeUsageDedupe");
104
+ Object.defineProperty(exports, "SYNTHETIC_MODEL", { enumerable: true, get: function () { return claudeUsageDedupe_1.SYNTHETIC_MODEL; } });
99
105
  var providerServiceStatus_1 = require("./providerServiceStatus");
100
106
  Object.defineProperty(exports, "fetchProviderServiceStatus", { enumerable: true, get: function () { return providerServiceStatus_1.fetchProviderServiceStatus; } });
@@ -19,6 +19,7 @@
19
19
  * the prompt is returned again under the same identity once its first
20
20
  * answering call brings model or usage (`metadataStatus` says how settled).
21
21
  */
22
+ import * as fs from 'fs';
22
23
  import { type HumanPromptProvider } from './humanPrompt';
23
24
  export type PromptHistoryProvider = HumanPromptProvider;
24
25
  export type PromptHistoryBound = 'maxSessions' | 'maxFileBytes' | 'maxTotalBytes' | 'maxEntries' | 'deadline' | 'aborted';
@@ -213,9 +214,74 @@ export interface PromptHistoryResult {
213
214
  /** A bound left bytes or files unread; call again with the cursor to continue. */
214
215
  hasMore: boolean;
215
216
  }
217
+ /** @internal */
218
+ export declare const DEFAULT_BOUNDS: Required<PromptHistoryBounds>;
216
219
  /** Test hooks; not part of the public entry points. */
217
220
  export declare const __promptHistoryTesting: {
218
221
  setReadChunkBytes(bytes: number | null): void;
219
222
  };
223
+ /** @internal */
224
+ export interface Candidate {
225
+ provider: PromptHistoryProvider;
226
+ sessionId: string;
227
+ filePath: string;
228
+ key: string;
229
+ }
230
+ /**
231
+ * Sees every parsed record of a file after the scanner, with the ordinal of the
232
+ * latest human prompt so far (-1 before the first). Used for whole-session reads.
233
+ * @internal
234
+ */
235
+ export type RecordObserver = (record: Record<string, unknown>, info: {
236
+ ordinal: number;
237
+ lineOffset: number;
238
+ }) => void;
239
+ /** @internal */
240
+ export interface ScanContext {
241
+ roots: string[];
242
+ sinceMs: number | null;
243
+ stats: PromptHistoryStats;
244
+ realpaths: Map<string, string | null>;
245
+ bounds: Required<PromptHistoryBounds>;
246
+ shouldStop: () => PromptHistoryBound | null;
247
+ /** Entries already collected from earlier files in this call. */
248
+ entriesSoFar: () => number;
249
+ exclude: (exclusion: PromptHistoryExclusion) => void;
250
+ observe?: RecordObserver;
251
+ }
252
+ /** @internal */
253
+ export interface FileBudget {
254
+ bytes: number;
255
+ /** Which bound `bytes` came from. */
256
+ bound: 'maxFileBytes' | 'maxTotalBytes';
257
+ /** First file of the call: may finish its first record even past the budget. */
258
+ forceProgress: boolean;
259
+ }
260
+ /** @internal */
261
+ export interface FileOutcome {
262
+ entries: PromptHistoryEntry[];
263
+ /** The pass moved the file's offset forward. */
264
+ progressed: boolean;
265
+ /** New cursor state, or undefined to drop it (rewrite found mid-pass). */
266
+ session: PromptHistoryCursorSession | undefined;
267
+ bytesRead: number;
268
+ stoppedBy: PromptHistoryBound | null;
269
+ notInteractive: boolean;
270
+ inScope: number;
271
+ outOfScope: number;
272
+ }
220
273
  /** Collect human-typed prompts from Claude Code and Codex logs under the given roots. */
221
274
  export declare function collectPromptHistory(options: CollectPromptHistoryOptions): Promise<PromptHistoryResult>;
275
+ /** @internal */
276
+ export declare function emptyStats(): PromptHistoryStats;
277
+ /** @internal */
278
+ export declare function compareStrings(left: string, right: string): number;
279
+ /** @internal */
280
+ export declare function resolveRoots(workspacePaths: string[], includeWorktrees: boolean, realpaths: Map<string, string | null>): {
281
+ roots: string[];
282
+ listingRoots: string[];
283
+ };
284
+ /** @internal */
285
+ export declare function listCandidates(providers: PromptHistoryProvider[], listingRoots: string[], sinceMs: number | null): Promise<Candidate[]>;
286
+ /** @internal */
287
+ export declare function scanFile(candidate: Candidate, stat: fs.Stats, prior: PromptHistoryCursorSession | undefined, budget: FileBudget, context: ScanContext): Promise<FileOutcome>;
@@ -54,8 +54,13 @@ var __importStar = (this && this.__importStar) || (function () {
54
54
  };
55
55
  })();
56
56
  Object.defineProperty(exports, "__esModule", { value: true });
57
- exports.__promptHistoryTesting = void 0;
57
+ exports.__promptHistoryTesting = exports.DEFAULT_BOUNDS = void 0;
58
58
  exports.collectPromptHistory = collectPromptHistory;
59
+ exports.emptyStats = emptyStats;
60
+ exports.compareStrings = compareStrings;
61
+ exports.resolveRoots = resolveRoots;
62
+ exports.listCandidates = listCandidates;
63
+ exports.scanFile = scanFile;
59
64
  const crypto_1 = require("crypto");
60
65
  const fs = __importStar(require("fs"));
61
66
  const path = __importStar(require("path"));
@@ -63,7 +68,8 @@ const humanPrompt_1 = require("./humanPrompt");
63
68
  const sessionPathResolver_1 = require("./parsers/sessionPathResolver");
64
69
  const claudeCode_1 = require("./providers/claudeCode");
65
70
  const codex_1 = require("./providers/codex");
66
- const DEFAULT_BOUNDS = {
71
+ /** @internal */
72
+ exports.DEFAULT_BOUNDS = {
67
73
  maxSessions: 1000,
68
74
  maxFileBytes: 16 * 1024 * 1024,
69
75
  maxTotalBytes: 256 * 1024 * 1024,
@@ -85,22 +91,10 @@ exports.__promptHistoryTesting = {
85
91
  };
86
92
  /** Collect human-typed prompts from Claude Code and Codex logs under the given roots. */
87
93
  async function collectPromptHistory(options) {
88
- const bounds = { ...DEFAULT_BOUNDS, ...definedBounds(options.bounds) };
94
+ const bounds = { ...exports.DEFAULT_BOUNDS, ...definedBounds(options.bounds) };
89
95
  const startedAt = Date.now();
90
96
  const boundsHit = new Set();
91
- const stats = {
92
- sessionsScanned: 0,
93
- sessionsSkippedUnchanged: 0,
94
- sessionsOutOfScope: 0,
95
- filesOverSizeLimit: 0,
96
- sessionsWithBacklog: 0,
97
- sessionsRewritten: 0,
98
- sessionsNotInteractive: 0,
99
- recordsOverSizeLimit: 0,
100
- recordsMalformed: 0,
101
- promptsMissingTimestamp: 0,
102
- promptsOutOfScope: 0,
103
- };
97
+ const stats = emptyStats();
104
98
  const { sessions: previous, next: previousNext } = acceptedCursor(options.cursor);
105
99
  const cursor = { version: 3, sessions: { ...previous } };
106
100
  const entries = [];
@@ -231,11 +225,27 @@ async function collectPromptHistory(options) {
231
225
  }
232
226
  return finish();
233
227
  }
228
+ /** @internal */
229
+ function emptyStats() {
230
+ return {
231
+ sessionsScanned: 0,
232
+ sessionsSkippedUnchanged: 0,
233
+ sessionsOutOfScope: 0,
234
+ filesOverSizeLimit: 0,
235
+ sessionsWithBacklog: 0,
236
+ sessionsRewritten: 0,
237
+ sessionsNotInteractive: 0,
238
+ recordsOverSizeLimit: 0,
239
+ recordsMalformed: 0,
240
+ promptsMissingTimestamp: 0,
241
+ promptsOutOfScope: 0,
242
+ };
243
+ }
234
244
  function definedBounds(bounds) {
235
245
  const result = {};
236
246
  if (!bounds)
237
247
  return result;
238
- for (const key of Object.keys(DEFAULT_BOUNDS)) {
248
+ for (const key of Object.keys(exports.DEFAULT_BOUNDS)) {
239
249
  const value = bounds[key];
240
250
  if (typeof value === 'number' && !Number.isNaN(value))
241
251
  result[key] = Math.max(0, value);
@@ -321,6 +331,7 @@ function compareEntries(left, right) {
321
331
  compareStrings(left.sessionId, right.sessionId) ||
322
332
  left.ordinal - right.ordinal);
323
333
  }
334
+ /** @internal */
324
335
  function compareStrings(left, right) {
325
336
  return left < right ? -1 : left > right ? 1 : 0;
326
337
  }
@@ -342,6 +353,7 @@ function realpathOrNull(input, cache) {
342
353
  cache.set(input, resolved);
343
354
  return resolved;
344
355
  }
356
+ /** @internal */
345
357
  function resolveRoots(workspacePaths, includeWorktrees, realpaths) {
346
358
  const roots = new Set();
347
359
  const listingRoots = new Set();
@@ -385,6 +397,7 @@ function scopedCwd(cwd, roots, realpaths) {
385
397
  }
386
398
  return null;
387
399
  }
400
+ /** @internal */
388
401
  async function listCandidates(providers, listingRoots, sinceMs) {
389
402
  const byPath = new Map();
390
403
  const listOptions = sinceMs !== null ? { since: sinceMs } : {};
@@ -468,6 +481,7 @@ async function verifyFile(handle, size, session) {
468
481
  }
469
482
  return { head: { bytes: head.length, hash: hashBytes(head) }, bytesRead };
470
483
  }
484
+ /** @internal */
471
485
  async function scanFile(candidate, stat, prior, budget, context) {
472
486
  const handle = await fs.promises.open(candidate.filePath, 'r');
473
487
  try {
@@ -728,7 +742,12 @@ function acceptLine(line, lineOffset, lineBytes, scanner, context, candidate) {
728
742
  }
729
743
  if (typeof record !== 'object' || record === null)
730
744
  return 'ok';
731
- return scanner.accept(record, lineOffset, lineBytes);
745
+ const row = record;
746
+ const accepted = scanner.accept(row, lineOffset, lineBytes);
747
+ if (accepted === 'ok' && context.observe) {
748
+ context.observe(row, { ordinal: scanner.lastOrdinal(), lineOffset });
749
+ }
750
+ return accepted;
732
751
  }
733
752
  /** Shared per-file prompt bookkeeping for both providers. */
734
753
  class LineScanner {