@denizokcu/haze 0.3.0 → 0.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 (42) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +31 -19
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +144 -52
  5. package/dist/cli/commands/commands.js +105 -114
  6. package/dist/cli/commands/streaming.d.ts +33 -5
  7. package/dist/cli/commands/streaming.js +235 -103
  8. package/dist/cli/contextReport.d.ts +1 -0
  9. package/dist/cli/contextReport.js +47 -0
  10. package/dist/config/contextFiles.d.ts +25 -0
  11. package/dist/config/contextFiles.js +53 -0
  12. package/dist/core/agent/compaction.d.ts +3 -0
  13. package/dist/core/agent/compaction.js +23 -3
  14. package/dist/core/agent/contextBudget.d.ts +33 -0
  15. package/dist/core/agent/contextBudget.js +88 -0
  16. package/dist/core/agent/requestAssembly.d.ts +22 -0
  17. package/dist/core/agent/requestAssembly.js +146 -0
  18. package/dist/core/agent/toolOutputStore.d.ts +11 -0
  19. package/dist/core/agent/toolOutputStore.js +33 -0
  20. package/dist/core/agent/workState.d.ts +38 -0
  21. package/dist/core/agent/workState.js +89 -0
  22. package/dist/core/goal/completionPolicy.js +1 -1
  23. package/dist/core/goal/sessionGoal.d.ts +2 -0
  24. package/dist/core/goal/sessionGoal.js +8 -1
  25. package/dist/core/log/llmLog.d.ts +68 -0
  26. package/dist/core/log/llmLog.js +55 -0
  27. package/dist/core/session/sessionStore.d.ts +6 -0
  28. package/dist/core/session/sessionStore.js +5 -0
  29. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  30. package/dist/core/subagent/subagentRunner.js +5 -15
  31. package/dist/core/validation/outputParser.js +15 -2
  32. package/dist/llm/client.d.ts +39 -0
  33. package/dist/llm/client.js +46 -2
  34. package/dist/llm/hazeTools.d.ts +37 -12
  35. package/dist/llm/hazeTools.js +133 -55
  36. package/dist/llm/systemPrompt.d.ts +6 -1
  37. package/dist/llm/systemPrompt.js +42 -81
  38. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  39. package/dist/skills/builder/SkillBuilder.js +68 -65
  40. package/dist/skills/skillTools.d.ts +2 -19
  41. package/dist/skills/skillTools.js +28 -19
  42. package/package.json +2 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,40 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.4.0 - 2026-06-15
6
+
7
+ ### Skills
8
+
9
+ - Replaced single-shot `/create-skill <description>` with a 3-step interactive wizard: name → optional role → description. The user-supplied name and role are used verbatim — the model no longer renames them.
10
+ - Added language-agnostic intent extraction. Skill descriptions are interpreted by the model in any language, replacing the previous English-only regex strip. `"crée une compétence qui vérifie le style du code"` now produces a skill that vérifies code style, not a skill about creating something.
11
+ - Added `toSkillDirName` for kebab-casing user-typed skill names without stop-word stripping (so `"create a skill"` stays `create-a-skill`, not `skill`).
12
+
13
+ ### Commands
14
+
15
+ - Removed the `/tasks` slash command. Tasks are now managed exclusively by the model via the `writeTasks` tool — `/clear` still wipes them as a side effect of clearing the conversation.
16
+ - Removed the `/list-skills` alias; `/skills` now shows the overview and the installed list.
17
+ - Removed the `/skill <subcommand>` and `/skills <subcommand>` legacy routing forms. Each skill operation now has exactly one user-facing form: `/skills`, `/create-skill`, `/skill-info`, `/validate-skill`, `/remove-skill`.
18
+ - Removed the `/tasks rm` alias for `/tasks remove`.
19
+ - Refactored `handleSkillCommand` from stringly-typed `value` parsing to a typed `SkillSubcommand` union argument.
20
+
21
+ ### Docs site
22
+
23
+ - Added §02 "Native skill creation" segment that frames the 3-step wizard as the haze superpower, with a live transcript of the wizard prompts, superpower bullets, and copy-pasteable recipe cards for `/code-review`, `/deploy-check`, `/release-prep`, `/security-review`.
24
+ - Added §07 "Commands index" — a categorized reference of all 16 slash commands plus the `/<skill-name>` dynamic invocations.
25
+ - Removed §04 "Serviceable procedures" (folded into §02).
26
+ - Renumbered sections sequentially (§01 Operation → §02 Native skill creation → §03 Field behavior → §04 Components → §05 Compatibility → §06 Install → §07 Commands index).
27
+ - Fixed §01 layout: switched from `.container-prose` (narrow, visually centered) to `.container` so it aligns with every other section.
28
+ - Updated all `/create-skill <description>` references to reflect the wizard.
29
+
30
+ ### Internal
31
+
32
+ - Added request-level context accounting, cache/no-cache usage metrics, a debug token breakdown, and an offline `context:report` command.
33
+ - Bounded `readFile`, structured and globally capped `grep`, and compacted large bash output behind paginated `readToolOutput` handles.
34
+ - Added structured `WorkState` snapshots, token-aware compaction, conservative old-tool-result pruning, bounded continuation slices, and no-progress termination for long agent workflows.
35
+ - Made Haze control nudges ephemeral, omitted tool schemas from text-only follow-ups, and replaced duplicated subagent prompting with a concise dedicated prompt.
36
+ - Consolidated installed workflows into one progressive `skill` catalog tool and added provider capability-gated cache keys, sticky session hints, and low-verbosity options.
37
+ - Shortened the model operating contract and final-response guidance while preserving edit recovery, validation evidence, and blocked/partial reporting.
38
+
5
39
  ## 0.3.0 - 2026-06-10
