reasonix 0.5.0 → 0.5.3

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
@@ -734,6 +734,7 @@ declare class ToolRegistry {
734
734
  dispatch(name: string, argumentsRaw: string | Record<string, unknown>, opts?: {
735
735
  signal?: AbortSignal;
736
736
  maxResultChars?: number;
737
+ maxResultTokens?: number;
737
738
  }): Promise<string>;
738
739
  }
739
740
 
@@ -902,17 +903,23 @@ declare class CacheFirstLoop {
902
903
  constructor(opts: CacheFirstLoopOptions);
903
904
  /**
904
905
  * Shrink the log by re-truncating oversized tool results to a tighter
905
- * cap, and persist the result back to disk so the next launch doesn't
906
- * re-inherit a fat session file. Returns a summary the TUI can
907
- * display.
906
+ * token cap, and persist the result back to disk so the next launch
907
+ * doesn't re-inherit a fat session file. Returns a summary the TUI
908
+ * can display.
909
+ *
910
+ * The cap is in DeepSeek V3 tokens (not chars) — so CJK text gets
911
+ * capped at the same effective context footprint as English instead
912
+ * of slipping past a char cap at 2× the token cost. Default 4000
913
+ * tokens, matching the token-aware dispatch cap from 0.5.2.
908
914
  *
909
915
  * Only tool-role messages are touched (same rationale as
910
916
  * {@link healLoadedMessages}). User and assistant messages carry
911
917
  * authored intent we can't mechanically shrink without losing
912
918
  * meaning.
913
919
  */
914
- compact(tightCapChars?: number): {
920
+ compact(maxTokens?: number): {
915
921
  healedCount: number;
922
+ tokensSaved: number;
916
923
  charsSaved: number;
917
924
  };
918
925
  private appendAndPersist;
@@ -1462,6 +1469,27 @@ interface ShellToolsOptions {
1462
1469
  * via concatenation. Exported for testing.
1463
1470
  */
1464
1471
  declare function tokenizeCommand(cmd: string): string[];
1472
+ /**
1473
+ * Scan `cmd` for a shell operator (`|`, `||`, `>`, `>>`, `<`, `<<`,
1474
+ * `&`, `&&`, `2>`, `2>>`, `2>&1`, `&>`) that appears unquoted at a
1475
+ * token boundary. Returns the operator string, or null if none.
1476
+ *
1477
+ * Why this exists: `run_command` documents "no shell expansion, no
1478
+ * pipes, no redirects" (the tool spawns argv directly, not through a
1479
+ * shell), but when the model writes `dir | findstr foo` the `|`
1480
+ * survives tokenization as a standalone token and gets quoted as the
1481
+ * literal string `"|"` by `quoteForCmdExe` — cmd.exe sees it as an
1482
+ * argument, not an operator, so the pipe silently fails. Detecting
1483
+ * operators up front lets us throw a clear error ("split into separate
1484
+ * calls") instead of letting the command run with surprising results.
1485
+ *
1486
+ * Quoted operators (`grep "a|b"`) and operator characters embedded in
1487
+ * larger tokens (`--flag=1&2`) are NOT flagged — those are literal
1488
+ * argv bytes and are safe to pass through.
1489
+ *
1490
+ * Exported for testing.
1491
+ */
1492
+ declare function detectShellOperator(cmd: string): string | null;
1465
1493
  /**
1466
1494
  * Return true when `cmd` matches an allowlisted prefix. Exported for
1467
1495
  * testing. Match is on the space-normalized leading tokens so
@@ -2386,6 +2414,17 @@ interface BridgeOptions {
2386
2414
  * that most file reads and directory listings fit un-truncated.
2387
2415
  */
2388
2416
  declare const DEFAULT_MAX_RESULT_CHARS = 32000;
2417
+ /**
2418
+ * Token-aware cap for tool results, in DeepSeek V3 tokens.
2419
+ *
2420
+ * 8,000 tokens ≈ 6% of DeepSeek V3's 131K context. One oversized tool
2421
+ * result can't eat more than that no matter what character density the
2422
+ * content has. The char cap (32K chars) only bounds tokens for English
2423
+ * — CJK text at 1 char/token blows past 16K tokens under the same
2424
+ * ceiling. With the tokenizer shipped in 0.5.0 we can cap the thing
2425
+ * that actually matters.
2426
+ */
2427
+ declare const DEFAULT_MAX_RESULT_TOKENS = 8000;
2389
2428
  interface BridgeResult {
2390
2429
  registry: ToolRegistry;
2391
2430
  /** Names actually registered (may differ from MCP names when a prefix is applied). */
@@ -2430,6 +2469,22 @@ declare function flattenMcpResult(result: CallToolResult, opts?: FlattenOptions)
2430
2469
  * tests and reuse by non-MCP tool adapters that want the same policy.
2431
2470
  */
2432
2471
  declare function truncateForModel(s: string, maxChars: number): string;
2472
+ /**
2473
+ * Token-aware truncation. Same head+tail policy as `truncateForModel`,
2474
+ * but sizes the slices against a DeepSeek V3 token budget instead of a
2475
+ * raw character count — so CJK text (which previously survived at 2×
2476
+ * the token cost per char) gets capped at the same effective context
2477
+ * footprint as English.
2478
+ *
2479
+ * Strategy: fast path when `s.length <= maxTokens` (every token is ≥1
2480
+ * char, so this bounds tokens ≤ maxTokens — skip tokenize entirely).
2481
+ * Short-ish strings are confirmed against the real token count.
2482
+ * Long strings go straight to char-sliced head+tail with one or two
2483
+ * tokenize-verify-and-shrink rounds per slice — we deliberately never
2484
+ * tokenize the full input, because pathological repetitive text
2485
+ * (megabytes of `AAAA…`) can cost 30s+ on the pure-TS BPE port.
2486
+ */
2487
+ declare function truncateForModelByTokens(s: string, maxTokens: number): string;
2433
2488
 
2434
2489
  /**
2435
2490
  * Parse the `--mcp` CLI argument into a transport-tagged spec.
@@ -2887,4 +2942,4 @@ declare function aggregateUsage(records: UsageRecord[], opts?: AggregateOptions)
2887
2942
  /** File-size helper for the stats header — "1.2 MB" etc. Returns "" if missing. */
2888
2943
  declare function formatLogSize(path?: string): string;
2889
2944
 
2890
- 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, 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, 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, webFetch, webSearch, withUtf8Codepage, writeConfig, writeMeta, writeRecord };
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 };