reasonix 0.4.28 → 0.5.2

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
@@ -138,6 +138,21 @@ interface UserBalance {
138
138
  is_available: boolean;
139
139
  balance_infos: BalanceInfo[];
140
140
  }
141
+ /**
142
+ * Response shape for DeepSeek's `/models` endpoint. Mirrors the OpenAI
143
+ * models list shape DeepSeek copied — `id` is the model name to pass to
144
+ * `/chat/completions`, `owned_by` is the provider string (always
145
+ * `"deepseek"` today).
146
+ */
147
+ interface ModelInfo {
148
+ id: string;
149
+ object: "model";
150
+ owned_by: string;
151
+ }
152
+ interface ModelList {
153
+ object: "list";
154
+ data: ModelInfo[];
155
+ }
141
156
  interface DeepSeekClientOptions {
142
157
  apiKey?: string;
143
158
  baseUrl?: string;
@@ -163,6 +178,16 @@ declare class DeepSeekClient {
163
178
  getBalance(opts?: {
164
179
  signal?: AbortSignal;
165
180
  }): Promise<UserBalance | null>;
181
+ /**
182
+ * Fetch the model catalog DeepSeek currently exposes. Today this is
183
+ * `deepseek-chat` (V3) and `deepseek-reasoner` (R1), but querying is
184
+ * the only way to learn about new ones without a Reasonix release.
185
+ * Returns null on any network/auth failure so callers can degrade
186
+ * gracefully — e.g. `/models` falls back to the hardcoded hint.
187
+ */
188
+ listModels(opts?: {
189
+ signal?: AbortSignal;
190
+ }): Promise<ModelList | null>;
166
191
  chat(opts: ChatRequestOptions): Promise<ChatResponse>;
167
192
  stream(opts: ChatRequestOptions): AsyncGenerator<StreamChunk>;
168
193
  }
@@ -708,6 +733,8 @@ declare class ToolRegistry {
708
733
  specs(): ToolSpec[];
709
734
  dispatch(name: string, argumentsRaw: string | Record<string, unknown>, opts?: {
710
735
  signal?: AbortSignal;
736
+ maxResultChars?: number;
737
+ maxResultTokens?: number;
711
738
  }): Promise<string>;
712
739
  }
713
740
 
@@ -1436,6 +1463,27 @@ interface ShellToolsOptions {
1436
1463
  * via concatenation. Exported for testing.
1437
1464
  */
1438
1465
  declare function tokenizeCommand(cmd: string): string[];
1466
+ /**
1467
+ * Scan `cmd` for a shell operator (`|`, `||`, `>`, `>>`, `<`, `<<`,
1468
+ * `&`, `&&`, `2>`, `2>>`, `2>&1`, `&>`) that appears unquoted at a
1469
+ * token boundary. Returns the operator string, or null if none.
1470
+ *
1471
+ * Why this exists: `run_command` documents "no shell expansion, no
1472
+ * pipes, no redirects" (the tool spawns argv directly, not through a
1473
+ * shell), but when the model writes `dir | findstr foo` the `|`
1474
+ * survives tokenization as a standalone token and gets quoted as the
1475
+ * literal string `"|"` by `quoteForCmdExe` — cmd.exe sees it as an
1476
+ * argument, not an operator, so the pipe silently fails. Detecting
1477
+ * operators up front lets us throw a clear error ("split into separate
1478
+ * calls") instead of letting the command run with surprising results.
1479
+ *
1480
+ * Quoted operators (`grep "a|b"`) and operator characters embedded in
1481
+ * larger tokens (`--flag=1&2`) are NOT flagged — those are literal
1482
+ * argv bytes and are safe to pass through.
1483
+ *
1484
+ * Exported for testing.
1485
+ */
1486
+ declare function detectShellOperator(cmd: string): string | null;
1439
1487
  /**
1440
1488
  * Return true when `cmd` matches an allowlisted prefix. Exported for
1441
1489
  * testing. Match is on the space-normalized leading tokens so
@@ -2360,6 +2408,17 @@ interface BridgeOptions {
2360
2408
  * that most file reads and directory listings fit un-truncated.
2361
2409
  */
2362
2410
  declare const DEFAULT_MAX_RESULT_CHARS = 32000;
2411
+ /**
2412
+ * Token-aware cap for tool results, in DeepSeek V3 tokens.
2413
+ *
2414
+ * 8,000 tokens ≈ 6% of DeepSeek V3's 131K context. One oversized tool
2415
+ * result can't eat more than that no matter what character density the
2416
+ * content has. The char cap (32K chars) only bounds tokens for English
2417
+ * — CJK text at 1 char/token blows past 16K tokens under the same
2418
+ * ceiling. With the tokenizer shipped in 0.5.0 we can cap the thing
2419
+ * that actually matters.
2420
+ */
2421
+ declare const DEFAULT_MAX_RESULT_TOKENS = 8000;
2363
2422
  interface BridgeResult {
2364
2423
  registry: ToolRegistry;
2365
2424
  /** Names actually registered (may differ from MCP names when a prefix is applied). */
@@ -2404,6 +2463,22 @@ declare function flattenMcpResult(result: CallToolResult, opts?: FlattenOptions)
2404
2463
  * tests and reuse by non-MCP tool adapters that want the same policy.
2405
2464
  */
2406
2465
  declare function truncateForModel(s: string, maxChars: number): string;
2466
+ /**
2467
+ * Token-aware truncation. Same head+tail policy as `truncateForModel`,
2468
+ * but sizes the slices against a DeepSeek V3 token budget instead of a
2469
+ * raw character count — so CJK text (which previously survived at 2×
2470
+ * the token cost per char) gets capped at the same effective context
2471
+ * footprint as English.
2472
+ *
2473
+ * Strategy: fast path when `s.length <= maxTokens` (every token is ≥1
2474
+ * char, so this bounds tokens ≤ maxTokens — skip tokenize entirely).
2475
+ * Short-ish strings are confirmed against the real token count.
2476
+ * Long strings go straight to char-sliced head+tail with one or two
2477
+ * tokenize-verify-and-shrink rounds per slice — we deliberately never
2478
+ * tokenize the full input, because pathological repetitive text
2479
+ * (megabytes of `AAAA…`) can cost 30s+ on the pure-TS BPE port.
2480
+ */
2481
+ declare function truncateForModelByTokens(s: string, maxTokens: number): string;
2407
2482
 
2408
2483
  /**
2409
2484
  * Parse the `--mcp` CLI argument into a transport-tagged spec.
@@ -2861,4 +2936,4 @@ declare function aggregateUsage(records: UsageRecord[], opts?: AggregateOptions)
2861
2936
  /** File-size helper for the stats header — "1.2 MB" etc. Returns "" if missing. */
2862
2937
  declare function formatLogSize(path?: string): string;
2863
2938
 
2864
- 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 };
2939
+ 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 };