reasonix 0.0.4 → 0.0.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
@@ -172,6 +172,58 @@ declare function emptyPlanState(): TypedPlanState;
172
172
  declare function isPlanStateEmpty(s: TypedPlanState | null | undefined): boolean;
173
173
  declare function harvest(reasoningContent: string | null | undefined, client?: DeepSeekClient, options?: HarvestOptions): Promise<TypedPlanState>;
174
174
 
175
+ /**
176
+ * Self-consistency branching.
177
+ *
178
+ * When enabled, the loop fans out into N parallel samples per turn (varied
179
+ * temperatures), runs Pillar 2 harvest on each, and selects the sample with
180
+ * the fewest flagged uncertainties (ties broken by answer length — a crude
181
+ * Occam prior).
182
+ *
183
+ * The unique opportunity here: because DeepSeek is ~20× cheaper than Claude,
184
+ * running N=3–5 samples per turn is still cheaper than a single Claude call,
185
+ * while the majority-confidence selection tends to dominate single-sample
186
+ * answers on fuzzy multi-step reasoning tasks.
187
+ */
188
+
189
+ interface BranchSample {
190
+ index: number;
191
+ temperature: number;
192
+ response: ChatResponse;
193
+ planState: TypedPlanState;
194
+ }
195
+ type BranchSelector = (samples: BranchSample[]) => BranchSample;
196
+ interface BranchOptions {
197
+ /** Number of parallel samples. 1 disables branching. Default 1. */
198
+ budget?: number;
199
+ /** Temperatures for each branch. Default spreads across [0, 1]. */
200
+ temperatures?: readonly number[];
201
+ /** Harvest options; the selector needs harvest to score samples. */
202
+ harvestOptions?: HarvestOptions;
203
+ /** Custom selector. Default: min uncertainties, tie-break shortest answer. */
204
+ selector?: BranchSelector;
205
+ /**
206
+ * Fires as each sample finishes (main call + harvest both complete).
207
+ * Useful for progress UI. Not awaited; exceptions are swallowed.
208
+ */
209
+ onSampleDone?: (sample: BranchSample) => void;
210
+ }
211
+ interface BranchResult {
212
+ chosen: BranchSample;
213
+ samples: BranchSample[];
214
+ }
215
+ /** Default: fewest uncertainties wins, ties broken by shorter answer content. */
216
+ declare const defaultSelector: BranchSelector;
217
+ declare function runBranches(client: DeepSeekClient, request: ChatRequestOptions, opts?: BranchOptions): Promise<BranchResult>;
218
+ /** Sum usage across branch samples for telemetry purposes. */
219
+ declare function aggregateBranchUsage(samples: readonly BranchSample[]): {
220
+ promptTokens: number;
221
+ completionTokens: number;
222
+ totalTokens: number;
223
+ promptCacheHitTokens: number;
224
+ promptCacheMissTokens: number;
225
+ };
226
+
175
227
  interface ImmutablePrefixOptions {
176
228
  system: string;
177
229
  toolSpecs?: readonly ToolSpec[];
@@ -364,7 +416,20 @@ declare class ToolRegistry {
364
416
  dispatch(name: string, argumentsRaw: string | Record<string, unknown>): Promise<string>;
365
417
  }
366
418
 
367
- type EventRole = "assistant_delta" | "assistant_final" | "tool" | "done" | "error";
419
+ type EventRole = "assistant_delta" | "assistant_final" | "tool" | "done" | "error" | "branch_start" | "branch_progress" | "branch_done";
420
+ interface BranchSummary {
421
+ budget: number;
422
+ chosenIndex: number;
423
+ uncertainties: number[];
424
+ temperatures: number[];
425
+ }
426
+ interface BranchProgress {
427
+ completed: number;
428
+ total: number;
429
+ latestIndex: number;
430
+ latestTemperature: number;
431
+ latestUncertainties: number;
432
+ }
368
433
  interface LoopEvent {
369
434
  turn: number;
370
435
  role: EventRole;
@@ -374,6 +439,8 @@ interface LoopEvent {
374
439
  stats?: TurnStats;
375
440
  planState?: TypedPlanState;
376
441
  repair?: RepairReport;
442
+ branch?: BranchSummary;
443
+ branchProgress?: BranchProgress;
377
444
  error?: string;
378
445
  }
379
446
  interface CacheFirstLoopOptions {
@@ -389,6 +456,19 @@ interface CacheFirstLoopOptions {
389
456
  * cheap but non-zero V3 call per turn).
390
457
  */
391
458
  harvest?: boolean | HarvestOptions;
459
+ /**
460
+ * Self-consistency branching. Pass a number for just a budget (e.g. 3) or
461
+ * a full `BranchOptions` object. Disables streaming for the branched turn
462
+ * because all samples must complete before selection. Auto-enables harvest
463
+ * since the default selector scores samples by plan-state uncertainty.
464
+ */
465
+ branch?: number | BranchOptions;
466
+ /**
467
+ * Session name. When set, the loop pre-loads the session's prior messages
468
+ * into its log on construction, and appends every new log entry to
469
+ * `~/.reasonix/sessions/<name>.jsonl` so the next run can resume.
470
+ */
471
+ session?: string;
392
472
  }
393
473
  /**
394
474
  * Pillar 1 — Cache-First Loop.
@@ -399,27 +479,79 @@ interface CacheFirstLoopOptions {
399
479
  *
400
480
  * Yields a stream of events so a TUI can render progressively.
401
481
  */
482
+ interface ReconfigurableOptions {
483
+ model?: string;
484
+ harvest?: boolean | HarvestOptions;
485
+ branch?: number | BranchOptions;
486
+ stream?: boolean;
487
+ }
402
488
  declare class CacheFirstLoop {
403
489
  readonly client: DeepSeekClient;
404
490
  readonly prefix: ImmutablePrefix;
405
491
  readonly tools: ToolRegistry;
406
- readonly model: string;
407
492
  readonly maxToolIters: number;
408
- readonly stream: boolean;
409
- readonly harvestEnabled: boolean;
410
- readonly harvestOptions: HarvestOptions;
411
493
  readonly log: AppendOnlyLog;
412
494
  readonly scratch: VolatileScratch;
413
495
  readonly stats: SessionStats;
414
496
  readonly repair: ToolCallRepair;
497
+ model: string;
498
+ stream: boolean;
499
+ harvestEnabled: boolean;
500
+ harvestOptions: HarvestOptions;
501
+ branchEnabled: boolean;
502
+ branchOptions: BranchOptions;
503
+ sessionName: string | null;
504
+ /** Number of messages that were pre-loaded from the session file. */
505
+ readonly resumedMessageCount: number;
415
506
  private _turn;
507
+ private _streamPreference;
416
508
  constructor(opts: CacheFirstLoopOptions);
509
+ private appendAndPersist;
510
+ /**
511
+ * Reconfigure model/harvest/branch/stream mid-session. The loop's log,
512
+ * scratch, and stats are preserved — only the per-turn behavior changes.
513
+ * Used by the TUI's slash commands and by library callers who want to
514
+ * flip a knob between turns.
515
+ */
516
+ configure(opts: ReconfigurableOptions): void;
417
517
  private buildMessages;
418
518
  step(userInput: string): AsyncGenerator<LoopEvent>;
419
519
  run(userInput: string, onEvent?: (ev: LoopEvent) => void): Promise<string>;
420
520
  private assistantMessage;
421
521
  }
422
522
 
523
+ /**
524
+ * Session persistence.
525
+ *
526
+ * Every turn's log entries (user / assistant / tool messages) are appended to
527
+ * a JSONL file under `~/.reasonix/sessions/<name>.jsonl`. Next time the user
528
+ * starts the CLI with the same session name, the loop pre-loads the file
529
+ * into its AppendOnlyLog so the new turn has full prior context.
530
+ *
531
+ * Design notes:
532
+ * - JSONL rather than JSON so concurrent writes don't corrupt.
533
+ * - 0600 permissions on Unix (chmod no-ops on Windows).
534
+ * - Name sanitization keeps paths safe: only [\w-] and CJK letters pass;
535
+ * anything else is replaced with underscore, max 64 chars.
536
+ * - The loop's stats/session aren't persisted — only the message log.
537
+ * Cost accounting resets each run (by design — old costs are sunk).
538
+ */
539
+
540
+ interface SessionInfo {
541
+ name: string;
542
+ path: string;
543
+ size: number;
544
+ messageCount: number;
545
+ mtime: Date;
546
+ }
547
+ declare function sessionsDir(): string;
548
+ declare function sessionPath(name: string): string;
549
+ declare function sanitizeName(name: string): string;
550
+ declare function loadSessionMessages(name: string): ChatMessage[];
551
+ declare function appendSessionMessage(name: string, message: ChatMessage): void;
552
+ declare function listSessions(): SessionInfo[];
553
+ declare function deleteSession(name: string): boolean;
554
+
423
555
  /**
424
556
  * Minimal `.env` loader; no dependency on dotenv.
425
557
  *
@@ -458,4 +590,4 @@ declare function redactKey(key: string): string;
458
590
 
459
591
  declare const VERSION = "0.0.1";
460
592
 
461
- export { AppendOnlyLog, CacheFirstLoop, type CacheFirstLoopOptions, type ChatMessage, type ChatResponse, DeepSeekClient, type DeepSeekClientOptions, type EventRole, type FlattenDecision, type HarvestOptions, ImmutablePrefix, type ImmutablePrefixOptions, type JSONSchema, type LoopEvent, type ReasonixConfig, type RepairReport, type RetryInfo, type RetryOptions, type Role, type ScavengeOptions, type ScavengeResult, SessionStats, type SessionSummary, StormBreaker, type StreamChunk, type ToolCall, ToolCallRepair, type ToolCallRepairOptions, type ToolDefinition, type ToolFunctionSpec, ToolRegistry, type ToolSpec, type TruncationRepairResult, type TurnStats, type TypedPlanState, Usage, VERSION, VolatileScratch, analyzeSchema, claudeEquivalentCost, costUsd, defaultConfigPath, emptyPlanState, fetchWithRetry, flattenSchema, harvest, isPlanStateEmpty, isPlausibleKey, loadApiKey, loadDotenv, nestArguments, readConfig, redactKey, repairTruncatedJson, saveApiKey, scavengeToolCalls, writeConfig };
593
+ export { AppendOnlyLog, type BranchOptions, type BranchProgress, type BranchResult, type BranchSample, type BranchSelector, type BranchSummary, CacheFirstLoop, type CacheFirstLoopOptions, type ChatMessage, type ChatResponse, DeepSeekClient, type DeepSeekClientOptions, type EventRole, type FlattenDecision, type HarvestOptions, ImmutablePrefix, type ImmutablePrefixOptions, type JSONSchema, type LoopEvent, type ReasonixConfig, type ReconfigurableOptions, type RepairReport, type RetryInfo, type RetryOptions, type Role, type ScavengeOptions, type ScavengeResult, type SessionInfo, SessionStats, type SessionSummary, StormBreaker, type StreamChunk, type ToolCall, ToolCallRepair, type ToolCallRepairOptions, type ToolDefinition, type ToolFunctionSpec, ToolRegistry, type ToolSpec, type TruncationRepairResult, type TurnStats, type TypedPlanState, Usage, VERSION, VolatileScratch, aggregateBranchUsage, analyzeSchema, appendSessionMessage, claudeEquivalentCost, costUsd, defaultConfigPath, defaultSelector, deleteSession, emptyPlanState, fetchWithRetry, flattenSchema, harvest, isPlanStateEmpty, isPlausibleKey, listSessions, loadApiKey, loadDotenv, loadSessionMessages, nestArguments, readConfig, redactKey, repairTruncatedJson, runBranches, sanitizeName as sanitizeSessionName, saveApiKey, scavengeToolCalls, sessionPath, sessionsDir, writeConfig };