@denizokcu/haze 1.1.1 → 1.4.0

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.
Files changed (133) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +26 -15
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +27 -7
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/inputSuggestions.js +3 -0
  7. package/dist/cli/chat/liveMessages.d.ts +36 -0
  8. package/dist/cli/chat/liveMessages.js +64 -0
  9. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  10. package/dist/cli/chat/sessionLifecycle.js +25 -2
  11. package/dist/cli/chat/sessionRecorder.d.ts +7 -0
  12. package/dist/cli/chat/sessionRecorder.js +6 -0
  13. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  14. package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
  15. package/dist/cli/commands/chat.js +63 -36
  16. package/dist/cli/commands/commandHelp.js +2 -0
  17. package/dist/cli/commands/commands.js +2 -0
  18. package/dist/cli/commands/formatters.js +5 -1
  19. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  20. package/dist/cli/commands/ndjsonSink.js +29 -0
  21. package/dist/cli/commands/reasoningCommand.d.ts +35 -0
  22. package/dist/cli/commands/reasoningCommand.js +46 -0
  23. package/dist/cli/commands/runCommand.d.ts +14 -0
  24. package/dist/cli/commands/runCommand.js +43 -11
  25. package/dist/cli/commands/settingsSummary.js +2 -0
  26. package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
  27. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  28. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  29. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  30. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  31. package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
  32. package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
  33. package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
  34. package/dist/cli/commands/streaming/attemptSetup.js +40 -15
  35. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
  36. package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
  37. package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
  38. package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
  39. package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
  40. package/dist/cli/commands/streaming/prepareStep.js +43 -22
  41. package/dist/cli/commands/streaming/stallRecovery.js +2 -2
  42. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  43. package/dist/cli/commands/streaming/streamLoop.js +280 -44
  44. package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
  45. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  46. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  47. package/dist/cli/commands/streaming.d.ts +15 -2
  48. package/dist/cli/commands/streaming.js +37 -8
  49. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  50. package/dist/cli/commands/wizardFlow.js +22 -0
  51. package/dist/cli/index.js +8 -3
  52. package/dist/config/modelCatalog.d.ts +32 -0
  53. package/dist/config/modelCatalog.js +84 -0
  54. package/dist/config/modelDiscovery.js +68 -5
  55. package/dist/config/settings.d.ts +18 -6
  56. package/dist/config/settings.js +11 -1
  57. package/dist/core/agent/budgets.d.ts +10 -2
  58. package/dist/core/agent/budgets.js +10 -2
  59. package/dist/core/agent/compaction.d.ts +42 -3
  60. package/dist/core/agent/compaction.js +53 -5
  61. package/dist/core/agent/completionController.d.ts +11 -1
  62. package/dist/core/agent/completionController.js +33 -0
  63. package/dist/core/agent/contextBudget.d.ts +56 -0
  64. package/dist/core/agent/contextBudget.js +53 -0
  65. package/dist/core/agent/errors.js +2 -2
  66. package/dist/core/agent/events.d.ts +26 -2
  67. package/dist/core/agent/goalPolicy.d.ts +7 -0
  68. package/dist/core/agent/goalPolicy.js +9 -0
  69. package/dist/core/agent/overflow.d.ts +45 -0
  70. package/dist/core/agent/overflow.js +91 -0
  71. package/dist/core/agent/reasoningPolicy.d.ts +45 -9
  72. package/dist/core/agent/reasoningPolicy.js +49 -9
  73. package/dist/core/agent/requestAssembly.d.ts +7 -0
  74. package/dist/core/agent/requestAssembly.js +15 -7
  75. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  76. package/dist/core/agent/toolCapabilities.js +31 -7
  77. package/dist/core/agent/workState.d.ts +6 -4
  78. package/dist/core/agent/workState.js +53 -29
  79. package/dist/core/deadline.js +22 -24
  80. package/dist/core/safety/secretPaths.js +10 -7
  81. package/dist/core/safety/shellClassifier.d.ts +18 -0
  82. package/dist/core/safety/shellClassifier.js +39 -0
  83. package/dist/core/session/sessionSlimming.d.ts +2 -0
  84. package/dist/core/session/sessionSlimming.js +50 -1
  85. package/dist/core/session/sessionStore.d.ts +14 -8
  86. package/dist/core/session/sessionStore.js +59 -32
  87. package/dist/core/shellOutput/reducers/git.js +7 -2
  88. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  89. package/dist/core/shellOutput/reducers/validation.js +14 -1
  90. package/dist/core/shellOutput/registry.js +3 -2
  91. package/dist/core/subagent/contracts.d.ts +8 -1
  92. package/dist/core/subagent/subagentRunner.d.ts +4 -0
  93. package/dist/core/subagent/subagentRunner.js +33 -25
  94. package/dist/core/tasks/taskStorage.js +8 -1
  95. package/dist/core/validation/outputParser.d.ts +1 -1
  96. package/dist/core/validation/outputParser.js +30 -1
  97. package/dist/llm/client.d.ts +4 -3
  98. package/dist/llm/client.js +34 -16
  99. package/dist/llm/hazeTools.d.ts +2039 -16
  100. package/dist/llm/hazeTools.js +43 -2
  101. package/dist/llm/lsp/client.d.ts +7 -1
  102. package/dist/llm/lsp/client.js +58 -9
  103. package/dist/llm/lsp/pool.d.ts +11 -0
  104. package/dist/llm/lsp/pool.js +61 -4
  105. package/dist/llm/lsp/protocol.d.ts +6 -23
  106. package/dist/llm/lsp/requests.d.ts +54 -60
  107. package/dist/llm/lsp/requests.js +152 -28
  108. package/dist/llm/lsp/symbols.d.ts +16 -0
  109. package/dist/llm/lsp/symbols.js +70 -0
  110. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  111. package/dist/llm/lsp/workspaceEdit.js +117 -0
  112. package/dist/llm/lspTools.d.ts +7518 -2859
  113. package/dist/llm/lspTools.js +195 -110
  114. package/dist/llm/requestContext.d.ts +3 -2
  115. package/dist/llm/requestContext.js +8 -4
  116. package/dist/llm/systemPrompt.js +2 -2
  117. package/dist/llm/tools/fetchTool.d.ts +4 -0
  118. package/dist/llm/tools/processTool.d.ts +4 -0
  119. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  120. package/dist/llm/tools/replaceInFiles.js +131 -0
  121. package/dist/llm/tools/shellTool.d.ts +4 -0
  122. package/dist/llm/tools/shellTool.js +27 -8
  123. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  124. package/dist/llm/tools/taskTool.d.ts +4 -0
  125. package/dist/llm/tools/toolContext.d.ts +3 -0
  126. package/dist/llm/tools/toolContext.js +26 -4
  127. package/dist/skills/SkillLoader.js +27 -1
  128. package/dist/ui/components/TextInput.d.ts +18 -1
  129. package/dist/ui/components/TextInput.js +44 -6
  130. package/dist/ui/components/useInputSuggestions.js +18 -6
  131. package/dist/utils/buildInfo.js +29 -8
  132. package/dist/utils/fs.js +5 -1
  133. package/package.json +20 -19
