@denizokcu/haze 0.2.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 (50) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +38 -22
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +411 -74
  5. package/dist/cli/commands/commands.js +122 -54
  6. package/dist/cli/commands/formatters.d.ts +2 -0
  7. package/dist/cli/commands/formatters.js +34 -0
  8. package/dist/cli/commands/streaming.d.ts +36 -1
  9. package/dist/cli/commands/streaming.js +312 -103
  10. package/dist/cli/contextReport.d.ts +1 -0
  11. package/dist/cli/contextReport.js +47 -0
  12. package/dist/config/contextFiles.d.ts +25 -0
  13. package/dist/config/contextFiles.js +53 -0
  14. package/dist/config/providerPresets.d.ts +23 -0
  15. package/dist/config/providerPresets.js +230 -0
  16. package/dist/core/agent/compaction.d.ts +3 -0
  17. package/dist/core/agent/compaction.js +23 -3
  18. package/dist/core/agent/contextBudget.d.ts +33 -0
  19. package/dist/core/agent/contextBudget.js +88 -0
  20. package/dist/core/agent/requestAssembly.d.ts +22 -0
  21. package/dist/core/agent/requestAssembly.js +146 -0
  22. package/dist/core/agent/toolOutputStore.d.ts +11 -0
  23. package/dist/core/agent/toolOutputStore.js +33 -0
  24. package/dist/core/agent/workState.d.ts +38 -0
  25. package/dist/core/agent/workState.js +89 -0
  26. package/dist/core/goal/completionPolicy.js +1 -1
  27. package/dist/core/goal/sessionGoal.d.ts +2 -0
  28. package/dist/core/goal/sessionGoal.js +8 -1
  29. package/dist/core/log/llmLog.d.ts +68 -0
  30. package/dist/core/log/llmLog.js +55 -0
  31. package/dist/core/session/sessionStore.d.ts +6 -0
  32. package/dist/core/session/sessionStore.js +5 -0
  33. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  34. package/dist/core/subagent/subagentRunner.js +5 -15
  35. package/dist/core/tasks/taskStorage.d.ts +13 -0
  36. package/dist/core/tasks/taskStorage.js +29 -0
  37. package/dist/core/validation/outputParser.js +15 -2
  38. package/dist/llm/client.d.ts +39 -0
  39. package/dist/llm/client.js +46 -2
  40. package/dist/llm/hazeTools.d.ts +53 -12
  41. package/dist/llm/hazeTools.js +170 -46
  42. package/dist/llm/systemPrompt.d.ts +6 -1
  43. package/dist/llm/systemPrompt.js +42 -79
  44. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  45. package/dist/skills/builder/SkillBuilder.js +68 -65
  46. package/dist/skills/skillTools.d.ts +2 -19
  47. package/dist/skills/skillTools.js +28 -19
  48. package/dist/ui/components/TextInput.d.ts +2 -1
  49. package/dist/ui/components/TextInput.js +6 -2
  50. package/package.json +2 -1
@@ -6,6 +6,7 @@ import { Box, render, Static, Text, useApp, useStdout } from 'ink';
6
6
  import Spinner from 'ink-spinner';
7
7
  import { readContextFiles } from '../../config/contextFiles.js';
8
8
  import { addInputHistoryItem, readInputHistory } from '../../config/inputHistory.js';
9
+ import { loadTasks as loadTasksFromStore, clearTasks as clearTasksFromStore } from '../../core/tasks/taskStorage.js';
9
10
  import { readSettings, updateSettings } from '../../config/settings.js';
10
11
  import { activeModel, configuredProviders, DEFAULT_PROVIDER_NAME, findProvider, modelSelector, providerHasKey, resolveModelSelector, upsertProvider } from '../../config/providers.js';
11
12
  import { Header } from '../../ui/components/Header.js';
@@ -14,11 +15,16 @@ import { MarkdownText } from '../../ui/components/MarkdownText.js';
14
15
  import { theme } from '../../ui/theme.js';
15
16
  import { handleSlashCommand } from './commands.js';
16
17
  import { runAgentTurn } from './streaming.js';
18
+ import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
19
+ import { formatElapsedTime, formatElapsedTimeWhole } from './formatters.js';
17
20
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
18
- import { appendSessionEntry, createSession, formatSession, latestSession, restoreConversation } from '../../core/session/sessionStore.js';
21
+ import { createSkill, toSkillDirName } from '../../skills/builder/SkillBuilder.js';
22
+ import { PROVIDER_PRESETS, findPreset } from '../../config/providerPresets.js';
23
+ import { appendSessionEntry, createSession, formatSession, latestSession, restoreConversation, restoreWorkState } from '../../core/session/sessionStore.js';
19
24
  import { compactModelMessages, modelMessageText } from '../../core/agent/compaction.js';
