@denizokcu/haze 0.8.0 → 0.9.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 (65) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/README.md +15 -13
  3. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  4. package/dist/cli/chat/sessionRecorder.js +23 -8
  5. package/dist/cli/commands/chat.js +90 -104
  6. package/dist/cli/commands/commands.d.ts +1 -1
  7. package/dist/cli/commands/commands.js +1 -1
  8. package/dist/cli/commands/formatters.js +3 -3
  9. package/dist/cli/commands/logsCommand.js +7 -21
  10. package/dist/cli/commands/mcpWizard.js +24 -2
  11. package/dist/cli/commands/providerWizard.js +18 -5
  12. package/dist/cli/commands/runCommand.js +7 -15
  13. package/dist/cli/commands/settingsSummary.js +3 -1
  14. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  15. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  16. package/dist/cli/commands/streaming.js +66 -29
  17. package/dist/cli/commands/wizardPrompts.js +1 -1
  18. package/dist/cli/commands/wizardSuggestions.js +2 -1
  19. package/dist/cli/commands/wizardTransition.d.ts +33 -0
  20. package/dist/cli/commands/wizardTransition.js +44 -0
  21. package/dist/config/contextFiles.js +6 -3
  22. package/dist/config/endpointSecurity.d.ts +2 -0
  23. package/dist/config/endpointSecurity.js +28 -0
  24. package/dist/config/inputHistory.js +4 -2
  25. package/dist/config/privateStorage.d.ts +6 -0
  26. package/dist/config/privateStorage.js +61 -0
  27. package/dist/config/settings.js +4 -4
  28. package/dist/config/updateCheck.js +4 -2
  29. package/dist/core/agent/toolOutputStore.d.ts +3 -0
  30. package/dist/core/agent/toolOutputStore.js +32 -11
  31. package/dist/core/goal/completionPolicy.d.ts +0 -28
  32. package/dist/core/goal/completionPolicy.js +0 -88
  33. package/dist/core/io/boundedRead.d.ts +15 -0
  34. package/dist/core/io/boundedRead.js +97 -0
  35. package/dist/core/limits/byteBudgets.d.ts +13 -0
  36. package/dist/core/limits/byteBudgets.js +13 -0
  37. package/dist/core/log/llmLog.d.ts +10 -0
  38. package/dist/core/log/llmLog.js +59 -13
  39. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  40. package/dist/core/persistence/orderedFileWriter.js +29 -0
  41. package/dist/core/process/runBoundedProcess.d.ts +27 -0
  42. package/dist/core/process/runBoundedProcess.js +80 -0
  43. package/dist/core/session/sessionStore.js +48 -25
  44. package/dist/core/subagent/subagentRunner.js +1 -1
  45. package/dist/llm/client.js +4 -1
  46. package/dist/llm/hazeTools.d.ts +410 -16
  47. package/dist/llm/hazeTools.js +36 -32
  48. package/dist/llm/lsp.d.ts +21 -3
  49. package/dist/llm/lsp.js +55 -13
  50. package/dist/llm/lspTools.d.ts +96 -48
  51. package/dist/llm/mcp.d.ts +1 -1
  52. package/dist/llm/mcp.js +65 -16
  53. package/dist/llm/requestContext.d.ts +1 -0
  54. package/dist/llm/requestContext.js +6 -3
  55. package/dist/llm/toolResultTypes.d.ts +1 -1
  56. package/dist/llm/tools/bashTool.d.ts +368 -16
  57. package/dist/llm/tools/bashTool.js +19 -57
  58. package/dist/llm/tools/grepRunner.d.ts +15 -0
  59. package/dist/llm/tools/grepRunner.js +85 -0
  60. package/dist/skills/SkillLoader.js +17 -5
  61. package/dist/skills/SkillRegistry.js +19 -6
  62. package/dist/skills/types.d.ts +5 -0
  63. package/dist/utils/path.d.ts +2 -0
  64. package/dist/utils/path.js +9 -4
  65. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,6 +1,16 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.9.0 - 2026-07-10
4
+
5
+ ### Security
6
+
7
+ - Private haze state now uses `0700` directories and `0600` files on POSIX. Bash/process output, raw-output handles, file reads, edits, LSP documents/frames, grep, and JSONL readers enforce collection-time byte limits; bash timeout/abort terminates process trees.
8
+ - Grep rejects explicitly ignored roots unless requested, skills and LSP enforce real workspace/root boundaries, MCP discovery and cleanup are bounded and abort-aware, and credentials are rejected on remote plaintext HTTP endpoints.
9
+
10
+ ### Fixed
11
+
12
+ - Turn/tool status is authoritative across UI, events, logs, sessions, and headless output; retries expose one turn lifecycle and structured `{ok:false}` results remain failures.
13
+ - Session/debug persistence is ordered and flushable, invalid skills are isolated, malformed settings remain visible, active provider/model removal clears selection, and stdio MCP setup no longer asks for HTTP headers.
4
14
 
5
15
  ## 0.8.0 - 2026-07-09
6
16
 