package/CHANGELOG.md CHANGED
@@ -1,5 +1,83 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 1.4.0 - 2026-09-24
6
+
7
+ Reasoning effort becomes a first-class per-run control, plus follow-up fixes from the 1.3.0 review.
8
+
9
+ ### Added
10
+
11
+ - `--reasoning <level>` CLI flag for headless/print mode: `haze -p "…" --reasoning xhigh` steers thinking effort for that run, and `--reasoning unset|off` sends no reasoning parameter so the provider default applies. The interactive status bar now shows the active reasoning level next to the model name (default `high` when unset), and `/reasoning` persists the choice across runs.
12
+
13
+ ### Fixed
14
+
15
+ - Provider model discovery no longer forwards credentials across redirect origins: the endpoint transport is validated before the first fetch and re-checked on redirects, so a draft API key can never leak to a different origin (follow-up to CI-01/CI-02).
16
+ - The NDJSON event sink queues events safely when the producer and consumer race on async stream errors, and goal checkpoints preserve their validation kind across supervisor boundaries (follow-ups to SU-06/R2-03).
17
+
18
+ ## 1.3.0 - 2026-09-22
19
+
20
+ Hardening pass from a 40-finding architecture review (2026-09-22; `reviews/2026-09-22/` — 33 round-1 findings plus a 7-finding round-2 follow-up, all resolved): consistent secret/file boundaries across every tool path, one shared mutation-effects projection, completion obligations that survive every failed exit, durable session lifecycle fixes, credential-safe discovery, and honest output reduction.
21
+
22
+ ### Added
23
+
24
+ - Symbol-aware LSP workflow: hierarchical symbol/body/signature retrieval, reference results enriched with enclosing symbols and snippets, symbol-scoped diagnostics, semantic rename, and reference-guarded safe delete. Warm language servers now receive external file-change notifications, wait for bounded indexing progress, and restart once after termination. Malformed LSP positions/ranges are rejected instead of being coerced into edits, and every file in a workspace edit is preflighted before the first write (TS-05).
25
+ - Guarded `replaceInFiles` bulk edits with dry-run previews, stable occurrence IDs, include/exclude globs, expected-count checks, stale-selection refusal, bounded diffs, and retrievable overflow output. Bulk scans guard every matched descendant through the shared read policy (secret protection included) before opening it (TS-01).
26
+
27
+ ### Fixed
28
+
29
+ - Secret and search boundaries are uniform across tools (TS-01/TS-02/TS-07): `replaceInFiles` scans refuse protected descendants before any read; grep traversal exclusions derive from the one secret-policy list (negated-only globs after any model glob, case-insensitive matching); and `includeIgnored` affects the ripgrep traversal only on explicit override, keeping `.git` and dependency roots out either way.
30
+ - Regex replacements use the engine's native sticky-regex mode, so lookarounds and capture-group semantics match the preview exactly instead of drifting on repeated matches (TS-04). Multi-file `writeFile` batches report changed and uncertain paths truthfully when a later write fails partway (TS-08).
31
+ - Shell output reducers apply only to unambiguous single foreground commands (TS-06): the git reducer requires a leading git command, stdout-owned output, and no stderr, and unknown status content no longer renders as a clean-status summary.
32
+ - Provider model discovery validates the endpoint transport before its first fetch and re-checks redirects, so a draft API key is never sent to an unvalidated URL; LSP pull diagnostics use the advertised `diagnosticProvider` capability and method names, distinguishing an explicit empty report from an absent or timed-out one (CI-01/CI-02).
33
+ - Skill bodies, references, and discovery responses share the file tools' secret-file policy and are bounded (count and aggregate bytes) (CI-03/CI-04); task storage resolves real workspace paths, refusing symlinked escapes out of the workspace (CI-05).
34
+ - Validation evidence is recorded in execution order so the latest run of a command decides the outcome, not insertion order; newline/background commands no longer count as direct artifact validation — the shared single-foreground-command check decides (AR-01/AR-03).
35
+ - One shared mutation-effects projection (`changedPathsFromTool`) feeds work state, LSP diagnostics, and worker capsules, and it tolerates success-only outputs; bulk edits, LSP workspace edits, delegated subagent mutations, and failed workers all count their confirmed effects and validation evidence (AR-02/AR-08).
36
+ - Structured completion obligations survive every failed exit (AR-04/AR-05): `TurnResult.checkpoint` preserves tasks, mutation counts, and red evidence on hard failures; an idle-stall resume keeps its checkpoint; headless relaunches never duplicate the request or drop carried evidence.
37
+ - Session lifecycle is durable and honest (SU-01..SU-06): one shared goal-frontier tracker reopens a paused goal on same-id resume instead of an earlier terminal entry winning; `/clear` persists an empty snapshot and restore replays the clear marker so a cleared session stays cleared; manual LLM compaction is timeout/output-bounded and discards commits over newer conversation state; recovery slash commands keep the paused-goal `R` affordance; the NDJSON sink captures async stream errors, bounds its queue, and exits non-zero on producer failure; mention completion is token-bound so stale results can never apply.
38
+ - The goal-ledger vacuum keeps the live frontier when snapshots interleave goal entries (round-2 R2-01, reproduced): the keep decision now uses original entry indexes in one pass, so a deferred vacuum can no longer drop the crash-resume frontier.
39
+ - `context_exhausted` checkpoints carry unresolved red→green evidence and the validation kind rides goal checkpoints end to end (R2-02/R2-03): a continuation cannot complete on a self-declared pass while a classifier-confirmed failure is carried — the same rule that already held inside a turn.
40
+ - Deadlines and attempt teardown are honest (AR-06/AR-07): a cleared deadline is permanently disposed and never fires late; abort listeners drop after settlement; every state-mutating callback — compaction recording included — is quarantined once an attempt is abandoned.
41
+ - Legacy slimmed tool results are re-wrapped into the AI SDK output envelope on session restore, so older persisted conversations load as protocol-safe `ModelMessage[]` values for the next provider request.
42
+ - Session-retrospective friction fixes (RT-01..RT-06): an empty `listFiles` cursor normalizes to absent (no more empty-repository misreport) and outside-workspace paths fail with a structured refusal; a ready voluntary stop at a budget boundary completes instead of looping; subagent provider-error capsules and validation summaries carry actionable detail; `turn_end` persists an explicit failure reason without `--debug`.
43
+
44
+ ### Changed
45
+
46
+ - Validation-command pairing normalizes `env` prefixes (bare, with flags, or with `VAR=value` assignments), so `env CI=1 npm test` after a bare `npm test` failure satisfies the same-check green rule (R2-06). The dead `validate` capability kind was removed — only a runtime-classifier-confirmed `shell` command is validation evidence (R2-04/R2-05).
47
+ - Release hygiene (MR-01..MR-06): `npm run release:verify` checks lockfile root, README, changelog, SECURITY series, docs stamps, and AGENTS stamps for the package version and runs in CI; CI packs a real tarball and fails the upload when it is absent; the launcher artifact suite runs after build; both Git HEAD readers resolve relative `gitdir`/`commondir` (spaces included); all ten unused exports were triaged (unexported or deleted).
48
+ - Refreshed all runtime and development dependencies to their latest releases, including Vitest 5; TypeScript deliberately remains on the latest 6.x release (`6.0.3`) rather than upgrading to TypeScript 7.
49
+
50
+ ## 1.2.1 - 2026-09-07
51
+
52
+ Edit-recovery UX fix: when a file mutation fails and haze requests `readFile` recovery, the model is now explicitly told which path to read and why — and the tool set is no longer narrowed, because the execution-time gate already enforces the fresh read with a recoverable structured error.
53
+
54
+ ### Fixed
55
+
56
+ - Read-only edit recovery instructs instead of restricting: when a failed mutation requests `readFile` recovery, the next step appends a control message naming the exact path and explaining that edit tools will reject retries until the read completes — while keeping the full tool set. The turn-scoped gate in the tool context (`failedMutationPaths` / `pathsReadAfterFailedMutation`) remains the structural enforcer: a premature retry gets a structured `Read <path> first` failure in the same step, not a request-time hard error. Previously haze silently narrowed the active tools to `readFile`, so small models that retried the failed mutation anyway hit `AI_NoSuchToolError` step failures and supervisor relaunch loops (22× observed).
57
+
58
+ ## 1.2.0 - 2026-08-31
59
+
60
+ Context truthfulness and never-stop-for-recoverable-reasons. A model-backed eval harness drove the changes: the completion gate's trust in real process results had four independent ways to be fed false positives, and the recovery paths still hard-failed on recoverable context conditions.
61
+
62
+ ### Added
63
+
64
+ - Model-backed eval harness: `npm run eval` runs the real turn stack (goal supervisor, tools, budgets, compaction) against the configured provider in throwaway workspaces and asserts on the structured goal envelope plus deterministic ground truth (fixture test commands, file hashes) — never on response text. Five canonical scenarios including an honesty invariant (an unsatisfiable, tamper-protected task can never be reported `complete`). Evals skip under plain `npm test`, serialize process-wide, and write transcripts under gitignored `.eval/`.
65
+ - Curated model catalog: known model families carry real context-window and output-cap metadata keyed by model-name pattern (gateway-style `vendor/model` ids match on the final segment), slotted between per-model `modelLimits` and the user fallback. Values are input-safe (the smaller window wins when variants differ); local inference servers never consult the catalog because their effective window is server-configured.
66
+ - Compaction observability: `compaction_start` / `compaction_end` stream events (reason, method, counts, `willRetry`) and durable `compact` session entries (method, older/kept counts, summary) make every compaction — manual, threshold, or overflow-recovery — observable and auditable.
67
+ - `retryBaseDelayMs` setting (integer 250–60000, default 1000): base delay for the shared model-retry pool's exponential backoff, capped at 4× the base.
68
+
69
+ ### Changed
70
+
71
+ - Context estimation prefers the provider's own accounting: each completed step re-anchors the estimate on reported usage (convention-robust across OpenAI-style and Anthropic-style cache reporting, so cache-heavy finishes are never double-counted), with chars/4 estimates only for trailing messages. Silent overflows (usage over the window on a successful finish) and length-stop overflows (truncated input filling the window) are detected from usage and route through the same compact-and-retry recovery as thrown overflow errors, alongside a 25-family provider error-pattern table with rate-limit exclusions.
72
+ - Context-overflow recovery no longer hard-fails: retries shrink the message budget progressively (60%, then 36%); once the bounded retries are exhausted the goal checkpoints (`context_exhausted`) and the supervisor pauses with a one-key resume instead of relaunching the same oversized request.
73
+ - Mid-turn compaction runs at epoch boundaries and prefers an LLM-written summary for large older halves — chained from any previous compaction summary and split-turn aware (a recent window landing mid-turn preserves the unfinished task's request, progress, and next action) — with the deterministic heuristic excerpt for small trims and as the fallback on any summarization failure.
74
+ - The shared model-retry pool resets whenever a failed attempt completed steps since the previous retry, so a long turn with intermittent provider blips never exhausts it; consecutive failures still chain backoff.
75
+ - Settings are re-read per attempt, so a provider or model switch made mid-goal applies from the next attempt.
76
+
77
+ ### Fixed
78
+
79
+ - Validation exit codes are truthful evidence (found by adversarial model-backed evals): validation-classified commands run under `pipefail` so a pipeline like `npm test | tail` can no longer report the final stage's success while the suite failed; a passing validation whose unquoted command can mask a failing stage (`;`, `||`, or single `&` list operators — redirections like `2>&1` are not) is demoted to unconfirmed; validation-kind inference matches only the unquoted command shape, so a quoted payload mentioning "test" cannot claim tool authority; and a passing self-declared custom check can no longer clear a failed classifier-confirmed validation, including one carried from a goal checkpoint.
80
+
3
81
  ## 1.1.1 - 2026-08-26
4
82
 
5
83
  Durable goal resume and a smaller autonomy core. This patch keeps the concrete headless/recovery gains developed after 1.1.0 while removing unproven completion ceremony before publication.
package/README.md CHANGED
@@ -2,17 +2,22 @@
2
2
 
3
3
  A minimal LLM harness for your terminal.
4
4
 
5
- ## What's new in 1.1.1
5
+ ## What's new in 1.4.0
6
6
 
7
- haze 1.1.1 makes long-running goals resumable while keeping the autonomy core small and evidence-based.
7
+ haze 1.4.0 adds per-run reasoning control (`--reasoning <level>` for headless runs and a live status-bar indicator) on top of the 1.3.0 hardening pass: consistent secret and file boundaries across every tool path, truthful validation and mutation evidence that survives failed exits and crashes, durable session lifecycle fixes, credential-safe provider discovery, and honest output reduction.
8
8
 
9
- - Durable goal progress: logical-goal boundaries are appended to the session JSONL with an exact-request hash and bounded task/validation state, so interrupted work can resume from a crash-safe frontier instead of replaying completed work.
10
- - Headless persistence: `--until-done` relaunches a goal after transient provider failures with exponential backoff, `goal_resume` events, the existing absolute timeout, and a three-strike no-progress guard. JSON output includes bounded goal notices so scripts can see why work continued or paused.
11
- - Simpler completion: declared tasks and fresh post-edit validation remain authoritative. Fixes do not require a pre-edit reproduction, but when a recognized check does fail before the first edit, that same command must pass afterward. Experimental ask gates, verifier/sweep calls, lane hints, and goal shapes were evaluated and removed before release because they added cost without improving the measured task.
12
- - Smaller internals: theme data now lives in one typed registry, provider presets use compact model tuples, and the large chat, wizard, input-suggestion, and streaming paths are split into focused modules without changing their public behavior.
9
+ - Uniform safety boundaries: `replaceInFiles` scans, grep traversal, and skill bodies/references all share one secret-file policy; bulk-edit and LSP edits preflight every file before the first write; task storage refuses symlinked escapes.
10
+ - Evidence that survives exits: validation evidence records in execution order, one shared mutation-effects projection feeds work state and worker capsules, and structured completion obligations ride every checkpoint — including `context_exhausted` and headless relaunches.
11
+ - Durable sessions: a `context_exhausted` checkpoint keeps its goal frontier across a crash resume, `/clear` stays cleared after restore, and manual compaction can no longer overwrite newer conversation state.
12
+ - Honest output: semantic reducers apply only to unambiguous single foreground commands, so mixed-command output is never misread as a clean git status or passing test run.
13
+ - Credential-safe discovery: provider model discovery validates the endpoint transport before sending any key and re-checks redirects before credential forwarding.
14
+ - Reasoning control: `haze -p "…" --reasoning <level>` (or `--reasoning unset|off` for the provider default) steers thinking effort per run; the chat status bar shows the active level next to the model name.
13
15
 
14
16
  Previous releases:
15
17
 
18
+ - `1.2.1`: edit-recovery instructs instead of restricting — the model is told which path to read and why, while the execution-time gate enforces the fresh read.
19
+ - `1.2.0`: provider-usage context accounting, recoverable compact-and-retry overflow handling, model-written split-turn-aware compaction, `pipefail` validation truthfulness, and a configurable retry pool.
20
+ - `1.1.1`: durable goal ledgers and crash-resume frontiers; headless `--until-done` relaunches with bounded notices and a no-progress guard; proportional task/validation completion gates; and smaller orchestration internals.
16
21
  - `1.1.0`: terminal theming with 14 built-in palettes and live `/themes` switching; hard secret-file protection across every file tool, including symlink, read-blessing, ignore-override, and grep-traversal defenses.
17
22
  - `1.0.0`: first stable release — the CLI flags, settings schema, `stream-json` event contract, session format, skill layout, and structured tool-result shape under the 1.x compatibility promise; a configurable model-retry pool; and four benchmark-driven reliability fixes (validated with the Harbor differential benchmark: 17/17 verifier tests, fewest input tokens of the reporting harnesses, zero stalls).
18
23
  - `0.11.0`: goal-level autonomy across physical-turn budgets (logical-goal supervisor, evidence-gated completion, `goal_*` stream events, cumulative goal envelope), runtime provenance and `haze doctor` (embedded build info, stale-build refusal, session build headers), model-aware context budgeting (per-preset limits, live discovery, 128K fallback, self-healing context overflow), headless `--timeout` with per-tool deadlines and abort-cause typing, performance work (batched ignore checks, LSP reuse, coalesced/vacuumed sessions, memoized estimates, incremental streaming, viewport-clamped live region), and model-written `/compact` summaries with a heuristic fallback.
@@ -98,6 +103,8 @@ Saved settings live in `~/.haze/settings.json`. ChatGPT OAuth credentials live s
98
103
 
99
104
  Switch the interface palette with `/themes`. The picker lists every built-in theme — light palettes and oh-my-zsh ports like `robbyrussell`, `af-magic`, and `solarized-dark` — and applies the choice immediately; `/themes <name>` sets one directly. The selection persists as `theme` in `~/.haze/settings.json`, and text already on screen keeps its old colors.
100
105
 
106
+ Control reasoning effort with `/reasoning`. The picker (or `/reasoning <level>`) sets one of `none`, `minimal`, `low`, `medium`, `high`, or `xhigh`; the default is `high` when nothing is saved. `/reasoning unset` returns to the provider default (no reasoning parameter is sent) and `/reasoning status` shows the current level. The level is sent as the AI SDK's portable reasoning parameter (the standard `reasoning_effort` field on OpenAI-compatible endpoints) and applies from the next turn. Endpoints without native support ignore it. The selection persists as `reasoning` in `~/.haze/settings.json`; the current level is shown in the bottom status bar next to the model name.
107
+
101
108
  haze focuses on chat, local tools, context files, sessions, and Markdown skills. Use `/skills` for workflows outside that core. Its interactive picker can generate a skill from a description, then enable, disable, validate, or remove it. For reviews, release prep, deploy checks, debugging routines, or a team-specific checklist, ask haze to create a skill and edit the resulting Markdown as needed.
102
109
 
103
110
  ## Start using haze
@@ -210,6 +217,7 @@ When you catch yourself repeating the same instructions, put them in a skill. Th
210
217
  /settings open
211
218
  /themes
212
219
  /themes <name>
220
+ /reasoning [level|unset|status]
213
221
  /logs [id]
214
222
  /lsp
215
223
  /mcp
@@ -252,7 +260,7 @@ echo "what does this project do?" | haze
252
260
 
253
261
  `-p` and `--prompt` run one agentic turn with the full tool set and print the final assistant text. `--model` accepts a bare model name or `provider:name` and overrides the active model for that run without changing `~/.haze/settings.json`. The model must already be registered under a provider's `models`; add it once with `/provider`. Unknown or ambiguous selectors print a specific error to stderr and exit nonzero.
254
262
 
255
- If you pipe stdin without `-p`, haze reads the prompt from stdin. Piped prompts are limited to 256 KiB; for larger input, pass a file path and ask haze to read it. One-shot runs do not create or update durable sessions, and they ignore `--continue`; `--resume <id>` can load an exact saved context for the turn without changing the original session. On a provider context overflow they compact the loaded conversation once, like the interactive path, and retry the same request; if there is too little history to compact, the run fails with a specific message. Add `--debug` to write a detailed JSONL log under `~/.haze/logs/`.
263
+ If you pipe stdin without `-p`, haze reads the prompt from stdin. Piped prompts are limited to 256 KiB; for larger input, pass a file path and ask haze to read it. One-shot runs do not create or update durable sessions, and they ignore `--continue`; `--resume <id>` can load an exact saved context for the turn without changing the original session. On a provider context overflow they compact the loaded conversation and retry at a progressively smaller message budget (up to twice), like the interactive path; if the window stays full the run ends failed with a resumable `context_exhausted` checkpoint, and when compaction is unavailable the error says so explicitly. Add `--debug` to write a detailed JSONL log under `~/.haze/logs/`.
256
264
 
257
265
  `--output` controls the result format: `text` is the default, `json` prints one final envelope, and `stream-json` writes live NDJSON events followed by the same envelope.
258
266
 
@@ -273,7 +281,7 @@ If you pipe stdin without `-p`, haze reads the prompt from stdin. Piped prompts
273
281
  }
