reasonix 0.4.22 → 0.4.23

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
@@ -253,6 +253,189 @@ declare function aggregateBranchUsage(samples: readonly BranchSample[]): {
253
253
  promptCacheMissTokens: number;
254
254
  };
255
255
 
256
+ /**
257
+ * Hooks — user-defined automation that fires at well-known points in
258
+ * the agent loop. Mirrors the two-scope layout we use for memory and
259
+ * skills:
260
+ *
261
+ * - `<project>/.reasonix/settings.json` — committable per-project
262
+ * - `~/.reasonix/settings.json` — every session
263
+ *
264
+ * A hook is a shell command. We invoke it with stdin = a JSON
265
+ * payload describing the event, and interpret the exit code:
266
+ *
267
+ * - `0` — pass; loop continues normally
268
+ * - `2` — block; for `PreToolUse` / `UserPromptSubmit` the
269
+ * loop refuses to continue with that step and surfaces the
270
+ * hook's stderr as the reason. For `PostToolUse` / `Stop` block
271
+ * is meaningless (the action already happened) — treat as warn.
272
+ * - anything else — warn; loop continues but stderr is rendered
273
+ * to the user as an inline notice.
274
+ *
275
+ * stdin JSON shape (one envelope per event):
276
+ *
277
+ * {
278
+ * "event": "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop",
279
+ * "cwd": "<absolute project root or process.cwd()>",
280
+ * "toolName": "<string>", // tool events only
281
+ * "toolArgs": <unknown>, // tool events only — already JSON-decoded
282
+ * "toolResult": "<string>", // PostToolUse only — same body the model sees
283
+ * "prompt": "<string>", // UserPromptSubmit only
284
+ * "lastAssistantText": "<string>", // Stop only
285
+ * "turn": <number>, // Stop only
286
+ * }
287
+ *
288
+ * Hooks are executed in order: project scope first, then global.
289
+ * `Pre*` events stop dispatching at the first block; non-block
290
+ * outcomes accumulate into a single report so the UI can render
291
+ * each warning inline.
292
+ */
293
+ type HookEvent = "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop";
294
+ /** All four events as a const array — drives slash listing + validation. */
295
+ declare const HOOK_EVENTS: readonly HookEvent[];
296
+ type HookScope = "project" | "global";
297
+ interface HookConfig {
298
+ /**
299
+ * Tool-name pattern (PreToolUse / PostToolUse only). Anchored regex.
300
+ * Omitted or `"*"` matches every tool. Ignored for prompt / Stop
301
+ * events (they have no tool name to match against).
302
+ */
303
+ match?: string;
304
+ /** Shell command to run. Spawned through the platform shell. */
305
+ command: string;
306
+ /** Optional human description — surfaced in `/hooks`. */
307
+ description?: string;
308
+ /** Per-hook timeout override in ms. */
309
+ timeout?: number;
310
+ /**
311
+ * Working directory for the spawned process. Defaults to:
312
+ * - project scope → the project root
313
+ * - global scope → process.cwd()
314
+ */
315
+ cwd?: string;
316
+ }
317
+ /** Shape of `<scope>/.reasonix/settings.json` — only `hooks` for now. */
318
+ interface HookSettings {
319
+ hooks?: Partial<Record<HookEvent, HookConfig[]>>;
320
+ }
321
+ /** A loaded hook with its origin scope baked in (used for ordering and `/hooks`). */
322
+ interface ResolvedHook extends HookConfig {
323
+ event: HookEvent;
324
+ scope: HookScope;
325
+ /** Absolute path to the settings.json the hook came from. */
326
+ source: string;
327
+ }
328
+ /** Outcome of a single hook invocation. */
329
+ interface HookOutcome {
330
+ /** Which hook fired. */
331
+ hook: ResolvedHook;
332
+ /**
333
+ * Decision:
334
+ * - `pass` — exit 0
335
+ * - `block` — exit 2 on a blocking event (otherwise downgraded to `warn`)
336
+ * - `warn` — non-zero exit that is not a successful block
337
+ * - `timeout` — the spawn was killed past `timeout`
338
+ * - `error` — could not spawn at all (missing command, etc.)
339
+ */
340
+ decision: "pass" | "block" | "warn" | "timeout" | "error";
341
+ exitCode: number | null;
342
+ /** Captured stdout (trimmed). May be empty. */
343
+ stdout: string;
344
+ /** Captured stderr (trimmed). The block / warn message comes from here. */
345
+ stderr: string;
346
+ durationMs: number;
347
+ }
348
+ /** Aggregate report for `runHooks`. */
349
+ interface HookReport {
350
+ event: HookEvent;
351
+ outcomes: HookOutcome[];
352
+ /** True iff at least one outcome was a `block` — only meaningful for blocking events. */
353
+ blocked: boolean;
354
+ }
355
+ declare const HOOK_SETTINGS_FILENAME = "settings.json";
356
+ declare const HOOK_SETTINGS_DIRNAME = ".reasonix";
357
+ /** Where the global settings.json lives. Equivalent to `~/.reasonix/settings.json`. */
358
+ declare function globalSettingsPath(homeDirOverride?: string): string;
359
+ /** Where the project settings.json lives for a given root. */
360
+ declare function projectSettingsPath(projectRoot: string): string;
361
+ /**
362
+ * Pull every configured hook out of the project + global settings
363
+ * files, in the order they should fire (project first, global second,
364
+ * within each scope: array order from the file).
365
+ *
366
+ * Returns a flat list — the dispatcher filters by event + match
367
+ * pattern at run time. Loading is cheap (one or two JSON files), so
368
+ * we don't memoize across processes; re-load is allowed via
369
+ * `/hooks reload` and on every fresh App mount.
370
+ */
371
+ interface LoadHookSettingsOptions {
372
+ /** Absolute project root, if any. Without it, only global hooks load. */
373
+ projectRoot?: string;
374
+ /** Override `~` for tests. */
375
+ homeDir?: string;
376
+ }
377
+ declare function loadHooks(opts?: LoadHookSettingsOptions): ResolvedHook[];
378
+ /**
379
+ * True if `toolName` matches the hook's `match` field. `"*"` and
380
+ * undefined match everything. Otherwise we anchor the field as a
381
+ * regex — partial-name matches don't fire, so `"file"` would not
382
+ * trigger on `read_file` (use `".*file"` for that).
383
+ */
384
+ declare function matchesTool(hook: ResolvedHook, toolName: string): boolean;
385
+ /** Payload envelope passed to hook stdin. */
386
+ interface HookPayload {
387
+ event: HookEvent;
388
+ cwd: string;
389
+ toolName?: string;
390
+ toolArgs?: unknown;
391
+ toolResult?: string;
392
+ prompt?: string;
393
+ lastAssistantText?: string;
394
+ turn?: number;
395
+ }
396
+ /** Test seam — same shape as Node's spawn but returns a Promise of the raw outcome bits. */
397
+ interface HookSpawnInput {
398
+ command: string;
399
+ cwd: string;
400
+ stdin: string;
401
+ timeoutMs: number;
402
+ }
403
+ interface HookSpawnResult {
404
+ exitCode: number | null;
405
+ stdout: string;
406
+ stderr: string;
407
+ timedOut: boolean;
408
+ /** True iff spawn() itself failed (ENOENT, EACCES, …). */
409
+ spawnError?: Error;
410
+ }
411
+ type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;
412
+ /**
413
+ * Format a hook outcome as a single-line UI string. Used by both the
414
+ * loop (for `warning` events) and the App (for UserPromptSubmit /
415
+ * Stop outcomes). Centralizing keeps the language consistent across
416
+ * scopes.
417
+ */
418
+ declare function formatHookOutcomeMessage(outcome: HookOutcome): string;
419
+ /**
420
+ * Decide the hook's outcome decision from raw spawn results.
421
+ * Pulled out as a pure function so tests can pin the matrix.
422
+ */
423
+ declare function decideOutcome(event: HookEvent, raw: HookSpawnResult): "pass" | "block" | "warn" | "timeout" | "error";
424
+ interface RunHooksOptions {
425
+ payload: HookPayload;
426
+ hooks: ResolvedHook[];
427
+ /** Test seam — defaults to a real `spawn`. */
428
+ spawner?: HookSpawner;
429
+ }
430
+ /**
431
+ * Filter hooks down to the ones that match `payload.event` (and
432
+ * `payload.toolName`, for tool events), then run them in order.
433
+ * Stops at the first `block` outcome on a blocking event so a
434
+ * gating hook can prevent later hooks from incorrectly seeing a
435
+ * success that wasn't going to happen.
436
+ */
437
+ declare function runHooks(opts: RunHooksOptions): Promise<HookReport>;
438
+
256
439
  interface ImmutablePrefixOptions {
257
440
  system: string;
258
441
  toolSpecs?: readonly ToolSpec[];
@@ -623,6 +806,21 @@ interface CacheFirstLoopOptions {
623
806
  * `~/.reasonix/sessions/<name>.jsonl` so the next run can resume.
624
807
  */
625
808
  session?: string;
809
+ /**
810
+ * Resolved hook list — loaded from `<project>/.reasonix/settings.json`
811
+ * + `~/.reasonix/settings.json` by the CLI before constructing the loop.
812
+ * The loop dispatches `PreToolUse` and `PostToolUse` events itself; the
813
+ * CLI handles `UserPromptSubmit` and `Stop` since they live at the App
814
+ * boundary. Empty / unset → no hooks fire (the runtime cost of an empty
815
+ * filter is one ms). See `src/hooks.ts` for the full contract.
816
+ */
817
+ hooks?: ResolvedHook[];
818
+ /**
819
+ * `cwd` reported to hooks via the stdin payload. Defaults to `process.cwd()`.
820
+ * `reasonix code` overrides this to the sandbox root so a hook that does
821
+ * `cd $REASONIX_CWD` lands in the project, not in the user's shell home.
822
+ */
823
+ hookCwd?: string;
626
824
  }
627
825
  /**
628
826
  * Pillar 1 — Cache-First Loop.
@@ -655,6 +853,14 @@ declare class CacheFirstLoop {
655
853
  branchEnabled: boolean;
656
854
  branchOptions: BranchOptions;
657
855
  sessionName: string | null;
856
+ /**
857
+ * Hook list, mutable so `/hooks reload` can swap it without
858
+ * reconstructing the loop. Default empty — the filter cost on a
859
+ * tool call is one array length check.
860
+ */
861
+ hooks: ResolvedHook[];
862
+ /** `cwd` reported to hook stdin. Resolved once at construction. */
863
+ readonly hookCwd: string;
658
864
  /** Number of messages that were pre-loaded from the session file. */
659
865
  readonly resumedMessageCount: number;
660
866
  private _turn;
@@ -2389,4 +2595,4 @@ declare function compareVersions(a: string, b: string): number;
2389
2595
  */
2390
2596
  declare function isNpxInstall(): boolean;
2391
2597
 
2392
- export { AppendOnlyLog, 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, type HarvestOptions, 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 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 RetryInfo, type RetryOptions, type Role, type RunCommandResult, 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 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, VERSION, VolatileScratch, type WebFetchOptions, type WebSearchOptions, type WebToolsOptions, aggregateBranchUsage, analyzeSchema, appendSessionMessage, applyEditBlock, applyEditBlocks, applyMemoryStack, applyProjectMemory, applyUserMemory, bridgeMcpTools, claudeEquivalentCost, codeSystemPrompt, compareVersions, computeReplayStats, costUsd, defaultConfigPath, defaultSelector, deleteSession, diffTranscripts, emptyPlanState, fetchWithRetry, flattenMcpResult, flattenSchema, formatCommandResult, formatLoopError, formatSearchResults, getLatestVersion, harvest, healLoadedMessages, htmlToText, inputCostUsd, inspectMcpServer, isAllowed, isJsonRpcError, isNpxInstall, isPlanStateEmpty, isPlausibleKey, listSessions, loadApiKey, loadDotenv, loadSessionMessages, memoryEnabled, nestArguments, openTranscriptFile, outputCostUsd, parseEditBlocks, parseMcpSpec, parseMojeekResults, parseTranscript, prepareSpawn, projectHash, quoteForCmdExe, readConfig, readProjectMemory, readTranscript, recordFromLoopEvent, redactKey, registerFilesystemTools, registerMemoryTools, registerPlanTool, registerShellTools, registerWebTools, renderMarkdown as renderDiffMarkdown, renderSummaryTable as renderDiffSummary, repairTruncatedJson, replayFromFile, resolveExecutable, restoreSnapshots, runBranches, runCommand, sanitizeMemoryName, sanitizeName as sanitizeSessionName, saveApiKey, scavengeToolCalls, sessionPath, sessionsDir, similarity, snapshotBeforeEdits, stripHallucinatedToolMarkup, tokenizeCommand, truncateForModel, webFetch, webSearch, writeConfig, writeMeta, writeRecord };
2598
+ export { AppendOnlyLog, 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 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, VERSION, VolatileScratch, type WebFetchOptions, type WebSearchOptions, type WebToolsOptions, aggregateBranchUsage, analyzeSchema, appendSessionMessage, applyEditBlock, applyEditBlocks, applyMemoryStack, applyProjectMemory, applyUserMemory, bridgeMcpTools, claudeEquivalentCost, codeSystemPrompt, compareVersions, computeReplayStats, costUsd, decideOutcome, defaultConfigPath, defaultSelector, deleteSession, diffTranscripts, emptyPlanState, fetchWithRetry, flattenMcpResult, flattenSchema, formatCommandResult, formatHookOutcomeMessage, formatLoopError, formatSearchResults, getLatestVersion, globalSettingsPath, harvest, healLoadedMessages, htmlToText, 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, recordFromLoopEvent, redactKey, registerFilesystemTools, registerMemoryTools, registerPlanTool, registerShellTools, 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, writeConfig, writeMeta, writeRecord };