@denizokcu/haze 0.3.0 → 0.5.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 (73) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +50 -36
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +244 -94
  5. package/dist/cli/commands/commands.js +119 -114
  6. package/dist/cli/commands/streaming.d.ts +37 -5
  7. package/dist/cli/commands/streaming.js +455 -192
  8. package/dist/cli/contextReport.d.ts +1 -0
  9. package/dist/cli/contextReport.js +47 -0
  10. package/dist/config/contextFiles.d.ts +31 -0
  11. package/dist/config/contextFiles.js +97 -13
  12. package/dist/config/providers.d.ts +2 -5
  13. package/dist/config/providers.js +16 -12
  14. package/dist/core/agent/compaction.d.ts +3 -0
  15. package/dist/core/agent/compaction.js +23 -3
  16. package/dist/core/agent/contextBudget.d.ts +33 -0
  17. package/dist/core/agent/contextBudget.js +88 -0
  18. package/dist/core/agent/requestAssembly.d.ts +22 -0
  19. package/dist/core/agent/requestAssembly.js +157 -0
  20. package/dist/core/agent/toolOutputStore.d.ts +16 -0
  21. package/dist/core/agent/toolOutputStore.js +65 -0
  22. package/dist/core/agent/workState.d.ts +38 -0
  23. package/dist/core/agent/workState.js +89 -0
  24. package/dist/core/bashOutput/ansi.d.ts +1 -0
  25. package/dist/core/bashOutput/ansi.js +7 -0
  26. package/dist/core/bashOutput/command.d.ts +2 -0
  27. package/dist/core/bashOutput/command.js +62 -0
  28. package/dist/core/bashOutput/lineFilter.d.ts +25 -0
  29. package/dist/core/bashOutput/lineFilter.js +62 -0
  30. package/dist/core/bashOutput/reducers/content.d.ts +3 -0
  31. package/dist/core/bashOutput/reducers/content.js +134 -0
  32. package/dist/core/bashOutput/reducers/git.d.ts +1 -0
  33. package/dist/core/bashOutput/reducers/git.js +147 -0
  34. package/dist/core/bashOutput/reducers/search.d.ts +7 -0
  35. package/dist/core/bashOutput/reducers/search.js +76 -0
  36. package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
  37. package/dist/core/bashOutput/reducers/validation.js +41 -0
  38. package/dist/core/bashOutput/registry.d.ts +4 -0
  39. package/dist/core/bashOutput/registry.js +126 -0
  40. package/dist/core/bashOutput/types.d.ts +46 -0
  41. package/dist/core/bashOutput/types.js +1 -0
  42. package/dist/core/goal/completionPolicy.d.ts +1 -0
  43. package/dist/core/goal/completionPolicy.js +5 -1
  44. package/dist/core/goal/sessionGoal.d.ts +2 -0
  45. package/dist/core/goal/sessionGoal.js +8 -1
  46. package/dist/core/log/llmLog.d.ts +68 -0
  47. package/dist/core/log/llmLog.js +55 -0
  48. package/dist/core/safety/urlGuard.d.ts +37 -0
  49. package/dist/core/safety/urlGuard.js +206 -0
  50. package/dist/core/session/sessionStore.d.ts +6 -0
  51. package/dist/core/session/sessionStore.js +5 -0
  52. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  53. package/dist/core/subagent/subagentRunner.js +5 -15
  54. package/dist/core/toolOutput/reduction.d.ts +25 -0
  55. package/dist/core/toolOutput/reduction.js +23 -0
  56. package/dist/core/validation/outputParser.js +15 -2
  57. package/dist/llm/client.d.ts +40 -1
  58. package/dist/llm/client.js +51 -5
  59. package/dist/llm/hazeTools.d.ts +165 -23
  60. package/dist/llm/hazeTools.js +317 -65
  61. package/dist/llm/initPrompt.js +2 -1
  62. package/dist/llm/systemPrompt.d.ts +6 -1
  63. package/dist/llm/systemPrompt.js +44 -81
  64. package/dist/llm/toolResultTypes.d.ts +1 -1
  65. package/dist/llm/webFetch.d.ts +57 -0
  66. package/dist/llm/webFetch.js +270 -0
  67. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  68. package/dist/skills/builder/SkillBuilder.js +68 -65
  69. package/dist/skills/skillTools.d.ts +2 -19
  70. package/dist/skills/skillTools.js +28 -19
  71. package/dist/ui/components/MarkdownText.d.ts +2 -0
  72. package/dist/ui/components/MarkdownText.js +116 -3
  73. package/package.json +18 -10
@@ -1,6 +1,7 @@
1
1
  import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { useEffect, useRef, useState } from 'react';
3
3
  import { execFile as execFileCallback } from 'node:child_process';