20
- import { createSessionGoal, formatGoalStatus } from '../../core/goal/sessionGoal.js';
25
+ import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
21
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 };
22
28
  async function currentBranchName() {
23
29
  try {
24
30
  const { stdout } = await execFile('git', ['branch', '--show-current'], { cwd: process.cwd() });
@@ -49,11 +55,6 @@ function formatTokenCount(tokens) {
49
55
  return `${(tokens / 1_000).toFixed(tokens >= 10_000 ? 0 : 1).replace(/\.0$/, '')}k`;
50
56
  return String(tokens);
51
57
  }
52
- function truncateWithEllipsis(text, maxLength) {
53
- if (text.length <= maxLength)
54
- return text;
55
- return `${text.slice(0, maxLength).trimEnd()}…`;
56
- }
57
58
  function displayMessagesFromConversation(conversation) {
58
59
  return conversation.flatMap(message => {
59
60
  if (message.role !== 'user' && message.role !== 'assistant')
@@ -100,18 +101,27 @@ function ToolMessageText({ text, streaming }) {
100
101
  }
101
102
  const row = /^(\s*)([✓✗…])\s+(\S+)(.*)$/.exec(line);
102
103
  if (!row) {
103
- return _jsxs(Text, { color: theme.muted, children: [index === 0 && streaming ? _jsxs(_Fragment, { children: [_jsx(Spinner, { type: "dots" }), " "] }) : null, line] }, `${index}-${line}`);
104
+ const timer = /(.*) (\([0-9]+(?:h [0-9]+m [0-9]+(?:\.[0-9])?s|m [0-9]+(?:\.[0-9])?s|(?:\.[0-9])?s)\))$/.exec(line);
105
+ return _jsxs(Text, { color: theme.muted, children: [index === 0 && streaming ? _jsxs(_Fragment, { children: [_jsx(Spinner, { type: "dots" }), " "] }) : null, timer ? timer[1] : line, timer ? _jsxs(Text, { color: theme.muted, bold: false, children: [" ", timer[2]] }) : null] }, `${index}-${line}`);
104
106
  }
105
107
  const [, indent, icon, toolName, rest] = row;
106
108
  const iconColor = icon === '✓' ? theme.success : icon === '✗' ? theme.danger : theme.muted;
107
- return _jsxs(Text, { color: theme.muted, children: [indent, _jsx(Text, { color: iconColor, children: icon }), " ", _jsx(Text, { color: theme.purple, children: toolName }), rest] }, `${index}-${line}`);
109
+ const timer = /(.*) (\([0-9]+(?:h [0-9]+m [0-9]+(?:\.[0-9])?s|m [0-9]+(?:\.[0-9])?s|(?:\.[0-9])?s)\))$/.exec(rest);
110
+ return _jsxs(Text, { color: theme.muted, children: [indent, _jsx(Text, { color: iconColor, children: icon }), " ", _jsx(Text, { color: theme.purple, children: toolName }), timer ? timer[1] : rest, timer ? _jsxs(Text, { color: theme.muted, bold: false, children: [" ", timer[2]] }) : null] }, `${index}-${line}`);
108
111
  }) });
109
112
  }
113
+ function messageElapsedLabel(message) {
114
+ if (message.startedAt == null)
115
+ return '';
116
+ const end = message.finishedAt ?? (message.streaming ? Date.now() : message.startedAt);
117
+ const elapsed = end - message.startedAt;
118
+ return message.streaming ? formatElapsedTimeWhole(elapsed) : formatElapsedTime(elapsed);
119
+ }
110
120
  function MessageView({ message, width }) {
111
121
  if (message.role === 'user') {
112
122
  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) })] });
113
123
  }