package/README.md CHANGED
@@ -2,17 +2,19 @@
2
2
 
3
3
  A minimal LLM harness for your terminal.
4
4
 
5
- ## What's new in 0.8.0
5
+ ## What's new in 0.9.0
6
6
 
7
- haze 0.8.0 focuses on runtime reliability and clearer terminal feedback while staying compact and low-friction.
7
+ haze 0.9.0 closes the security and correctness findings from the 0.8.0 code review: private state, truthful status, bounded work, and robust boundaries.
8
8
 
9
- - **AI SDK v7 runtime.** The main agent and subagent runners now use AI SDK v7 APIs with explicit per-tool context wiring, keeping built-in tool state turn-scoped and compatible with the newer runtime.
10
- - **Live busy status.** The active-turn indicator now shows the current model, elapsed time, and the tool activity underway — reading, editing, searching, running commands, loading skills, or calling MCP/LSP tools — so long turns look alive instead of stuck.
11
- - **Bounded bash output processing.** Bash output reduction paths are tightened so large command output remains controlled before it reaches transcript/model context.
12
- - **Input and maintenance polish.** Multiline input shortcuts are fixed, core agent maintenance paths are hardened, model/status labels are shorter and safer, and user-facing naming is consistently lowercase `haze`.
9
+ - **Private home-state storage.** Settings, sessions, logs, and history now use `0700` directories and `0600` files on POSIX, with opportunistic tightening of pre-existing overly-broad modes.
10
+ - **Truthful turn and tool status.** Turn and tool status is now authoritative across the UI, events, logs, sessions, and headless exit codes — a turn that ends without a substantive answer, after an unresolved tool failure, or at a hard step/tool budget reports `failed` even when the provider returned normally.
11
+ - **Bounded work, not just bounded output.** Bash, grep, and LSP output, file reads, edits, and stored handles enforce collection-time byte limits; bash timeout and abort terminate the whole process tree, not just the shell.
12
+ - **Stronger filesystem and integration boundaries.** `grep` rejects directly named ignored files, skills and LSP confine to real workspace/root paths (symlink-safe), MCP discovery is bounded and abort-aware, and credentialed remote plaintext HTTP is rejected while loopback HTTP stays supported.
13
+ - **Ordered, flushable persistence.** Sessions and debug logs preserve write order and flush at turn end and shutdown, surfacing persistence failures instead of swallowing them.
13
14
 
14
15
  Previous releases:
15
16
 
17
+ - **0.8.0** — AI SDK v7 runtime, live busy status with model/elapsed/tool labels, bounded bash output processing, and standardized lowercase `haze` naming.
16
18
  - **0.7.0** — Headless `-p`/`--output json`/`--output stream-json`, pinned-connection `fetch` safety, scoped instruction refresh during turns, smaller durable sessions, and startup context visibility.
17
19
  - **0.6.0** — AI SDK-native ToolLoopAgent core, optional LSP semantic navigation, MCP server support, unified config pickers, cleaner transcripts, `/context`, and startup update checks.
18
20
  - **0.5.0** — `fetch` tool for public URLs (Markdown/JSON/text, SSRF-protected), removed all provider env vars (config via `/provider`/`/model`/`/settings`), debug-only LLM logs, command-aware output reduction, Markdown rendering in the CLI, scoped nested context files, and auto-clearing completed tasks.