4
+ import os from 'node:os';
4
5
  import { promisify } from 'node:util';
5
6
  import { Box, render, Static, Text, useApp, useStdout } from 'ink';
6
7
  import Spinner from 'ink-spinner';
@@ -8,20 +9,23 @@ import { readContextFiles } from '../../config/contextFiles.js';
8
9
  import { addInputHistoryItem, readInputHistory } from '../../config/inputHistory.js';
9
10
  import { loadTasks as loadTasksFromStore, clearTasks as clearTasksFromStore } from '../../core/tasks/taskStorage.js';
10
11
  import { readSettings, updateSettings } from '../../config/settings.js';
11
- import { activeModel, configuredProviders, DEFAULT_PROVIDER_NAME, findProvider, modelSelector, providerHasKey, resolveModelSelector, upsertProvider } from '../../config/providers.js';
12
+ import { activeModel, configuredProviders, findProvider, modelSelector, providerHasKey, resolveModelSelector, upsertProvider } from '../../config/providers.js';
12
13
  import { Header } from '../../ui/components/Header.js';
13
14
  import { TextInput } from '../../ui/components/TextInput.js';
14
15
  import { MarkdownText } from '../../ui/components/MarkdownText.js';
15
16
  import { theme } from '../../ui/theme.js';
16
17
  import { handleSlashCommand } from './commands.js';
17
18
  import { runAgentTurn } from './streaming.js';
19
+ import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
18
20
  import { formatElapsedTime, formatElapsedTimeWhole } from './formatters.js';
19
21
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
22
+ import { createSkill, toSkillDirName } from '../../skills/builder/SkillBuilder.js';
20
23
  import { PROVIDER_PRESETS, findPreset } from '../../config/providerPresets.js';
21
- import { appendSessionEntry, createSession, formatSession, latestSession, restoreConversation } from '../../core/session/sessionStore.js';
24
+ import { appendSessionEntry, createSession, formatSession, latestSession, restoreConversation, restoreWorkState } from '../../core/session/sessionStore.js';
22
25
  import { compactModelMessages, modelMessageText } from '../../core/agent/compaction.js';
23
- import { createSessionGoal, formatGoalStatus } from '../../core/goal/sessionGoal.js';
26
+ import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
24
27
  const execFile = promisify(execFileCallback);