114
- return _jsxs(Box, { flexDirection: "column", marginBottom: 1, 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' }), message.role === 'tool'
124
+ 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'
115
125
  ? _jsx(ToolMessageText, { text: message.text, streaming: message.streaming })
116
126
  : message.role === 'assistant' && !message.streaming
117
127
  ? _jsx(MarkdownText, { content: message.text })
@@ -137,6 +147,43 @@ function startupProviderInfo(settings) {
137
147
  `- Configured providers: ${configuredProviders(settings).length}`,
138
148
  ].join('\n');
139
149
  }
150
+ const TASK_STATUS_ICON = {
151
+ pending: '\u25CB',
152
+ in_progress: '\u25D0',
153
+ completed: '\u2713',
154
+ };
155
+ function taskStatusColor(status) {
156
+ switch (status) {
157
+ case 'completed': return theme.success;
158
+ case 'in_progress': return theme.warning;
159
+ default: return theme.muted;
160
+ }
161
+ }
162
+ const MAX_VISIBLE_TASKS = 5;
163
+ function TaskBarContent({ tasks, width, expanded, padding }) {
164
+ const maxTitleWidth = Math.max(10, width - 6);
165
+ const inProgress = tasks.filter(t => t.status === 'in_progress');
166
+ const pending = tasks.filter(t => t.status === 'pending');
167
+ const completed = tasks.filter(t => t.status === 'completed');
168
+ const limit = expanded ? tasks.length : MAX_VISIBLE_TASKS;
169
+ const ordered = [];
170
+ for (const t of inProgress) {
171
+ if (ordered.length < limit)
172
+ ordered.push(t);
173
+ }
174
+ for (const t of pending) {
175
+ if (ordered.length < limit)
176
+ ordered.push(t);
177
+ }
178
+ for (let i = completed.length - 1; i >= 0 && ordered.length < limit; i--) {
179
+ ordered.push(completed[i]);
180
+ }
181
+ const counts = `${inProgress.length > 0 ? `${inProgress.length} active` : ''}${pending.length > 0 ? `${inProgress.length > 0 ? ', ' : ''}${pending.length} pending` : ''}${completed.length > 0 ? `${inProgress.length + pending.length > 0 ? ', ' : ''}${completed.length} done` : ''}`;
182
+ return (_jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [padding > 0 && Array.from({ length: padding }, (_, i) => _jsx(Text, { children: ' ' }, `pad-${i}`)), _jsxs(Text, { children: [_jsx(Text, { color: theme.purple, bold: true, children: "Tasks" }), counts ? _jsxs(Text, { color: theme.muted, children: [" (", counts, ")"] }) : null, tasks.length > MAX_VISIBLE_TASKS ? _jsxs(Text, { color: theme.muted, dimColor: true, children: [" \u00B7 ctrl+o ", expanded ? 'collapse' : 'expand'] }) : null] }), ordered.map(task => {
183
+ const title = task.title.length > maxTitleWidth ? task.title.slice(0, maxTitleWidth - 1) + '\u2026' : task.title;
184
+ return (_jsxs(Text, { wrap: "truncate-end", children: [_jsxs(Text, { color: taskStatusColor(task.status), children: [TASK_STATUS_ICON[task.status], " "] }), _jsx(Text, { color: task.status === 'completed' ? theme.muted : 'white', children: title })] }, task.id));
185
+ })] }));
186
+ }
140
187
  function ChatScreen({ debug = false, version, continueSession = false, noSession = false }) {
141
188
  const { exit } = useApp();
142
189
  const { stdout } = useStdout();
@@ -158,6 +205,9 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
158
205
  const lastAssistantTextRef = useRef('');
159
206
  const abortControllerRef = useRef(null);
160
207
  const sessionRef = useRef(undefined);
208
+ const sessionStartRef = useRef(new Date());
209
+ const workStateRef = useRef(undefined);
210
+ const llmLogRef = useRef(undefined);
161
211
  const followUpQueueRef = useRef([]);
162
212
  const [inputHistory, setInputHistory] = useState([]);
163
213
  const [debugLogs, setDebugLogs] = useState([]);
@@ -166,13 +216,23 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
166
216
  const [busy, setBusy] = useState(false);
167
217
  const [busyLabel, setBusyLabel] = useState('Haze is thinking');
168
218
  const [activeGoalStatus, setActiveGoalStatus] = useState();
169
- const [sessionLabel, setSessionLabel] = useState();
219
+ const [visibleTasks, setVisibleTasks] = useState([]);
220
+ const [tasksExpanded, setTasksExpanded] = useState(false);
221
+ const [taskBarPadding, setTaskBarPadding] = useState(0);
222
+ const [, setSessionLabel] = useState();
223
+ const [tokenUsage, setTokenUsage] = useState({ ...EMPTY_TOKEN_USAGE });
224
+ const [, setTimerTick] = useState(0);
170
225
  const [queuedFollowUps, setQueuedFollowUps] = useState([]);
171
226
  const [skills, setSkills] = useState([]);
172
227
  const [branchName, setBranchName] = useState();
173
228
  const [modelProviderFilter, setModelProviderFilter] = useState();
174
229
  const [selectedProviderName, setSelectedProviderName] = useState();
175
230
  const [providerDraft, setProviderDraft] = useState({});
231
+ const [skillCreateDraft, setSkillCreateDraft] = useState({});
232
+ useEffect(() => {
233
+ const timer = setInterval(() => setTimerTick(tick => tick + 1), 1000);
234
+ return () => clearInterval(timer);
235
+ }, []);
176
236
  useEffect(() => {
177
237
  Promise.all([readSettings(), currentBranchName()]).then(([next, branch]) => {
178
238
  setSettings(next);
@@ -193,6 +253,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
193
253
  readInputHistory().then(setInputHistory).catch(() => undefined);
194
254
  readContextFiles().then(setContextFiles).catch(() => undefined);
195
255
  refreshSkills().catch(() => undefined);
256
+ loadTasksFromStore().then(setVisibleTasks).catch(() => undefined);
196
257
  const branchTimer = setInterval(() => {
197
258
  currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
198
259
  }, 3000);
@@ -221,7 +282,18 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
221
282
  return;
222
283
  setDebugLogs(current => [...current.slice(-7), line]);
223
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
+ }
224
293
  async function startNewSession(message = 'Started a new session.') {
294
+ clearToolOutputs();
295
+ workStateRef.current = undefined;
296
+ sessionStartRef.current = new Date();
225
297
  if (noSession) {
226
298
  sessionRef.current = undefined;
227
299
  setSessionLabel('session off');
@@ -229,6 +301,8 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
229
301
  }
230
302
  const session = await createSession({ hazeVersion: version });
231
303
  sessionRef.current = session;
304
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE });
305
+ await startNewLog();
232
306
  setSessionLabel(session.id);
233
307
  setMessages(m => [...m, { role: 'system', text: `${message}\nSession saved: ${session.file}` }]);
234
308
  }
@@ -242,26 +316,35 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
242
316
  if (session) {
243
317
  const conversation = await restoreConversation(session);
244
318
  sessionRef.current = session;
319
+ sessionStartRef.current = new Date();
245
320
  conversationRef.current = conversation;
246
321
  setSessionLabel(session.id);
247
322
  setLiveMessagesState(() => []);
248
- setMessages(m => [...m, { role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...displayMessagesFromConversation(conversation)]);
323
+ const restoredMessages = displayMessagesFromConversation(conversation);
324
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE, messages: estimateConversationTokens(restoredMessages).input, outputEstimate: estimateConversationTokens(restoredMessages).output });
325
+ workStateRef.current = await restoreWorkState(session);
326
+ setMessages(m => [...m, { role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...restoredMessages]);
327
+ await startNewLog();
249
328
  return;
250
329
  }
251
330
  }
252
331
  await startNewSession(continueSession ? 'No previous session found. Started a new session.' : 'Started a new session.');
253
332
  }