274
282
  ```
275
283
 
276
- The `status` field is authoritative (driven by the agent's terminal state, not by parsing `result`), and the exit code mirrors it: `0` only for `complete`. A run that ends without a substantive final answer, after an unresolved final tool failure, or with declared tasks or required validation still unfinished is `failed` even if the provider returned normally; the evidence envelope carries the task counts and validation outcome that gated it. For fixes, red→green evidence is opportunistic: haze does not require a pre-edit failing repro, but if a recognized validation fails before the first mutation, that same command must pass after the fix. Per-turn step/tool budgets are safety boundaries, not completion: haze automatically continues the logical goal in fresh turns while measurable progress remains, so a budget boundary alone never fails a run. `--timeout` bounds the entire logical goal (not each internal turn), and `--until-done` additionally relaunches the goal after transient provider failures (exponential backoff, `goal_resume` events, a three-strike no-progress guard) until it structurally completes or the deadline hits — without granting any extra authority. The result envelope additionally carries a `goal` object (physical turns used, stop reason, total mutations, final validation outcome and task counts) when goal-level continuation was involved, and a bounded `notices` array with the gate decisions the run made (such as pause reasons) so scripts can see why a goal continued or stopped — the same decisions stream live as `goal_notice` events in `--output stream-json`.
284
+ The `status` field is authoritative (driven by the agent's terminal state, not by parsing `result`), and the exit code mirrors it: `0` only for `complete`. A run that ends without a substantive final answer, after an unresolved final tool failure, or with declared tasks or required validation still unfinished is `failed` even if the provider returned normally; the evidence envelope carries the task counts and validation outcome that gated it. For fixes, red→green evidence is opportunistic: haze does not require a pre-edit failing repro, but if a recognized validation fails before the first mutation, that same command must pass after the fix. Long tool loops use one bounded Vercel AI SDK step at a time, releasing request-local SDK state while appending the exact provider message prefix for prompt-cache reuse. Per-turn step/tool budgets are safety boundaries, not completion: haze automatically continues the logical goal in fresh turns while measurable progress remains, so a budget boundary alone never fails a run. `--timeout` bounds the entire logical goal (not each internal turn), and `--until-done` additionally relaunches the goal after transient provider failures (exponential backoff, `goal_resume` events, a three-strike no-progress guard) until it structurally completes or the deadline hits — without granting any extra authority. The result envelope additionally carries a `goal` object (physical turns used, stop reason, total mutations, final validation outcome and task counts) when goal-level continuation was involved, and a bounded `notices` array with the gate decisions the run made (such as pause reasons) so scripts can see why a goal continued or stopped — the same decisions stream live as `goal_notice` events in `--output stream-json`.
277
285
 
278
286
  `--output stream-json` writes progress as the run happens. Each public event is one newline-delimited JSON object on stdout. The last line uses the same `{ type: "result", status, result, usage }` envelope as `--output json`, so consumers can display progress and parse the final result in the same way:
279
287
 
@@ -288,7 +296,7 @@ The `status` field is authoritative (driven by the agent's terminal state, not b
288
296
  {"type":"result","status":"complete","result":"Here are the findings…","usage":{"inputTokens":0,"outputTokens":0,"cacheReadTokens":0,"cacheWriteTokens":0,"reasoningTokens":0}}
289
297
  ```
