@denizokcu/haze 0.4.0 → 0.6.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 (79) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +68 -36
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +789 -106
  5. package/dist/cli/commands/commands.d.ts +2 -1
  6. package/dist/cli/commands/commands.js +77 -102
  7. package/dist/cli/commands/formatters.d.ts +27 -0
  8. package/dist/cli/commands/formatters.js +137 -0
  9. package/dist/cli/commands/streaming.d.ts +14 -13
  10. package/dist/cli/commands/streaming.js +399 -665
  11. package/dist/config/contextFiles.d.ts +6 -0
  12. package/dist/config/contextFiles.js +47 -16
  13. package/dist/config/lspSettings.d.ts +16 -0
  14. package/dist/config/lspSettings.js +98 -0
  15. package/dist/config/mcpSettings.d.ts +24 -0
  16. package/dist/config/mcpSettings.js +100 -0
  17. package/dist/config/providers.d.ts +2 -5
  18. package/dist/config/providers.js +16 -12
  19. package/dist/config/settings.d.ts +34 -0
  20. package/dist/config/skillSettings.d.ts +15 -0
  21. package/dist/config/skillSettings.js +31 -0
  22. package/dist/config/updateCheck.d.ts +44 -0
  23. package/dist/config/updateCheck.js +83 -0
  24. package/dist/core/agent/requestAssembly.js +12 -1
  25. package/dist/core/agent/toolOutputStore.d.ts +6 -1
  26. package/dist/core/agent/toolOutputStore.js +33 -1
  27. package/dist/core/bashOutput/ansi.d.ts +1 -0
  28. package/dist/core/bashOutput/ansi.js +7 -0
  29. package/dist/core/bashOutput/command.d.ts +2 -0
  30. package/dist/core/bashOutput/command.js +62 -0
  31. package/dist/core/bashOutput/lineFilter.d.ts +25 -0
  32. package/dist/core/bashOutput/lineFilter.js +62 -0
  33. package/dist/core/bashOutput/reducers/content.d.ts +3 -0
  34. package/dist/core/bashOutput/reducers/content.js +134 -0
  35. package/dist/core/bashOutput/reducers/git.d.ts +1 -0
  36. package/dist/core/bashOutput/reducers/git.js +147 -0
  37. package/dist/core/bashOutput/reducers/search.d.ts +7 -0
  38. package/dist/core/bashOutput/reducers/search.js +76 -0
  39. package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
  40. package/dist/core/bashOutput/reducers/validation.js +41 -0
  41. package/dist/core/bashOutput/registry.d.ts +4 -0
  42. package/dist/core/bashOutput/registry.js +126 -0
  43. package/dist/core/bashOutput/types.d.ts +46 -0
  44. package/dist/core/bashOutput/types.js +1 -0
  45. package/dist/core/goal/completionPolicy.d.ts +1 -0
  46. package/dist/core/goal/completionPolicy.js +4 -0
  47. package/dist/core/safety/urlGuard.d.ts +37 -0
  48. package/dist/core/safety/urlGuard.js +206 -0
  49. package/dist/core/subagent/subagentRunner.d.ts +1 -1
  50. package/dist/core/subagent/subagentRunner.js +2 -2
  51. package/dist/core/toolOutput/reduction.d.ts +25 -0
  52. package/dist/core/toolOutput/reduction.js +23 -0
  53. package/dist/llm/client.d.ts +2 -2
  54. package/dist/llm/client.js +6 -4
  55. package/dist/llm/hazeTools.d.ts +133 -16
  56. package/dist/llm/hazeTools.js +205 -31
  57. package/dist/llm/initPrompt.js +2 -1
  58. package/dist/llm/lsp.d.ts +64 -0
  59. package/dist/llm/lsp.js +241 -0
  60. package/dist/llm/lspTools.d.ts +122 -0
  61. package/dist/llm/lspTools.js +115 -0
  62. package/dist/llm/mcp.d.ts +19 -0
  63. package/dist/llm/mcp.js +64 -0
  64. package/dist/llm/requestContext.d.ts +28 -0
  65. package/dist/llm/requestContext.js +56 -0
  66. package/dist/llm/systemPrompt.d.ts +4 -1
  67. package/dist/llm/systemPrompt.js +11 -3
  68. package/dist/llm/toolResultTypes.d.ts +1 -1
  69. package/dist/llm/webFetch.d.ts +57 -0
  70. package/dist/llm/webFetch.js +270 -0
  71. package/dist/skills/builder/SkillBuilder.js +23 -44
  72. package/dist/ui/components/MarkdownText.d.ts +2 -0
  73. package/dist/ui/components/MarkdownText.js +116 -3
  74. package/dist/ui/components/TextInput.d.ts +1 -1
  75. package/dist/utils/version.d.ts +20 -0
  76. package/dist/utils/version.js +72 -0
  77. package/package.json +18 -10
  78. package/dist/cli/commands/skills.d.ts +0 -4
  79. package/dist/cli/commands/skills.js +0 -38
@@ -1,20 +1,27 @@
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';
6
+ import fs from 'fs-extra';
5
7
  import { Box, render, Static, Text, useApp, useStdout } from 'ink';
6
8
  import Spinner from 'ink-spinner';
7
9
  import { readContextFiles } from '../../config/contextFiles.js';
10
+ import { checkForUpdate } from '../../config/updateCheck.js';
8
11
  import { addInputHistoryItem, readInputHistory } from '../../config/inputHistory.js';
9
12
  import { loadTasks as loadTasksFromStore, clearTasks as clearTasksFromStore } from '../../core/tasks/taskStorage.js';
10
13
  import { readSettings, updateSettings } from '../../config/settings.js';
11
- import { activeModel, configuredProviders, DEFAULT_PROVIDER_NAME, findProvider, modelSelector, providerHasKey, resolveModelSelector, upsertProvider } from '../../config/providers.js';
14
+ import { activeModel, configuredProviders, findProvider, modelSelector, providerHasKey, resolveModelSelector, upsertProvider } from '../../config/providers.js';
15
+ import { configuredLspServers, lspPreset, LSP_PRESETS, removeLspServer, setLspServerEnabled, upsertLspServer } from '../../config/lspSettings.js';
16
+ import { configuredMcpServers, findMcpPreset, findMcpServer, presetIds, removeMcpServer, toggleMcpServer, upsertMcpServer } from '../../config/mcpSettings.js';
17
+ import { isSkillEnabled, removeSkillSetting, setSkillEnabled } from '../../config/skillSettings.js';
12
18
  import { Header } from '../../ui/components/Header.js';
13
19
  import { TextInput } from '../../ui/components/TextInput.js';
14
20
  import { MarkdownText } from '../../ui/components/MarkdownText.js';
15
21
  import { theme } from '../../ui/theme.js';
16
22
  import { handleSlashCommand } from './commands.js';
17
23
  import { runAgentTurn } from './streaming.js';
24
+ import { formatContextReport } from './formatters.js';
18
25
  import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
19
26
  import { formatElapsedTime, formatElapsedTimeWhole } from './formatters.js';
20
27
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
@@ -22,7 +29,18 @@ import { createSkill, toSkillDirName } from '../../skills/builder/SkillBuilder.j
22
29
  import { PROVIDER_PRESETS, findPreset } from '../../config/providerPresets.js';
23
30
  import { appendSessionEntry, createSession, formatSession, latestSession, restoreConversation, restoreWorkState } from '../../core/session/sessionStore.js';
24
31
  import { compactModelMessages, modelMessageText } from '../../core/agent/compaction.js';
32
+ import { contextBreakdown } from '../../core/agent/contextBudget.js';
33
+ import { stripSyntheticControls } from '../../core/agent/requestAssembly.js';
34
+ import { modelWithConfig } from '../../llm/client.js';
35
+ import { assembleRequestContext } from '../../llm/requestContext.js';
36
+ import { closeMcpClients } from '../../llm/mcp.js';
25
37
  import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
38
+ /** Modes that show an always-on suggestion picker (server/preset lists). */
39
+ const PICKER_MODES = new Set(['provider', 'providerAction', 'providerAddPreset', 'model', 'skills', 'skillsAction', 'lsp', 'lspAction', 'lspAddPreset', 'mcp', 'mcpAction', 'mcpAddPreset', 'mcpAddTransport']);
40
+ /** Modes that mask input (secrets/API keys). */
41
+ const MASKED_MODES = new Set(['providerAddKey', 'providerSetKey', 'mcpAddKey', 'mcpSetKey']);
42
+ /** Modes where submitting an empty value is valid (optional steps). */
43
+ const SUBMIT_EMPTY_MODES = new Set(['providerAddKey', 'mcpAddKey']);
26
44
  const execFile = promisify(execFileCallback);
