reasonix 0.12.16 → 0.12.20

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/dist/index.d.ts CHANGED
@@ -392,6 +392,13 @@ interface HookOutcome {
392
392
  /** Captured stderr (trimmed). The block / warn message comes from here. */
393
393
  stderr: string;
394
394
  durationMs: number;
395
+ /**
396
+ * True when stdout or stderr crossed the per-stream byte cap and was
397
+ * truncated. The hook still completed; the loop just sees a clipped
398
+ * view of its output. Surfaced via `formatHookOutcomeMessage` so the
399
+ * user knows their script wrote more than Reasonix kept.
400
+ */
401
+ truncated?: boolean;
395
402
  }
396
403
  /** Aggregate report for `runHooks`. */
397
404
  interface HookReport {
@@ -455,6 +462,14 @@ interface HookSpawnResult {
455
462
  timedOut: boolean;
456
463
  /** True iff spawn() itself failed (ENOENT, EACCES, …). */
457
464
  spawnError?: Error;
465
+ /**
466
+ * True iff stdout or stderr was capped at the byte limit. The hook
467
+ * still ran to completion / timeout, but downstream consumers see a
468
+ * truncated view of its output. Surface this in the UI so a hook
469
+ * author who relies on long output knows the loop didn't see all
470
+ * of it.
471
+ */
472
+ truncated?: boolean;
458
473
  }
459
474
  type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;
460
475
  /**
@@ -502,6 +517,23 @@ declare class ImmutablePrefix {
502
517
  */
503
518
  private _toolSpecs;
504
519
  readonly fewShots: readonly ChatMessage[];
520
+ /**
521
+ * Cached SHA-256 of the prefix payload. Computed lazily on first
522
+ * `fingerprint` access, invalidated only by mutations that go
523
+ * through `addTool` (the one legitimate post-construction mutation
524
+ * path). The TUI reads `fingerprint` on every render — without the
525
+ * cache, that means a fresh `JSON.stringify` + sha256 over the
526
+ * full prefix (system prompt + tools list + few-shots, typically
527
+ * 5-10KB) on every keystroke.
528
+ *
529
+ * The lazy-init also acts as a cheap drift guard: if some future
530
+ * code path mutates `_toolSpecs` directly without going through
531
+ * `addTool`, `fingerprint` will return the stale cached value
532
+ * while the actual prefix sent to DeepSeek diverges — the cache
533
+ * miss would be the first symptom. {@link verifyFingerprint}
534
+ * lets dev / test code assert the cache matches reality.
535
+ */
536
+ private _fingerprintCache;
505
537
  constructor(opts: ImmutablePrefixOptions);
506
538
  get toolSpecs(): readonly ToolSpec[];
507
539
  toMessages(): ChatMessage[];
@@ -514,6 +546,16 @@ declare class ImmutablePrefix {
514
546
  */
515
547
  addTool(spec: ToolSpec): boolean;
516
548
  get fingerprint(): string;
549
+ /**
550
+ * Recompute the fingerprint from scratch and assert it matches the
551
+ * cached value. Returns the freshly-computed hash on success; throws
552
+ * with a diff if the cache drifted, which always indicates a bug —
553
+ * either a non-`addTool` mutation path was added, or `addTool`
554
+ * forgot to invalidate the cache. Dev / test only; the live loop
555
+ * doesn't call this on the hot path.
556
+ */
557
+ verifyFingerprint(): string;
558
+ private computeFingerprint;
517
559
  }
518
560
  declare class AppendOnlyLog {
519
561
  private _entries;
@@ -951,6 +993,18 @@ interface CacheFirstLoopOptions {
951
993
  * presets pass `false` to lock the running session to one model.
952
994
  */
953
995
  autoEscalate?: boolean;
996
+ /**
997
+ * Soft USD budget for the entire session. When set, the loop:
998
+ * - Emits a one-shot warning event when cumulative cost crosses 80%
999
+ * - Refuses to run the next turn once cumulative cost ≥ budget,
1000
+ * yielding an error that explains how to bump or clear the cap
1001
+ *
1002
+ * Default `undefined` — no cap, no warnings. Reasonix is the cost-
1003
+ * focused agent; the budget is opt-in so users new to the tool
1004
+ * don't get blocked at $0.50 wondering what happened, but heavy /
1005
+ * headless / CI users have a clean circuit breaker available.
1006
+ */
1007
+ budgetUsd?: number;
954
1008
  /**
955
1009
  * Session name. When set, the loop pre-loads the session's prior messages
956
1010
  * into its log on construction, and appends every new log entry to
@@ -1029,6 +1083,19 @@ declare class CacheFirstLoop {
1029
1083
  * flip it live alongside `model`.
1030
1084
  */
1031
1085
  autoEscalate: boolean;
1086
+ /**
1087
+ * Soft USD budget — see {@link CacheFirstLoopOptions.budgetUsd}.
1088
+ * Mutable so `/budget` slash can set / change / clear it mid-session.
1089
+ * `null` (the default) disables all budget checks.
1090
+ */
1091
+ budgetUsd: number | null;
1092
+ /**
1093
+ * Set the first time a turn crosses 80% of the budget so the warning
1094
+ * doesn't repeat every turn afterwards. Cleared by `setBudget` (any
1095
+ * change re-arms the warning, including raising the cap above the
1096
+ * current spend).
1097
+ */
1098
+ private _budgetWarned;
1032
1099
  sessionName: string | null;
1033
1100
  /**
1034
1101
  * Hook list, mutable so `/hooks reload` can swap it without
@@ -1185,6 +1252,13 @@ declare class CacheFirstLoop {
1185
1252
  * flip a knob between turns.
1186
1253
  */
1187
1254
  configure(opts: ReconfigurableOptions): void;
1255
+ /**
1256
+ * Set / change / clear the soft USD budget. `null` (or any non-
1257
+ * positive number) disables the cap entirely. Re-arms the 80%
1258
+ * warning so a user who bumps the cap mid-session sees a fresh
1259
+ * threshold message at the new boundary.
1260
+ */
1261
+ setBudget(usd: number | null): void;
1188
1262
  /**
1189
1263
  * Arm pro for the next turn (consumed at turn start). Called by
1190
1264
  * `/pro`. Idempotent — repeated calls stay armed, `disarmPro()`
@@ -1435,6 +1509,19 @@ interface FileWithStats {
1435
1509
  * recency sort).
1436
1510
  */
1437
1511
  declare function listFilesWithStatsSync(root: string, opts?: ListFilesOptions): FileWithStats[];
1512
+ /**
1513
+ * Async variant of {@link listFilesWithStatsSync}. Same walk semantics
1514
+ * (DFS, alphabetical, respects ignore + maxResults), but each
1515
+ * directory's entries are stat'd in parallel via `Promise.all`,
1516
+ * which slashes wall-clock time on Windows where individual stat
1517
+ * syscalls are 3-5x slower than Linux.
1518
+ *
1519
+ * Use this from the TUI mount path so a 500-file repo doesn't add
1520
+ * 200-300ms of synchronous block to first paint. Sync variant is
1521
+ * kept for paths where the caller can't `await` (server APIs,
1522
+ * test scaffolding).
1523
+ */
1524
+ declare function listFilesWithStatsAsync(root: string, opts?: ListFilesOptions): Promise<FileWithStats[]>;
1438
1525
  /**
1439
1526
  * Prefix pattern used by the `@` picker to detect an IN-PROGRESS
1440
1527
  * mention at the END of the input buffer. Captures the partial path
@@ -3873,6 +3960,12 @@ interface AppendUsageInput {
3873
3960
  * Returns the record that was written (or would have been written
3874
3961
  * if the disk had cooperated) so tests / callers can assert on the
3875
3962
  * computed cost fields without a round trip through the log file.
3963
+ *
3964
+ * On every Nth append the log is checked for size; if it crosses
3965
+ * {@link USAGE_COMPACTION_THRESHOLD_BYTES} we drop records older
3966
+ * than {@link USAGE_RETENTION_DAYS}. Cheaper than a startup-time
3967
+ * scan because most processes don't reach the threshold; the size
3968
+ * check is one statSync regardless.
3876
3969
  */
3877
3970
  declare function appendUsage(input: AppendUsageInput): UsageRecord;
3878
3971
  /**
@@ -3962,4 +4055,4 @@ declare function aggregateUsage(records: UsageRecord[], opts?: AggregateOptions)
3962
4055
  /** File-size helper for the stats header — "1.2 MB" etc. Returns "" if missing. */
3963
4056
  declare function formatLogSize(path?: string): string;
3964
4057
 
3965
- export { AT_MENTION_PATTERN, AT_PICKER_PREFIX, type AggregateOptions, AppendOnlyLog, type AppendUsageInput, type ApplyResult, type ApplyStatus, type AtMentionExpansion, type AtMentionOptions, type BranchOptions, type BranchProgress, type BranchResult, type BranchSample, type BranchSelector, type BranchSummary, type BridgeOptions, type BridgeResult, CODE_SYSTEM_PROMPT, CacheFirstLoop, type CacheFirstLoopOptions, type CallToolResult, type ChatMessage, type ChatResponse, type ChoiceOption, ChoiceRequestedError, type ChoiceToolOptions, DEFAULT_AT_MENTION_MAX_BYTES, DEFAULT_MAX_RESULT_CHARS, DEFAULT_MAX_RESULT_TOKENS, DEFAULT_PICKER_IGNORE_DIRS, DeepSeekClient, type DeepSeekClientOptions, type RenderOptions as DiffRenderOptions, type DiffReport, type DiffSide, type EditBlock, type EditSnapshot, type EventRole, type FileWithStats, type FilesystemToolsOptions, type FlattenDecision, type FlattenOptions, type GetLatestVersionOptions, type GetPromptResult, HOOK_EVENTS, HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME, type HarvestOptions, type HookConfig, type HookEvent, type HookOutcome, type HookPayload, type HookReport, type HookScope, type HookSettings, type HookSpawnInput, type HookSpawnResult, type HookSpawner, ImmutablePrefix, type ImmutablePrefixOptions, type InitializeResult, type InspectionReport, type JSONSchema, type JsonRpcMessage, type JsonRpcRequest, type JsonRpcResponse, LATEST_CACHE_TTL_MS, LATEST_FETCH_TIMEOUT_MS, type ListFilesOptions, type ListPromptsResult, type ListResourcesResult, type ListToolsResult, type LoadHookSettingsOptions, type LoopEvent, MCP_PROTOCOL_VERSION, MEMORY_INDEX_FILE, MEMORY_INDEX_MAX_CHARS, McpClient, type McpClientOptions, type McpContentBlock, type McpProgressHandler, type McpProgressInfo, type McpPrompt, type McpPromptArgument, type McpPromptMessage, type McpPromptResourceBlock, type McpResource, type McpResourceContents, type McpResourceContentsBlob, type McpResourceContentsText, type McpSpec, type McpTool, type McpToolSchema, type McpTransport, type MemoryEntry, type MemoryScope, MemoryStore, type MemoryStoreOptions, type MemoryToolsOptions, type MemoryType, type WriteInput as MemoryWriteInput, NeedsConfirmationError, PROJECT_MEMORY_FILE, PROJECT_MEMORY_MAX_CHARS, type PageContent, type PickerCandidate, PlanCheckpointError, PlanProposedError, PlanRevisionProposedError, type PlanStep, type PlanStepRisk, type PlanToolOptions, type ProgressNotificationParams, type ProjectMemory, type RankPickerOptions, type ReadResourceResult, type ReadTranscriptResult, type ReasonixConfig, type ReconfigurableOptions, type RepairReport, type ReplayStats, type ResolvedHook, type RetryInfo, type RetryOptions, type Role, type RunCommandResult, type RunHooksOptions, type ScavengeOptions, type ScavengeResult, type SearchResult, type SectionResult, type SessionInfo, SessionStats, type SessionSummary, type ShellToolsOptions, type SseMcpSpec, SseTransport, type SseTransportOptions, type StdioMcpSpec, StdioTransport, type StdioTransportOptions, type StepCompletion, StormBreaker, type StreamChunk, type StreamableHttpMcpSpec, StreamableHttpTransport, type StreamableHttpTransportOptions, type SubagentEvent, type SubagentSink, type SubagentToolOptions, type ToolCall, type ToolCallContext, ToolCallRepair, type ToolCallRepairOptions, type ToolDefinition, type ToolFunctionSpec, ToolRegistry, type ToolSpec, type TranscriptMeta, type TranscriptRecord, type TruncationRepairResult, type TurnPair, type TurnStats, type TypedPlanState, USER_MEMORY_DIR, Usage, type UsageAggregate, type UsageBucket, type UsageRecord, VERSION, VolatileScratch, type WebFetchOptions, type WebSearchOptions, type WebToolsOptions, aggregateBranchUsage, aggregateUsage, analyzeSchema, appendSessionMessage, appendUsage, applyEditBlock, applyEditBlocks, applyMemoryStack, applyProjectMemory, applyUserMemory, bridgeMcpTools, bucketCacheHitRatio, bucketSavingsFraction, claudeEquivalentCost, codeSystemPrompt, compareVersions, computeReplayStats, costUsd, decideOutcome, defaultConfigPath, defaultSelector, defaultUsageLogPath, deleteSession, detectAtPicker, detectShellOperator, diffTranscripts, emptyPlanState, expandAtMentions, fetchWithRetry, fixToolCallPairing, flattenMcpResult, flattenSchema, forkRegistryExcluding, formatCommandResult, formatHookOutcomeMessage, formatLogSize, formatLoopError, formatSearchResults, getLatestVersion, globalSettingsPath, harvest, healLoadedMessages, healLoadedMessagesByTokens, htmlToText, injectPowerShellUtf8, inputCostUsd, inspectMcpServer, isAllowed, isJsonRpcError, isNpxInstall, isPlanStateEmpty, isPlausibleKey, listFilesSync, listFilesWithStatsSync, listSessions, loadApiKey, loadDotenv, loadHooks, loadSessionMessages, matchesTool, memoryEnabled, nestArguments, openTranscriptFile, outputCostUsd, parseEditBlocks, parseMcpSpec, parseMojeekResults, parseTranscript, prepareSpawn, projectHash, projectSettingsPath, quoteForCmdExe, rankPickerCandidates, readConfig, readProjectMemory, readTranscript, readUsageLog, recordFromLoopEvent, redactKey, registerChoiceTool, registerFilesystemTools, registerMemoryTools, registerPlanTool, registerShellTools, registerSubagentTool, registerWebTools, renderMarkdown as renderDiffMarkdown, renderSummaryTable as renderDiffSummary, repairTruncatedJson, replayFromFile, resolveExecutable, restoreSnapshots, runBranches, runCommand, runHooks, sanitizeMemoryName, sanitizeName as sanitizeSessionName, saveApiKey, scavengeToolCalls, sessionPath, sessionsDir, similarity, snapshotBeforeEdits, stripHallucinatedToolMarkup, tokenizeCommand, truncateForModel, truncateForModelByTokens, webFetch, webSearch, withUtf8Codepage, writeConfig, writeMeta, writeRecord };
4058
+ export { AT_MENTION_PATTERN, AT_PICKER_PREFIX, type AggregateOptions, AppendOnlyLog, type AppendUsageInput, type ApplyResult, type ApplyStatus, type AtMentionExpansion, type AtMentionOptions, type BranchOptions, type BranchProgress, type BranchResult, type BranchSample, type BranchSelector, type BranchSummary, type BridgeOptions, type BridgeResult, CODE_SYSTEM_PROMPT, CacheFirstLoop, type CacheFirstLoopOptions, type CallToolResult, type ChatMessage, type ChatResponse, type ChoiceOption, ChoiceRequestedError, type ChoiceToolOptions, DEFAULT_AT_MENTION_MAX_BYTES, DEFAULT_MAX_RESULT_CHARS, DEFAULT_MAX_RESULT_TOKENS, DEFAULT_PICKER_IGNORE_DIRS, DeepSeekClient, type DeepSeekClientOptions, type RenderOptions as DiffRenderOptions, type DiffReport, type DiffSide, type EditBlock, type EditSnapshot, type EventRole, type FileWithStats, type FilesystemToolsOptions, type FlattenDecision, type FlattenOptions, type GetLatestVersionOptions, type GetPromptResult, HOOK_EVENTS, HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME, type HarvestOptions, type HookConfig, type HookEvent, type HookOutcome, type HookPayload, type HookReport, type HookScope, type HookSettings, type HookSpawnInput, type HookSpawnResult, type HookSpawner, ImmutablePrefix, type ImmutablePrefixOptions, type InitializeResult, type InspectionReport, type JSONSchema, type JsonRpcMessage, type JsonRpcRequest, type JsonRpcResponse, LATEST_CACHE_TTL_MS, LATEST_FETCH_TIMEOUT_MS, type ListFilesOptions, type ListPromptsResult, type ListResourcesResult, type ListToolsResult, type LoadHookSettingsOptions, type LoopEvent, MCP_PROTOCOL_VERSION, MEMORY_INDEX_FILE, MEMORY_INDEX_MAX_CHARS, McpClient, type McpClientOptions, type McpContentBlock, type McpProgressHandler, type McpProgressInfo, type McpPrompt, type McpPromptArgument, type McpPromptMessage, type McpPromptResourceBlock, type McpResource, type McpResourceContents, type McpResourceContentsBlob, type McpResourceContentsText, type McpSpec, type McpTool, type McpToolSchema, type McpTransport, type MemoryEntry, type MemoryScope, MemoryStore, type MemoryStoreOptions, type MemoryToolsOptions, type MemoryType, type WriteInput as MemoryWriteInput, NeedsConfirmationError, PROJECT_MEMORY_FILE, PROJECT_MEMORY_MAX_CHARS, type PageContent, type PickerCandidate, PlanCheckpointError, PlanProposedError, PlanRevisionProposedError, type PlanStep, type PlanStepRisk, type PlanToolOptions, type ProgressNotificationParams, type ProjectMemory, type RankPickerOptions, type ReadResourceResult, type ReadTranscriptResult, type ReasonixConfig, type ReconfigurableOptions, type RepairReport, type ReplayStats, type ResolvedHook, type RetryInfo, type RetryOptions, type Role, type RunCommandResult, type RunHooksOptions, type ScavengeOptions, type ScavengeResult, type SearchResult, type SectionResult, type SessionInfo, SessionStats, type SessionSummary, type ShellToolsOptions, type SseMcpSpec, SseTransport, type SseTransportOptions, type StdioMcpSpec, StdioTransport, type StdioTransportOptions, type StepCompletion, StormBreaker, type StreamChunk, type StreamableHttpMcpSpec, StreamableHttpTransport, type StreamableHttpTransportOptions, type SubagentEvent, type SubagentSink, type SubagentToolOptions, type ToolCall, type ToolCallContext, ToolCallRepair, type ToolCallRepairOptions, type ToolDefinition, type ToolFunctionSpec, ToolRegistry, type ToolSpec, type TranscriptMeta, type TranscriptRecord, type TruncationRepairResult, type TurnPair, type TurnStats, type TypedPlanState, USER_MEMORY_DIR, Usage, type UsageAggregate, type UsageBucket, type UsageRecord, VERSION, VolatileScratch, type WebFetchOptions, type WebSearchOptions, type WebToolsOptions, aggregateBranchUsage, aggregateUsage, analyzeSchema, appendSessionMessage, appendUsage, applyEditBlock, applyEditBlocks, applyMemoryStack, applyProjectMemory, applyUserMemory, bridgeMcpTools, bucketCacheHitRatio, bucketSavingsFraction, claudeEquivalentCost, codeSystemPrompt, compareVersions, computeReplayStats, costUsd, decideOutcome, defaultConfigPath, defaultSelector, defaultUsageLogPath, deleteSession, detectAtPicker, detectShellOperator, diffTranscripts, emptyPlanState, expandAtMentions, fetchWithRetry, fixToolCallPairing, flattenMcpResult, flattenSchema, forkRegistryExcluding, formatCommandResult, formatHookOutcomeMessage, formatLogSize, formatLoopError, formatSearchResults, getLatestVersion, globalSettingsPath, harvest, healLoadedMessages, healLoadedMessagesByTokens, htmlToText, injectPowerShellUtf8, inputCostUsd, inspectMcpServer, isAllowed, isJsonRpcError, isNpxInstall, isPlanStateEmpty, isPlausibleKey, listFilesSync, listFilesWithStatsAsync, listFilesWithStatsSync, listSessions, loadApiKey, loadDotenv, loadHooks, loadSessionMessages, matchesTool, memoryEnabled, nestArguments, openTranscriptFile, outputCostUsd, parseEditBlocks, parseMcpSpec, parseMojeekResults, parseTranscript, prepareSpawn, projectHash, projectSettingsPath, quoteForCmdExe, rankPickerCandidates, readConfig, readProjectMemory, readTranscript, readUsageLog, recordFromLoopEvent, redactKey, registerChoiceTool, registerFilesystemTools, registerMemoryTools, registerPlanTool, registerShellTools, registerSubagentTool, registerWebTools, renderMarkdown as renderDiffMarkdown, renderSummaryTable as renderDiffSummary, repairTruncatedJson, replayFromFile, resolveExecutable, restoreSnapshots, runBranches, runCommand, runHooks, sanitizeMemoryName, sanitizeName as sanitizeSessionName, saveApiKey, scavengeToolCalls, sessionPath, sessionsDir, similarity, snapshotBeforeEdits, stripHallucinatedToolMarkup, tokenizeCommand, truncateForModel, truncateForModelByTokens, webFetch, webSearch, withUtf8Codepage, writeConfig, writeMeta, writeRecord };