@@ -78,9 +80,9 @@ Use `/mcp` to connect [Model Context Protocol](https://modelcontextprotocol.io)
78
80
  # add server -> custom -> name -> stdio -> cmd (custom local)
79
81
  ```
80
82
 
81
- API keys are entered in a masked prompt and sent as `Authorization: Bearer <value>`. Servers persist in `~/.haze/settings.json` under `mcpServers` and support `http`, `sse`, and `stdio` transports. Their tools load at the start of each agent turn and the connections close when the turn ends. An unreachable server is isolated and never blocks the agent, and MCP tools never shadow built-in tools.
83
+ API keys for HTTP/SSE servers are entered in a masked prompt and sent as `Authorization: Bearer <value>`. Stdio authentication belongs in the command or wrapper; haze does not attach HTTP headers to stdio. Servers persist in `~/.haze/settings.json` under `mcpServers`. Discovery and cleanup have bounded deadlines, failures are isolated, and MCP tools never shadow built-ins.
82
84
 
83
- Saved settings live in `~/.haze/settings.json`. Providers can include API keys, base URLs, and model lists; local OpenAI-compatible providers can be configured without a key. Use `/provider`, `/model`, and `/settings` to configure everything from inside haze — there are no environment variables to set.
85
+ Saved settings live in `~/.haze/settings.json`. Provider keys and MCP headers require HTTPS unless the endpoint is loopback HTTP (`localhost`, `*.localhost`, `127/8`, or `::1`); keyless HTTP remains available. Local OpenAI-compatible providers can be configured without a key. Malformed settings are shown as an actionable startup error rather than treated as empty. Use `/provider`, `/model`, and `/settings` to configure everything from inside haze — there are no environment variables to set.
84
86
 
85
87
  haze is intentionally minimal: chat, local tools, context files, sessions, and Markdown skills. Any workflow beyond the core is meant to be grown with the LLM through `/skills` (an interactive picker: generate a custom skill from a description, then enable/disable, validate, or remove it). If you want reviews, release prep, deploy checks, debugging rituals, or your team's strange checklist, ask haze to create a skill and then refine the Markdown.
86
88
 
@@ -92,7 +94,7 @@ Open a project and ask for work:
92
94
  create a calculator in calc-app in ruby with add subtract multiply divide
93
95
  ```
94
96
 
95
- haze will inspect, search, write files, fetch public URLs, run commands, and show compact tool activity inline. Small file edits include a colorized line diff with one context line before and after the change; large diffs stay summarized so the transcript does not become a wall of noise. Bash output is reduced by command-aware filters for validation, git, search, JSON, diffs, and noisy logs; failures point at the relevant files, tests, or diagnostics, and raw output remains available by handle when it was omitted. Sessions are saved by default so you can resume the latest workspace conversation with `haze --continue` or `/resume`.
97
+ haze will inspect, search, write files, fetch public URLs, run commands, and show compact tool activity inline. Small file edits include a colorized line diff with one context line before and after the change; large diffs stay summarized so the transcript does not become a wall of noise. Bash output is bounded while the process runs, then reduced by command-aware filters for validation, git, search, JSON, diffs, and noisy logs; failures point at relevant diagnostics. Handles retain raw output only within explicit per-entry and aggregate memory budgets, and report omitted bytes when collection overflow is dropped. Sessions are saved by default so you can resume the latest workspace conversation with `haze --continue` or `/resume`.
96
98
 
97
99
  Use `/` to discover commands and skills. `Tab` completes the top suggestion.
98
100
 
@@ -233,7 +235,7 @@ echo "what does this project do?" | haze
233
235
  }
