reasonix 0.5.4 → 0.5.6

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
@@ -982,11 +982,47 @@ declare class CacheFirstLoop {
982
982
  * Exported so tests can exercise it against concrete R1 outputs.
983
983
  */
984
984
  declare function stripHallucinatedToolMarkup(s: string): string;
985
+ /**
986
+ * Enforce tool_calls ↔ tool pairing across a message log. DeepSeek
987
+ * rejects two shapes at the API boundary:
988
+ * (a) assistant with tool_calls not followed by matching tool
989
+ * responses ("insufficient tool messages following tool_calls")
990
+ * (b) tool message without a preceding assistant.tool_calls with
991
+ * the matching tool_call_id ("must be a response to a preceding
992
+ * message with 'tool_calls'")
993
+ *
994
+ * Corrupted session files from earlier builds have hit both. This pass
995
+ * rebuilds the message stream so only well-formed (assistant.tool_calls
996
+ * + all matching responses) groups survive. Plain user/assistant/system
997
+ * messages (no tool_calls) always pass through.
998
+ *
999
+ * Exported so both char-based and token-based heal can compose it.
1000
+ */
1001
+ declare function fixToolCallPairing(messages: ChatMessage[]): {
1002
+ messages: ChatMessage[];
1003
+ droppedAssistantCalls: number;
1004
+ droppedStrayTools: number;
1005
+ };
985
1006
  declare function healLoadedMessages(messages: ChatMessage[], maxChars: number): {
986
1007
  messages: ChatMessage[];
987
1008
  healedCount: number;
988
1009
  healedFrom: number;
989
1010
  };
1011
+ /**
1012
+ * Token-aware counterpart of {@link healLoadedMessages}. Used at
1013
+ * session-load time so resumed sessions come back capped at the same
1014
+ * token budget (not char budget) as live tool results — CJK text no
1015
+ * longer slips past at 2× the intended token cost when re-hydrated.
1016
+ *
1017
+ * Still does the same structural pass for tool_calls ↔ tool pairing;
1018
+ * that logic is orthogonal to the truncation cap.
1019
+ */
1020
+ declare function healLoadedMessagesByTokens(messages: ChatMessage[], maxTokens: number): {
1021
+ messages: ChatMessage[];
1022
+ healedCount: number;
1023
+ tokensSaved: number;
1024
+ charsSaved: number;
1025
+ };
990
1026
  /**
991
1027
  * Annotate the `DeepSeek 400: … maximum context length …` error the API
992
1028
  * returns when a session's history has grown past 131,072 tokens. The
@@ -997,6 +1033,76 @@ declare function healLoadedMessages(messages: ChatMessage[], maxChars: number):
997
1033
  */
998
1034
  declare function formatLoopError(err: Error): string;
999
1035
 
1036
+ /**
1037
+ * Expand `@path/to/file` mentions in a user prompt to inline file
1038
+ * content.
1039
+ *
1040
+ * Why: most interactive coding sessions start with "look at X, then
1041
+ * change Y". Typing `@src/loop.ts` reads faster and cheaper than
1042
+ * "look at src/loop.ts (and the model fires read_file, and we pay for
1043
+ * the round trip)" — the model sees the file content from turn 1
1044
+ * instead of round-tripping a tool call for it.
1045
+ *
1046
+ * Shape: the user's text is kept verbatim. Expanded file contents are
1047
+ * appended in a "Referenced files" block at the end, each wrapped in
1048
+ * `<file path="...">...</file>` so the model can cite them back
1049
+ * unambiguously.
1050
+ *
1051
+ * Safety: paths must resolve inside `rootDir` (no `..` escape, no
1052
+ * absolute paths), must exist as a regular file, and must be under
1053
+ * `maxBytes`. Missing / too-large / escaping paths get a short note
1054
+ * appended instead of content so the user sees why it was skipped.
1055
+ */
1056
+ /** Caps match tool-result dispatch truncation (0.5.2). */
1057
+ declare const DEFAULT_AT_MENTION_MAX_BYTES: number;
1058
+ /**
1059
+ * Matches `@` at a word boundary (start-of-string or preceded by
1060
+ * whitespace) followed by a path-like token. Deliberately rejects `@`
1061
+ * embedded in longer words (email addresses, mentions on social sites)
1062
+ * by requiring the word boundary.
1063
+ *
1064
+ * Path charset keeps it to the characters that appear in real repo
1065
+ * paths — letters, digits, `_` `-` `.` `/` `\`. Trailing `.` (e.g.
1066
+ * `@foo.ts.`) is stripped before lookup so a sentence-terminating
1067
+ * period doesn't break the mention.
1068
+ */
1069
+ declare const AT_MENTION_PATTERN: RegExp;
1070
+ interface AtMentionExpansion {
1071
+ /** The raw `@path` token as it appeared in the text. */
1072
+ token: string;
1073
+ /** The relative path, as resolved against rootDir. */
1074
+ path: string;
1075
+ /** True if the content was inlined. False = skipped (reason in `skip`). */
1076
+ ok: boolean;
1077
+ /** Bytes read (only for ok=true). */
1078
+ bytes?: number;
1079
+ /** Why the mention was skipped. Set when ok=false. */
1080
+ skip?: "missing" | "not-file" | "too-large" | "escape" | "read-error";
1081
+ }
1082
+ interface AtMentionOptions {
1083
+ /** Max file size in bytes before a mention is skipped. */
1084
+ maxBytes?: number;
1085
+ /**
1086
+ * Optional file-system overrides for tests. Real callers omit these;
1087
+ * the helper falls through to `node:fs`.
1088
+ */
1089
+ fs?: {
1090
+ exists: (path: string) => boolean;
1091
+ isFile: (path: string) => boolean;
1092
+ size: (path: string) => number;
1093
+ read: (path: string) => string;
1094
+ };
1095
+ }
1096
+ /**
1097
+ * Expand `@path` mentions in `text`. Returns the (possibly augmented)
1098
+ * text plus a per-mention report so the caller can surface expansions
1099
+ * in the UI.
1100
+ */
1101
+ declare function expandAtMentions(text: string, rootDir: string, opts?: AtMentionOptions): {
1102
+ text: string;
1103
+ expansions: AtMentionExpansion[];
1104
+ };
1105
+
1000
1106
  /**
1001
1107
  * Project memory — a user-authored `REASONIX.md` in the project root
1002
1108
  * that gets pinned into the immutable-prefix system prompt.
@@ -2942,4 +3048,4 @@ declare function aggregateUsage(records: UsageRecord[], opts?: AggregateOptions)
2942
3048
  /** File-size helper for the stats header — "1.2 MB" etc. Returns "" if missing. */
2943
3049
  declare function formatLogSize(path?: string): string;
2944
3050
 
2945
- export { type AggregateOptions, AppendOnlyLog, type AppendUsageInput, type ApplyResult, type ApplyStatus, 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, DEFAULT_MAX_RESULT_CHARS, DEFAULT_MAX_RESULT_TOKENS, DeepSeekClient, type DeepSeekClientOptions, type RenderOptions as DiffRenderOptions, type DiffReport, type DiffSide, type EditBlock, type EditSnapshot, type EventRole, 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 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, PlanProposedError, type PlanToolOptions, type ProgressNotificationParams, type ProjectMemory, 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, StormBreaker, type StreamChunk, 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, detectShellOperator, diffTranscripts, emptyPlanState, fetchWithRetry, flattenMcpResult, flattenSchema, forkRegistryExcluding, formatCommandResult, formatHookOutcomeMessage, formatLogSize, formatLoopError, formatSearchResults, getLatestVersion, globalSettingsPath, harvest, healLoadedMessages, htmlToText, injectPowerShellUtf8, inputCostUsd, inspectMcpServer, isAllowed, isJsonRpcError, isNpxInstall, isPlanStateEmpty, isPlausibleKey, listSessions, loadApiKey, loadDotenv, loadHooks, loadSessionMessages, matchesTool, memoryEnabled, nestArguments, openTranscriptFile, outputCostUsd, parseEditBlocks, parseMcpSpec, parseMojeekResults, parseTranscript, prepareSpawn, projectHash, projectSettingsPath, quoteForCmdExe, readConfig, readProjectMemory, readTranscript, readUsageLog, recordFromLoopEvent, redactKey, 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 };
3051
+ export { AT_MENTION_PATTERN, 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, DEFAULT_AT_MENTION_MAX_BYTES, DEFAULT_MAX_RESULT_CHARS, DEFAULT_MAX_RESULT_TOKENS, DeepSeekClient, type DeepSeekClientOptions, type RenderOptions as DiffRenderOptions, type DiffReport, type DiffSide, type EditBlock, type EditSnapshot, type EventRole, 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 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, PlanProposedError, type PlanToolOptions, type ProgressNotificationParams, type ProjectMemory, 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, StormBreaker, type StreamChunk, 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, 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, listSessions, loadApiKey, loadDotenv, loadHooks, loadSessionMessages, matchesTool, memoryEnabled, nestArguments, openTranscriptFile, outputCostUsd, parseEditBlocks, parseMcpSpec, parseMojeekResults, parseTranscript, prepareSpawn, projectHash, projectSettingsPath, quoteForCmdExe, readConfig, readProjectMemory, readTranscript, readUsageLog, recordFromLoopEvent, redactKey, 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 };