27
45
  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 };
28
46
  async function currentBranchName() {
@@ -48,6 +66,12 @@ function toolCallCount(messages) {
48
66
  function estimateTokens(text) {
49
67
  return Math.ceil(text.length / 4);
50
68
  }
69
+ function compactHomePath(filePath) {
70
+ const home = os.homedir();
71
+ if (filePath === home)
72
+ return '~';
73
+ return filePath.startsWith(`${home}/`) ? `~/${filePath.slice(home.length + 1)}` : filePath;
74
+ }
51
75
  function formatTokenCount(tokens) {
52
76
  if (tokens >= 1_000_000)
53
77
  return `${(tokens / 1_000_000).toFixed(tokens >= 10_000_000 ? 0 : 1).replace(/\.0$/, '')}m`;
@@ -115,13 +139,16 @@ function messageElapsedLabel(message) {
115
139
  return '';
116
140
  const end = message.finishedAt ?? (message.streaming ? Date.now() : message.startedAt);
117
141
  const elapsed = end - message.startedAt;
142
+ if (message.role === 'assistant' && !message.streaming && message.tokensPerSecond != null) {
143
+ return `✓ Done in ${formatElapsedTime(elapsed)} · ${Math.round(message.tokensPerSecond)} tok/s`;
144
+ }
118
145
  return message.streaming ? formatElapsedTimeWhole(elapsed) : formatElapsedTime(elapsed);
119
146
  }
120
- function MessageView({ message, width }) {
147
+ function MessageView({ message, width, suppressAssistantHeader = false }) {
121
148
  if (message.role === 'user') {
122
149
  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) })] });
123
150
  }
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'
151
+ 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'
125
152
  ? _jsx(ToolMessageText, { text: message.text, streaming: message.streaming })
126
153
  : message.role === 'assistant' && !message.streaming
127
154
  ? _jsx(MarkdownText, { content: message.text })