290
298
 
291
- Each line is valid JSON and can be piped through `jq -c .`. Event types include `turn_start`, `message_start` / `message_update` / `message_end`, `tool_start` / `tool_end`, `retry`, `context_overflow`, and `turn_end`. Every event has an ISO-8601 `at` timestamp. Tool events omit raw inputs and outputs because CI and harness logs often capture stdout; use `--debug` for detailed local JSONL logs.
299
+ Each line is valid JSON and can be piped through `jq -c .`. Event types include `turn_start`, `message_start` / `message_update` / `message_end`, `tool_start` / `tool_end`, `resource_rollover`, `retry`, `context_overflow`, `compaction_start` / `compaction_end`, and `turn_end`. `resource_rollover` reports bounded SDK-step transitions and whether the provider prefix was preserved, without exposing prompts or tool output. Every event has an ISO-8601 `at` timestamp. Tool events omit raw inputs and outputs because CI and harness logs often capture stdout; use `--debug` for detailed local JSONL logs.
292
300
 
293
301
  This mode is intended for harnesses that run haze without a person at the terminal. A supervisor can watch stdout for progress, stalls, or loops. The final `result` envelope contains the authoritative status, text, and usage. The `text` and `json` formats are unchanged.
294
302
 
@@ -302,6 +310,7 @@ haze has a small built-in toolset:
302
310
  - `readFile` returns numbered UTF-8 lines in bounded pages, with `nextOffset` when more remain. It keeps a small, signature-checked index of line offsets so later pages do not start from the top of the file. File contents are not cached.