254
333
  function clearConversation() {
334
+ clearToolOutputs();
255
335
  conversationRef.current = [];
256
336
  lastAssistantTextRef.current = '';
337
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE });
338
+ workStateRef.current = undefined;
257
339
  setLiveMessagesState(() => []);
258
340
  setMessages([{ role: 'system', text: 'Cleared. The void is productive.' }]);
341
+ void startNewLog();
259
342
  const session = sessionRef.current;
260
343
  if (session)
261
344
  void appendSessionEntry(session, { type: 'event', at: new Date().toISOString(), name: 'clear', text: 'Conversation cleared' }).catch(() => undefined);
262
345
  }
263
346
  function compactConversation(instructions) {
264
- const result = compactModelMessages(conversationRef.current, { instructions });
347
+ const result = compactModelMessages(conversationRef.current, { instructions, tokenBudget: 40_000, workState: workStateRef.current });
265
348
  if (!result.compacted) {
266
349
  setMessages(m => [...m, { role: 'system', text: `Compaction skipped: only ${result.keptCount} model messages in context.` }]);
267
350
  return false;
@@ -282,9 +365,12 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
282
365
  return;
283
366
  }
284
367
  const conversation = await restoreConversation(session);
368
+ clearToolOutputs();
285
369
  sessionRef.current = session;
286
370
  conversationRef.current = conversation;
371
+ workStateRef.current = await restoreWorkState(session);
287
372
  setSessionLabel(session.id);
373
+ setTokenUsage({ ...EMPTY_TOKEN_USAGE });
288
374
  setLiveMessagesState(() => []);
289
375
  setMessages([{ role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...displayMessagesFromConversation(conversation)]);
290
376
  }
@@ -308,10 +394,12 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
308
394
  setMessages(m => [...m, { role: 'system', text: `Queued follow-up (${followUpQueueRef.current.length}): ${trimmed}` }]);
309
395
  }
310
396
  function closeInputList() {
311
- if (mode === 'provider' || mode === 'providerAction' || mode === 'model') {
397
+ if (mode !== 'chat') {
312
398
  setMode('chat');
313
399
  setModelProviderFilter(undefined);
314
400
  setSelectedProviderName(undefined);
401
+ setProviderDraft({});
402
+ setSkillCreateDraft({});
315
403
  }
316
404
  }
317
405
  function providerSuggestions() {
@@ -321,13 +409,34 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
321
409
  description: `${provider.url} · ${provider.models.length} model${provider.models.length === 1 ? '' : 's'}`,
322
410
  kind: 'provider',
323
411
  })),
324
- { value: 'add provider', description: 'Add a new OpenAI-compatible provider', kind: 'provider' },
412
+ { value: 'add provider', description: 'Add a new provider (presets available)', kind: 'provider' },
325
413
  ];
326
414
  }
327
415
  function providerActionSuggestions() {
416
+ const provider = selectedProviderName ? findProvider(settings, selectedProviderName) : undefined;
328
417
  return [
329
418
  { value: 'use provider', description: 'Set this provider and choose a model', kind: 'provider' },
330
- { value: 'add models', description: 'Append comma-separated model names to this provider', kind: 'provider' },
419
+ { value: 'add models', description: 'Append comma-separated model names', kind: 'provider' },
420
+ { value: 'set API key', description: provider?.key ? 'Update the saved API key' : 'Add an API key', kind: 'provider' },
421
+ ...(provider?.models?.length ? [{ value: 'remove models', description: 'Remove models from this provider', kind: 'provider' }] : []),
422
+ { value: 'remove provider', description: 'Delete this provider from settings', kind: 'provider' },
423
+ ];
424
+ }
425
+ function presetSuggestions() {
426
+ const cloudPresets = PROVIDER_PRESETS.filter(p => p.category === 'cloud');
427
+ const localPresets = PROVIDER_PRESETS.filter(p => p.category === 'local');
428
+ return [
429
+ ...cloudPresets.map(preset => ({
430
+ value: preset.id,
431
+ description: `${preset.baseUrl}${preset.suggestedModels?.length ? ' · e.g. ' + preset.suggestedModels.slice(0, 2).join(', ') : ''}`,
432
+ kind: 'provider',
433
+ })),
434
+ ...localPresets.map(preset => ({
435
+ value: preset.id,
436
+ description: `${preset.baseUrl} · local, no API key needed`,
437
+ kind: 'provider',
438
+ })),
439
+ { value: 'custom', description: 'Enter provider name, URL, and API key manually', kind: 'provider' },
331
440
  ];
332
441
  }