28
+ 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
29
  async function currentBranchName() {
26
30
  try {
27
31
  const { stdout } = await execFile('git', ['branch', '--show-current'], { cwd: process.cwd() });
@@ -45,6 +49,12 @@ function toolCallCount(messages) {
45
49
  function estimateTokens(text) {
46
50
  return Math.ceil(text.length / 4);
47
51
  }
52
+ function compactHomePath(filePath) {
53
+ const home = os.homedir();
54
+ if (filePath === home)
55
+ return '~';
56
+ return filePath.startsWith(`${home}/`) ? `~/${filePath.slice(home.length + 1)}` : filePath;
57
+ }
48
58
  function formatTokenCount(tokens) {
49
59
  if (tokens >= 1_000_000)
50
60
  return `${(tokens / 1_000_000).toFixed(tokens >= 10_000_000 ? 0 : 1).replace(/\.0$/, '')}m`;
@@ -112,13 +122,16 @@ function messageElapsedLabel(message) {
112
122
  return '';
113
123
  const end = message.finishedAt ?? (message.streaming ? Date.now() : message.startedAt);
114
124
  const elapsed = end - message.startedAt;
125
+ if (message.role === 'assistant' && !message.streaming && message.tokensPerSecond != null) {
126
+ return `✓ Done in ${formatElapsedTime(elapsed)} · ${Math.round(message.tokensPerSecond)} tok/s`;
127
+ }
115
128
  return message.streaming ? formatElapsedTimeWhole(elapsed) : formatElapsedTime(elapsed);
116
129
  }
117
- function MessageView({ message, width }) {
130
+ function MessageView({ message, width, suppressAssistantHeader = false }) {
118
131
  if (message.role === 'user') {
119
132
  return _jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { backgroundColor: theme.quoteBg, children: fullWidthBlankLine(width) }), _jsx(Text, { color: theme.success, bold: true, backgroundColor: theme.quoteBg, children: ' You asked'.padEnd(width) }), fullWidthLines(message.text, width, 2).map((line, lineIndex) => _jsx(Text, { color: "white", backgroundColor: theme.quoteBg, children: line }, lineIndex)), _jsx(Text, { backgroundColor: theme.quoteBg, children: fullWidthBlankLine(width) })] });
120
133
  }
121
- return _jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: message.role === 'assistant' ? theme.purple : message.role === 'tool' ? theme.blue : theme.muted, bold: true, children: message.role === 'assistant' ? 'haze' : message.role === 'tool' ? 'Tool' : 'Info' }), messageElapsedLabel(message) ? _jsxs(Text, { color: theme.muted, bold: false, children: [" \u00B7 ", messageElapsedLabel(message)] }) : null] }), message.role === 'tool'
134
+ return _jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [!suppressAssistantHeader && _jsxs(Text, { children: [_jsx(Text, { color: message.role === 'assistant' ? theme.purple : message.role === 'tool' ? theme.blue : theme.muted, bold: true, children: message.role === 'assistant' ? 'haze' : message.role === 'tool' ? 'Tool' : 'Info' }), messageElapsedLabel(message) ? _jsxs(Text, { color: theme.muted, bold: false, children: [" \u00B7 ", messageElapsedLabel(message)] }) : null] }), message.role === 'tool'
122
135
  ? _jsx(ToolMessageText, { text: message.text, streaming: message.streaming })
123
136
  : message.role === 'assistant' && !message.streaming
124
137
  ? _jsx(MarkdownText, { content: message.text })
@@ -127,21 +140,47 @@ function MessageView({ message, width }) {
127
140
  function messageKey(message, index) {
128
141
  return message.id ?? `${index}-${message.role}-${message.text}`;
129
142
  }
143
+ function orderedDisplayMessages(messages) {
144
+ return messages
145
+ .map((message, index) => ({ message, index }))
146
+ .sort((a, b) => {
147
+ if (a.message.displayOrder != null && b.message.displayOrder != null && a.message.displayOrder !== b.message.displayOrder) {
148
+ return a.message.displayOrder - b.message.displayOrder;
149
+ }
150
+ return a.index - b.index;
151
+ })
152
+ .map(item => item.message);
153
+ }
154
+ function annotateTurnHeaders(messages) {
155
+ return messages.map(message => ({ message, suppressAssistantHeader: false }));
156
+ }
130
157
  function startupProviderInfo(settings) {
131
158
  const selection = activeModel(settings);
132
- const model = process.env.HAZE_MODEL ?? selection.model;
133
- const modelSource = process.env.HAZE_MODEL ? 'HAZE_MODEL env' : settings.model ? 'settings' : 'provider default';
134
- const baseURL = process.env.OPENAI_BASE_URL ?? selection.provider.url;
135
- const baseURLSource = process.env.OPENAI_BASE_URL ? 'OPENAI_BASE_URL env' : 'settings';
136
- const apiKeySource = process.env.OPENAI_API_KEY ? 'OPENAI_API_KEY env' : providerHasKey(settings, selection.provider) ? `provider ${selection.provider.name}` : 'missing';
137
- const provider = process.env.OPENAI_BASE_URL ? 'OpenAI-compatible custom endpoint' : selection.provider.name;
159
+ const configuredCount = configuredProviders(settings).length;
160
+ if (!selection) {
161
+ return [
162
+ 'Provider configuration',
163
+ '- Provider: not configured',
164
+ '- Model: not set',
165
+ '- Base URL: not configured',
166
+ '- API key: missing',
167
+ `- Configured providers: ${configuredCount}`,
168
+ '',
169
+ 'Run /provider to choose or add a provider, then select a model.',
170
+ ].join('\n');
171
+ }
172
+ const model = selection.model;
173
+ const modelSource = settings.model ? 'settings' : 'provider default';
174
+ const baseURL = selection.provider.url;
175
+ const apiKeySource = providerHasKey(settings, selection.provider) ? `provider ${selection.provider.name}` : 'missing';
176
+ const provider = selection.provider.name;
138
177
  return [
139
178
  'Provider configuration',
140
179
  `- Provider: ${provider}`,
141
180
  `- Model: ${model} (${modelSource})`,
142
- `- Base URL: ${baseURL} (${baseURLSource})`,
181
+ `- Base URL: ${baseURL} (settings)`,
143
182
  `- API key: ${apiKeySource === 'missing' ? 'not configured; local providers may not need one' : `configured via ${apiKeySource}`}`,
144
- `- Configured providers: ${configuredProviders(settings).length}`,
183
+ `- Configured providers: ${configuredCount}`,
145
184
  ].join('\n');
146
185
  }
147
186
  const TASK_STATUS_ICON = {
@@ -185,14 +224,24 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
185
224
  const { exit } = useApp();
186
225
  const { stdout } = useStdout();
187
226
  const width = stdout.columns ?? process.stdout.columns ?? 80;
188
- const [messages, setMessages] = useState([
189
- { role: 'system', text: 'Welcome to Haze. Use /help for commands.' }
227
+ const nextDisplayOrderRef = useRef(1);
228
+ const withDisplayOrder = (message) => {
229
+ if (message.displayOrder != null)
230
+ return message;
231
+ return { ...message, displayOrder: nextDisplayOrderRef.current++ };
232
+ };
233
+ const withDisplayOrders = (next) => next.map(withDisplayOrder);
234
+ const [messages, setMessagesRaw] = useState([
235
+ { role: 'system', text: 'Welcome to Haze. Use /help for commands.', displayOrder: 0 }
190
236
  ]);
237
+ const setMessages = (updater) => {
238
+ setMessagesRaw(previous => withDisplayOrders(typeof updater === 'function' ? updater(previous) : updater));
239
+ };
191
240
  const [liveMessages, setLiveMessages] = useState([]);
192
241
  const liveMessagesRef = useRef([]);
193
242
  const setLiveMessagesState = (updater) => {
194
243
  setLiveMessages(previous => {
195
- const next = updater(previous);
244
+ const next = withDisplayOrders(updater(previous));
196
245
  liveMessagesRef.current = next;
197
246
  return next;
198
247
  });
@@ -202,6 +251,9 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
202
251
  const lastAssistantTextRef = useRef('');
203
252
  const abortControllerRef = useRef(null);
204
253
  const sessionRef = useRef(undefined);
254
+ const sessionStartRef = useRef(new Date());
255
+ const workStateRef = useRef(undefined);
256
+ const llmLogRef = useRef(undefined);
205
257
  const followUpQueueRef = useRef([]);
206
258
  const [inputHistory, setInputHistory] = useState([]);
207
259
  const [debugLogs, setDebugLogs] = useState([]);
@@ -214,18 +266,14 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
214
266
  const [tasksExpanded, setTasksExpanded] = useState(false);
215
267
  const [taskBarPadding, setTaskBarPadding] = useState(0);
216
268
  const [, setSessionLabel] = useState();
217
- const [llmTokenEstimate, setLlmTokenEstimate] = useState({ input: 0, output: 0 });
218
- const [, setTimerTick] = useState(0);
269
+ const [tokenUsage, setTokenUsage] = useState({ ...EMPTY_TOKEN_USAGE });
219
270
  const [queuedFollowUps, setQueuedFollowUps] = useState([]);
220
271
  const [skills, setSkills] = useState([]);
221
272
  const [branchName, setBranchName] = useState();
222
273
  const [modelProviderFilter, setModelProviderFilter] = useState();
223
274
  const [selectedProviderName, setSelectedProviderName] = useState();
224
275
  const [providerDraft, setProviderDraft] = useState({});
225
- useEffect(() => {
226
- const timer = setInterval(() => setTimerTick(tick => tick + 1), 1000);
227
- return () => clearInterval(timer);
228
- }, []);
276
+ const [skillCreateDraft, setSkillCreateDraft] = useState({});
229
277
  useEffect(() => {
230
278
  Promise.all([readSettings(), currentBranchName()]).then(([next, branch]) => {
231
279
  setSettings(next);
@@ -275,7 +323,20 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
275
323
  return;
276
324
  setDebugLogs(current => [...current.slice(-7), line]);
277
325
  }
326
+ async function startNewLog() {
327
+ if (!debug)
328
+ return undefined;
329
+ if (llmLogRef.current) {
330
+ await endLlmLog(llmLogRef.current).catch(() => undefined);
331
+ }
332
+ const log = await createLlmLog();
333
+ llmLogRef.current = log;
334
+ return log;
335
+ }
278
336
  async function startNewSession(message = 'Started a new session.') {
337
+ clearToolOutputs();
338
+ workStateRef.current = undefined;
339
+ sessionStartRef.current = new Date();
279
340
  if (noSession) {
280
341
  sessionRef.current = undefined;
281
342
  setSessionLabel('session off');
@@ -283,7 +344,8 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
283
344
  }
284
345
  const session = await createSession({ hazeVersion: version });
285
346
  sessionRef.current = session;
286
- setLlmTokenEstimate({ input: 0, output: 0 });
347
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE });
348
+ await startNewLog();
287
349
  setSessionLabel(session.id);
288
350
  setMessages(m => [...m, { role: 'system', text: `${message}\nSession saved: ${session.file}` }]);
289
351
  }
@@ -297,29 +359,35 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
297
359
  if (session) {
298
360
  const conversation = await restoreConversation(session);
299
361
  sessionRef.current = session;
362
+ sessionStartRef.current = new Date();
300
363
  conversationRef.current = conversation;
301
364
  setSessionLabel(session.id);
302
365
  setLiveMessagesState(() => []);
303
366
  const restoredMessages = displayMessagesFromConversation(conversation);
304
- setLlmTokenEstimate(estimateConversationTokens(restoredMessages));
367
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE, messages: estimateConversationTokens(restoredMessages).input, outputEstimate: estimateConversationTokens(restoredMessages).output });
368
+ workStateRef.current = await restoreWorkState(session);
305
369
  setMessages(m => [...m, { role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...restoredMessages]);
370
+ await startNewLog();
306
371
  return;
307
372
  }
308
373
  }
309
374
  await startNewSession(continueSession ? 'No previous session found. Started a new session.' : 'Started a new session.');
310
375
  }
311
376
  function clearConversation() {
377
+ clearToolOutputs();
312
378
  conversationRef.current = [];
313
379
  lastAssistantTextRef.current = '';
314
- setLlmTokenEstimate({ input: 0, output: 0 });
380
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE });
381
+ workStateRef.current = undefined;
315
382
  setLiveMessagesState(() => []);
316
383
  setMessages([{ role: 'system', text: 'Cleared. The void is productive.' }]);
384
+ void startNewLog();
317
385
  const session = sessionRef.current;
318
386
  if (session)
319
387
  void appendSessionEntry(session, { type: 'event', at: new Date().toISOString(), name: 'clear', text: 'Conversation cleared' }).catch(() => undefined);
320
388
  }
321
389
  function compactConversation(instructions) {
322
- const result = compactModelMessages(conversationRef.current, { instructions });
390
+ const result = compactModelMessages(conversationRef.current, { instructions, tokenBudget: 40_000, workState: workStateRef.current });
323
391
  if (!result.compacted) {
324
392
  setMessages(m => [...m, { role: 'system', text: `Compaction skipped: only ${result.keptCount} model messages in context.` }]);
325
393
  return false;
@@ -340,9 +408,12 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
340
408
  return;
341
409
  }
342
410
  const conversation = await restoreConversation(session);
411
+ clearToolOutputs();
343
412
  sessionRef.current = session;
344
413
  conversationRef.current = conversation;
414
+ workStateRef.current = await restoreWorkState(session);
345
415
  setSessionLabel(session.id);
416
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE });
346
417
  setLiveMessagesState(() => []);
347
418
  setMessages([{ role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...displayMessagesFromConversation(conversation)]);
348
419
  }
@@ -371,6 +442,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
371
442
  setModelProviderFilter(undefined);
372
443
  setSelectedProviderName(undefined);
373
444
  setProviderDraft({});
445
+ setSkillCreateDraft({});
374
446
  }