6
40
 
7
41
  - Redesigned docs site with cleaner layout, improved typography, better mobile responsiveness, scroll-reveal animations, skip-link accessibility, and refreshed content structure.
package/README.md CHANGED
@@ -2,16 +2,19 @@
2
2
 
3
3
  A minimal LLM harness for your terminal.
4
4
 
5
- ## What's new in 0.3.0
5
+ ## What's new in 0.4.0
6
6
 
7
- Haze 0.3.0 polishes the experience around sessions and the docs site.
7
+ Haze 0.4.0 reworks skill creation and simplifies the command surface.
8
8
 
9
- - The docs site has been redesigned with a cleaner layout, improved typography, better mobile responsiveness, scroll-reveal animations, and accessibility improvements.
10
- - The task bar now appears above the activity spinner so in-progress and pending tasks are always visible during active agent turns.
11
- - Tasks are automatically cleared when starting or exiting a session, preventing stale task state from leaking across conversations.
9
+ - **3-step skill wizard.** `/create-skill` is now an interactive wizard: name the skill, optionally give it a role, then describe what it does. The model writes the Markdown body. Your typed name and role are used verbatim — no LLM rename.
10
+ - **Language-agnostic intent extraction.** Skill descriptions are interpreted by the model in any language. `"crée une compétence qui vérifie le style du code"` produces a skill that vérifies code style, not a skill about creating one.
11
+ - **Tasks are model-managed.** The `/tasks` slash command is gone. The model tracks multi-step work via the `writeTasks` tool — you talk, it plans. `/clear` still wipes tasks as part of clearing the conversation.
12
+ - **Leaner command surface.** Removed `/list-skills` (folded into `/skills`), the `/skill X` legacy subcommand forms, and the `/tasks rm` alias. Each operation now has exactly one way to be invoked.
13
+ - **Docs site additions.** New §02 segment frames skill creation as the native superpower with copy-pasteable recipe cards; new §07 commands index lists all 16 commands grouped by category. §04 "Serviceable procedures" was removed and sections renumbered sequentially.
12
14
 
13
15
  Previous releases:
14
16
 
17
+ - **0.3.0** — Docs site redesign, task bar moves above the activity spinner, tasks auto-clear between sessions.
15
18
  - **0.2.0** — Reliability release: stronger continuation after failed edits and validation, structured bash classification, parsed validation summaries, multi-line chat input with vertical cursor movement.
16
19
  - **0.1.0** — Bundled ripgrep, subagent delegation, inline diff display.
17
20
  - **0.0.3** — Durable sessions, context compaction, provider management.
@@ -72,7 +75,7 @@ export HAZE_MODEL=anthropic/claude-sonnet-4.6 # or gpt-4.1, llama3.1, qwen2.5-co
72
75
 
73
76
  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.
74
77
 
75
- 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 `/create-skill <description>`. 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.
78
+ 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 `/create-skill` (a 3-step wizard: name, role, description). 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.
76
79
 
77
80
  ## Get productive immediately
78
81
 
@@ -90,9 +93,10 @@ Useful starters:
90
93
 
91
94
  ```txt
92
95
  /init
93
- /create-skill review my current branch against main like a senior engineer
94
- /create-skill prepare clean git commits from my uncommitted changes
95
- /create-skill implement small features with tests and a concise summary
96
+ /create-skill # then the wizard asks for name, role, and a description like:
97
+ # "review my current branch against main like a senior engineer"
98
+ # "prepare clean git commits from my uncommitted changes"
99
+ # "implement small features with tests and a concise summary"
96
100
  ```
97
101
 
98
102
  `/init` creates or updates `AGENTS.md` so future sessions understand the project.
@@ -104,7 +108,9 @@ Skills are Markdown workflows that Haze creates with `/create-skill` and stores
104
108
  If you do something for the second time, build a skill for it:
105
109
 
106
110
  ```txt
107
- /create-skill review the diff between my current branch and main, focusing on bugs, tests, DRY and KISS
111
+ /create-skill
112
+ # Wizard: name=branch-diff-review, role="Senior engineer reviewing diffs",
113
+ # description="review the diff between my current branch and main, focusing on bugs, tests, DRY and KISS"
108
114
  ```
109
115
 
110
116
  Haze uses the model to create the skill file for you:
@@ -151,7 +157,7 @@ Installed skills appear as slash commands like:
151
157
  /code-review-diff-main