333
442
  function modelSuggestions() {
@@ -341,8 +450,8 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
341
450
  async function selectProvider(providerName) {
342
451
  if (providerName === 'add provider') {
343
452
  setProviderDraft({});
344
- setMode('providerAddName');
345
- setMessages(m => [...m, { role: 'system', text: 'Provider name? Example: openrouter, local, lmstudio.' }]);
453
+ setMode('providerAddPreset');
454
+ setMessages(m => [...m, { role: 'system', text: 'Choose a provider preset, or select "custom" to enter details manually.' }]);
346
455
  return;
347
456
  }
348
457
  const provider = findProvider(settings, providerName);
@@ -355,6 +464,39 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
355
464
  setMode('providerAction');
356
465
  setMessages(m => [...m, { role: 'system', text: `${provider.name}: choose an action.` }]);
357
466
  }
467
+ async function selectPreset(presetId) {
468
+ if (presetId === 'custom') {
469
+ setProviderDraft({});
470
+ setMode('providerAddName');
471
+ setMessages(m => [...m, { role: 'system', text: 'Provider name? Example: openrouter, local, lmstudio.' }]);
472
+ return;
473
+ }
474
+ const preset = findPreset(presetId);
475
+ if (!preset) {
476
+ setMessages(m => [...m, { role: 'system', text: `Unknown preset: ${presetId}.` }]);
477
+ return;
478
+ }
479
+ // Check if a provider with this name already exists
480
+ const existingName = settings.providers?.some(p => p.name === preset.name) ? preset.id : preset.name;
481
+ const nameConflict = settings.providers?.some(p => p.name === existingName);
482
+ if (nameConflict) {
483
+ setMessages(m => [...m, { role: 'system', text: `Provider ${existingName} already exists. Use /provider to manage existing providers.` }]);
484
+ setMode('chat');
485
+ setProviderDraft({});
486
+ return;
487
+ }
488
+ setProviderDraft({ name: existingName, url: preset.baseUrl });
489
+ if (preset.needsApiKey) {
490
+ setMode('providerAddKey');
491
+ setMessages(m => [...m, { role: 'system', text: `${preset.name} (${preset.baseUrl})\nAPI key${preset.apiKeyHint ? ` (${preset.apiKeyHint})` : ''}?` }]);
492
+ }
493
+ else {
494
+ // Local/keyless: skip API key, go straight to models
495
+ setMode('providerAddModels');
496
+ const hint = preset.suggestedModels?.length ? ` Example: ${preset.suggestedModels.join(', ')}` : '';
497
+ setMessages(m => [...m, { role: 'system', text: `${preset.name} (${preset.baseUrl}) — no API key needed.\nComma-separated model names?${hint}` }]);
498
+ }
499
+ }
358
500
  async function useProvider(providerName) {
359
501
  const provider = findProvider(settings, providerName);
360
502
  if (!provider) {
@@ -375,6 +517,13 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
375
517
  setMode('provider');
376
518
  return;
377
519
  }
520
+ const provider = findProvider(settings, selectedProviderName);
521
+ if (!provider) {
522
+ setMessages(m => [...m, { role: 'system', text: `Provider ${selectedProviderName} not found.` }]);
523
+ setMode('chat');
524
+ setSelectedProviderName(undefined);
525
+ return;
526
+ }
378
527
  if (action === 'use provider') {
379
528
  await useProvider(selectedProviderName);
380
529
  return;
@@ -384,6 +533,21 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
384
533
  setMessages(m => [...m, { role: 'system', text: `Comma-separated model names to add to ${selectedProviderName}?` }]);
385
534
  return;
386
535
  }
536
+ if (action === 'set API key') {
537
+ setMode('providerSetKey');
538
+ setMessages(m => [...m, { role: 'system', text: `New API key for ${selectedProviderName}? (current: ${provider.key ? 'saved' : 'not set'})` }]);
539
+ return;
540
+ }
541
+ if (action === 'remove models') {
542
+ setMode('providerRemoveModels');
543
+ setMessages(m => [...m, { role: 'system', text: `Comma-separated model names to remove from ${selectedProviderName}?\nCurrent models: ${provider.models.join(', ')}` }]);
544
+ return;
545
+ }
546
+ if (action === 'remove provider') {
547
+ setMode('providerConfirmRemove');
548
+ setMessages(m => [...m, { role: 'system', text: `Remove provider ${selectedProviderName}? Type "yes" to confirm. Esc to cancel.` }]);
549
+ return;
550
+ }
387
551
  setMessages(m => [...m, { role: 'system', text: `Unknown provider action: ${action}` }]);
388
552
  }
389
553
  async function selectModel(selector) {
@@ -444,12 +608,76 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
444
608
  setMode('model');
445
609
  setMessages(m => [...m, { role: 'system', text: `Added provider ${provider.name}. Choose a model.` }]);
446
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
+ }
447
663
  async function submit(value) {
448
664
  if (busy) {
449
665
  if (mode === 'chat')
450
666
  queueFollowUp(value);
451
667
  return;
452
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
+ }
453
681
  if (mode === 'provider') {
454
682
  await selectProvider(value);
455
683
  return;
@@ -458,6 +686,10 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
458
686
  await selectProviderAction(value);
459
687
  return;
460
688
  }
689
+ if (mode === 'providerAddPreset') {
690
+ await selectPreset(value);
691
+ return;
692
+ }
461
693
  if (mode === 'model') {
462
694
  await selectModel(value);
463
695
  return;
@@ -504,22 +736,93 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
504
736
  await appendModelsToProvider(value);
505
737
  return;
506
738
  }
739
+ if (mode === 'providerSetKey') {
740
+ const provider = selectedProviderName ? findProvider(settings, selectedProviderName) : undefined;
741
+ if (!provider) {
742
+ setMessages(m => [...m, { role: 'system', text: 'No provider selected.' }]);
743
+ setMode('chat');
744
+ return;
745
+ }
746
+ const key = value.trim();
747
+ if (!key) {
748
+ setMessages(m => [...m, { role: 'system', text: 'API key cannot be empty. Esc to cancel.' }]);
749
+ return;
750
+ }
751
+ const updated = { ...provider, key };
752
+ const next = await updateSettings({ providers: upsertProvider(settings, updated) });
753
+ setSettings(next);
754
+ setSelectedProviderName(undefined);
755
+ setMode('chat');
756
+ setMessages(m => [...m, { role: 'system', text: `API key updated for ${provider.name}.` }]);
757
+ return;
758
+ }
759
+ if (mode === 'providerRemoveModels') {
760
+ const provider = selectedProviderName ? findProvider(settings, selectedProviderName) : undefined;
761
+ if (!provider) {
762
+ setMessages(m => [...m, { role: 'system', text: 'No provider selected.' }]);
763
+ setMode('chat');
764
+ return;
765
+ }
766
+ const toRemove = value.split(',').map(m => m.trim()).filter(Boolean);
767
+ if (toRemove.length === 0) {
768
+ setMessages(m => [...m, { role: 'system', text: 'Enter at least one model name. Esc to cancel.' }]);
769
+ return;
770
+ }
771
+ const remaining = provider.models.filter(m => !toRemove.includes(m));
772
+ if (remaining.length === 0) {
773
+ setMessages(m => [...m, { role: 'system', text: 'A provider must have at least one model. Remove the provider instead.' }]);
774
+ return;
775
+ }
776
+ const removed = provider.models.filter(m => toRemove.includes(m));
777
+ const notFound = toRemove.filter(m => !provider.models.includes(m));
778
+ const updated = { ...provider, models: remaining };
779
+ const wasActive = settings.model && provider.models.includes(settings.model) && !remaining.includes(settings.model);
780
+ const next = await updateSettings({
781
+ providers: upsertProvider(settings, updated),
782
+ ...(wasActive ? { model: remaining[0] } : {}),
783
+ });
784
+ setSettings(next);
785
+ setSelectedProviderName(undefined);
786
+ setMode('chat');
787
+ const parts = [`Removed ${removed.join(', ')} from ${provider.name}.`];
788
+ if (notFound.length)
789
+ parts.push(`Not found: ${notFound.join(', ')}.`);
790
+ if (wasActive)
791
+ parts.push(`Active model updated to ${remaining[0]}.`);
792
+ setMessages(m => [...m, { role: 'system', text: parts.join(' ') }]);
793
+ return;
794
+ }
795
+ if (mode === 'providerConfirmRemove') {
796
+ const provider = selectedProviderName ? findProvider(settings, selectedProviderName) : undefined;
797
+ if (!provider) {
798
+ setMessages(m => [...m, { role: 'system', text: 'No provider selected.' }]);
799
+ setMode('chat');
800
+ return;
801
+ }
802
+ if (value.trim().toLowerCase() !== 'yes') {
803
+ setMessages(m => [...m, { role: 'system', text: 'Cancelled. Provider not removed.' }]);
804
+ setSelectedProviderName(undefined);
805
+ setMode('chat');
806
+ return;
807
+ }
808
+ const providers = configuredProviders(settings).filter(p => p.name !== selectedProviderName);
809
+ const wasActiveProvider = settings.provider === selectedProviderName || (!settings.provider && configuredProviders(settings)[0]?.name === selectedProviderName);
810
+ const next = await updateSettings({
811
+ providers,
812
+ ...(wasActiveProvider ? { provider: providers[0]?.name, model: providers[0]?.models[0] } : {}),
813
+ });
814
+ setSettings(next);
815
+ setSelectedProviderName(undefined);
816
+ setMode('chat');
817
+ setMessages(m => [...m, { role: 'system', text: `Removed provider ${provider.name}.${wasActiveProvider ? ` Switched to ${providers[0]?.name ?? 'no provider'}.` : ''}` }]);
818
+ return;
819
+ }
507
820
  const invokedSkill = skillInvocation(value);
508
821
  if (invokedSkill) {
509
822
  const argumentText = invokedSkill.args ? `\nUser-provided skill arguments: ${invokedSkill.args}` : '';
510
- 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);
511
824
  return;
512
825
  }
513
- const isSkillCreate = /^\/create-skill(?:\s|$)/.test(value) || /^\/skills? create(?:\s|$)/.test(value);
514
- const skillCreateGoal = isSkillCreate ? createSessionGoal(value) : undefined;
515
- if (skillCreateGoal) {
516
- setDebugLogs([]);
517
- setMessages(m => [...m, { role: 'user', text: value }]);
518
- const session = sessionRef.current;
519
- if (session)
520
- void appendSessionEntry(session, { type: 'ui_message', at: new Date().toISOString(), role: 'user', text: value }).catch(() => undefined);
521
- setActiveGoalStatus(formatGoalStatus(skillCreateGoal));
522
- }
523
826
  const ctx = {
524
827
  settings,
525
828
  contextFiles,
@@ -546,40 +849,23 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
546
849
  },
547
850
  };