375
447
  }
376
448
  function providerSuggestions() {
@@ -579,12 +651,76 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
579
651
  setMode('model');
580
652
  setMessages(m => [...m, { role: 'system', text: `Added provider ${provider.name}. Choose a model.` }]);
581
653
  }
654
+ async function captureSkillName(value) {
655
+ const dirName = toSkillDirName(value);
656
+ if (!dirName) {
657
+ setMessages(m => [...m, { role: 'system', text: 'Skill name must contain at least one letter or number. Try again, or press ESC to cancel.' }]);
658
+ return;
659
+ }
660
+ const registry = await loadSkillRegistry();
661
+ if (registry.skills.has(dirName)) {
662
+ setMessages(m => [...m, { role: 'system', text: `A skill named "${dirName}" already exists. Pick another name, or press ESC to cancel.` }]);
663
+ return;
664
+ }
665
+ setSkillCreateDraft(d => ({ ...d, name: dirName }));
666
+ setMode('skillCreateRole');
667
+ 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).` }]);
668
+ }
669
+ function captureSkillRole(value) {
670
+ const role = value.trim();
671
+ setSkillCreateDraft(d => ({ ...d, ...(role ? { role } : {}) }));
672
+ setMode('skillCreateDescription');
673
+ 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.` }]);
674
+ }
675
+ async function captureSkillDescription(value) {
676
+ const description = value.trim();
677
+ if (!description) {
678
+ setMessages(m => [...m, { role: 'system', text: 'Description is required. Try again, or press ESC to cancel.' }]);
679
+ return;
680
+ }
681
+ const name = skillCreateDraft.name;
682
+ if (!name) {
683
+ setMode('chat');
684
+ setSkillCreateDraft({});
685
+ setMessages(m => [...m, { role: 'system', text: 'Skill wizard lost the name. Start over with /create-skill.' }]);
686
+ return;
687
+ }
688
+ setMode('chat');
689
+ setBusyLabel('Creating skill');
690
+ setBusy(true);
691
+ try {
692
+ const result = await createSkill({ name, role: skillCreateDraft.role, description });
693
+ 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.` }]);
694
+ await refreshSkills();
695
+ }
696
+ catch (error) {
697
+ const text = error instanceof Error ? error.message : String(error);
698
+ setMessages(m => [...m, { role: 'system', text: `Skill creation failed: ${text}` }]);
699
+ }
700
+ finally {
701
+ setSkillCreateDraft({});
702
+ setBusy(false);
703
+ setBusyLabel('Haze is thinking');
704
+ }
705
+ }
582
706
  async function submit(value) {
583
707
  if (busy) {
584
708
  if (mode === 'chat')
585
709
  queueFollowUp(value);
586
710
  return;
587
711
  }
712
+ if (mode === 'skillCreateName') {
713
+ await captureSkillName(value);
714
+ return;
715
+ }
716
+ if (mode === 'skillCreateRole') {
717
+ captureSkillRole(value);
718
+ return;
719
+ }
720
+ if (mode === 'skillCreateDescription') {
721
+ await captureSkillDescription(value);
722
+ return;
723
+ }
588
724
  if (mode === 'provider') {
589
725
  await selectProvider(value);
590
726
  return;
@@ -727,19 +863,9 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
727
863
  const invokedSkill = skillInvocation(value);
728
864
  if (invokedSkill) {
729
865
  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);
866
+ 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
867
  return;
732
868
  }
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
869
  const ctx = {
744
870
  settings,
745
871
  contextFiles,
@@ -766,41 +892,21 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
766
892
  },
767
893
  };
768
894
  let result;
769
- if (isSkillCreate) {
770
- setBusyLabel('Creating skill');
771
- setBusy(true);
772
- }
773
895
  try {
774
896
  result = await handleSlashCommand(value, ctx);
775
897
  }
776
898
  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
899
  const text = error instanceof Error ? error.message : String(error);
783
- setMessages(m => [...m, { role: 'system', text: `Skill creation failed: ${text}` }]);
900
+ setMessages(m => [...m, { role: 'system', text: `Command failed: ${text}` }]);
784
901
  return;
785
902
  }
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
903
  if (result === 'exit')
798
904
  return exit();
799
905
  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 ')) {
906
+ if (value.startsWith('/remove-skill ')) {
801
907
  await refreshSkills().catch(() => undefined);
802
908
  }
803
- if (value.startsWith('/tasks') || value === '/clear') {
909
+ if (value === '/clear') {
804
910
  loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
805
911
  }
806
912
  return;
@@ -809,6 +915,15 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
809
915
  }
810
916
  async function doAgentTurn(value, displayValue) {
811
917
  setDebugLogs([]);
918
+ // When every task is already completed, start the new turn with a clean
919
+ // slate: the task bar clears (nothing shown for simple questions) and the
920
+ // model may create fresh todos via writeTasks if the new question warrants.
921
+ if (visibleTasks.length > 0 && visibleTasks.every(t => t.status === 'completed')) {
922
+ setVisibleTasks([]);
923
+ setTasksExpanded(false);
924
+ setTaskBarPadding(0);
925
+ await clearTasksFromStore().catch(() => undefined);
926
+ }
812
927
  await runSingleAgentTurn(value, displayValue);
813
928
  while (followUpQueueRef.current.length > 0) {
814
929
  const next = followUpQueueRef.current[0];
@@ -827,16 +942,18 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
827
942
  const finalizeMessage = (msg) => {
828
943
  if (msg.hidden)
829
944
  return;
830
- setMessages(m => [...m, msg]);
831
- persistUiMessage(msg);
945
+ const ordered = withDisplayOrder(msg);
946
+ setMessages(m => [...m, ordered]);
947
+ persistUiMessage(ordered);
832
948
  };
833
949
  await runAgentTurn(value, displayValue, contextFiles, {
834
950
  addMessage: msg => {
835
- if (msg.streaming) {
836
- setLiveMessagesState(m => [...m, msg]);
951
+ const ordered = withDisplayOrder(msg);
952
+ if (ordered.streaming) {
953
+ setLiveMessagesState(m => [...m, ordered]);
837
954
  return;
838
955
  }
839
- finalizeMessage(msg);
956
+ finalizeMessage(ordered);
840
957
  },
841
958
  updateMessage: (id, update) => {
842
959
  const liveMessage = liveMessagesRef.current.find(msg => msg.id === id);
@@ -866,9 +983,28 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
866
983
  setLastAssistantText: text => { lastAssistantTextRef.current = text; },
867
984
  setAbortController: controller => { abortControllerRef.current = controller; },
868
985
  setGoalStatus: setActiveGoalStatus,
986
+ setWorkState: state => {
987
+ workStateRef.current = state;
988
+ const session = sessionRef.current;
989
+ if (session)
990
+ void appendSessionEntry(session, { type: 'work_state_snapshot', at: new Date().toISOString(), state }).catch(() => undefined);
991
+ },
869
992
  compactConversation,
870
- recordTokenEstimate: tokens => {
871
- setLlmTokenEstimate(current => ({ input: current.input + tokens.input, output: current.output + tokens.output }));
993
+ recordTokenUsage: usage => {
994
+ setTokenUsage(current => ({
995
+ inputTokens: (current.inputTokens ?? 0) + (usage.inputTokens ?? 0) || usage.inputTokens,
996
+ outputTokens: (current.outputTokens ?? 0) + (usage.outputTokens ?? 0) || usage.outputTokens,
997
+ systemPrompt: current.systemPrompt + usage.systemPrompt,
998
+ messages: current.messages + usage.messages,
999
+ toolSchemas: current.toolSchemas + usage.toolSchemas,
1000
+ outputEstimate: current.outputEstimate + usage.outputEstimate,
1001
+ cacheReadTokens: current.cacheReadTokens + usage.cacheReadTokens,
1002
+ cacheWriteTokens: current.cacheWriteTokens + usage.cacheWriteTokens,
1003
+ noCacheTokens: current.noCacheTokens + usage.noCacheTokens,
1004
+ reasoningTokens: current.reasoningTokens + usage.reasoningTokens,
1005
+ logicalInputEstimate: current.logicalInputEstimate + usage.logicalInputEstimate,
1006
+ effectiveNonCachedInput: (current.effectiveNonCachedInput ?? 0) + (usage.effectiveNonCachedInput ?? 0) || usage.effectiveNonCachedInput,
1007
+ }));
872
1008
  },
873
1009
  onEvent: event => {
874
1010
  const session = sessionRef.current;
@@ -876,11 +1012,16 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
876
1012
  void appendSessionEntry(session, { type: 'event', at: event.at, name: event.type, text: JSON.stringify(event) }).catch(() => undefined);
877
1013
  },
878
1014
  onTasksChanged: () => { loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined); },
879
- });
1015
+ log: llmLogRef.current,
1016
+ }, 0, false, false, { start: sessionStartRef.current, cwd: process.cwd() });
880
1017
  }
881
1018
  const visible = messages.filter(message => !message.hidden);
882
- const transcriptItems = visible.map((message, index) => ({ key: messageKey(message, index), message }));
883
1019
  const activeLiveMessages = liveMessages.filter(message => !message.hidden);
1020
+ const orderedVisibleMessages = orderedDisplayMessages([...visible, ...activeLiveMessages]);
1021
+ const annotatedDisplayMessages = annotateTurnHeaders(orderedVisibleMessages);
1022
+ const staticDisplayItems = annotatedDisplayMessages.filter(item => !item.message.streaming);
1023
+ const transcriptItems = staticDisplayItems.map((item, index) => ({ key: messageKey(item.message, index), ...item }));
1024
+ const activeLiveItems = annotatedDisplayMessages.filter(item => item.message.streaming);
884
1025
  const activeSelection = activeModel(settings);
885
1026
  const placeholder = mode === 'provider'
886
1027
  ? 'Choose provider'
@@ -902,28 +1043,38 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
902
1043
  ? 'model-a, model-b'
903
1044
  : mode === 'providerConfirmRemove'
904
1045
  ? 'Type "yes" to confirm'
905
- : busy ? 'Queue a follow-up, or Esc to interrupt' : 'Ask Haze to help build your app';
906
- const activeModelName = `${activeSelection.provider.name}:${process.env.HAZE_MODEL ?? activeSelection.model}`;
907
- const hasLogin = Boolean(process.env.OPENAI_API_KEY ?? settings.apiKey ?? activeSelection.provider.key) || activeSelection.provider.name !== DEFAULT_PROVIDER_NAME;
908
- const hasChosenModel = Boolean(process.env.HAZE_MODEL ?? settings.model ?? activeSelection.model);
909
- const headerSubtitle = hasLogin && hasChosenModel
910
- ? [
911
- 'A minimal LLM harness for growing your own workflows while you work.',
912
- '',
913
- 'Start with simple chat, then teach Haze your habits with skills:',
914
- '/create-skill review my branch against main — tiny spell, useful goblin.',
915
- '',
916
- 'The most adaptive workflow is the one you shape as you go.',
917
- '',
918
- 'Guardrails are light: Haze lets the LLM work from the terminal almost like you,',
919
- 'while trying to stay scoped to this project.',
920
- ].join('\n')
921
- : 'First things first: run /provider to choose or add a provider, then select a model.';
922
- const workspaceLabel = `${process.cwd()}${branchName ? ` (${branchName})` : ''}`;
1046
+ : mode === 'skillCreateName'
1047
+ ? 'Skill name (kebab-case, e.g. security-review)'
1048
+ : mode === 'skillCreateRole'
1049
+ ? 'Role (optional — Enter to skip)'
1050
+ : mode === 'skillCreateDescription'
1051
+ ? 'Describe what the skill should do'
1052
+ : busy ? 'Queue a follow-up, or Esc to interrupt' : 'Ask Haze to help build your app';
1053
+ const activeModelName = activeSelection ? `${activeSelection.provider.name}:${activeSelection.model}` : 'unconfigured';
1054
+ const headerSubtitle = [
1055
+ 'A minimal LLM harness for growing your own workflows while you work.',
1056
+ '',
1057
+ 'Start with simple chat, then teach Haze your habits with skills:',
1058
+ '/create-skill — three-step skill wizard (name, role, description).',
1059
+ '',
1060
+ 'The most adaptive workflow is the one you shape as you go.',
1061
+ '',
1062
+ 'Guardrails are light: Haze lets the LLM work from the terminal almost like you,',
1063
+ 'while trying to stay scoped to this project.',
1064
+ ].join('\n');
1065
+ const workspaceLabel = `${compactHomePath(process.cwd())}${branchName ? ` (${branchName})` : ''}`;
923
1066
  const allDisplayMessages = [...messages, ...liveMessages];
1067
+ const hazeMessages = allDisplayMessages.filter(message => message.role === 'assistant' && !message.hidden).length;
924
1068
  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'}`;
1069
+ const fallbackTokens = estimateConversationTokens(allDisplayMessages);
1070
+ const estimatedLogicalInput = tokenUsage.logicalInputEstimate || fallbackTokens.input || 0;
1071
+ const providerInput = tokenUsage.inputTokens;
1072
+ const effectiveInput = providerInput == null ? estimatedLogicalInput : Math.max(providerInput, estimatedLogicalInput);
1073
+ const effectiveOutput = tokenUsage.outputTokens ?? (fallbackTokens.output || 0);
1074
+ const inputEstimated = providerInput == null || effectiveInput !== providerInput;
1075
+ const outputEstimated = tokenUsage.outputTokens == null;
1076
+ const statusDetailLabel = `${hazeMessages} haze message${hazeMessages === 1 ? '' : 's'} / ${toolsUsed} tool call${toolsUsed === 1 ? '' : 's'} / LLM ${inputEstimated ? '~' : ''}↑${formatTokenCount(effectiveInput)} ${outputEstimated ? '~' : ''}↓${formatTokenCount(effectiveOutput)} / ${skills.length} skill${skills.length === 1 ? '' : 's'}`;
1077
+ const hasTokenBreakdown = tokenUsage.systemPrompt > 0 || tokenUsage.messages > 0 || tokenUsage.toolSchemas > 0 || effectiveInput > 0 || effectiveOutput > 0;
927
1078
  const goalText = activeGoalStatus?.replace(/^Goal:\s*/, '');
928
1079
  // Goal tracking is internal; display removed in favor of task bar
929
1080
  void goalText;
@@ -932,8 +1083,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
932
1083
  { value: '/provider', description: 'Choose a provider', kind: 'command' },
933
1084
  { value: '/model', description: 'Choose a model', kind: 'command' },
934
1085
  { 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' },
1086
+ { value: '/create-skill ', description: 'Launch the skill wizard', kind: 'command' },
937
1087
  { value: '/skill-info ', description: 'Show details for a skill', kind: 'command' },
938
1088
  { value: '/validate-skill ', description: 'Validate a skill', kind: 'command' },
939
1089
  { value: '/remove-skill ', description: 'Remove a skill with --yes', kind: 'command' },
@@ -948,12 +1098,12 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
948
1098
  ...skills.map(skill => ({ value: `/${skill.name}`, description: skill.description, kind: 'skill' })),
949
1099
  ] : [];
950
1100
  const staticItems = [
951
- { kind: 'header', key: `header-${activeModelName}-${hasLogin}-${hasChosenModel}`, subtitle: headerSubtitle },
1101
+ { kind: 'header', key: `header-${activeModelName}`, subtitle: headerSubtitle },
952
1102
  ...transcriptItems.map(item => ({ kind: 'message', ...item })),
953
1103
  ];
954
1104
  return _jsxs(Box, { flexDirection: "column", children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
955
1105
  ? _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: () => {
1106
+ : _jsx(MessageView, { message: item.message, width: width, suppressAssistantHeader: item.suppressAssistantHeader }, item.key) }), activeLiveItems.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, children: activeLiveItems.map((item, index) => _jsx(MessageView, { message: item.message, width: width, suppressAssistantHeader: item.suppressAssistantHeader }, messageKey(item.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
1107
  if (!tasksExpanded) {
958
1108
  setTaskBarPadding(0);
959
1109
  setTasksExpanded(true);
@@ -969,7 +1119,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
969
1119
  cancelThinking();
970
1120
  else
971
1121
  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 }) })] })] });
1122
+ }, onSubmit: submit }) }) }), debug && hasTokenBreakdown && _jsxs(Box, { flexShrink: 0, flexDirection: "column", paddingX: 1, children: [_jsxs(Text, { color: theme.muted, bold: true, children: ["Token usage ", inputEstimated || outputEstimated ? '(estimated)' : '(precise)'] }), _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
1123
  }
974
1124
  export async function chatCommand(options = {}) {
975
1125
  if (process.stdout.isTTY) {