303
311
  - `grep` runs structured ripgrep searches with a global result cap and compacts long lines and result sets. It rejects directly named ignored roots unless `includeIgnored` is set.
304
312
  - `editFile` makes unique text replacements, tolerates accidental line-number prefixes, and returns a structured diff.
313
+ - `replaceInFiles` previews or applies guarded literal/regex changes across files using stable occurrence IDs, globs, and expected-count checks.
305
314
  - `replaceLines` edits line ranges when exact replacements are awkward, clamps ranges that extend slightly past EOF, and returns a structured diff.
306
315
  - `writeFile` creates, overwrites, or appends files and parent directories, returning a diff for each successful content change.
307
316
  - `shell` runs tests, builds, git and gh commands, scripts, installs, and other command-line work in your configured login shell. Set `HAZE_SHELL` to an explicit executable for deterministic CI or service accounts. Its schema identifies the active shell dialect. Output is trimmed according to the command type while preserving useful failure details. A timeout or abort kills the process tree, escalates if necessary, and returns even when an escaped child keeps stdout or stderr open.
@@ -309,13 +318,13 @@ haze has a small built-in toolset:
309
318
  - `fetch` reads public `http(s)` URLs as Markdown, formatted JSON, or text. It rejects non-HTTP schemes, private and loopback addresses, metadata hosts, and malformed IPv6-like hosts. Bounded output remains available through `readToolOutput`.
310
319
  - `writeTasks` replaces the task list at meaningful phase changes. Completed lists clear on the next user turn.
311
320
  - `skill` loads an installed Markdown workflow or one of its references.
312
- - `lspWorkspaceSymbols`, `lspSymbols`, `lspDefinition`, and `lspReferences` provide optional read-only navigation through configured language servers. They appear only when an enabled server command is installed.
321
+ - Optional LSP tools provide hierarchical symbol/body retrieval, definitions, enriched references, implementations, symbol-scoped diagnostics, semantic rename, and checked safe delete. They appear only when an enabled server command is installed.
313
322
 
314
- Tool calls are grouped in the transcript so you can see what happened without reading a novella. Every successful `editFile`, `replaceLines`, and `writeFile` content change shows colored additions and removals with line numbers and context. Large diffs keep an eight-row preview—the first four and last four rows, separated by an omission marker—and expose the complete retained diff through `readToolOutput`; no-op mutations are labeled explicitly. File-tool failures include a reason code and a recovery hint; protected secret files (SSH keys, shell histories, `.env` files, credentials) are refused outright with `secret_file_protected` and show as `blocked: protected secret file` in the transcript. Large shell, search, and fetch results stay behind an in-memory handle. Later model calls see a compact summary tailored to validation, git, search, diffs, JSON, logs, or the head and tail of the output.
323
+ Tool calls are grouped in the transcript so you can see what happened without reading a novella. Every successful `editFile`, `replaceInFiles`, `replaceLines`, `writeFile`, and mutating LSP content change shows colored additions and removals with line numbers and context. Large diffs keep an eight-row preview—the first four and last four rows, separated by an omission marker—and expose the complete retained diff through `readToolOutput`; no-op mutations are labeled explicitly. File-tool failures include a reason code and a recovery hint; protected secret files (SSH keys, shell histories, `.env` files, credentials) are refused outright with `secret_file_protected` and show as `blocked: protected secret file` in the transcript. Large shell, search, and fetch results stay behind an in-memory handle. Later model calls see a compact summary tailored to validation, git, search, diffs, JSON, logs, or the head and tail of the output.
315
324
 
316
325
  ### Optional LSP navigation
317
326
 
318
- haze can use stdio Language Server Protocol servers for semantic code navigation. Open `/lsp` to add a preset or custom command, then enable, disable, or remove it. The presets cover TypeScript, Rust, Python, Go, and PHP. You install the server yourself. haze only exposes LSP tools when an enabled server command is on `PATH`; otherwise it uses `grep`, `listFiles`, and `readFile`. When haze closes a server or rejects malformed protocol output, it terminates the server's process tree and forces it to exit if necessary.
327
+ haze can use stdio Language Server Protocol servers for semantic code navigation and refactoring. Open `/lsp` to add a preset or custom command, then enable, disable, or remove it. The presets cover TypeScript, Rust, Python, Go, and PHP. You install the server yourself. haze only exposes LSP tools when an enabled server command is on `PATH`; otherwise it uses `grep`, `listFiles`, and `readFile`. Warm servers are refreshed after external file changes, bounded indexing progress is respected, and a terminated server is restarted for one retry. Returned locations and workspace edits remain confined to the workspace. When haze closes a server or rejects malformed protocol output, it terminates the server's process tree and forces it to exit if necessary.
319
328
 
320
329
  Example TypeScript setup:
321
330
 
@@ -364,7 +373,7 @@ Keep trivial, conversation-coupled, sequential, user-interactive, or uncertain s
364
373
 
365
374
  ## Context files
366
375
 
367
- haze saves durable workspace sessions in `~/.haze/sessions`. It writes a session after the first resumable message, so empty sessions do not create files or appear under `/resume`. Settings, history, sessions, and debug logs use private POSIX directory/file permissions (`0700`/`0600`) and ordered, flushable writes. Use `/session` to see the current file, `/new` to start fresh, and `/resume` to browse workspace sessions, resume one, or fork its latest snapshot into a new session. `/resume <id>` and `haze --resume <id>` select an exact session. Use `/compact` to condense older model context: by default the active model writes a continuity summary of the older history (set `manualCompaction: "heuristic"` in settings to keep the model-free bounded excerpt instead); automatic mid-turn compaction always uses the heuristic excerpt. Sessions also persist compact structured work state: the active goal, touched files, validation evidence, blockers, and next action.
376
+ haze saves durable workspace sessions in `~/.haze/sessions`. It writes a session after the first resumable message, so empty sessions do not create files or appear under `/resume`. Settings, history, sessions, and debug logs use private POSIX directory/file permissions (`0700`/`0600`) and ordered, flushable writes. Use `/session` to see the current file, `/new` to start fresh, and `/resume` to browse workspace sessions, resume one, or fork its latest snapshot into a new session. `/resume <id>` and `haze --resume <id>` select an exact session. Use `/compact` to condense older model context: by default the active model writes a continuity summary of the older history (set `manualCompaction: "heuristic"` in settings to keep the model-free bounded excerpt instead); automatic mid-turn compaction also prefers a model-written summary once the older history is large, keeping the bounded excerpt for small trims and as the fallback when summarization fails. Sessions also persist compact structured work state: the active goal, touched files, validation evidence, blockers, and next action.
368
377
 
369
378
  Snapshots are written at turn boundaries, not per tool call. If haze crashes or is killed mid-turn, the session resumes from the last completed turn: work already on disk (file edits, command side effects) is not reflected in the session record, so after a crash verify the working tree (`git status`, `git diff`) before continuing. To keep long sessions from growing quadratically — every turn appends the full history again — session files are automatically compacted once superseded snapshots dominate the file: only the newest conversation and work-state snapshots are kept and the file is rewritten atomically.
370
379
 
@@ -387,9 +396,11 @@ Use `AGENTS.md` for project conventions, commands, architecture notes, and anyth
387
396
  Most haze behaviour needs no configuration; a few optional keys in `~/.haze/settings.json` tune reliability and context handling. All are validated loudly — malformed values fail with a clear settings error instead of being silently ignored.