@@ -130,21 +157,61 @@ function MessageView({ message, width }) {
130
157
  function messageKey(message, index) {
131
158
  return message.id ?? `${index}-${message.role}-${message.text}`;
132
159
  }
160
+ function orderedDisplayMessages(messages) {
161
+ return messages
162
+ .map((message, index) => ({ message, index }))
163
+ .sort((a, b) => {
164
+ if (a.message.displayOrder != null && b.message.displayOrder != null && a.message.displayOrder !== b.message.displayOrder) {
165
+ return a.message.displayOrder - b.message.displayOrder;
166
+ }
167
+ return a.index - b.index;
168
+ })
169
+ .map(item => item.message);
170
+ }
171
+ function annotateTurnHeaders(messages) {
172
+ return messages.map(message => ({ message, suppressAssistantHeader: false }));
173
+ }
133
174
  function startupProviderInfo(settings) {
134
175
  const selection = activeModel(settings);
135
- const model = process.env.HAZE_MODEL ?? selection.model;
136
- const modelSource = process.env.HAZE_MODEL ? 'HAZE_MODEL env' : settings.model ? 'settings' : 'provider default';
137
- const baseURL = process.env.OPENAI_BASE_URL ?? selection.provider.url;
138
- const baseURLSource = process.env.OPENAI_BASE_URL ? 'OPENAI_BASE_URL env' : 'settings';
139
- const apiKeySource = process.env.OPENAI_API_KEY ? 'OPENAI_API_KEY env' : providerHasKey(settings, selection.provider) ? `provider ${selection.provider.name}` : 'missing';
140
- const provider = process.env.OPENAI_BASE_URL ? 'OpenAI-compatible custom endpoint' : selection.provider.name;
176
+ const configuredCount = configuredProviders(settings).length;
177
+ const lspServers = configuredLspServers(settings);
178
+ const enabledLsp = lspServers.filter(server => server.enabled !== false);
179
+ const lspLine = enabledLsp.length > 0
180
+ ? `- LSP: ${enabledLsp.length} configured (${enabledLsp.map(server => server.name).join(', ')}; tools appear only when the command is installed)`
181
+ : '- LSP: none configured (optional: install a language server, then /lsp presets and /lsp add typescript for semantic code navigation)';
182
+ const mcpServers = configuredMcpServers(settings);
183
+ const enabledMcp = mcpServers.filter(server => server.enabled !== false);
184
+ const mcpLine = enabledMcp.length > 0
185
+ ? `- MCP: ${enabledMcp.length} configured (${enabledMcp.map(server => server.name).join(', ')}; tools load each turn)`
186
+ : '- MCP: none configured (optional: /mcp add context7 for up-to-date library docs)';
187
+ if (!selection) {
188
+ return [
189
+ 'Provider configuration',
190
+ '- Provider: not configured',
191
+ '- Model: not set',
192
+ '- Base URL: not configured',
193
+ '- API key: missing',
194
+ `- Configured providers: ${configuredCount}`,
195
+ lspLine,
196
+ mcpLine,
197
+ '',
198
+ 'Run /provider to choose or add a provider, then select a model.',
199
+ ].join('\n');
200
+ }
201
+ const model = selection.model;
202
+ const modelSource = settings.model ? 'settings' : 'provider default';
203
+ const baseURL = selection.provider.url;
204
+ const apiKeySource = providerHasKey(settings, selection.provider) ? `provider ${selection.provider.name}` : 'missing';
205
+ const provider = selection.provider.name;
141
206
  return [
142
207
  'Provider configuration',
143
208
  `- Provider: ${provider}`,
144
209
  `- Model: ${model} (${modelSource})`,
145
- `- Base URL: ${baseURL} (${baseURLSource})`,
210
+ `- Base URL: ${baseURL} (settings)`,
146
211
  `- API key: ${apiKeySource === 'missing' ? 'not configured; local providers may not need one' : `configured via ${apiKeySource}`}`,
147
- `- Configured providers: ${configuredProviders(settings).length}`,
212
+ `- Configured providers: ${configuredCount}`,
213
+ lspLine,
214
+ mcpLine,
148
215
  ].join('\n');
149
216
  }
150
217
  const TASK_STATUS_ICON = {
@@ -188,14 +255,24 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
188
255
  const { exit } = useApp();
189
256
  const { stdout } = useStdout();
190
257
  const width = stdout.columns ?? process.stdout.columns ?? 80;
191
- const [messages, setMessages] = useState([
192
- { role: 'system', text: 'Welcome to Haze. Use /help for commands.' }
258
+ const nextDisplayOrderRef = useRef(1);
259
+ const withDisplayOrder = (message) => {
260
+ if (message.displayOrder != null)
261
+ return message;
262
+ return { ...message, displayOrder: nextDisplayOrderRef.current++ };
263
+ };
264
+ const withDisplayOrders = (next) => next.map(withDisplayOrder);
265
+ const [messages, setMessagesRaw] = useState([
266
+ { role: 'system', text: 'Welcome to Haze. Use /help for commands.', displayOrder: 0 }
193
267
  ]);
268
+ const setMessages = (updater) => {
269
+ setMessagesRaw(previous => withDisplayOrders(typeof updater === 'function' ? updater(previous) : updater));
270
+ };
194
271
  const [liveMessages, setLiveMessages] = useState([]);
195
272
  const liveMessagesRef = useRef([]);
196
273
  const setLiveMessagesState = (updater) => {
197
274
  setLiveMessages(previous => {
198
- const next = updater(previous);
275
+ const next = withDisplayOrders(updater(previous));
199
276
  liveMessagesRef.current = next;
200
277
  return next;
201
278
  });
@@ -221,18 +298,18 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
221
298
  const [taskBarPadding, setTaskBarPadding] = useState(0);
222
299
  const [, setSessionLabel] = useState();
223
300
  const [tokenUsage, setTokenUsage] = useState({ ...EMPTY_TOKEN_USAGE });
224
- const [, setTimerTick] = useState(0);
225
301
  const [queuedFollowUps, setQueuedFollowUps] = useState([]);
226
302
  const [skills, setSkills] = useState([]);
227
303
  const [branchName, setBranchName] = useState();
228
304
  const [modelProviderFilter, setModelProviderFilter] = useState();
229
305
  const [selectedProviderName, setSelectedProviderName] = useState();
230
306
  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
- }, []);
307
+ const [skillDraft, setSkillDraft] = useState({});
308
+ const [selectedSkillName, setSelectedSkillName] = useState();
309
+ const [selectedLspName, setSelectedLspName] = useState();
310
+ const [lspDraft, setLspDraft] = useState({});
311
+ const [selectedMcpName, setSelectedMcpName] = useState();
312
+ const [mcpDraft, setMcpDraft] = useState({});
236
313
  useEffect(() => {
237
314
  Promise.all([readSettings(), currentBranchName()]).then(([next, branch]) => {
238
315
  setSettings(next);
@@ -254,6 +331,15 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
254
331
  readContextFiles().then(setContextFiles).catch(() => undefined);
255
332
  refreshSkills().catch(() => undefined);
256
333
  loadTasksFromStore().then(setVisibleTasks).catch(() => undefined);
334
+ if (version) {
335
+ checkForUpdate({ currentVersion: version, packageName: '@denizokcu/haze' })
336
+ .then(result => {
337
+ if (result?.isOutdated) {
338
+ setMessages(m => [...m, { role: 'system', text: `A new version of Haze is available: ${result.latestVersion} (you have ${version}). Update with: npm i -g @denizokcu/haze` }]);
339
+ }
340
+ })
341
+ .catch(() => undefined);
342
+ }
257
343
  const branchTimer = setInterval(() => {
258
344
  currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
259
345
  }, 3000);
@@ -275,7 +361,9 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
275
361
  if (!name)
276
362
  return undefined;
277
363
  const skill = skills.find(candidate => candidate.name === name);
278
- return skill ? { skill, args: args.join(' ') } : undefined;
364
+ // Disabled skills are not invocable: they are absent from the model catalog,
365
+ // mirroring how disabled LSP/MCP tools never load.
366
+ return skill && isSkillEnabled(settings, skill.name) ? { skill, args: args.join(' ') } : undefined;
279
367
  }
280
368
  function debugLog(line) {
281
369
  if (!debug)
@@ -283,6 +371,8 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
283
371
  setDebugLogs(current => [...current.slice(-7), line]);
284
372
  }
285
373
  async function startNewLog() {
374
+ if (!debug)
375
+ return undefined;
286
376
  if (llmLogRef.current) {
287
377
  await endLlmLog(llmLogRef.current).catch(() => undefined);
288
378
  }
@@ -374,6 +464,40 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
374
464
  setLiveMessagesState(() => []);
375
465
  setMessages([{ role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...displayMessagesFromConversation(conversation)]);
376
466
  }
467
+ async function buildContextReport() {
468
+ const runtime = await modelWithConfig({ cwd: process.cwd() });
469
+ if (!runtime?.model) {
470
+ return 'No model provider configured. Run /provider to choose or add a provider before /context can estimate tokens.';
471
+ }
472
+ const session = { start: sessionStartRef.current, cwd: process.cwd() };
473
+ const assembled = await assembleRequestContext({ contextFiles, session, model: runtime.model });
474
+ try {
475
+ const messages = stripSyntheticControls(conversationRef.current);
476
+ const breakdown = contextBreakdown({ system: assembled.systemPrompt, contextFiles, messages, tools: assembled.availableTools });
477
+ const tools = breakdown.toolSchemas.map(tool => ({
478
+ name: tool.name,
479
+ tokens: tool.tokens,
480
+ category: assembled.toolCategories.get(tool.name) ?? 'builtin',
481
+ }));
482
+ return formatContextReport({
483
+ modelLabel: `${runtime.config.providerName}:${runtime.config.modelName}`,
484
+ systemTokens: breakdown.system,
485
+ projectContext: breakdown.projectContext,
486
+ tools,
487
+ messagesByRole: breakdown.messagesByRole,
488
+ toolResults: breakdown.toolResults,
489
+ toolInputs: breakdown.toolInputs,
490
+ syntheticControl: breakdown.syntheticControl,
491
+ logicalInputEstimate: breakdown.logicalInputEstimate,
492
+ messageCount: messages.length,
493
+ mcpErrors: assembled.loadedMcp?.errors ?? [],
494
+ });
495
+ }
496
+ finally {
497
+ if (assembled.loadedMcp?.clients.length)
498
+ await closeMcpClients(assembled.loadedMcp.clients);
499
+ }
500
+ }
377
501
  function cancelThinking() {
378
502
  if (!busy)
379
503
  return;
@@ -399,7 +523,12 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
399
523
  setModelProviderFilter(undefined);
400
524
  setSelectedProviderName(undefined);
401
525
  setProviderDraft({});
402
- setSkillCreateDraft({});
526
+ setSkillDraft({});
527
+ setSelectedSkillName(undefined);
528
+ setSelectedLspName(undefined);
529
+ setLspDraft({});
530
+ setSelectedMcpName(undefined);
531
+ setMcpDraft({});
403
532
  }
404
533
  }
405
534
  function providerSuggestions() {
@@ -447,6 +576,87 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
447
576
  kind: 'model',
448
577
  })));
449
578
  }
579
+ function lspSuggestions() {
580
+ const servers = configuredLspServers(settings);
581
+ return [{ value: 'add server', description: 'add an LSP server (presets available)', kind: 'lsp' },
582
+ ...servers.map(server => ({
583
+ value: server.name,
584
+ description: `${server.command}${(server.args ?? []).length ? ` ${(server.args ?? []).join(' ')}` : ''} · ${server.enabled === false ? 'disabled' : 'enabled'}`,
585
+ kind: 'lsp',
586
+ }))];
587
+ }
588
+ function lspActionSuggestions() {
589
+ const server = selectedLspName ? configuredLspServers(settings).find(s => s.name === selectedLspName) : undefined;
590
+ const result = [];
591
+ if (server)
592
+ result.push({ value: server.enabled === false ? 'enable' : 'disable', description: `${server.enabled === false ? 'enable' : 'disable'} this server`, kind: 'lsp' });
593
+ result.push({ value: 'remove server', description: 'remove this server', kind: 'lsp' });
594
+ return result;
595
+ }
596
+ function lspPresetSuggestions() {
597
+ return [
598
+ ...Object.values(LSP_PRESETS).map(preset => ({
599
+ value: preset.name,
600
+ description: `${preset.command} ${(preset.args ?? []).join(' ')} [${(preset.extensions ?? []).join(', ')}]`,
601
+ kind: 'lsp',
602
+ })),
603
+ { value: 'custom', description: 'enter a name and command manually', kind: 'lsp' },
604
+ ];
605
+ }
606
+ function mcpSuggestions() {
607
+ const servers = configuredMcpServers(settings);
608
+ return [{ value: 'add server', description: 'add an MCP server (presets available)', kind: 'mcp' },
609
+ ...servers.map(server => {
610
+ const location = server.url ?? (server.command ? `${server.command} ${(server.args ?? []).join(' ')}`.trim() : '');
611
+ return { value: server.name, description: `${server.transport}${location ? ` ${location}` : ''} · ${server.enabled === false ? 'disabled' : 'enabled'}`, kind: 'mcp' };
612
+ })];
613
+ }
614
+ function mcpActionSuggestions() {
615
+ const server = selectedMcpName ? findMcpServer(settings, selectedMcpName) : undefined;
616
+ const result = [];
617
+ if (server) {
618
+ result.push({ value: server.enabled === false ? 'enable' : 'disable', description: `${server.enabled === false ? 'enable' : 'disable'} this server`, kind: 'mcp' });
619
+ result.push({ value: 'set API key', description: server.headers?.length ? 'update the saved API key' : 'add an API key', kind: 'mcp' });
620
+ }
621
+ result.push({ value: 'remove server', description: 'remove this server', kind: 'mcp' });
622
+ return result;
623
+ }
624
+ function mcpPresetSuggestions() {
625
+ return [
626
+ ...presetIds().map(presetId => {
627
+ const preset = findMcpPreset(presetId);
628
+ return { value: presetId, description: preset.description ?? `${preset.transport} server`, kind: 'mcp' };
629
+ }),
630
+ { value: 'custom', description: 'enter name, transport, and URL or command manually', kind: 'mcp' },
631
+ ];
632
+ }
633
+ function mcpTransportSuggestions() {
634
+ return [
635
+ { value: 'http', description: 'Streamable HTTP (remote)', kind: 'mcp' },
636
+ { value: 'sse', description: 'Server-Sent Events (remote)', kind: 'mcp' },
637
+ { value: 'stdio', description: 'local process', kind: 'mcp' },
638
+ ];
639
+ }
640
+ function skillsSuggestions() {
641
+ return [{ value: 'add skill', description: 'describe a new skill for Haze to generate', kind: 'skill' },
642
+ ...skills.map(skill => ({
643
+ value: skill.name,
644
+ description: `${skill.description}${isSkillEnabled(settings, skill.name) ? '' : ' · disabled'}`,
645
+ kind: 'skill',
646
+ }))];
647
+ }
648
+ function skillsActionSuggestions() {
649
+ const skill = selectedSkillName ? skills.find(candidate => candidate.name === selectedSkillName) : undefined;
650
+ const result = [];
651
+ if (skill) {
652
+ const enabled = isSkillEnabled(settings, skill.name);
653
+ result.push({ value: enabled ? 'disable' : 'enable', description: `${enabled ? 'disable' : 'enable'} this skill`, kind: 'skill' });
654
+ result.push({ value: 'show info', description: 'show description, references, and path', kind: 'skill' });
655
+ result.push({ value: 'validate', description: 're-load and validate SKILL.md', kind: 'skill' });
656
+ }
657
+ result.push({ value: 'remove skill', description: 'delete this skill directory', kind: 'skill' });
658
+ return result;
659
+ }
450
660
  async function selectProvider(providerName) {
451
661
  if (providerName === 'add provider') {
452
662
  setProviderDraft({});
@@ -608,6 +818,288 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
608
818
  setMode('model');
609
819
  setMessages(m => [...m, { role: 'system', text: `Added provider ${provider.name}. Choose a model.` }]);
610
820
  }
821
+ // --- LSP wizard handlers (mirror the provider wizard) ---
822
+ async function selectLspServer(serverName) {
823
+ if (serverName === 'add server') {
824
+ setLspDraft({});
825
+ setMode('lspAddPreset');
826
+ setMessages(m => [...m, { role: 'system', text: 'Choose an LSP preset, or select "custom" to enter a name and command manually.' }]);
827
+ return;
828
+ }
829
+ const server = configuredLspServers(settings).find(s => s.name === serverName);
830
+ if (!server) {
831
+ setMessages(m => [...m, { role: 'system', text: `No LSP server named ${serverName}. Use /lsp and choose add server.` }]);
832
+ setMode('chat');
833
+ return;
834
+ }
835
+ setSelectedLspName(server.name);
836
+ setMode('lspAction');
837
+ setMessages(m => [...m, { role: 'system', text: `${server.name}: choose an action.` }]);
838
+ }
839
+ async function selectLspPreset(presetId) {
840
+ if (presetId === 'custom') {
841
+ setLspDraft({});
842
+ setMode('lspAddName');
843
+ setMessages(m => [...m, { role: 'system', text: 'LSP server name? Example: typescript, rust, my-lsp.' }]);
844
+ return;
845
+ }
846
+ const preset = lspPreset(presetId);
847
+ if (!preset) {
848
+ setMessages(m => [...m, { role: 'system', text: `Unknown preset: ${presetId}.` }]);
849
+ return;
850
+ }
851
+ if (configuredLspServers(settings).some(s => s.name === preset.name)) {
852
+ setMessages(m => [...m, { role: 'system', text: `LSP server ${preset.name} already exists. Use /lsp to manage existing servers.` }]);
853
+ setMode('chat');
854
+ return;
855
+ }
856
+ const next = await updateSettings({ lspServers: upsertLspServer(settings, preset) });
857
+ setSettings(next);
858
+ setMode('chat');
859
+ setMessages(m => [...m, { role: 'system', text: `Added LSP preset ${preset.name}. Ensure ${preset.command} is installed and on PATH; tools appear once it is.` }]);
860
+ }
861
+ async function selectLspAction(action) {
862
+ if (!selectedLspName) {
863
+ setMode('lsp');
864
+ return;
865
+ }
866
+ const server = configuredLspServers(settings).find(s => s.name === selectedLspName);
867
+ if (!server) {
868
+ setMessages(m => [...m, { role: 'system', text: `LSP server ${selectedLspName} not found.` }]);
869
+ setMode('chat');
870
+ setSelectedLspName(undefined);
871
+ return;
872
+ }
873
+ if (action === 'enable' || action === 'disable') {
874
+ const next = await updateSettings({ lspServers: setLspServerEnabled(settings, selectedLspName, action === 'enable') });
875
+ setSettings(next);
876
+ setMessages(m => [...m, { role: 'system', text: `LSP server ${selectedLspName} ${action === 'enable' ? 'enabled' : 'disabled'}.` }]);
877
+ setSelectedLspName(undefined);
878
+ setMode('chat');
879
+ return;
880
+ }
881
+ if (action === 'remove server') {
882
+ setMode('lspConfirmRemove');
883
+ setMessages(m => [...m, { role: 'system', text: `Remove LSP server ${selectedLspName}? Type "yes" to confirm. Esc to cancel.` }]);
884
+ return;
885
+ }
886
+ setMessages(m => [...m, { role: 'system', text: `Unknown LSP action: ${action}` }]);
887
+ }
888
+ async function finishLspCustom(commandLine) {
889
+ const name = lspDraft.name?.trim();
890
+ const parts = commandLine.trim().split(/\s+/).filter(Boolean);
891
+ const command = parts[0];
892
+ if (!name || !command) {
893
+ setMessages(m => [...m, { role: 'system', text: 'LSP server name and command are required.' }]);
894
+ setMode('chat');
895
+ setLspDraft({});
896
+ return;
897
+ }
898
+ const server = { name, command, args: parts.slice(1), extensions: [], rootPatterns: ['.git'], enabled: true };
899
+ const next = await updateSettings({ lspServers: upsertLspServer(settings, server) });
900
+ setSettings(next);
901
+ setLspDraft({});
902
+ setMode('chat');
903
+ setMessages(m => [...m, { role: 'system', text: `Added LSP server ${name} (${command}${parts.length > 1 ? ` ${parts.slice(1).join(' ')}` : ''}). Add extensions in ~/.haze/settings.json so tools can auto-select it.` }]);
904
+ }
905
+ // --- MCP wizard handlers (mirror the provider wizard) ---
906
+ async function selectMcpServer(serverName) {
907
+ if (serverName === 'add server') {
908
+ setMcpDraft({});
909
+ setMode('mcpAddPreset');
910
+ setMessages(m => [...m, { role: 'system', text: 'Choose an MCP preset, or select "custom" to enter details manually.' }]);
911
+ return;
912
+ }
913
+ const server = findMcpServer(settings, serverName);
914
+ if (!server) {
915
+ setMessages(m => [...m, { role: 'system', text: `No MCP server named ${serverName}. Use /mcp and choose add server.` }]);
916
+ setMode('chat');
917
+ return;
918
+ }
919
+ setSelectedMcpName(server.name);
920
+ setMode('mcpAction');
921
+ setMessages(m => [...m, { role: 'system', text: `${server.name}: choose an action.` }]);
922
+ }
923
+ async function selectMcpPreset(presetId) {
924
+ if (presetId === 'custom') {
925
+ setMcpDraft({});
926
+ setMode('mcpAddName');
927
+ setMessages(m => [...m, { role: 'system', text: 'MCP server name? Example: context7, github, filesystem.' }]);
928
+ return;
929
+ }
930
+ const preset = findMcpPreset(presetId);
931
+ if (!preset) {
932
+ setMessages(m => [...m, { role: 'system', text: `Unknown preset: ${presetId}.` }]);
933
+ return;
934
+ }
935
+ if (findMcpServer(settings, presetId)) {
936
+ setMessages(m => [...m, { role: 'system', text: `MCP server ${presetId} already exists. Use /mcp to manage existing servers.` }]);
937
+ setMode('chat');
938
+ return;
939
+ }
940
+ setMcpDraft({ name: presetId, transport: preset.transport, ...(preset.url ? { url: preset.url } : {}) });
941
+ setMode('mcpAddKey');
942
+ setMessages(m => [...m, { role: 'system', text: `Adding ${presetId} (${preset.transport}${preset.url ? `, ${preset.url}` : ''}).\nOptional API key or auth header value? (Leave blank to skip — Enter works.)` }]);
943
+ }
944
+ async function selectMcpAction(action) {
945
+ if (!selectedMcpName) {
946
+ setMode('mcp');
947
+ return;
948
+ }
949
+ const server = findMcpServer(settings, selectedMcpName);
950
+ if (!server) {
951
+ setMessages(m => [...m, { role: 'system', text: `MCP server ${selectedMcpName} not found.` }]);
952
+ setMode('chat');
953
+ setSelectedMcpName(undefined);
954
+ return;
955
+ }
956
+ if (action === 'enable' || action === 'disable') {
957
+ const toggled = toggleMcpServer(settings, selectedMcpName, action === 'enable');
958
+ const next = await updateSettings({ mcpServers: toggled ?? [] });
959
+ setSettings(next);
960
+ setMessages(m => [...m, { role: 'system', text: `MCP server ${selectedMcpName} ${action === 'enable' ? 'enabled' : 'disabled'}.` }]);
961
+ setSelectedMcpName(undefined);
962
+ setMode('chat');
963
+ return;
964
+ }
965
+ if (action === 'set API key') {
966
+ setMode('mcpSetKey');
967
+ setMessages(m => [...m, { role: 'system', text: `New API key for ${selectedMcpName}? (current: ${server.headers?.length ? 'saved' : 'not set'}) Sent as Authorization: Bearer <value>.` }]);
968
+ return;
969
+ }
970
+ if (action === 'remove server') {
971
+ setMode('mcpConfirmRemove');
972
+ setMessages(m => [...m, { role: 'system', text: `Remove MCP server ${selectedMcpName}? Type "yes" to confirm. Esc to cancel.` }]);
973
+ return;
974
+ }
975
+ setMessages(m => [...m, { role: 'system', text: `Unknown MCP action: ${action}` }]);
976
+ }
977
+ async function finishMcpCustom(keyValue) {
978
+ const name = mcpDraft.name?.trim();
979
+ const transport = mcpDraft.transport;
980
+ if (!name || !transport) {
981
+ setMessages(m => [...m, { role: 'system', text: 'MCP server name and transport are required.' }]);
982
+ setMode('chat');
983
+ setMcpDraft({});
984
+ return;
985
+ }
986
+ const headers = keyValue?.trim() ? [{ name: 'Authorization', value: `Bearer ${keyValue.trim()}` }] : undefined;
987
+ const server = transport === 'stdio'
988
+ ? { name, transport, command: mcpDraft.command, args: mcpDraft.args, ...(headers ? { headers } : {}), enabled: true }
989
+ : { name, transport, url: mcpDraft.url, ...(headers ? { headers } : {}), enabled: true };
990
+ // Re-validate the transport-specific required field.
991
+ if (transport === 'stdio' && !server.command) {
992
+ setMessages(m => [...m, { role: 'system', text: 'Command is required for stdio transport.' }]);
993
+ setMode('chat');
994
+ setMcpDraft({});
995
+ return;
996
+ }
997
+ if (transport !== 'stdio' && !server.url) {
998
+ setMessages(m => [...m, { role: 'system', text: `URL is required for ${transport} transport.` }]);
999
+ setMode('chat');
1000
+ setMcpDraft({});
1001
+ return;
1002
+ }
1003
+ const next = await updateSettings({ mcpServers: upsertMcpServer(settings, server) });
1004
+ setSettings(next);
1005
+ setMcpDraft({});
1006
+ setMode('chat');
1007
+ const location = transport === 'stdio' ? `${server.command}${(server.args ?? []).length ? ` ${(server.args ?? []).join(' ')}` : ''}` : server.url;
1008
+ setMessages(m => [...m, { role: 'system', text: `Added MCP server ${name} (${transport}, ${location}). Tools load on the next turn.` }]);
1009
+ }
1010
+ async function setMcpServerKey(keyValue) {
1011
+ if (!selectedMcpName) {
1012
+ setMode('mcp');
1013
+ return;
1014
+ }
1015
+ const server = findMcpServer(settings, selectedMcpName);
1016
+ if (!server) {
1017
+ setMessages(m => [...m, { role: 'system', text: `MCP server ${selectedMcpName} not found.` }]);
1018
+ setMode('chat');
1019
+ setSelectedMcpName(undefined);
1020
+ return;
1021
+ }
1022
+ const key = keyValue.trim();
1023
+ if (!key) {
1024
+ setMessages(m => [...m, { role: 'system', text: 'API key cannot be empty. Esc to cancel.' }]);
1025
+ return;
1026
+ }
1027
+ const headers = (server.headers ?? []).filter(header => header.name !== 'Authorization');
1028
+ headers.push({ name: 'Authorization', value: `Bearer ${key}` });
1029
+ const next = await updateSettings({ mcpServers: upsertMcpServer(settings, { ...server, headers }) });
1030
+ setSettings(next);
1031
+ setSelectedMcpName(undefined);
1032
+ setMode('chat');
1033
+ setMessages(m => [...m, { role: 'system', text: `API key updated for ${server.name}.` }]);
1034
+ }
1035
+ // --- Skills wizard handlers (mirror the provider/LSP/MCP wizards) ---
1036
+ async function selectSkill(name) {
1037
+ if (name === 'add skill') {
1038
+ setSkillDraft({});
1039
+ setMode('skillsAddName');
1040
+ setMessages(m => [...m, { role: 'system', text: 'Name the skill (kebab-case, e.g. security-review). ESC cancels.' }]);
1041
+ return;
1042
+ }
1043
+ const skill = skills.find(candidate => candidate.name === name);
1044
+ if (!skill) {
1045
+ setMessages(m => [...m, { role: 'system', text: `No skill named ${name}. Use /skills and choose add skill.` }]);
1046
+ setMode('chat');
1047
+ return;
1048
+ }
1049
+ setSelectedSkillName(skill.name);
1050
+ setMode('skillsAction');
1051
+ setMessages(m => [...m, { role: 'system', text: `${skill.name}: choose an action.` }]);
1052
+ }
1053
+ async function selectSkillAction(action) {
1054
+ if (!selectedSkillName) {
1055
+ setMode('skills');
1056
+ return;
1057
+ }
1058
+ const skill = skills.find(candidate => candidate.name === selectedSkillName);
1059
+ if (!skill) {
1060
+ setMessages(m => [...m, { role: 'system', text: `Skill ${selectedSkillName} not found.` }]);
1061
+ setMode('chat');
1062
+ setSelectedSkillName(undefined);
1063
+ return;
1064
+ }
1065
+ if (action === 'enable' || action === 'disable') {
1066
+ const next = await updateSettings({ skills: setSkillEnabled(settings, selectedSkillName, action === 'enable') });
1067
+ setSettings(next);
1068
+ setMessages(m => [...m, { role: 'system', text: `Skill ${selectedSkillName} ${action === 'enable' ? 'enabled' : 'disabled'}.` }]);
1069
+ setSelectedSkillName(undefined);
1070
+ setMode('chat');
1071
+ return;
1072
+ }
1073
+ if (action === 'show info') {
1074
+ setMessages(m => [...m, { role: 'system', text: [
1075
+ `${skill.name}`,
1076
+ skill.description,
1077
+ '',
1078
+ `References: ${skill.references.length}`,
1079
+ `Path: ${skill.dir}`,
1080
+ `State: ${isSkillEnabled(settings, skill.name) ? 'enabled' : 'disabled'}`,
1081
+ ].join('\n') }]);
1082
+ return;
1083
+ }
1084
+ if (action === 'validate') {
1085
+ const { loadSkill } = await import('../../skills/SkillLoader.js');
1086
+ try {
1087
+ const loaded = await loadSkill(skill.dir, 'global');
1088
+ setMessages(m => [...m, { role: 'system', text: loaded ? `Valid: ${loaded.name}` : 'No SKILL.md found' }]);
1089
+ }
1090
+ catch (error) {
1091
+ const text = error instanceof Error ? error.message : String(error);
1092
+ setMessages(m => [...m, { role: 'system', text: `Invalid skill: ${text}` }]);
1093
+ }
1094
+ return;
1095
+ }
1096
+ if (action === 'remove skill') {
1097
+ setMode('skillsConfirmRemove');
1098
+ setMessages(m => [...m, { role: 'system', text: `Remove skill ${selectedSkillName}? This deletes ~/.haze/skills/${selectedSkillName}. Type "yes" to confirm. Esc to cancel.` }]);
1099
+ return;
1100
+ }
1101
+ setMessages(m => [...m, { role: 'system', text: `Unknown skill action: ${action}` }]);
1102
+ }
611
1103
  async function captureSkillName(value) {
612
1104
  const dirName = toSkillDirName(value);
613
1105
  if (!dirName) {
@@ -619,15 +1111,9 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
619
1111
  setMessages(m => [...m, { role: 'system', text: `A skill named "${dirName}" already exists. Pick another name, or press ESC to cancel.` }]);
620
1112
  return;
621
1113
  }
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.` }]);
1114
+ setSkillDraft(d => ({ ...d, name: dirName }));
1115
+ setMode('skillsAddDescription');
1116
+ setMessages(m => [...m, { role: 'system', text: `Describe what "${dirName}" should do. This is the work the LLM will expand into the skill body.` }]);
631
1117
  }
632
1118
  async function captureSkillDescription(value) {
633
1119
  const description = value.trim();
@@ -635,18 +1121,19 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
635
1121
  setMessages(m => [...m, { role: 'system', text: 'Description is required. Try again, or press ESC to cancel.' }]);
636
1122
  return;
637
1123
  }
638
- const name = skillCreateDraft.name;
1124
+ const name = skillDraft.name;
639
1125
  if (!name) {
640
1126
  setMode('chat');
641
- setSkillCreateDraft({});
642
- setMessages(m => [...m, { role: 'system', text: 'Skill wizard lost the name. Start over with /create-skill.' }]);
1127
+ setSkillDraft({});
1128
+ setMessages(m => [...m, { role: 'system', text: 'Skill wizard lost the name. Start over with /skills.' }]);
643
1129
  return;
644
1130
  }
645
1131
  setMode('chat');
1132
+ setSkillDraft({});
646
1133
  setBusyLabel('Creating skill');
647
1134
  setBusy(true);
648
1135
  try {
649
- const result = await createSkill({ name, role: skillCreateDraft.role, description });
1136
+ const result = await createSkill({ name, description });
650
1137
  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
1138
  await refreshSkills();
652
1139
  }
@@ -655,7 +1142,6 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
655
1142
  setMessages(m => [...m, { role: 'system', text: `Skill creation failed: ${text}` }]);
656
1143
  }
657
1144
  finally {
658
- setSkillCreateDraft({});
659
1145
  setBusy(false);
660
1146
  setBusyLabel('Haze is thinking');
661
1147
  }
@@ -666,18 +1152,49 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
666
1152
  queueFollowUp(value);
667
1153
  return;
668
1154
  }
669
- if (mode === 'skillCreateName') {
670
- await captureSkillName(value);
1155
+ if (mode === 'skills') {
1156
+ await selectSkill(value);
1157
+ return;
1158
+ }
1159
+ if (mode === 'skillsAction') {
1160
+ await selectSkillAction(value);
671
1161
  return;
672
1162
  }
673
- if (mode === 'skillCreateRole') {
674
- captureSkillRole(value);
1163
+ if (mode === 'skillsAddName') {
1164
+ await captureSkillName(value);
675
1165
  return;
676
1166
  }
677
- if (mode === 'skillCreateDescription') {
1167
+ if (mode === 'skillsAddDescription') {
678
1168
  await captureSkillDescription(value);
679
1169
  return;
680
1170
  }
1171
+ if (mode === 'skillsConfirmRemove') {
1172
+ if (!selectedSkillName) {
1173
+ setMode('chat');
1174
+ return;
1175
+ }
1176
+ if (value.trim().toLowerCase() !== 'yes') {
1177
+ setMessages(m => [...m, { role: 'system', text: 'Cancelled. Skill not removed.' }]);
1178
+ setSelectedSkillName(undefined);
1179
+ setMode('chat');
1180
+ return;
1181
+ }
1182
+ const skill = skills.find(candidate => candidate.name === selectedSkillName);
1183
+ if (!skill) {
1184
+ setMessages(m => [...m, { role: 'system', text: `Skill ${selectedSkillName} not found.` }]);
1185
+ setSelectedSkillName(undefined);
1186
+ setMode('chat');
1187
+ return;
1188
+ }
1189
+ await fs.remove(skill.dir);
1190
+ const next = await updateSettings({ skills: removeSkillSetting(settings, selectedSkillName) });
1191
+ setSettings(next);
1192
+ setMessages(m => [...m, { role: 'system', text: `Removed skill ${selectedSkillName}.` }]);
1193
+ setSelectedSkillName(undefined);
1194
+ setMode('chat');
1195
+ await refreshSkills();
1196
+ return;
1197
+ }
681
1198
  if (mode === 'provider') {
682
1199
  await selectProvider(value);
683
1200
  return;
@@ -817,6 +1334,149 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
817
1334
  setMessages(m => [...m, { role: 'system', text: `Removed provider ${provider.name}.${wasActiveProvider ? ` Switched to ${providers[0]?.name ?? 'no provider'}.` : ''}` }]);
818
1335
  return;
819
1336
  }
1337
+ if (mode === 'lsp') {
1338
+ await selectLspServer(value);
1339
+ return;
1340
+ }
1341
+ if (mode === 'lspAction') {
1342
+ await selectLspAction(value);
1343
+ return;
1344
+ }
1345
+ if (mode === 'lspAddPreset') {
1346
+ await selectLspPreset(value);
1347
+ return;
1348
+ }
1349
+ if (mode === 'lspAddName') {
1350
+ const name = value.trim();
1351
+ if (!name) {
1352
+ setMessages(m => [...m, { role: 'system', text: 'LSP server name is required.' }]);
1353
+ return;
1354
+ }
1355
+ if (configuredLspServers(settings).some(s => s.name === name)) {
1356
+ setMessages(m => [...m, { role: 'system', text: `LSP server ${name} already exists. Choose a unique name.` }]);
1357
+ return;
1358
+ }
1359
+ setLspDraft({ name });
1360
+ setMode('lspAddCommand');
1361
+ setMessages(m => [...m, { role: 'system', text: 'Command to run? Example: typescript-language-server --stdio' }]);
1362
+ return;
1363
+ }
1364
+ if (mode === 'lspAddCommand') {
1365
+ await finishLspCustom(value);
1366
+ return;
1367
+ }
1368
+ if (mode === 'lspConfirmRemove') {
1369
+ if (!selectedLspName) {
1370
+ setMode('chat');
1371
+ return;
1372
+ }
1373
+ if (value.trim().toLowerCase() !== 'yes') {
1374
+ setMessages(m => [...m, { role: 'system', text: 'Cancelled. LSP server not removed.' }]);
1375
+ setSelectedLspName(undefined);
1376
+ setMode('chat');
1377
+ return;
1378
+ }
1379
+ const next = await updateSettings({ lspServers: removeLspServer(settings, selectedLspName) });
1380
+ setSettings(next);
1381
+ setMessages(m => [...m, { role: 'system', text: `Removed LSP server ${selectedLspName}.` }]);
1382
+ setSelectedLspName(undefined);
1383
+ setMode('chat');
1384
+ return;
1385
+ }
1386
+ if (mode === 'mcp') {
1387
+ await selectMcpServer(value);
1388
+ return;
1389
+ }
1390
+ if (mode === 'mcpAction') {
1391
+ await selectMcpAction(value);
1392
+ return;
1393
+ }
1394
+ if (mode === 'mcpAddPreset') {
1395
+ await selectMcpPreset(value);
1396
+ return;
1397
+ }
1398
+ if (mode === 'mcpAddName') {
1399
+ const name = value.trim();
1400
+ if (!name) {
1401
+ setMessages(m => [...m, { role: 'system', text: 'MCP server name is required.' }]);
1402
+ return;
1403
+ }
1404
+ if (findMcpServer(settings, name)) {
1405
+ setMessages(m => [...m, { role: 'system', text: `MCP server ${name} already exists. Choose a unique name.` }]);
1406
+ return;
1407
+ }
1408
+ setMcpDraft({ name });
1409
+ setMode('mcpAddTransport');
1410
+ setMessages(m => [...m, { role: 'system', text: 'Transport type? http (Streamable HTTP), sse (Server-Sent Events), or stdio (local process).' }]);
1411
+ return;
1412
+ }
1413
+ if (mode === 'mcpAddTransport') {
1414
+ const transport = value.trim().toLowerCase();
1415
+ if (transport !== 'http' && transport !== 'sse' && transport !== 'stdio') {
1416
+ setMessages(m => [...m, { role: 'system', text: 'Enter http, sse, or stdio.' }]);
1417
+ return;
1418
+ }
1419
+ setMcpDraft(draft => ({ ...draft, transport: transport }));
1420
+ if (transport === 'stdio') {
1421
+ setMode('mcpAddCommand');
1422
+ setMessages(m => [...m, { role: 'system', text: 'Command to run? Example: npx -y @modelcontextprotocol/server-filesystem .' }]);
1423
+ }
1424
+ else {
1425
+ setMode('mcpAddUrl');
1426
+ setMessages(m => [...m, { role: 'system', text: `MCP server URL? Example: https://mcp.context7.com/mcp for ${transport}.` }]);
1427
+ }
1428
+ return;
1429
+ }
1430
+ if (mode === 'mcpAddUrl') {
1431
+ try {
1432
+ new URL(value);
1433
+ }
1434
+ catch {
1435
+ setMessages(m => [...m, { role: 'system', text: 'Enter a valid URL, for example https://mcp.context7.com/mcp.' }]);
1436
+ return;
1437
+ }
1438
+ setMcpDraft(draft => ({ ...draft, url: value.trim() }));
1439
+ setMode('mcpAddKey');
1440
+ setMessages(m => [...m, { role: 'system', text: 'Optional API key or auth header value? (Leave blank to skip — Enter works.) Sent as Authorization: Bearer <value>.' }]);
1441
+ return;
1442
+ }
1443
+ if (mode === 'mcpAddCommand') {
1444
+ const parts = value.trim().split(/\s+/).filter(Boolean);
1445
+ if (parts.length === 0) {
1446
+ setMessages(m => [...m, { role: 'system', text: 'Command is required.' }]);
1447
+ return;
1448
+ }
1449
+ setMcpDraft(draft => ({ ...draft, command: parts[0], args: parts.slice(1) }));
1450
+ setMode('mcpAddKey');
1451
+ setMessages(m => [...m, { role: 'system', text: 'Optional API key or auth header value? (Leave blank to skip — Enter works.) Sent as Authorization: Bearer <value>.' }]);
1452
+ return;
1453
+ }
1454
+ if (mode === 'mcpAddKey') {
1455
+ await finishMcpCustom(value);
1456
+ return;
1457
+ }
1458
+ if (mode === 'mcpSetKey') {
1459
+ await setMcpServerKey(value);
1460
+ return;
1461
+ }
1462
+ if (mode === 'mcpConfirmRemove') {
1463
+ if (!selectedMcpName) {
1464
+ setMode('chat');
1465
+ return;
1466
+ }
1467
+ if (value.trim().toLowerCase() !== 'yes') {
1468
+ setMessages(m => [...m, { role: 'system', text: 'Cancelled. MCP server not removed.' }]);
1469
+ setSelectedMcpName(undefined);
1470
+ setMode('chat');
1471
+ return;
1472
+ }
1473
+ const next = await updateSettings({ mcpServers: removeMcpServer(settings, selectedMcpName) });
1474
+ setSettings(next);
1475
+ setMessages(m => [...m, { role: 'system', text: `Removed MCP server ${selectedMcpName}.` }]);
1476
+ setSelectedMcpName(undefined);
1477
+ setMode('chat');
1478
+ return;
1479
+ }
820
1480
  const invokedSkill = skillInvocation(value);
821
1481
  if (invokedSkill) {
822
1482
  const argumentText = invokedSkill.args ? `\nUser-provided skill arguments: ${invokedSkill.args}` : '';
@@ -847,6 +1507,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
847
1507
  setSettings(next);
848
1508
  return next;
849
1509
  },
1510
+ getContextReport: async () => buildContextReport(),
850
1511
  };
851
1512
  let result;
852
1513
  try {
@@ -860,9 +1521,6 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
860
1521
  if (result === 'exit')
861
1522
  return exit();
862
1523
  if (result === 'handled') {
863
- if (value.startsWith('/remove-skill ')) {
864
- await refreshSkills().catch(() => undefined);
865
- }
866
1524
  if (value === '/clear') {
867
1525
  loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
868
1526
  }
@@ -872,6 +1530,15 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
872
1530
  }
873
1531
  async function doAgentTurn(value, displayValue) {
874
1532
  setDebugLogs([]);
1533
+ // When every task is already completed, start the new turn with a clean
1534
+ // slate: the task bar clears (nothing shown for simple questions) and the
1535
+ // model may create fresh todos via writeTasks if the new question warrants.
1536
+ if (visibleTasks.length > 0 && visibleTasks.every(t => t.status === 'completed')) {
1537
+ setVisibleTasks([]);
1538
+ setTasksExpanded(false);
1539
+ setTaskBarPadding(0);
1540
+ await clearTasksFromStore().catch(() => undefined);
1541
+ }
875
1542
  await runSingleAgentTurn(value, displayValue);
876
1543
  while (followUpQueueRef.current.length > 0) {
877
1544
  const next = followUpQueueRef.current[0];
@@ -890,16 +1557,18 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
890
1557
  const finalizeMessage = (msg) => {
891
1558
  if (msg.hidden)
892
1559
  return;
893
- setMessages(m => [...m, msg]);
894
- persistUiMessage(msg);
1560
+ const ordered = withDisplayOrder(msg);
1561
+ setMessages(m => [...m, ordered]);
1562
+ persistUiMessage(ordered);
895
1563
  };
896
1564
  await runAgentTurn(value, displayValue, contextFiles, {
897
1565
  addMessage: msg => {
898
- if (msg.streaming) {
899
- setLiveMessagesState(m => [...m, msg]);
1566
+ const ordered = withDisplayOrder(msg);
1567
+ if (ordered.streaming) {
1568
+ setLiveMessagesState(m => [...m, ordered]);
900
1569
  return;
901
1570
  }
902
- finalizeMessage(msg);
1571
+ finalizeMessage(ordered);
903
1572
  },
904
1573
  updateMessage: (id, update) => {
905
1574
  const liveMessage = liveMessagesRef.current.find(msg => msg.id === id);
@@ -962,73 +1631,87 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
962
1631
  }, 0, false, false, { start: sessionStartRef.current, cwd: process.cwd() });
963
1632
  }
964
1633
  const visible = messages.filter(message => !message.hidden);
965
- const transcriptItems = visible.map((message, index) => ({ key: messageKey(message, index), message }));
966
1634
  const activeLiveMessages = liveMessages.filter(message => !message.hidden);
1635
+ const orderedVisibleMessages = orderedDisplayMessages([...visible, ...activeLiveMessages]);
1636
+ const annotatedDisplayMessages = annotateTurnHeaders(orderedVisibleMessages);
1637
+ const staticDisplayItems = annotatedDisplayMessages.filter(item => !item.message.streaming);
1638
+ const transcriptItems = staticDisplayItems.map((item, index) => ({ key: messageKey(item.message, index), ...item }));
1639
+ const activeLiveItems = annotatedDisplayMessages.filter(item => item.message.streaming);
967
1640
  const activeSelection = activeModel(settings);
968
- const placeholder = mode === 'provider'
969
- ? 'Choose provider'
970
- : mode === 'providerAction'
971
- ? 'Choose provider action'
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';
995
- const activeModelName = `${activeSelection.provider.name}:${process.env.HAZE_MODEL ?? activeSelection.model}`;
996
- const hasLogin = Boolean(process.env.OPENAI_API_KEY ?? settings.apiKey ?? activeSelection.provider.key) || activeSelection.provider.name !== DEFAULT_PROVIDER_NAME;
997
- const hasChosenModel = Boolean(process.env.HAZE_MODEL ?? settings.model ?? activeSelection.model);
998
- const headerSubtitle = hasLogin && hasChosenModel
999
- ? [
1000
- 'A minimal LLM harness for growing your own workflows while you work.',
1001
- '',
1002
- 'Start with simple chat, then teach Haze your habits with skills:',
1003
- '/create-skill — three-step skill wizard (name, role, description).',
1004
- '',
1005
- 'The most adaptive workflow is the one you shape as you go.',
1006
- '',
1007
- 'Guardrails are light: Haze lets the LLM work from the terminal almost like you,',
1008
- 'while trying to stay scoped to this project.',
1009
- ].join('\n')
1010
- : 'First things first: run /provider to choose or add a provider, then select a model.';
1011
- const workspaceLabel = `${process.cwd()}${branchName ? ` (${branchName})` : ''}`;
1641
+ const PLACEHOLDERS = {
1642
+ provider: 'Choose provider',
1643
+ providerAction: 'Choose provider action',
1644
+ providerAddPreset: 'Choose a provider preset or custom',
1645
+ model: 'Choose model',
1646
+ providerAddName: 'Provider name',
1647
+ providerAddUrl: 'https://example.com/v1',
1648
+ providerAddKey: 'API key, or blank for local',
1649
+ providerSetKey: 'API key',
1650
+ providerAddModels: 'model-a, model-b',
1651
+ providerAppendModels: 'model-a, model-b',
1652
+ providerRemoveModels: 'model-a, model-b',
1653
+ providerConfirmRemove: 'Type "yes" to confirm',
1654
+ skills: 'Choose a skill or add skill',
1655
+ skillsAction: 'show info, enable, disable, validate, or remove',
1656
+ skillsAddName: 'Skill name (kebab-case, e.g. security-review)',
1657
+ skillsAddDescription: 'Describe what the skill should do',
1658
+ skillsConfirmRemove: 'Type "yes" to confirm',
1659
+ lsp: 'Choose LSP server or add server',
1660
+ lspAction: 'enable, disable, or remove server',
1661
+ lspAddPreset: 'Choose an LSP preset or custom',
1662
+ lspAddName: 'LSP server name (e.g. typescript)',
1663
+ lspAddCommand: 'Command (e.g. typescript-language-server --stdio)',
1664
+ lspConfirmRemove: 'Type "yes" to confirm',
1665
+ mcp: 'Choose MCP server or add server',
1666
+ mcpAction: 'enable, disable, remove, or set key',
1667
+ mcpAddPreset: 'Choose an MCP preset or custom',
1668
+ mcpAddName: 'MCP server name (e.g. context7)',
1669
+ mcpAddTransport: 'http, sse, or stdio',
1670
+ mcpAddUrl: 'https://mcp.example.com/mcp',
1671
+ mcpAddCommand: 'Command (e.g. npx -y @pkg/server)',
1672
+ mcpAddKey: 'API key, or blank to skip',
1673
+ mcpSetKey: 'API key',
1674
+ mcpConfirmRemove: 'Type "yes" to confirm',
1675
+ };
1676
+ const placeholder = PLACEHOLDERS[mode] ?? (busy ? 'Queue a follow-up, or Esc to interrupt' : 'Ask Haze to help build your app');
1677
+ const activeModelName = activeSelection ? `${activeSelection.provider.name}:${activeSelection.model}` : 'unconfigured';
1678
+ const headerSubtitle = [
1679
+ 'A minimal LLM harness for growing your own workflows while you work.',
1680
+ '',
1681
+ 'Start with simple chat, then teach Haze your habits with skills:',
1682
+ '/skills — add, enable/disable, validate, or remove Markdown skills.',
1683
+ '',
1684
+ 'The most adaptive workflow is the one you shape as you go.',
1685
+ '',
1686
+ 'Guardrails are light: Haze lets the LLM work from the terminal almost like you,',
1687
+ 'while trying to stay scoped to this project.',
1688
+ ].join('\n');
1689
+ const workspaceLabel = `${compactHomePath(process.cwd())}${branchName ? ` (${branchName})` : ''}`;
1012
1690
  const allDisplayMessages = [...messages, ...liveMessages];
1691
+ const hazeMessages = allDisplayMessages.filter(message => message.role === 'assistant' && !message.hidden).length;
1013
1692
  const toolsUsed = toolCallCount(allDisplayMessages);
1014
1693
  const fallbackTokens = estimateConversationTokens(allDisplayMessages);
1015
- const effectiveInput = tokenUsage.inputTokens ?? (fallbackTokens.input || 0);
1694
+ const estimatedLogicalInput = tokenUsage.logicalInputEstimate || fallbackTokens.input || 0;
1695
+ const providerInput = tokenUsage.inputTokens;
1696
+ const effectiveInput = providerInput == null ? estimatedLogicalInput : Math.max(providerInput, estimatedLogicalInput);
1016
1697
  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'}`;
1698
+ const inputEstimated = providerInput == null || effectiveInput !== providerInput;
1699
+ const outputEstimated = tokenUsage.outputTokens == null;
1700
+ const enabledSkills = skills.filter(skill => isSkillEnabled(settings, skill.name));
1701
+ const statusDetailLabel = `${hazeMessages} haze message${hazeMessages === 1 ? '' : 's'} / ${toolsUsed} tool call${toolsUsed === 1 ? '' : 's'} / LLM ${inputEstimated ? '~' : ''}↑${formatTokenCount(effectiveInput)} ${outputEstimated ? '~' : ''}↓${formatTokenCount(effectiveOutput)} / ${enabledSkills.length} skill${enabledSkills.length === 1 ? '' : 's'}`;
1019
1702
  const hasTokenBreakdown = tokenUsage.systemPrompt > 0 || tokenUsage.messages > 0 || tokenUsage.toolSchemas > 0 || effectiveInput > 0 || effectiveOutput > 0;
1020
1703
  const goalText = activeGoalStatus?.replace(/^Goal:\s*/, '');
1021
1704
  // Goal tracking is internal; display removed in favor of task bar
1022
1705
  void goalText;
1023
- const inputSuggestions = mode === 'provider' ? providerSuggestions() : mode === 'providerAction' ? providerActionSuggestions() : mode === 'providerAddPreset' ? presetSuggestions() : mode === 'model' ? modelSuggestions() : mode === 'chat' ? [
1706
+ const inputSuggestions = mode === 'provider' ? providerSuggestions() : mode === 'providerAction' ? providerActionSuggestions() : mode === 'providerAddPreset' ? presetSuggestions() : mode === 'model' ? modelSuggestions() : mode === 'skills' ? skillsSuggestions() : mode === 'skillsAction' ? skillsActionSuggestions() : mode === 'lsp' ? lspSuggestions() : mode === 'lspAction' ? lspActionSuggestions() : mode === 'lspAddPreset' ? lspPresetSuggestions() : mode === 'mcp' ? mcpSuggestions() : mode === 'mcpAction' ? mcpActionSuggestions() : mode === 'mcpAddPreset' ? mcpPresetSuggestions() : mode === 'mcpAddTransport' ? mcpTransportSuggestions() : mode === 'chat' ? [
1024
1707
  { value: '/help', description: 'Show commands', kind: 'command' },
1025
1708
  { value: '/provider', description: 'Choose a provider', kind: 'command' },
1026
1709
  { value: '/model', description: 'Choose a model', kind: 'command' },
1710
+ { value: '/lsp', description: 'Manage LSP servers (semantic navigation)', kind: 'command' },
1711
+ { value: '/mcp', description: 'Manage MCP servers (Context7, etc.)', kind: 'command' },
1027
1712
  { value: '/settings', description: 'Show provider, model, API key, and context status', kind: 'command' },
1028
- { value: '/create-skill ', description: 'Launch the skill wizard', kind: 'command' },
1029
- { value: '/skill-info ', description: 'Show details for a skill', kind: 'command' },
1030
- { value: '/validate-skill ', description: 'Validate a skill', kind: 'command' },
1031
- { value: '/remove-skill ', description: 'Remove a skill with --yes', kind: 'command' },
1713
+ { value: '/context', description: 'Show token breakdown of system, tools, MCP, and messages', kind: 'command' },
1714
+ { value: '/skills', description: 'Manage Markdown skills (add, enable/disable, validate, remove)', kind: 'command' },
1032
1715
  { value: '/init', description: 'Create or update AGENTS.md project instructions', kind: 'command' },
1033
1716
  { value: '/session', description: 'Show current session path', kind: 'command' },
1034
1717
  { value: '/resume', description: 'Resume latest session for this workspace', kind: 'command' },
@@ -1037,15 +1720,15 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
1037
1720
  { value: '/clear', description: 'Clear conversation history', kind: 'command' },
1038
1721
  { value: '/exit', description: 'Exit Haze', kind: 'command' },
1039
1722
  { value: '/quit', description: 'Exit Haze', kind: 'command' },
1040
- ...skills.map(skill => ({ value: `/${skill.name}`, description: skill.description, kind: 'skill' })),
1723
+ ...skills.filter(skill => isSkillEnabled(settings, skill.name)).map(skill => ({ value: `/${skill.name}`, description: skill.description, kind: 'skill' })),
1041
1724
  ] : [];
1042
1725
  const staticItems = [
1043
- { kind: 'header', key: `header-${activeModelName}-${hasLogin}-${hasChosenModel}`, subtitle: headerSubtitle },
1726
+ { kind: 'header', key: `header-${activeModelName}`, subtitle: headerSubtitle },
1044
1727
  ...transcriptItems.map(item => ({ kind: 'message', ...item })),
1045
1728
  ];
1046
1729
  return _jsxs(Box, { flexDirection: "column", children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
1047
1730
  ? _jsx(Header, { subtitle: item.subtitle, version: version }, item.key)
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: () => {
1731
+ : _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: MASKED_MODES.has(mode), historyItems: inputHistory, recordHistory: mode === 'chat', suggestions: inputSuggestions, suggestionMode: PICKER_MODES.has(mode) ? 'always' : 'slash', submitOnEmpty: SUBMIT_EMPTY_MODES.has(mode), width: Math.max(20, width - 4), onHistoryAdd: persistInputHistory, onToggleTasks: () => {
1049
1732
  if (!tasksExpanded) {
1050
1733
  setTaskBarPadding(0);
1051
1734
  setTasksExpanded(true);
@@ -1061,7 +1744,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
1061
1744
  cancelThinking();
1062
1745
  else
1063
1746
  closeInputList();
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 }) })] })] });
1747
+ }, 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 }) })] })] });
1065
1748
  }
1066
1749
  export async function chatCommand(options = {}) {
1067
1750
  if (process.stdout.isTTY) {