234
236
  ```
235
237
 
236
- 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 `complete` run with an empty `result` means the model produced no visible text — distinct from a `failed` run.
238
+ 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 turn that ends without a substantive final answer, after an unresolved final tool failure, or at a hard step/tool budget is `failed` even if the provider returned normally.
237
239
 
238
240
  `--output stream-json` streams the run as it happens instead of staying silent until the end. Each public progress event is written to stdout as one newline-delimited JSON object (NDJSON), and the **last** line is the exact same `{ type: "result", status, result, usage }` envelope as `--output json` — so a consumer can render live progress and still parse the final line identically:
239
241
 
@@ -258,12 +260,12 @@ haze exposes a deliberately small toolset:
258
260
 
259
261
  - `listFiles` — structured discovery, recursive with cursor pagination when needed.
260
262
  - `readFile` — read numbered UTF-8 lines in bounded pages, with `nextOffset` when more remain.
261
- - `grep` — structured ripgrep search with a true global result cap and compacted long lines/results.
263
+ - `grep` — structured ripgrep search with a true global result cap and compacted long lines/results; directly named ignored roots are rejected unless `includeIgnored` is explicitly set.
262
264
  - `editFile` — unique text replacements, with line-number-prefix tolerance for common model mistakes.
263
265
  - `replaceLines` — line-range edits when exact replacements are awkward; slightly-too-large EOF ranges are clamped.
264
266
  - `writeFile` — create files and parent directories.
265
267
  - `bash` — run tests, builds, git/gh commands, inspections, scripts, installs, and other shell workflows with command-aware output reduction (git, gh, search, JSON, diffs, logs) and compact validation output.
266
- - `readToolOutput` — page through full/raw output omitted from an oversized or reduced tool result.
268
+ - `readToolOutput` — page through retained raw output omitted from an oversized or reduced tool result (subject to bounded in-memory budgets).
267
269
  - `fetch` — read a public `http(s)` URL and return readable content (Markdown for docs, pretty JSON, or text). Private/loopback/metadata hosts and non-`http(s)` schemes are blocked; output is bounded and retrievable via `readToolOutput`.
268
270
  - `writeTasks` — replace the task list at meaningful phase changes; completed lists auto-clear on the next user turn.
269
271
  - `skill` — load one installed Markdown workflow or one of its references.
@@ -294,7 +296,7 @@ Use them for parallel investigation across separate areas of a codebase. Do not
294
296
 
295
297
  ## Context files
296
298
 
297
- haze saves durable workspace sessions in `~/.haze/sessions`. Use `/session` to see the current file, `/new` to start fresh, `/resume` to restore the latest session, and `/compact` to summarize older model context. Sessions also persist compact structured work state: the active goal, touched files, validation evidence, blockers, and next action.
299
+ haze saves durable workspace sessions in `~/.haze/sessions`. 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, `/resume` to restore the latest session, and `/compact` to summarize older model context. Sessions also persist compact structured work state: the active goal, touched files, validation evidence, blockers, and next action.
298
300
 
299
301
  Session files are optimized for resume and audit, not token-by-token playback: completed user/assistant messages, tool lifecycle events, conversation snapshots, and work-state snapshots are persisted, but streaming `message_update` events are skipped. Large persisted tool outputs are replaced with previews and byte counts so a resumed model can reread current files instead of carrying stale megabytes forward.
300
302
 
@@ -8,5 +8,8 @@ export declare function createSessionRecorder(getSession: () => HazeSession | un
8
8
  recordConversation(messages: ModelMessage[]): void;
9
9
  recordWorkState(state: WorkState): void;
10
10
  recordEvent(event: AgentEvent): void;
11
+ recordNamedEvent(name: string, text: string): void;
12
+ flush(): Promise<void>;
13
+ error(): Error | undefined;
11
14
  };
12
15
  export type SessionRecorder = ReturnType<typeof createSessionRecorder>;
@@ -1,21 +1,36 @@
1
1
  import { appendSessionEntry } from '../../core/session/sessionStore.js';
2
- function appendFireAndForget(session, entry) {
3
- if (session)
4
- void appendSessionEntry(session, entry).catch(() => undefined);
5
- }
6
2
  export function createSessionRecorder(getSession) {
3
+ let tail = Promise.resolve();
4
+ let firstError;
5
+ const append = (entry) => {
6
+ const session = getSession();
7
+ if (!session)
8
+ return;
9
+ tail = tail.then(() => appendSessionEntry(session, entry)).catch(error => {
10
+ firstError ??= error instanceof Error ? error : new Error(String(error));
11
+ });
12
+ };
7
13
  return {
8
14
  recordUiMessage(message) {
9
- appendFireAndForget(getSession(), { type: 'ui_message', at: new Date().toISOString(), role: message.role, text: message.text });
15
+ append({ type: 'ui_message', at: new Date().toISOString(), role: message.role, text: message.text });
10
16
  },
11
17
  recordConversation(messages) {
12
- appendFireAndForget(getSession(), { type: 'conversation_snapshot', at: new Date().toISOString(), messages });
18
+ append({ type: 'conversation_snapshot', at: new Date().toISOString(), messages });
13
19
  },
14
20
  recordWorkState(state) {
15
- appendFireAndForget(getSession(), { type: 'work_state_snapshot', at: new Date().toISOString(), state });
21
+ append({ type: 'work_state_snapshot', at: new Date().toISOString(), state });
16
22
  },
17
23
  recordEvent(event) {
18
- appendFireAndForget(getSession(), { type: 'event', at: event.at, name: event.type, text: JSON.stringify(event) });
24
+ append({ type: 'event', at: event.at, name: event.type, text: JSON.stringify(event) });
25
+ },
26
+ recordNamedEvent(name, text) {
27
+ append({ type: 'event', at: new Date().toISOString(), name, text });
28
+ },
29
+ async flush() {
30
+ await tail;
31
+ if (firstError)
32
+ throw firstError;
19
33
  },
34
+ error() { return firstError; },
20
35
  };
21
36
  }
@@ -24,7 +24,7 @@ import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/l
24
24
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
25
25
  import { createSkill, toSkillDirName } from '../../skills/builder/SkillBuilder.js';
26
26
  import { findPreset } from '../../config/providerPresets.js';
27
- import { appendSessionEntry, createSession, formatSession, latestSession, restoreConversation, restoreWorkState } from '../../core/session/sessionStore.js';
27
+ import { createSession, formatSession, latestSession, restoreConversation, restoreWorkState } from '../../core/session/sessionStore.js';
28
28
  import { compactModelMessages } from '../../core/agent/compaction.js';
29
29
  import { contextBreakdown } from '../../core/agent/contextBudget.js';
30
30
  import { stripSyntheticControls } from '../../core/agent/requestAssembly.js';
@@ -42,7 +42,8 @@ import { MASKED_MODES, PICKER_MODES, SUBMIT_EMPTY_MODES, placeholderForMode } fr
42
42
  import { inputSuggestionsForState } from '../chat/inputSuggestions.js';
43
43
  import { modelThinkingLabel } from '../../utils/modelName.js';
44
44
  import { PROVIDER_ACTIONS, PROVIDER_CHOICES, SERVER_CHOICES } from './wizardActions.js';
45
- import { captureLspName, captureMcpCommand, captureMcpName, captureMcpTransport, captureMcpUrl, captureProviderName, captureProviderUrl } from './wizardPrompts.js';
45
+ import { captureLspName } from './wizardPrompts.js';
46
+ import { transitionMcpField, transitionProviderField } from './wizardTransition.js';
46
47
  import { finishLspCustomResult, selectLspActionResult, selectLspPresetResult, selectLspServerResult } from './lspWizard.js';
47
48
  import { finishMcpCustomResult, selectMcpActionResult, selectMcpPresetResult, selectMcpServerResult, setMcpServerKeyResult } from './mcpWizard.js';
48
49
  import { providerActionResult, providerAppendModels, providerFinishAdd, providerRemove, providerRemoveModels, providerSetKey } from './providerWizard.js';
@@ -97,13 +98,19 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
97
98
  });
98
99
  };
99
100
  const [settings, setSettings] = useState({});
101
+ const [settingsError, setSettingsError] = useState();
100
102
  const conversationRef = useRef([]);
101
103
  const lastAssistantTextRef = useRef('');
102
104
  const abortControllerRef = useRef(null);
103
105
  const sessionRef = useRef(undefined);
106
+ const sessionRecorderRef = useRef(undefined);
107
+ if (!sessionRecorderRef.current)
108
+ sessionRecorderRef.current = createSessionRecorder(() => sessionRef.current);
104
109
  const sessionStartRef = useRef(new Date());
105
110
  const workStateRef = useRef(undefined);
106
111
  const llmLogRef = useRef(undefined);
112
+ const persistenceWarningShownRef = useRef(false);
113
+ const skillErrorSignatureRef = useRef('');
107
114
  const contextFileSignaturesRef = useRef(new Map());
108
115
  const followUpQueueRef = useRef([]);
109
116
  const [inputHistory, setInputHistory] = useState([]);
@@ -152,15 +159,17 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
152
159
  }, [busy]);
153
160
  useEffect(() => {
154
161
  Promise.all([
155
- readSettings().catch(() => ({})),
162
+ readSettings().then(value => ({ value, error: undefined })).catch(error => ({ value: {}, error: error instanceof Error ? error.message : String(error) })),
156
163
  currentBranchName().catch(() => undefined),
157
164
  readContextFiles().catch(() => []),
158
- ]).then(([next, branch, files]) => {
165
+ ]).then(([settingsResult, branch, files]) => {
166
+ const next = settingsResult.value;
159
167
  setSettings(next);
168
+ setSettingsError(settingsResult.error);
160
169
  setBranchName(branch);
161
170
  setContextFiles(files);
162
171
  contextFileSignaturesRef.current = new Map(files.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
163
- setMessages(m => [...m, { role: 'system', text: `${startupProviderInfo(next)}\n\n${startupContextInfo(files)}` }]);
172
+ setMessages(m => [...m, { role: 'system', text: settingsResult.error ? settingsResult.error : `${startupProviderInfo(next)}\n\n${startupContextInfo(files)}` }]);
164
173
  }).catch(() => undefined);
165
174
  initializeSession().catch(error => {
166
175
  const text = error instanceof Error ? error.message : String(error);
@@ -190,6 +199,11 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
190
199
  const registry = await loadSkillRegistry();
191
200
  const nextSkills = [...registry.skills.values()];
192
201
  setSkills(nextSkills);
202
+ const errorSignature = registry.errors.map(error => `${error.directory}: ${error.message}`).join('\n');
203
+ if (errorSignature && errorSignature !== skillErrorSignatureRef.current) {
204
+ setMessages(messages => [...messages, { role: 'system', text: `Invalid skills were isolated:\n${errorSignature}` }]);
205
+ }
206
+ skillErrorSignatureRef.current = errorSignature;
193
207
  return nextSkills;
194
208
  }
195
209
  function skillInvocation(value) {
@@ -208,17 +222,25 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
208
222
  return;
209
223
  setDebugLogs(current => [...current.slice(-7), line]);
210
224
  }
225
+ function showPersistenceWarning(error) {
226
+ if (persistenceWarningShownRef.current)
227
+ return;
228
+ persistenceWarningShownRef.current = true;
229
+ const text = error instanceof Error ? error.message : String(error);
230
+ setMessages(messages => [...messages, { role: 'system', text: `Persistence warning: ${text}` }]);
231
+ }
211
232
  async function startNewLog() {
212
233
  if (!debug)
213
234
  return undefined;
214
235
  if (llmLogRef.current) {
215
- await endLlmLog(llmLogRef.current).catch(() => undefined);
236
+ await endLlmLog(llmLogRef.current).catch(showPersistenceWarning);
216
237
  }
217
238
  const log = await createLlmLog();
218
239
  llmLogRef.current = log;
219
240
  return log;
220
241
  }
221
242
  async function startNewSession(message = 'Started a new session.') {
243
+ await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
222
244
  clearToolOutputs();
223
245
  contextFileSignaturesRef.current = new Map(contextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
224
246
  workStateRef.current = undefined;
@@ -259,7 +281,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
259
281
  }
260
282
  await startNewSession(continueSession ? 'No previous session found. Started a new session.' : 'Started a new session.');
261
283
  }
262
- function clearConversation() {
284
+ async function clearConversation() {
263
285
  clearToolOutputs();
264
286
  conversationRef.current = [];
265
287
  lastAssistantTextRef.current = '';
@@ -267,10 +289,9 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
267
289
  workStateRef.current = undefined;
268
290
  setLiveMessagesState(() => []);
269
291
  setMessages([{ role: 'system', text: 'Cleared. The void is productive.' }]);
270
- void startNewLog();
271
- const session = sessionRef.current;
272
- if (session)
273
- void appendSessionEntry(session, { type: 'event', at: new Date().toISOString(), name: 'clear', text: 'Conversation cleared' }).catch(() => undefined);
292
+ sessionRecorderRef.current?.recordNamedEvent('clear', 'Conversation cleared');
293
+ await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
294
+ await startNewLog().catch(showPersistenceWarning);
274
295
  }
275
296
  function compactConversation(instructions) {
276
297
  const result = compactModelMessages(conversationRef.current, { instructions, tokenBudget: 40_000, workState: workStateRef.current });
@@ -279,15 +300,13 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
279
300
  return false;
280
301
  }
281
302
  conversationRef.current = result.messages;
282
- const session = sessionRef.current;
283
- if (session) {
284
- void appendSessionEntry(session, { type: 'event', at: new Date().toISOString(), name: 'compact', text: `Compacted ${result.olderCount} messages; kept ${result.keptCount}.` }).catch(() => undefined);
285
- void appendSessionEntry(session, { type: 'conversation_snapshot', at: new Date().toISOString(), messages: result.messages }).catch(() => undefined);
286
- }
303
+ sessionRecorderRef.current?.recordNamedEvent('compact', `Compacted ${result.olderCount} messages; kept ${result.keptCount}.`);
304
+ sessionRecorderRef.current?.recordConversation(result.messages);
287
305
  setMessages(m => [...m, { role: 'system', text: `Compacted context: summarized ${result.olderCount} older model messages and kept the last ${result.keptCount}.` }]);
288
306
  return true;
289
307
  }
290
308
  async function resumeLatestSession() {
309
+ await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
291
310
  const session = await latestSession();
292
311
  if (!session) {
293
312
  setMessages(m => [...m, { role: 'system', text: 'No previous session found for this workspace.' }]);
@@ -591,8 +610,8 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
591
610
  setMode(result.mode);
592
611
  showWizardMessage(result.message);
593
612
  }
594
- async function finishMcpCustom(keyValue) {
595
- const result = finishMcpCustomResult(settings, mcpDraft, keyValue);
613
+ async function finishMcpCustom(keyValue, draft = mcpDraft) {
614
+ const result = finishMcpCustomResult(settings, draft, keyValue);
596
615
  if (result.settingsPatch)
597
616
  setSettings(await updateSettings(result.settingsPatch));
598
617
  if (result.clearDraft)
@@ -689,11 +708,56 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
689
708
  }
690
709
  }
691
710
  async function submit(value) {
711
+ if (settingsError) {
712
+ try {
713
+ const repaired = await readSettings();
714
+ setSettings(repaired);
715
+ setSettingsError(undefined);
716
+ }
717
+ catch (error) {
718
+ const message = error instanceof Error ? error.message : String(error);
719
+ setSettingsError(message);
720
+ if (!/^\/(?:settings\s+(?:open|edit)|help|exit|quit)\b/i.test(value.trim())) {
721
+ setMessages(messages => [...messages, { role: 'system', text: `${message}\nRepair settings, then retry. /settings open, /help, and /exit remain available.` }]);
722
+ return;
723
+ }
724
+ }
725
+ }
692
726
  if (busy) {
693
727
  if (mode === 'chat')
694
728
  queueFollowUp(value);
695
729
  return;
696
730
  }
731
+ const providerEffects = transitionProviderField({ mode, value, settings });
732
+ if (providerEffects) {
733
+ for (const effect of providerEffects) {
734
+ if (effect.type === 'message')
735
+ showWizardMessage(effect.text);
736
+ else if (effect.type === 'mode')
737
+ setMode(effect.mode);
738
+ else if (effect.type === 'provider-draft') {
739
+ if (effect.replace)
740
+ setProviderDraft(effect.patch);
741
+ else
742
+ setProviderDraft(draft => ({ ...draft, ...effect.patch }));
743
+ }
744
+ }
745
+ return;
746
+ }
747
+ const mcpEffects = transitionMcpField({ mode, value, settings, draft: mcpDraft });
748
+ if (mcpEffects) {
749
+ for (const effect of mcpEffects) {
750
+ if (effect.type === 'message')
751
+ showWizardMessage(effect.text);
752
+ else if (effect.type === 'mode')
753
+ setMode(effect.mode);
754
+ else if (effect.type === 'mcp-draft')
755
+ setMcpDraft(draft => ({ ...draft, ...effect.patch }));
756
+ else if (effect.type === 'finish-mcp-stdio')
757
+ await finishMcpCustom(undefined, effect.draft);
758
+ }
759
+ return;
760
+ }
697
761
  if (mode === 'skills') {
698
762
  await selectSkill(value);
699
763
  return;
@@ -744,38 +808,6 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
744
808
  await selectModel(value);
745
809
  return;
746
810
  }
747
- if (mode === 'providerAddName') {
748
- const result = captureProviderName(settings, value);
749
- if (result.message) {
750
- showWizardMessage(result.message);
751
- return;
752
- }
753
- if (result.draft)
754
- setProviderDraft({ name: result.draft.name });
755
- if (result.nextMode)
756
- setMode(result.nextMode);
757
- showWizardMessage(result.systemMessage);
758
- return;
759
- }
760
- if (mode === 'providerAddUrl') {
761
- const result = captureProviderUrl(value);
762
- if (result.message) {
763
- showWizardMessage(result.message);
764
- return;
765
- }
766
- if (result.draft)
767
- setProviderDraft(draft => ({ ...draft, ...result.draft }));
768
- if (result.nextMode)
769
- setMode(result.nextMode);
770
- showWizardMessage(result.systemMessage);
771
- return;
772
- }
773
- if (mode === 'providerAddKey') {
774
- setProviderDraft(draft => ({ ...draft, ...(value.trim() ? { key: value.trim() } : {}) }));
775
- setMode('providerAddModels');
776
- setMessages(m => [...m, { role: 'system', text: 'Comma-separated model names? Example: llama3.1, qwen2.5-coder, gpt-4o' }]);
777
- return;
778
- }
779
811
  if (mode === 'providerAddModels') {
780
812
  await finishProviderAdd(value);
781
813
  return;
@@ -899,58 +931,6 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
899
931
  await selectMcpPreset(value);
900
932
  return;
901
933
  }
902
- if (mode === 'mcpAddName') {
903
- const result = captureMcpName(settings, value);
904
- if (result.message) {
905
- showWizardMessage(result.message);
906
- return;
907
- }
908
- if (result.draft)
909
- setMcpDraft({ name: result.draft.name });
910
- if (result.nextMode)
911
- setMode(result.nextMode);
912
- showWizardMessage(result.systemMessage);
913
- return;
914
- }
915
- if (mode === 'mcpAddTransport') {
916
- const result = captureMcpTransport(value);
917
- if (result.message) {
918
- showWizardMessage(result.message);
919
- return;
920
- }
921
- if (result.draft)
922
- setMcpDraft(draft => ({ ...draft, ...result.draft }));
923
- if (result.nextMode)
924
- setMode(result.nextMode);
925
- showWizardMessage(result.systemMessage);
926
- return;
927
- }
928
- if (mode === 'mcpAddUrl') {
929
- const result = captureMcpUrl(value);
930
- if (result.message) {
931
- showWizardMessage(result.message);
932
- return;
933
- }
934
- if (result.draft)
935
- setMcpDraft(draft => ({ ...draft, ...result.draft }));
936
- if (result.nextMode)
937
- setMode(result.nextMode);
938
- showWizardMessage(result.systemMessage);
939
- return;
940
- }
941
- if (mode === 'mcpAddCommand') {
942
- const result = captureMcpCommand(value);
943
- if (result.message) {
944
- showWizardMessage(result.message);
945
- return;
946
- }
947
- if (result.draft)
948
- setMcpDraft(draft => ({ ...draft, ...result.draft }));
949
- if (result.nextMode)
950
- setMode(result.nextMode);
951
- showWizardMessage(result.systemMessage);
952
- return;
953
- }
954
934
  if (mode === 'mcpAddKey') {
955
935
  await finishMcpCustom(value);
956
936
  return;
@@ -1023,8 +1003,12 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
1023
1003
  setMessages(m => [...m, { role: 'system', text: `Command failed: ${text}` }]);
1024
1004
  return;
1025
1005
  }
1026
- if (result === 'exit')
1006
+ if (result === 'exit') {
1007
+ await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
1008
+ if (llmLogRef.current)
1009
+ await endLlmLog(llmLogRef.current).catch(showPersistenceWarning);
1027
1010
  return exit();
1011
+ }
1028
1012
  if (result === 'handled') {
1029
1013
  if (value === '/clear') {
1030
1014
  loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
@@ -1054,7 +1038,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
1054
1038
  }
1055
1039
  }
1056
1040
  async function runSingleAgentTurn(value, displayValue) {
1057
- const sessionRecorder = createSessionRecorder(() => sessionRef.current);
1041
+ const sessionRecorder = sessionRecorderRef.current;
1058
1042
  const finalizeMessage = (msg) => {
1059
1043
  if (msg.hidden)
1060
1044
  return;
@@ -1111,6 +1095,8 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
1111
1095
  contextFileSignatures: contextFileSignaturesRef.current,
1112
1096
  log: llmLogRef.current,
1113
1097
  }, 0, false, false, { start: sessionStartRef.current, cwd: process.cwd() });
1098
+ await sessionRecorder.flush().catch(showPersistenceWarning);
1099
+ await llmLogRef.current?.writer?.flush().catch(showPersistenceWarning);
1114
1100
  }
1115
1101
  const visible = messages.filter(message => !message.hidden);
1116
1102
  const activeLiveMessages = liveMessages.filter(message => !message.hidden);
@@ -7,7 +7,7 @@ export type CommandContext = {
7
7
  setMode: (mode: Mode) => void;
8
8
  setModelProviderFilter?: (providerName: string | undefined) => void;
9
9
  addSystemMessage: (text: string) => void;
10
- clearConversation: () => void;
10
+ clearConversation: () => void | Promise<void>;
11
11
  newSession?: () => Promise<void>;
12
12
  resumeSession?: () => Promise<void>;
13
13
  sessionInfo?: () => string;
@@ -45,7 +45,7 @@ const SLASH_COMMANDS = [
45
45
  ctx.compactConversation(args || undefined);
46
46
  else
47
47
  ctx.addSystemMessage('Compaction is unavailable.'); return HANDLED; } },
48
- { match: exact('/clear'), run: async (_args, ctx) => { ctx.clearConversation(); await clearTasks(); ctx.addSystemMessage('Cleared. The void is productive.'); return HANDLED; } },
48
+ { match: exact('/clear'), run: async (_args, ctx) => { await ctx.clearConversation(); await clearTasks(); ctx.addSystemMessage('Cleared. The void is productive.'); return HANDLED; } },
49
49
  { match: exactOrArgs('/logs'), run: async (args, ctx) => await handleLogsCommand(args, ctx) },
50
50
  { match: exactOrArgs('/lsp'), run: (_args, ctx) => { ctx.setMode('lsp'); ctx.addSystemMessage('Choose an LSP server to enable, disable, or remove it. Choose "add server" to add one from presets (e.g. typescript) or enter a custom command.'); return HANDLED; } },
51
51
  { match: exactOrArgs('/mcp'), run: (_args, ctx) => { ctx.setMode('mcp'); ctx.addSystemMessage('Choose an MCP server to enable, disable, remove, or set a key for it. Choose "add server" to add one from presets (e.g. context7) or enter custom details.'); return HANDLED; } },
@@ -59,14 +59,14 @@ export function toolCallSummary(toolName, input) {
59
59
  return `${toolName} ${compact(input)}`;
60
60
  }
61
61
  export function toolResultSummary(event) {
62
- if (!event.success)
63
- return `failed: ${compact(event.error)}`;
64
62
  const output = event.output;
63
+ if (!event.success)
64
+ return `failed: ${compact(event.error ?? output?.error ?? event.output)}`;
65
65
  if (output?.duplicateSkipped === true)
66
66
  return 'skipped duplicate';
67
67
  if (typeof output?.totalMatches === 'number') {
68
68
  const count = output.totalMatches;
69
- return count === 0 ? 'no matches' : `${count} match${count === 1 ? '' : 'es'}`;
69
+ return count === 0 ? 'no matches' : `${output.matchCountIsLowerBound === true ? 'at least ' : ''}${count} match${count === 1 ? '' : 'es'}`;
70
70
  }
71
71
  if (typeof output?.validationSummary === 'object' && output.validationSummary != null && 'summaryText' in output.validationSummary) {
72
72
  const summary = output.validationSummary;
@@ -1,4 +1,4 @@
1
- import { listLogs, readLogEntries } from '../../core/log/llmLog.js';
1
+ import { listLogs, summarizeLog } from '../../core/log/llmLog.js';
2
2
  function formatBytes(bytes) {
3
3
  if (bytes < 1024)
4
4
  return `${bytes} B`;
@@ -21,39 +21,25 @@ export async function handleLogsCommand(args, ctx) {
21
21
  ctx.addSystemMessage(['Recent logs:', ' ID Size Modified', ...lines].join('\n'));
22
22
  return 'handled';
23
23
  }
24
- const entries = await readLogEntries(id);
25
- if (entries.length === 0) {
24
+ const summary = await summarizeLog(id);
25
+ if (!summary) {
26
26
  ctx.addSystemMessage(`No log found with id ${id}.`);
27
27
  return 'handled';
28
28
  }
29
- const typeCounts = {};
30
- let totalInput = 0;
31
- let totalOutput = 0;
32
- const toolCallCounts = {};
33
- for (const entry of entries) {
34
- typeCounts[entry.type] = (typeCounts[entry.type] ?? 0) + 1;
35
- if (entry.usage) {
36
- totalInput += entry.usage.inputTokens ?? 0;
37
- totalOutput += entry.usage.outputTokens ?? 0;
38
- }
39
- if (entry.type === 'tool_call' && entry.toolCall) {
40
- toolCallCounts[entry.toolCall.name] = (toolCallCounts[entry.toolCall.name] ?? 0) + 1;
41
- }
42
- }
43
- const typeLines = Object.entries(typeCounts)
29
+ const typeLines = Object.entries(summary.typeCounts)
44
30
  .sort(([a], [b]) => a.localeCompare(b))
45
31
  .map(([type, count]) => ` ${type}: ${count}`);
46
- const toolLines = Object.entries(toolCallCounts)
32
+ const toolLines = Object.entries(summary.toolCallCounts)
47
33
  .sort(([, a], [, b]) => b - a)
48
34
  .map(([name, count]) => ` ${name}: ${count}`);
49
35
  const parts = [
50
36
  `Log: ${id}`,
51
- `Entries: ${entries.length}`,
37
+ `Entries: ${summary.entries}`,
52
38
  '',
53
39
  'Entry counts by type:',
54
40
  ...typeLines,
55
41
  '',
56
- `Total token usage: in=${totalInput} out=${totalOutput}`,
42
+ `Total token usage: in=${summary.totalInput} out=${summary.totalOutput}`,
57
43
  ];
58
44
  if (toolLines.length > 0) {
59
45
  parts.push('', 'Tool call counts:', ...toolLines);