388
397
 
389
398
  - `modelRetries` (integer 0–10, default 2): size of the shared bounded retry pool for transient model errors and idle-stream stalls. Raise it for providers that terminate long streams aggressively; `0` disables automatic retries (a stalled stream pauses with the goal preserved for a one-key resume). The effective value is reported in `timeout` and `retry` stream events as `maxRetries`.
390
- - `contextWindowFallbackTokens` / `localContextWindowFallbackTokens` (default 128K hosted / 32K local): context-window guess for models without limits metadata. Every turn emits a `context_budget` event naming the window and its source, and the interactive warning fires once per model per session when the built-in default was used.
399
+ - `retryBaseDelayMs` (integer 250–60000, default 1000): base delay for the shared retry pool's exponential backoff (`base × 2^attempt`, capped at 4× the base). The pool resets whenever a failed attempt completed steps since the previous retry, so intermittent blips on a long turn never exhaust it.
400
+ - `contextWindowFallbackTokens` / `localContextWindowFallbackTokens` (default 128K hosted / 32K local): context-window guess for models without limits metadata or a curated catalog entry. Every turn emits a `context_budget` event naming the window and its source, and the interactive warning fires once per model per session when the built-in default was used.
391
401
  - `manualCompaction` (`"llm-summary"` default, or `"heuristic"`): whether manual `/compact` asks the active model for a continuity summary or keeps the model-free bounded excerpt.
392
402
  - `theme` (string, default `purple`): name of a built-in palette (`/themes` lists and sets them, with `light` and oh-my-zsh ports like `robbyrussell` included). Unknown names fail loudly at startup with the valid names listed.
403
+ - `reasoning` (`"none"` | `"minimal"` | `"low"` | `"medium"` | `"high"` | `"xhigh"` | `"provider-default"`, default `high`): reasoning-effort level sent as the portable reasoning parameter. An absent key means `high`; the `provider-default` sentinel means no parameter is sent. `/reasoning` lists, sets, and clears it.
393
404
 
394
405
  ## Safety model
395
406
 
@@ -452,7 +463,7 @@ Package check:
452
463
  npm pack --dry-run