548
851
  let result;
549
- if (isSkillCreate) {
550
- setBusyLabel('Creating skill');
551
- setBusy(true);
552
- }
553
852
  try {
554
853
  result = await handleSlashCommand(value, ctx);
555
854
  }
556
855
  catch (error) {
557
- if (skillCreateGoal) {
558
- skillCreateGoal.status = 'blocked';
559
- skillCreateGoal.blocker = error instanceof Error ? error.message : String(error);
560
- setActiveGoalStatus(formatGoalStatus(skillCreateGoal));
561
- }
562
856
  const text = error instanceof Error ? error.message : String(error);
563
- setMessages(m => [...m, { role: 'system', text: `Skill creation failed: ${text}` }]);
857
+ setMessages(m => [...m, { role: 'system', text: `Command failed: ${text}` }]);
564
858
  return;
565
859
  }
566
- finally {
567
- if (isSkillCreate) {
568
- if (skillCreateGoal?.status === 'active') {
569
- skillCreateGoal.phase = 'done';
570
- skillCreateGoal.status = 'complete';
571
- setActiveGoalStatus(undefined);
572
- }
573
- setBusy(false);
574
- setBusyLabel('Haze is thinking');
575
- }
576
- }
577
860
  if (result === 'exit')
578
861
  return exit();