152
158
  ```
153
159
 
154
- They are also exposed to the model as `skill_*` tools. The skill does not execute code; it gives Haze a workflow to follow.
160
+ They are also available through one `skill` catalog tool. Haze loads one workflow body first and fetches large references only when needed. Skills provide instructions; they do not execute code.
155
161
 
156
162
  This is the trick: do normal work, notice friction, create a skill, keep going. Your workflow adapts instead of asking you to adapt to the tool. Rude, but in a good way.
157
163
 
@@ -172,8 +178,7 @@ This is the trick: do normal work, notice friction, create a skill, keep going.
172
178
  /clear
173
179
  /exit
174
180
 
175
- /create-skill <description>
176
- /list-skills
181
+ /create-skill
177
182
  /skill-info <name>
178
183
  /validate-skill <name-or-dir>
179
184
  /remove-skill <name> --yes
@@ -194,15 +199,17 @@ haze --no-session # run without durable session storage
194
199
  Haze exposes a deliberately small toolset:
195
200
 
196
201
  - `listFiles` — structured discovery, recursive with cursor pagination when needed.
197
- - `readFile` — read UTF-8 files with optional line ranges.
198
- - `grep` — ripgrep-backed regex search with path, glob, context-line, case, and result-limit controls.
202
+ - `readFile` — read numbered UTF-8 lines in bounded pages, with `nextOffset` when more remain.
203
+ - `grep` — structured ripgrep search with a true global result cap.
199
204
  - `editFile` — unique text replacements, with line-number-prefix tolerance for common model mistakes.
200
205
  - `replaceLines` — line-range edits when exact replacements are awkward; slightly-too-large EOF ranges are clamped.
201
206
  - `writeFile` — create files and parent directories.
202
- - `bash` — run tests, builds, git commands, inspections, scripts, installs, and other shell workflows with command classification metadata.
203
- - `skill_*` — load Markdown skill instructions on demand.
207
+ - `bash` — run tests, builds, git commands, inspections, scripts, installs, and other shell workflows with compact validation output.
208
+ - `readToolOutput` — page through full output omitted from an oversized tool result.
209
+ - `writeTasks` — replace the task list at meaningful phase changes.
210
+ - `skill` — load one installed Markdown workflow or one of its references.
204
211
 
205
- Tool calls are grouped in the transcript so you can see what happened without reading a novella. Successful targeted file edits show a compact diff with colored additions/removals and one context line around the change when the diff is small; larger diffs are summarized with a pointer to `git diff`. File-tool failures return structured reason codes and recovery hints instead of mystery stack traces. Bash validation commands can return parsed summaries with failed files, failed tests, diagnostics, and suggested next steps.
212
+ Tool calls are grouped in the transcript so you can see what happened without reading a novella. Successful targeted file edits show a compact diff with colored additions/removals and one context line around the change when the diff is small; larger diffs are summarized with a pointer to `git diff`. File-tool failures return structured reason codes and recovery hints. Large bash output is kept behind an in-memory handle so later model calls carry only a bounded head/tail or validation summary.
206
213
 
207
214
  ## Subagents
208
215
 
@@ -212,7 +219,9 @@ Use them for parallel investigation across separate areas of a codebase. Do not
212
219
 
213
220
  ## Context files
214
221
 
215
- 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 while keeping recent messages.
222
+ 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.
223
+
224
+ Long turns use bounded tool slices. Older successful tool results are compacted while failures and recent evidence remain verbatim, synthetic Haze control nudges are not persisted as user requests, and token-pressure compaction preserves the structured work state.
216
225
 
217
226
  Haze loads project instructions from:
218
227
 
@@ -241,8 +250,11 @@ npm run typecheck
241
250
  npm test
242
251
  npm run lint
243
252
  npm run build
253
+ npm run context:report
244
254
  ```
245
255
 
256
+ `npm run context:report` prints estimated system, project-context, and tool-schema tokens without reading `~/.haze`. Pass explicit context-file paths, or use `npm run context:report -- --trace tests/fixtures/agent-traces/long-workflow.json` for offline trace accounting.
257
+
246
258
  Package check:
247
259
 