453
464
  ```
454
465
 
455
- The npm package ships `bin`, `dist`, README, license, changelog, and examples.
466
+ The npm package ships `bin`, `dist`, README, SECURITY.md, license, and changelog.
456
467
 
457
468
  ## Release
458
469
 
package/SECURITY.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  | Version | Supported |
6
6
  |---------|-----------|
7
- | Latest minor (`1.1.x`) | Yes — security fixes |
7
+ | Latest minor (`1.4.x`) | Yes — security fixes |
8
8
  | Older minors and pre-1.0 (`0.x`) | No — upgrade required |
9
9
 
10
10
  Security fixes are provided for the latest published minor release. Upgrade to the newest release before reporting an issue that may already have been fixed.
package/bin/haze.js CHANGED
@@ -29,19 +29,39 @@ function readJson(file) {
29
29
 
30
30
  function readGitHead() {
31
31
  const sha = (value) => (/^[0-9a-f]{7,40}$/i.test((value ?? '').trim()) ? value.trim() : undefined);
32
+ const readOptional = (file) => {
33
+ try {
34
+ return readFileSync(file, 'utf8');
35
+ } catch {
36
+ return undefined;
37
+ }
38
+ };
32
39
  try {
33
40
  const dotGit = path.join(root, '.git');
34
41
  const stat = statSync(dotGit);
35
- const gitDir = stat.isDirectory() ? dotGit : /gitdir:\s*(\S+)/.exec(readFileSync(dotGit, 'utf8'))?.[1];
42
+ // `gitdir: <path>` may be relative (resolve against root) and contain
43
+ // spaces; linked worktrees keep refs in the common dir via `commondir`
44
+ // (MR-05). Mirrors src/utils/buildInfo.ts gitHeadCommit by design.
45
+ const gitDir = stat.isDirectory()
46
+ ? dotGit
47
+ : path.resolve(root, (/gitdir:\s*(.+?)\s*$/m.exec(readOptional(dotGit) ?? '') ?? [])[1]);
36
48
  if (!gitDir) return undefined;
37
- const head = readFileSync(path.join(gitDir, 'HEAD'), 'utf8').trim();
49
+ const commonDirRaw = /\s*(.+?)\s*$/.exec(readOptional(path.join(gitDir, 'commondir')) ?? '')?.[1];
50
+ const refDirs = commonDirRaw ? [path.resolve(gitDir, commonDirRaw)] : [];
51
+ const head = (readOptional(path.join(gitDir, 'HEAD')) ?? '').trim();
38
52
  if (!head.startsWith('ref:')) return sha(head);
39
53
  const ref = head.slice(4).trim();
40
- const refPath = path.join(gitDir, ref);
41
- if (existsSync(refPath)) return sha(readFileSync(refPath, 'utf8'));
42
- const packed = readFileSync(path.join(gitDir, 'packed-refs'), 'utf8');
43
- const escaped = ref.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
44
- return sha(new RegExp(`^([0-9a-f]{40}) ${escaped}$`, 'm').exec(packed)?.[1]);
54
+ for (const dir of [gitDir, ...refDirs]) {
55
+ const loose = sha(readOptional(path.join(dir, ref)));
56
+ if (loose) return loose;
57
+ const packed = readOptional(path.join(dir, 'packed-refs'));
58
+ if (packed) {
59
+ const escaped = ref.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
60
+ const packedSha = sha(new RegExp(`^([0-9a-f]{40}) ${escaped}$`, 'm').exec(packed)?.[1]);
61
+ if (packedSha) return packedSha;
62
+ }
63
+ }
64
+ return undefined;
45
65
  } catch {
46
66
  return undefined;
47
67
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@denizokcu/haze",
3
- "version": "1.1.1",
4
- "commit": "26906fadb2553848b273fc254f2e0f57ba27cd0c",
5
- "builtAt": "2026-08-26T17:12:54.837Z",
3
+ "version": "1.4.0",
4
+ "commit": "a2f3d3e568b4d07ba6a33f6fa2218e24e11bad9c",
5
+ "builtAt": "2026-09-24T21:04:10.115Z",
6
6
  "sourceRoot": "/Users/deniz.okcu/development/haze"
7
7
  }
@@ -8,13 +8,16 @@ const CHAT_COMMAND_SUGGESTIONS = [
8
8
  { value: '/mcp', description: 'Manage MCP servers (Context7, etc.)', kind: 'command' },
9
9
  { value: '/settings', description: 'Show provider, model, API key, and context status', kind: 'command' },
10
10
  { value: '/themes', description: 'Choose a terminal theme (light palettes and oh-my-zsh ports included)', kind: 'command' },
11
+ { value: '/reasoning', description: 'Set reasoning effort (none, minimal, low, medium, high, xhigh) or unset', kind: 'command' },
11
12
  { value: '/context', description: 'Show token breakdown of system, tools, MCP, and messages', kind: 'command' },
12
13
  { value: '/skills', description: 'Manage Markdown skills (add, enable/disable, validate, remove)', kind: 'command' },
14
+ { value: '/tips', description: 'Toggle the rotating tips shown while the model is thinking', kind: 'command' },
13
15
  { value: '/fleet ', description: 'Parallelize independent work in disposable contexts (flags: --review/--profile/--workers/--concurrency)', kind: 'command' },
14
16
  { value: '/init', description: 'Create or update AGENTS.md project instructions', kind: 'command' },
15
17
  { value: '/session', description: 'Show current session path', kind: 'command' },
16
18
  { value: '/resume', description: 'Browse saved sessions for this workspace', kind: 'command' },
17
19
  { value: '/new', description: 'Start a new session', kind: 'command' },
20
+ { value: '/logs', description: 'List recent LLM logs, or summarize one by id (--debug runs only)', kind: 'command' },
18
21
  { value: '/compact ', description: 'Summarize older context and keep recent messages', kind: 'command' },
19
22
  { value: '/clear', description: 'Clear conversation history', kind: 'command' },
20
23
  { value: '/exit', description: 'Exit haze', kind: 'command' },
@@ -0,0 +1,36 @@
1
+ import type { Message } from '../commands/streaming.js';
2
+ /**
3
+ * The dynamic live tail: streaming messages shown below the append-only
4
+ * `<Static>` transcript (streamed assistant text and the active tool group).
5
+ *
6
+ * The tail is a synchronous ref-first store, not plain React state: agent
7
+ * callbacks (addMessage → message_update deltas → the finalizing update that
8
+ * flips `streaming: false`) routinely arrive back-to-back inside one React
9
+ * batch window — a fast or buffered model stream never yields to the scheduler
10
+ * between them. If `liveMessagesRef` were written only inside the state
11
+ * updater, routing decisions made during the burst would read a stale tail:
12
+ * deltas would be dropped and the finalize would misroute, stranding a
13
+ * truncated streaming fragment in the tail forever. Mutations therefore
14
+ * advance the ref immediately (synchronously visible to the next callback)
15
+ * and mirror into state purely for rendering.
16
+ */
17
+ export declare function useLiveMessages(finalizeMessage: (message: Message) => void): {
18
+ liveMessages: Message[];
19
+ liveMessagesRef: import("react").RefObject<Message[]>;
20
+ addStreaming: (message: Message) => void;
21
+ patch: (id: string, update: Partial<Message>) => {
22
+ id?: string;
23
+ role: "system" | "user" | "assistant" | "tool";
24
+ text: string;
25
+ streaming?: boolean;
26
+ hidden?: boolean;
27
+ startedAt?: number;
28
+ finishedAt?: number;
29
+ tokensPerSecond?: number;
30
+ displayOrder?: number;
31
+ toolCount?: number;
32
+ toolDiffs?: import("../commands/streaming/toolGroupRenderer.js").ToolDisplayDiff[];
33
+ } | undefined;
34
+ drain: (finalize?: (message: Message) => void) => void;
35
+ clear: () => void;
36
+ };
@@ -0,0 +1,64 @@
1
+ import { useRef, useState } from 'react';
2
+ /**
3
+ * The dynamic live tail: streaming messages shown below the append-only
4
+ * `<Static>` transcript (streamed assistant text and the active tool group).
5
+ *
6
+ * The tail is a synchronous ref-first store, not plain React state: agent
7
+ * callbacks (addMessage → message_update deltas → the finalizing update that
8
+ * flips `streaming: false`) routinely arrive back-to-back inside one React
9
+ * batch window — a fast or buffered model stream never yields to the scheduler
10
+ * between them. If `liveMessagesRef` were written only inside the state
11
+ * updater, routing decisions made during the burst would read a stale tail:
12
+ * deltas would be dropped and the finalize would misroute, stranding a
13
+ * truncated streaming fragment in the tail forever. Mutations therefore
14
+ * advance the ref immediately (synchronously visible to the next callback)
15
+ * and mirror into state purely for rendering.
16
+ */
17
+ export function useLiveMessages(finalizeMessage) {
18
+ const [liveMessages, setLiveMessages] = useState([]);
19
+ const liveMessagesRef = useRef([]);
20
+ function commit(next) {
21
+ liveMessagesRef.current = next;
22
+ setLiveMessages(next);
23
+ }
24
+ /** Add a streaming message to the tail. */
25
+ function addStreaming(message) {
26
+ commit([...liveMessagesRef.current, message]);
27
+ }
28
+ /** Patch one live message by id (deltas keep it streaming). */
29
+ function patch(id, update) {
30
+ const liveMessage = liveMessagesRef.current.find(message => message.id === id);
31
+ if (!liveMessage)
32
+ return undefined;
33
+ const updated = { ...liveMessage, ...update };
34
+ if (updated.streaming === false) {
35
+ commit(liveMessagesRef.current.filter(message => message.id !== id));
36
+ finalizeMessage(updated);
37
+ return updated;
38
+ }
39
+ commit(liveMessagesRef.current.map(message => message.id === id ? updated : message));
40
+ return updated;
41
+ }
42
+ /**
43
+ * Settle every still-streaming message at a turn boundary. Aborted or
44
+ * forcibly settled attempts are quarantined before they can emit the
45
+ * finalizing update, so any message left streaming here would otherwise
46
+ * strand in the dynamic tail forever. Finalized text is preserved verbatim;
47
+ * nothing is lost, it just stops being dynamic.
48
+ */
49
+ function drain(finalize = finalizeMessage) {
50
+ const stranded = liveMessagesRef.current.filter(message => message.streaming);
51
+ if (stranded.length === 0)
52
+ return;
53
+ commit(liveMessagesRef.current.filter(message => !message.streaming));
54
+ for (const message of stranded)
55
+ finalize({ ...message, streaming: false });
56
+ }
57
+ /** Drop the tail (clear/new-session). */
58
+ function clear() {
59
+ if (liveMessagesRef.current.length === 0)
60
+ return;
61
+ commit([]);
62
+ }
63
+ return { liveMessages, liveMessagesRef, addStreaming, patch, drain, clear };
64
+ }
@@ -47,7 +47,8 @@ export interface SessionLifecycleDeps {
47
47
  current: Map<string, string>;
48
48
  };
49
49
  setMessages: (updater: (messages: Message[]) => Message[]) => void;
50
- setLiveMessagesState: (updater: (messages: Message[]) => Message[]) => void;
50
+ /** Drop the live tail (clear/new-session). */
51
+ clearLiveMessages: () => void;
51
52
  setTokenUsage: (usage: TokenUsage) => void;
52
53
  /** Manual /compact mode: model-written summary (default) or heuristic excerpt. */
53
54
  manualCompaction?: () => 'llm-summary' | 'heuristic';
@@ -1,12 +1,15 @@
1
1
  import { generateText } from 'ai';
2
2
  import { buildLlmCompactionPrompt, compactModelMessages, compactModelMessagesWithSummary, splitForCompaction } from '../../core/agent/compaction.js';
3
3
  import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
4
+ import { COMPACTION_LLM_MAX_OUTPUT_TOKENS } from '../../core/agent/budgets.js';
4
5
  import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
5
6
  import { modelWithConfig } from '../../llm/client.js';
6
7
  import { createSession, findSession, forkSession, formatSession, latestSession, restoreSessionState } from '../../core/session/sessionStore.js';
7
8
  import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
8
9
  import { displayMessagesFromConversation, estimateConversationTokens } from './chatMetrics.js';
9
10
  import { EMPTY_TOKEN_USAGE } from './turnState.js';
11
+ /** Bounded wall-clock budget for one manual LLM compaction summary (SU-03). */
12
+ const COMPACT_SUMMARY_TIMEOUT_MS = 120_000;
10
13
  import { teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
11
14
  export function createSessionLifecycle(deps) {
12
15
  async function startNewLog() {
@@ -47,7 +50,7 @@ export function createSessionLifecycle(deps) {
47
50
  const { messages: conversation, workState, parseErrors, goalFrontier } = await restoreSessionState(session);
48
51
  deps.sessionRef.current = session;
49
52
  deps.conversationRef.current = conversation;
50
- deps.setLiveMessagesState(() => []);
53
+ deps.clearLiveMessages();
51
54
  const restoredMessages = displayMessagesFromConversation(conversation);
52
55
  deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE, messages: estimateConversationTokens(restoredMessages).input, outputEstimate: estimateConversationTokens(restoredMessages).output });
53
56
  deps.workStateRef.current = workState;
@@ -75,6 +78,7 @@ export function createSessionLifecycle(deps) {
75
78
  }
76
79
  deps.conversationRef.current = result.messages;
77
80
  deps.sessionRecorder()?.recordNamedEvent('compact', `Compacted ${result.olderCount} messages; kept ${result.keptCount}.`);
81
+ deps.sessionRecorder()?.recordCompactEntry({ method: 'heuristic', olderCount: result.olderCount, keptCount: result.keptCount, ...(instructions ? { instructions } : {}), summary: result.summary ?? '' });
78
82
  deps.sessionRecorder()?.recordConversation(result.messages);
79
83
  deps.setMessages(m => [...m, { role: 'system', text: `Compacted context: condensed ${result.olderCount} older model messages into a bounded excerpt and kept the last ${result.keptCount}.` }]);
80
84
  return true;
@@ -163,8 +167,12 @@ export function createSessionLifecycle(deps) {
163
167
  deps.lastAssistantTextRef.current = '';
164
168
  deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE });
165
169
  deps.workStateRef.current = undefined;
166
- deps.setLiveMessagesState(() => []);
170
+ deps.clearLiveMessages();
167
171
  deps.setMessages(() => [{ role: 'system', text: 'Cleared. The void is productive.' }]);
172
+ // SU-02: record the empty snapshot so the clear is durable immediately;
173
+ // restore replays the clear marker and yields an empty conversation even
174
+ // if the process exits before the next conversation snapshot arrives.
175
+ deps.sessionRecorder()?.recordConversation([]);
168
176
  deps.sessionRecorder()?.recordNamedEvent('clear', 'Conversation cleared');
169
177
  await deps.sessionRecorder()?.flush().catch(deps.showPersistenceWarning);
170
178
  await startNewLog().catch(deps.showPersistenceWarning);
@@ -181,6 +189,10 @@ export function createSessionLifecycle(deps) {
181
189
  deps.setMessages(m => [...m, { role: 'system', text: `Compaction skipped: only ${messages.length} model messages in context.` }]);
182
190
  return false;
183
191
  }
192
+ // SU-03: commit against the exact session and conversation we captured.
193
+ // A submission/session change while the summary was pending must not be
194
+ // overwritten — the stale compaction is reported and discarded instead.
195
+ const sessionAtStart = deps.sessionRef.current;
184
196
  try {
185
197
  const runtime = await modelWithConfig();
186
198
  if (!runtime?.model)
@@ -188,7 +200,17 @@ export function createSessionLifecycle(deps) {
188
200
  const summarization = await generateText({
189
201
  model: runtime.model,
190
202
  prompt: buildLlmCompactionPrompt({ older: split.older, instructions }),
203
+ maxOutputTokens: COMPACTION_LLM_MAX_OUTPUT_TOKENS,
204
+ abortSignal: AbortSignal.timeout(COMPACT_SUMMARY_TIMEOUT_MS),
191
205
  });
206
+ if (deps.sessionRef.current !== sessionAtStart) {
207
+ deps.setMessages(m => [...m, { role: 'system', text: 'Compaction result discarded: the session changed while the summary was being written.' }]);
208
+ return false;
209
+ }
210
+ if (deps.conversationRef.current !== messages) {
211
+ deps.setMessages(m => [...m, { role: 'system', text: 'Compaction result discarded: the conversation changed while the summary was being written. Run /compact again.' }]);
212
+ return false;
213
+ }
192
214
  const summaryText = summarization.text.trim();
193
215
  if (!summaryText)
194
216
  throw new Error('model returned an empty summary');
@@ -197,6 +219,7 @@ export function createSessionLifecycle(deps) {
197
219
  throw new Error('nothing older to compact');
198
220
  deps.conversationRef.current = result.messages;
199
221
  deps.sessionRecorder()?.recordNamedEvent('compact', `Compacted ${result.olderCount} messages with a model-written summary; kept ${result.keptCount}.`);
222
+ deps.sessionRecorder()?.recordCompactEntry({ method: 'llm', olderCount: result.olderCount, keptCount: result.keptCount, ...(instructions ? { instructions } : {}), summary: result.summary ?? '' });
200
223
  deps.sessionRecorder()?.recordConversation(result.messages);
201
224
  deps.setMessages(m => [...m, { role: 'system', text: `Compacted context: replaced ${result.olderCount} older model messages with a model-written summary and kept the last ${result.keptCount}.` }]);
202
225
  return true;
@@ -11,6 +11,13 @@ export declare function createSessionRecorder(getSession: () => HazeSession | un
11
11
  recordEvent(event: AgentEvent): void;
12
12
  recordGoalEntry(entry: GoalLedgerAppend): void;
13
13
  recordNamedEvent(name: string, text: string): void;
14
+ recordCompactEntry(entry: {
15
+ method: "heuristic" | "llm";
16
+ olderCount: number;
17
+ keptCount: number;
18
+ instructions?: string;
19
+ summary: string;
20
+ }): void;
14
21
  flush(): Promise<void>;
15
22
  error(): Error | undefined;
16
23
  };
@@ -89,6 +89,12 @@ export function createSessionRecorder(getSession) {
89
89
  recordNamedEvent(name, text) {
90
90
  appendEntry({ type: 'event', at: new Date().toISOString(), name, text });
91
91
  },
92
+ // First-class compaction audit entry (Pillar 1.7): what was compacted,
93
+ // when, how, and the summary that replaced it. Snapshots stay the restore
94
+ // source of truth; this entry is the durable narrative.
95
+ recordCompactEntry(entry) {
96
+ appendEntry({ type: 'compact', at: new Date().toISOString(), method: entry.method, olderCount: entry.olderCount, keptCount: entry.keptCount, ...(entry.instructions ? { instructions: entry.instructions } : {}), summary: entry.summary });
97
+ },
92
98
  async flush() {
93
99
  // Fold coalesced snapshots into the writer queue, then wait for the queue
94
100
  // to drain. Loop because a write completing mid-flush may have queued a
@@ -1,4 +1,4 @@
1
1
  import type { Mode } from '../../commands/chatModes.js';
2
2
  import type { WizardDispatchDeps, WizardHandler, WizardSetterContext } from './types.js';
3
- /** Session picker and theme picker handlers (both tiny single-purpose flows). */
3
+ /** Session picker, theme picker, and reasoning picker handlers (tiny single-purpose flows). */
4
4
  export declare function createSessionThemeHandlers(deps: WizardDispatchDeps, ctx: WizardSetterContext): Partial<Record<Mode, WizardHandler>>;
@@ -1,6 +1,7 @@
1
+ import { resolveReasoningCommand } from '../../commands/reasoningCommand.js';
1
2
  import { selectThemeResult } from '../../commands/themesCommand.js';
2
3
  import { SESSION_ACTIONS } from '../../commands/sessionPicker.js';
3
- /** Session picker and theme picker handlers (both tiny single-purpose flows). */
4
+ /** Session picker, theme picker, and reasoning picker handlers (tiny single-purpose flows). */
4
5
  export function createSessionThemeHandlers(deps, ctx) {
5
6
  const { setMode, showMessage } = ctx;
6
7
  const setSelectedSessionId = ctx.setSelectedSessionId;
@@ -40,9 +41,23 @@ export function createSessionThemeHandlers(deps, ctx) {
40
41
  }
41
42
  showMessage(result.message);
42
43
  }
44
+ async function selectReasoning(value) {
45
+ const result = resolveReasoningCommand(value, deps.settings.reasoning);
46
+ if (result.action === 'set' || result.action === 'clear') {
47
+ await ctx.applySettings(result.settingsPatch);
48
+ setMode('chat');
49
+ showMessage(result.message);
50
+ return;
51
+ }
52
+ // Unreachable from the picker (its values always set or clear) but narrows
53
+ // the remaining variants for the type checker.
54
+ if (result.action !== 'open-picker')
55
+ showMessage(result.message);
56
+ }
43
57
  return {
44
58
  sessions: selectSession,
45
59
  sessionAction: selectSessionAction,
46
60
  themes: selectTheme,
61
+ reasoning: selectReasoning,
47
62
  };
48
63
  }