579
862
  if (result === 'handled') {
580
- 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 ')) {
581
864
  await refreshSkills().catch(() => undefined);
582
865
  }
866
+ if (value === '/clear') {
867
+ loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
868
+ }
583
869
  return;
584
870
  }
585
871
  await doAgentTurn(value);
@@ -643,13 +929,37 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
643
929
  setLastAssistantText: text => { lastAssistantTextRef.current = text; },
644
930
  setAbortController: controller => { abortControllerRef.current = controller; },
645
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
+ },
646
938
  compactConversation,
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
+ }));
954
+ },
647
955
  onEvent: event => {
648
956
  const session = sessionRef.current;
649
957
  if (session)
650
958
  void appendSessionEntry(session, { type: 'event', at: event.at, name: event.type, text: JSON.stringify(event) }).catch(() => undefined);
651
959
  },
652
- });
960
+ onTasksChanged: () => { loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined); },
961
+ log: llmLogRef.current,
962
+ }, 0, false, false, { start: sessionStartRef.current, cwd: process.cwd() });
653
963
  }
654
964
  const visible = messages.filter(message => !message.hidden);
655
965
  const transcriptItems = visible.map((message, index) => ({ key: messageKey(message, index), message }));
@@ -659,17 +969,29 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
659
969
  ? 'Choose provider'
660
970
  : mode === 'providerAction'
661
971
  ? 'Choose provider action'
662
- : mode === 'model'
663
- ? 'Choose model'
664
- : mode === 'providerAddName'
665
- ? 'Provider name'
666
- : mode === 'providerAddUrl'
667
- ? 'https://example.com/v1'
668
- : mode === 'providerAddKey'
669
- ? 'API key, or blank for local'
670
- : mode === 'providerAddModels' || mode === 'providerAppendModels'
671
- ? 'model-a, model-b'
672
- : busy ? 'Queue a follow-up, or Esc to interrupt' : 'Ask Haze to help build your app';
972
+ : mode === 'providerAddPreset'
973
+ ? 'Choose a provider preset or custom'
974
+ : mode === 'model'
975
+ ? 'Choose model'
976
+ : mode === 'providerAddName'
977
+ ? 'Provider name'
978
+ : mode === 'providerAddUrl'
979
+ ? 'https://example.com/v1'
980
+ : mode === 'providerAddKey' || mode === 'providerSetKey'
981
+ ? 'API key, or blank for local'
982
+ : mode === 'providerAddModels' || mode === 'providerAppendModels'
983
+ ? 'model-a, model-b'
984
+ : mode === 'providerRemoveModels'
985
+ ? 'model-a, model-b'
986
+ : mode === 'providerConfirmRemove'
987
+ ? 'Type "yes" to confirm'
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';
673
995
  const activeModelName = `${activeSelection.provider.name}:${process.env.HAZE_MODEL ?? activeSelection.model}`;
674
996
  const hasLogin = Boolean(process.env.OPENAI_API_KEY ?? settings.apiKey ?? activeSelection.provider.key) || activeSelection.provider.name !== DEFAULT_PROVIDER_NAME;
675
997
  const hasChosenModel = Boolean(process.env.HAZE_MODEL ?? settings.model ?? activeSelection.model);
@@ -678,7 +1000,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
678
1000
  'A minimal LLM harness for growing your own workflows while you work.',
679
1001
  '',
680
1002
  'Start with simple chat, then teach Haze your habits with skills:',