248
260
  ```bash
@@ -1,4 +1,4 @@
1
- export type Mode = 'chat' | 'provider' | 'providerAction' | 'model' | 'providerAddPreset' | 'providerAddName' | 'providerAddUrl' | 'providerAddKey' | 'providerAddModels' | 'providerAppendModels' | 'providerSetKey' | 'providerRemoveModels' | 'providerConfirmRemove';
1
+ export type Mode = 'chat' | 'provider' | 'providerAction' | 'model' | 'providerAddPreset' | 'providerAddName' | 'providerAddUrl' | 'providerAddKey' | 'providerAddModels' | 'providerAppendModels' | 'providerSetKey' | 'providerRemoveModels' | 'providerConfirmRemove' | 'skillCreateName' | 'skillCreateRole' | 'skillCreateDescription';
2
2
  interface ChatOptions {
3
3
  debug?: boolean;
4
4
  version?: string;
@@ -15,13 +15,16 @@ import { MarkdownText } from '../../ui/components/MarkdownText.js';
15
15
  import { theme } from '../../ui/theme.js';
16
16
  import { handleSlashCommand } from './commands.js';
17
17
  import { runAgentTurn } from './streaming.js';
18
+ import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
18
19
  import { formatElapsedTime, formatElapsedTimeWhole } from './formatters.js';
19
20
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
21
+ import { createSkill, toSkillDirName } from '../../skills/builder/SkillBuilder.js';
20
22
  import { PROVIDER_PRESETS, findPreset } from '../../config/providerPresets.js';
21
- import { appendSessionEntry, createSession, formatSession, latestSession, restoreConversation } from '../../core/session/sessionStore.js';
23
+ import { appendSessionEntry, createSession, formatSession, latestSession, restoreConversation, restoreWorkState } from '../../core/session/sessionStore.js';
22
24
  import { compactModelMessages, modelMessageText } from '../../core/agent/compaction.js';
23
- import { createSessionGoal, formatGoalStatus } from '../../core/goal/sessionGoal.js';
25
+ import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
24
26
  const execFile = promisify(execFileCallback);
27
+ const EMPTY_TOKEN_USAGE = { inputTokens: undefined, outputTokens: undefined, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: 0, reasoningTokens: 0, logicalInputEstimate: 0, effectiveNonCachedInput: undefined };
25
28
  async function currentBranchName() {
26
29
  try {
27
30
  const { stdout } = await execFile('git', ['branch', '--show-current'], { cwd: process.cwd() });
@@ -202,6 +205,9 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
202
205
  const lastAssistantTextRef = useRef('');
203
206
  const abortControllerRef = useRef(null);
204
207
  const sessionRef = useRef(undefined);
208
+ const sessionStartRef = useRef(new Date());
209
+ const workStateRef = useRef(undefined);
210
+ const llmLogRef = useRef(undefined);
205
211
  const followUpQueueRef = useRef([]);
206
212
  const [inputHistory, setInputHistory] = useState([]);
207
213
  const [debugLogs, setDebugLogs] = useState([]);
@@ -214,7 +220,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
214
220
  const [tasksExpanded, setTasksExpanded] = useState(false);
215
221
  const [taskBarPadding, setTaskBarPadding] = useState(0);
216
222
  const [, setSessionLabel] = useState();
217
- const [llmTokenEstimate, setLlmTokenEstimate] = useState({ input: 0, output: 0 });
223
+ const [tokenUsage, setTokenUsage] = useState({ ...EMPTY_TOKEN_USAGE });
218
224
  const [, setTimerTick] = useState(0);
219
225
  const [queuedFollowUps, setQueuedFollowUps] = useState([]);
220
226
  const [skills, setSkills] = useState([]);
@@ -222,6 +228,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
222
228
  const [modelProviderFilter, setModelProviderFilter] = useState();
223
229
  const [selectedProviderName, setSelectedProviderName] = useState();
224
230
  const [providerDraft, setProviderDraft] = useState({});
231
+ const [skillCreateDraft, setSkillCreateDraft] = useState({});
225
232
  useEffect(() => {
226
233
  const timer = setInterval(() => setTimerTick(tick => tick + 1), 1000);
227
234
  return () => clearInterval(timer);
@@ -275,7 +282,18 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
275
282
  return;
276
283
  setDebugLogs(current => [...current.slice(-7), line]);
277
284
  }
285
+ async function startNewLog() {
286
+ if (llmLogRef.current) {
287
+ await endLlmLog(llmLogRef.current).catch(() => undefined);
288
+ }
289
+ const log = await createLlmLog();
290
+ llmLogRef.current = log;
291
+ return log;
292
+ }
278
293
  async function startNewSession(message = 'Started a new session.') {
294
+ clearToolOutputs();
295
+ workStateRef.current = undefined;
296
+ sessionStartRef.current = new Date();
279
297
  if (noSession) {
280
298
  sessionRef.current = undefined;
281
299
  setSessionLabel('session off');
@@ -283,7 +301,8 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
283
301
  }
284
302
  const session = await createSession({ hazeVersion: version });
285
303
  sessionRef.current = session;
286
- setLlmTokenEstimate({ input: 0, output: 0 });
304
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE });
305
+ await startNewLog();
287
306
  setSessionLabel(session.id);
288
307
  setMessages(m => [...m, { role: 'system', text: `${message}\nSession saved: ${session.file}` }]);
289
308
  }
@@ -297,29 +316,35 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
297
316
  if (session) {
298
317
  const conversation = await restoreConversation(session);
299
318
  sessionRef.current = session;
319
+ sessionStartRef.current = new Date();
300
320
  conversationRef.current = conversation;
301
321
  setSessionLabel(session.id);
302
322
  setLiveMessagesState(() => []);
303
323
  const restoredMessages = displayMessagesFromConversation(conversation);
304
- setLlmTokenEstimate(estimateConversationTokens(restoredMessages));
324
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE, messages: estimateConversationTokens(restoredMessages).input, outputEstimate: estimateConversationTokens(restoredMessages).output });
325
+ workStateRef.current = await restoreWorkState(session);
305
326
  setMessages(m => [...m, { role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...restoredMessages]);
327
+ await startNewLog();
306
328
  return;
307
329
  }
308
330
  }
309
331
  await startNewSession(continueSession ? 'No previous session found. Started a new session.' : 'Started a new session.');
310
332
  }
311
333
  function clearConversation() {
334
+ clearToolOutputs();
312
335
  conversationRef.current = [];
313
336
  lastAssistantTextRef.current = '';
314
- setLlmTokenEstimate({ input: 0, output: 0 });
337
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE });
338
+ workStateRef.current = undefined;
315
339
  setLiveMessagesState(() => []);
316
340
  setMessages([{ role: 'system', text: 'Cleared. The void is productive.' }]);
341
+ void startNewLog();
317
342
  const session = sessionRef.current;
318
343
  if (session)
319
344
  void appendSessionEntry(session, { type: 'event', at: new Date().toISOString(), name: 'clear', text: 'Conversation cleared' }).catch(() => undefined);
320
345
  }
321
346
  function compactConversation(instructions) {
322
- const result = compactModelMessages(conversationRef.current, { instructions });
347
+ const result = compactModelMessages(conversationRef.current, { instructions, tokenBudget: 40_000, workState: workStateRef.current });
323
348
  if (!result.compacted) {
324
349
  setMessages(m => [...m, { role: 'system', text: `Compaction skipped: only ${result.keptCount} model messages in context.` }]);
325
350
  return false;
@@ -340,9 +365,12 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
340
365
  return;
341
366
  }
342
367
  const conversation = await restoreConversation(session);
368
+ clearToolOutputs();
343
369
  sessionRef.current = session;
344
370
  conversationRef.current = conversation;
371
+ workStateRef.current = await restoreWorkState(session);
345
372
  setSessionLabel(session.id);
373
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE });
346
374
  setLiveMessagesState(() => []);
347
375
  setMessages([{ role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...displayMessagesFromConversation(conversation)]);
348
376
  }
@@ -371,6 +399,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
371
399
  setModelProviderFilter(undefined);
372
400
  setSelectedProviderName(undefined);
373
401
  setProviderDraft({});
402
+ setSkillCreateDraft({});
374
403
  }
375
404
  }
376
405
  function providerSuggestions() {
@@ -579,12 +608,76 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
579
608
  setMode('model');
580
609
  setMessages(m => [...m, { role: 'system', text: `Added provider ${provider.name}. Choose a model.` }]);
581
610
  }
611
+ async function captureSkillName(value) {
612
+ const dirName = toSkillDirName(value);
613
+ if (!dirName) {
614
+ setMessages(m => [...m, { role: 'system', text: 'Skill name must contain at least one letter or number. Try again, or press ESC to cancel.' }]);
615
+ return;
616
+ }
617
+ const registry = await loadSkillRegistry();
618
+ if (registry.skills.has(dirName)) {
619
+ setMessages(m => [...m, { role: 'system', text: `A skill named "${dirName}" already exists. Pick another name, or press ESC to cancel.` }]);
620
+ return;
621
+ }
622
+ setSkillCreateDraft(d => ({ ...d, name: dirName }));
623
+ setMode('skillCreateRole');
624
+ setMessages(m => [...m, { role: 'system', text: `Skill wizard — step 2/3: Role for "${dirName}". Describe who the skill should be (optional — press Enter to skip, ESC to cancel).` }]);
625
+ }
626
+ function captureSkillRole(value) {
627
+ const role = value.trim();
628
+ setSkillCreateDraft(d => ({ ...d, ...(role ? { role } : {}) }));
629
+ setMode('skillCreateDescription');
630
+ setMessages(m => [...m, { role: 'system', text: `Skill wizard — step 3/3: Describe what the skill should do. This is the work the LLM will expand into the skill body.` }]);
631
+ }
632
+ async function captureSkillDescription(value) {
633
+ const description = value.trim();
634
+ if (!description) {
635
+ setMessages(m => [...m, { role: 'system', text: 'Description is required. Try again, or press ESC to cancel.' }]);
636
+ return;
637
+ }
638
+ const name = skillCreateDraft.name;
639
+ if (!name) {
640
+ setMode('chat');
641
+ setSkillCreateDraft({});
642
+ setMessages(m => [...m, { role: 'system', text: 'Skill wizard lost the name. Start over with /create-skill.' }]);
643
+ return;
644
+ }
645
+ setMode('chat');
646
+ setBusyLabel('Creating skill');
647
+ setBusy(true);
648
+ try {
649
+ const result = await createSkill({ name, role: skillCreateDraft.role, description });
650
+ setMessages(m => [...m, { role: 'system', text: `Created skill ${result.name} at ${result.file}. Invoke it with /${result.name}. Edit SKILL.md to refine its workflow.` }]);
651
+ await refreshSkills();
652
+ }
653
+ catch (error) {
654
+ const text = error instanceof Error ? error.message : String(error);
655
+ setMessages(m => [...m, { role: 'system', text: `Skill creation failed: ${text}` }]);
656
+ }
657
+ finally {
658
+ setSkillCreateDraft({});
659
+ setBusy(false);
660
+ setBusyLabel('Haze is thinking');
661
+ }
662
+ }
582
663
  async function submit(value) {
583
664
  if (busy) {
584
665
  if (mode === 'chat')
585
666
  queueFollowUp(value);
586
667
  return;
587
668
  }
669
+ if (mode === 'skillCreateName') {
670
+ await captureSkillName(value);
671
+ return;
672
+ }
673
+ if (mode === 'skillCreateRole') {
674
+ captureSkillRole(value);
675
+ return;
676
+ }
677
+ if (mode === 'skillCreateDescription') {
678
+ await captureSkillDescription(value);
679
+ return;
680
+ }
588
681
  if (mode === 'provider') {
589
682
  await selectProvider(value);
590
683
  return;
@@ -727,19 +820,9 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
727
820
  const invokedSkill = skillInvocation(value);
728
821
  if (invokedSkill) {
729
822
  const argumentText = invokedSkill.args ? `\nUser-provided skill arguments: ${invokedSkill.args}` : '';
730
- await doAgentTurn(`The user explicitly invoked the "${invokedSkill.skill.name}" skill. Call skill_${invokedSkill.skill.name.replace(/[^a-zA-Z0-9_]/g, '_')} and follow its returned instructions.${argumentText}`, value);
823
+ await doAgentTurn(`The user explicitly invoked the "${invokedSkill.skill.name}" skill. Call skill with name="${invokedSkill.skill.name}" and follow its returned instructions.${argumentText}`, value);
731
824
  return;
732
825
  }
733
- const isSkillCreate = /^\/create-skill(?:\s|$)/.test(value) || /^\/skills? create(?:\s|$)/.test(value);
734
- const skillCreateGoal = isSkillCreate ? createSessionGoal(value) : undefined;
735
- if (skillCreateGoal) {
736
- setDebugLogs([]);
737
- setMessages(m => [...m, { role: 'user', text: value }]);
738
- const session = sessionRef.current;
739
- if (session)
740
- void appendSessionEntry(session, { type: 'ui_message', at: new Date().toISOString(), role: 'user', text: value }).catch(() => undefined);
741
- setActiveGoalStatus(formatGoalStatus(skillCreateGoal));
742
- }
743
826
  const ctx = {
744
827
  settings,
745
828
  contextFiles,
@@ -766,41 +849,21 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
766
849
  },
767
850
  };
768
851
  let result;
769
- if (isSkillCreate) {
770
- setBusyLabel('Creating skill');
771
- setBusy(true);
772
- }
773
852
  try {
774
853
  result = await handleSlashCommand(value, ctx);
775
854
  }
776
855
  catch (error) {
777
- if (skillCreateGoal) {
778
- skillCreateGoal.status = 'blocked';
779
- skillCreateGoal.blocker = error instanceof Error ? error.message : String(error);
780
- setActiveGoalStatus(formatGoalStatus(skillCreateGoal));
781
- }
782
856
  const text = error instanceof Error ? error.message : String(error);
783
- setMessages(m => [...m, { role: 'system', text: `Skill creation failed: ${text}` }]);
857
+ setMessages(m => [...m, { role: 'system', text: `Command failed: ${text}` }]);
784
858
  return;
785
859
  }
786
- finally {
787
- if (isSkillCreate) {
788
- if (skillCreateGoal?.status === 'active') {
789
- skillCreateGoal.phase = 'done';
790
- skillCreateGoal.status = 'complete';
791
- setActiveGoalStatus(undefined);
792
- }
793
- setBusy(false);
794
- setBusyLabel('Haze is thinking');
795
- }
796
- }
797
860
  if (result === 'exit')
798
861
  return exit();
799
862
  if (result === 'handled') {
800
- if (value === '/create-skill' || value.startsWith('/create-skill ') || value === '/skill create' || value.startsWith('/skill create ') || value === '/skills create' || value.startsWith('/skills create ') || value.startsWith('/remove-skill ') || value.startsWith('/skill remove ') || value.startsWith('/skills remove ')) {
863
+ if (value.startsWith('/remove-skill ')) {
801
864
  await refreshSkills().catch(() => undefined);
802
865
  }
803
- if (value.startsWith('/tasks') || value === '/clear') {
866
+ if (value === '/clear') {
804
867
  loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
805
868
  }
806
869
  return;
@@ -866,9 +929,28 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
866
929
  setLastAssistantText: text => { lastAssistantTextRef.current = text; },
867
930
  setAbortController: controller => { abortControllerRef.current = controller; },
868
931
  setGoalStatus: setActiveGoalStatus,
932
+ setWorkState: state => {
933
+ workStateRef.current = state;
934
+ const session = sessionRef.current;
935
+ if (session)
936
+ void appendSessionEntry(session, { type: 'work_state_snapshot', at: new Date().toISOString(), state }).catch(() => undefined);
937
+ },
869
938
  compactConversation,
870
- recordTokenEstimate: tokens => {
871
- setLlmTokenEstimate(current => ({ input: current.input + tokens.input, output: current.output + tokens.output }));
939
+ recordTokenUsage: usage => {
940
+ setTokenUsage(current => ({
941
+ inputTokens: (current.inputTokens ?? 0) + (usage.inputTokens ?? 0) || usage.inputTokens,
942
+ outputTokens: (current.outputTokens ?? 0) + (usage.outputTokens ?? 0) || usage.outputTokens,
943
+ systemPrompt: current.systemPrompt + usage.systemPrompt,
944
+ messages: current.messages + usage.messages,
945
+ toolSchemas: current.toolSchemas + usage.toolSchemas,
946
+ outputEstimate: current.outputEstimate + usage.outputEstimate,
947
+ cacheReadTokens: current.cacheReadTokens + usage.cacheReadTokens,
948
+ cacheWriteTokens: current.cacheWriteTokens + usage.cacheWriteTokens,
949
+ noCacheTokens: current.noCacheTokens + usage.noCacheTokens,
950
+ reasoningTokens: current.reasoningTokens + usage.reasoningTokens,
951
+ logicalInputEstimate: current.logicalInputEstimate + usage.logicalInputEstimate,
952
+ effectiveNonCachedInput: (current.effectiveNonCachedInput ?? 0) + (usage.effectiveNonCachedInput ?? 0) || usage.effectiveNonCachedInput,
953
+ }));
872
954
  },
873
955
  onEvent: event => {
874
956
  const session = sessionRef.current;
@@ -876,7 +958,8 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
876
958
  void appendSessionEntry(session, { type: 'event', at: event.at, name: event.type, text: JSON.stringify(event) }).catch(() => undefined);
877
959
  },
878
960
  onTasksChanged: () => { loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined); },
879
- });
961
+ log: llmLogRef.current,
962
+ }, 0, false, false, { start: sessionStartRef.current, cwd: process.cwd() });
880
963
  }
881
964
  const visible = messages.filter(message => !message.hidden);
882
965
  const transcriptItems = visible.map((message, index) => ({ key: messageKey(message, index), message }));
@@ -902,7 +985,13 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
902
985
  ? 'model-a, model-b'
903
986
  : mode === 'providerConfirmRemove'
904
987
  ? 'Type "yes" to confirm'
905
- : busy ? 'Queue a follow-up, or Esc to interrupt' : 'Ask Haze to help build your app';
988
+ : mode === 'skillCreateName'
989
+ ? 'Skill name (kebab-case, e.g. security-review)'
990
+ : mode === 'skillCreateRole'
991
+ ? 'Role (optional — Enter to skip)'
992
+ : mode === 'skillCreateDescription'
993
+ ? 'Describe what the skill should do'
994
+ : busy ? 'Queue a follow-up, or Esc to interrupt' : 'Ask Haze to help build your app';
906
995
  const activeModelName = `${activeSelection.provider.name}:${process.env.HAZE_MODEL ?? activeSelection.model}`;
907
996
  const hasLogin = Boolean(process.env.OPENAI_API_KEY ?? settings.apiKey ?? activeSelection.provider.key) || activeSelection.provider.name !== DEFAULT_PROVIDER_NAME;
908
997
  const hasChosenModel = Boolean(process.env.HAZE_MODEL ?? settings.model ?? activeSelection.model);
@@ -911,7 +1000,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
911
1000
  'A minimal LLM harness for growing your own workflows while you work.',
912
1001
  '',
913
1002
  'Start with simple chat, then teach Haze your habits with skills:',
914
- '/create-skill review my branch against main — tiny spell, useful goblin.',
1003
+ '/create-skill — three-step skill wizard (name, role, description).',
915
1004
  '',
916
1005
  'The most adaptive workflow is the one you shape as you go.',
917
1006
  '',
@@ -922,8 +1011,12 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
922
1011
  const workspaceLabel = `${process.cwd()}${branchName ? ` (${branchName})` : ''}`;
923
1012
  const allDisplayMessages = [...messages, ...liveMessages];
924
1013
  const toolsUsed = toolCallCount(allDisplayMessages);
925
- const estimatedTokens = llmTokenEstimate.input > 0 || llmTokenEstimate.output > 0 ? llmTokenEstimate : estimateConversationTokens(allDisplayMessages);
926
- const statusDetailLabel = `${conversationRef.current.length} messages / ${toolsUsed} tool call${toolsUsed === 1 ? '' : 's'} / LLM ↑ ~${formatTokenCount(estimatedTokens.input)} ↓ ~${formatTokenCount(estimatedTokens.output)} / ${skills.length} skill${skills.length === 1 ? '' : 's'}`;
1014
+ const fallbackTokens = estimateConversationTokens(allDisplayMessages);
1015
+ const effectiveInput = tokenUsage.inputTokens ?? (fallbackTokens.input || 0);
1016
+ const effectiveOutput = tokenUsage.outputTokens ?? (fallbackTokens.output || 0);
1017
+ const precise = tokenUsage.inputTokens != null;
1018
+ const statusDetailLabel = `${conversationRef.current.length} messages / ${toolsUsed} tool call${toolsUsed === 1 ? '' : 's'} / LLM ${precise ? '' : '~'}↑${formatTokenCount(effectiveInput)} ${precise ? '' : '~'}↓${formatTokenCount(effectiveOutput)} / ${skills.length} skill${skills.length === 1 ? '' : 's'}`;
1019
+ const hasTokenBreakdown = tokenUsage.systemPrompt > 0 || tokenUsage.messages > 0 || tokenUsage.toolSchemas > 0 || effectiveInput > 0 || effectiveOutput > 0;
927
1020
  const goalText = activeGoalStatus?.replace(/^Goal:\s*/, '');
928
1021
  // Goal tracking is internal; display removed in favor of task bar
929
1022
  void goalText;
@@ -932,8 +1025,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
932
1025
  { value: '/provider', description: 'Choose a provider', kind: 'command' },
933
1026
  { value: '/model', description: 'Choose a model', kind: 'command' },
934
1027
  { value: '/settings', description: 'Show provider, model, API key, and context status', kind: 'command' },
935
- { value: '/create-skill ', description: 'Create a Markdown skill', kind: 'command' },
936
- { value: '/list-skills', description: 'List installed skills', kind: 'command' },
1028
+ { value: '/create-skill ', description: 'Launch the skill wizard', kind: 'command' },
937
1029
  { value: '/skill-info ', description: 'Show details for a skill', kind: 'command' },
938
1030
  { value: '/validate-skill ', description: 'Validate a skill', kind: 'command' },
939
1031
  { value: '/remove-skill ', description: 'Remove a skill with --yes', kind: 'command' },
@@ -953,7 +1045,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
953
1045
  ];
954
1046
  return _jsxs(Box, { flexDirection: "column", children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
955
1047
  ? _jsx(Header, { subtitle: item.subtitle, version: version }, item.key)
956
- : _jsx(MessageView, { message: item.message, width: width }, item.key) }), activeLiveMessages.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, children: activeLiveMessages.map((message, index) => _jsx(MessageView, { message: message, width: width }, messageKey(message, index))) }), debug && debugLogs.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { color: theme.muted, bold: true, children: "Debug" }), debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, children: ["\u2022 ", line] }, index))] }), queuedFollowUps.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: [_jsx(Text, { color: theme.muted, children: "Queued follow-ups:" }), queuedFollowUps.map((item, index) => _jsxs(Text, { color: theme.muted, dimColor: true, children: [" ", index + 1, ". ", item] }, `${index}-${item}`))] }), visibleTasks.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: _jsx(TaskBarContent, { tasks: visibleTasks, width: width, expanded: tasksExpanded, padding: taskBarPadding }) }), busy && _jsx(Box, { flexShrink: 0, children: _jsxs(Text, { children: [_jsxs(Text, { color: theme.orange, bold: true, children: [_jsx(Spinner, { type: "dots" }), " ", busyLabel] }), _jsx(Text, { color: theme.muted, dimColor: true, children: " \u00B7 type to queue follow-up \u00B7 esc to interrupt" })] }) }), _jsx(Box, { borderStyle: "round", borderColor: theme.deepPurple, paddingX: 1, flexShrink: 0, children: _jsx(Box, { flexGrow: 1, minWidth: 0, children: _jsx(TextInput, { placeholder: placeholder, disabled: busy && mode !== 'chat', mask: mode === 'providerAddKey' || mode === 'providerSetKey', historyItems: inputHistory, recordHistory: mode === 'chat', suggestions: inputSuggestions, suggestionMode: mode === 'provider' || mode === 'providerAction' || mode === 'providerAddPreset' || mode === 'model' ? 'always' : 'slash', submitOnEmpty: mode === 'providerAddKey', width: Math.max(20, width - 4), onHistoryAdd: persistInputHistory, onToggleTasks: () => {
1048
+ : _jsx(MessageView, { message: item.message, width: width }, item.key) }), activeLiveMessages.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, children: activeLiveMessages.map((message, index) => _jsx(MessageView, { message: message, width: width }, messageKey(message, index))) }), debug && debugLogs.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { color: theme.muted, bold: true, children: "Debug" }), debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, children: ["\u2022 ", line] }, index))] }), queuedFollowUps.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: [_jsx(Text, { color: theme.muted, children: "Queued follow-ups:" }), queuedFollowUps.map((item, index) => _jsxs(Text, { color: theme.muted, dimColor: true, children: [" ", index + 1, ". ", item] }, `${index}-${item}`))] }), visibleTasks.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: _jsx(TaskBarContent, { tasks: visibleTasks, width: width, expanded: tasksExpanded, padding: taskBarPadding }) }), busy && _jsx(Box, { flexShrink: 0, children: _jsxs(Text, { children: [_jsxs(Text, { color: theme.orange, bold: true, children: [_jsx(Spinner, { type: "dots" }), " ", busyLabel] }), _jsx(Text, { color: theme.muted, dimColor: true, children: " \u00B7 type to queue follow-up \u00B7 esc to interrupt" })] }) }), _jsx(Box, { borderStyle: "round", borderColor: theme.deepPurple, paddingX: 1, flexShrink: 0, children: _jsx(Box, { flexGrow: 1, minWidth: 0, children: _jsx(TextInput, { placeholder: placeholder, disabled: busy && mode !== 'chat', mask: mode === 'providerAddKey' || mode === 'providerSetKey', historyItems: inputHistory, recordHistory: mode === 'chat', suggestions: inputSuggestions, suggestionMode: mode === 'provider' || mode === 'providerAction' || mode === 'providerAddPreset' || mode === 'model' ? 'always' : 'slash', submitOnEmpty: mode === 'providerAddKey' || mode === 'skillCreateRole', width: Math.max(20, width - 4), onHistoryAdd: persistInputHistory, onToggleTasks: () => {
957
1049
  if (!tasksExpanded) {
958
1050
  setTaskBarPadding(0);
959
1051
  setTasksExpanded(true);
@@ -969,7 +1061,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
969
1061
  cancelThinking();
970
1062
  else
971
1063
  closeInputList();
972
- }, onSubmit: submit }) }) }), _jsxs(Box, { flexShrink: 0, justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", flexShrink: 1, minWidth: 0, children: [_jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-end", children: workspaceLabel }), _jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-end", children: statusDetailLabel })] }), _jsx(Box, { flexShrink: 0, marginLeft: 2, children: _jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-start", children: activeModelName }) })] })] });
1064
+ }, onSubmit: submit }) }) }), debug && hasTokenBreakdown && _jsxs(Box, { flexShrink: 0, flexDirection: "column", paddingX: 1, children: [_jsxs(Text, { color: theme.muted, bold: true, children: ["Token usage ", precise ? '(precise)' : '(estimated)'] }), _jsxs(Text, { color: theme.muted, children: [" in=", formatTokenCount(effectiveInput), " out=", formatTokenCount(effectiveOutput), tokenUsage.cacheReadTokens > 0 ? ` cached=${formatTokenCount(tokenUsage.cacheReadTokens)}` : '', tokenUsage.noCacheTokens > 0 ? ` uncached=${formatTokenCount(tokenUsage.noCacheTokens)}` : '', tokenUsage.cacheWriteTokens > 0 ? ` cache_write=${formatTokenCount(tokenUsage.cacheWriteTokens)}` : '', tokenUsage.reasoningTokens > 0 ? ` reasoning=${formatTokenCount(tokenUsage.reasoningTokens)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" logical=", formatTokenCount(tokenUsage.logicalInputEstimate), tokenUsage.effectiveNonCachedInput != null ? ` effective_non_cached=${formatTokenCount(tokenUsage.effectiveNonCachedInput)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" system=", formatTokenCount(tokenUsage.systemPrompt), " messages=", formatTokenCount(tokenUsage.messages), " tools=", formatTokenCount(tokenUsage.toolSchemas), " output=", formatTokenCount(tokenUsage.outputEstimate)] })] }), _jsxs(Box, { flexShrink: 0, justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", flexShrink: 1, minWidth: 0, children: [_jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-end", children: workspaceLabel }), _jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-end", children: statusDetailLabel })] }), _jsx(Box, { flexShrink: 0, marginLeft: 2, children: _jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-start", children: activeModelName }) })] })] });
973
1065
  }
974
1066
  export async function chatCommand(options = {}) {
975
1067
  if (process.stdout.isTTY) {