681
- '/create-skill review my branch against main — tiny spell, useful goblin.',
1003
+ '/create-skill — three-step skill wizard (name, role, description).',
682
1004
  '',
683
1005
  'The most adaptive workflow is the one you shape as you go.',
684
1006
  '',
@@ -689,19 +1011,21 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
689
1011
  const workspaceLabel = `${process.cwd()}${branchName ? ` (${branchName})` : ''}`;
690
1012
  const allDisplayMessages = [...messages, ...liveMessages];
691
1013
  const toolsUsed = toolCallCount(allDisplayMessages);
692
- const estimatedTokens = estimateConversationTokens(allDisplayMessages);
693
- const statusDetailLabel = `${conversationRef.current.length} messages / ${toolsUsed} tool call${toolsUsed === 1 ? '' : 's'} / ↑ ~${formatTokenCount(estimatedTokens.input)} ↓ ~${formatTokenCount(estimatedTokens.output)} / ${skills.length} skill${skills.length === 1 ? '' : 's'}${sessionLabel ? ` / ${sessionLabel}` : ''}`;
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;
694
1020
  const goalText = activeGoalStatus?.replace(/^Goal:\s*/, '');
695
- const [rawGoalRequest, ...goalStatusParts] = goalText?.split(' · ') ?? [];
696
- const goalRequest = truncateWithEllipsis(rawGoalRequest ?? '', 120);
697
- const goalStatusText = goalStatusParts.join(' · ');
698
- const inputSuggestions = mode === 'provider' ? providerSuggestions() : mode === 'providerAction' ? providerActionSuggestions() : mode === 'model' ? modelSuggestions() : mode === 'chat' ? [
1021
+ // Goal tracking is internal; display removed in favor of task bar
1022
+ void goalText;
1023
+ const inputSuggestions = mode === 'provider' ? providerSuggestions() : mode === 'providerAction' ? providerActionSuggestions() : mode === 'providerAddPreset' ? presetSuggestions() : mode === 'model' ? modelSuggestions() : mode === 'chat' ? [
699
1024
  { value: '/help', description: 'Show commands', kind: 'command' },
700
1025
  { value: '/provider', description: 'Choose a provider', kind: 'command' },
701
1026
  { value: '/model', description: 'Choose a model', kind: 'command' },
702
1027
  { value: '/settings', description: 'Show provider, model, API key, and context status', kind: 'command' },
703
- { value: '/create-skill ', description: 'Create a Markdown skill', kind: 'command' },
704
- { value: '/list-skills', description: 'List installed skills', kind: 'command' },
1028
+ { value: '/create-skill ', description: 'Launch the skill wizard', kind: 'command' },
705
1029
  { value: '/skill-info ', description: 'Show details for a skill', kind: 'command' },
706
1030
  { value: '/validate-skill ', description: 'Validate a skill', kind: 'command' },
707
1031
  { value: '/remove-skill ', description: 'Remove a skill with --yes', kind: 'command' },
@@ -721,17 +1045,30 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
721
1045
  ];
722
1046
  return _jsxs(Box, { flexDirection: "column", children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
723
1047
  ? _jsx(Header, { subtitle: item.subtitle, version: version }, item.key)
724
- : _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}`))] }), busy && _jsx(Box, { flexShrink: 0, marginBottom: 1, 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" })] }) }), goalText && _jsx(Box, { flexShrink: 0, children: _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: theme.blue, bold: true, children: "Goal:" }), _jsxs(Text, { color: "white", children: [" ", goalRequest] }), goalStatusText ? _jsxs(Text, { color: theme.orange, children: [" \u00B7 ", goalStatusText] }) : null] }) }), _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', historyItems: inputHistory, recordHistory: mode === 'chat', suggestions: inputSuggestions, suggestionMode: mode === 'provider' || mode === 'providerAction' || mode === 'model' ? 'always' : 'slash', submitOnEmpty: mode === 'providerAddKey', width: Math.max(20, width - 4), onHistoryAdd: persistInputHistory, onCancel: cancelThinking, onEscape: () => {
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: () => {
1049
+ if (!tasksExpanded) {
1050
+ setTaskBarPadding(0);
1051
+ setTasksExpanded(true);
1052
+ }
1053
+ else {
1054
+ const expandedRows = visibleTasks.length + 1;
1055
+ const collapsedRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS) + 1;
1056
+ setTaskBarPadding(Math.max(0, expandedRows - collapsedRows));
1057
+ setTasksExpanded(false);
1058
+ }
1059
+ }, onCancel: cancelThinking, onEscape: () => {
725
1060
  if (busy)
726
1061
  cancelThinking();
727
1062
  else
728
1063
  closeInputList();
729
- }, 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 }) })] })] });
730
1065
  }
731
1066
  export async function chatCommand(options = {}) {
732
1067
  if (process.stdout.isTTY) {
733
1068
  process.stdout.write('\u001B[2J\u001B[3J\u001B[H');
734
1069
  }
1070
+ await clearTasksFromStore().catch(() => undefined);
735
1071
  const app = render(_jsx(ChatScreen, { debug: options.debug, version: options.version, continueSession: options.continueSession, noSession: options.noSession }));
736
1072
  await app.waitUntilExit();
1073
+ await clearTasksFromStore().catch(() => undefined);
737
1074
  }