@denizokcu/haze 0.6.0 → 0.7.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 (147) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +59 -12
  3. package/dist/cli/chat/TaskBar.d.ts +9 -0
  4. package/dist/cli/chat/TaskBar.js +40 -0
  5. package/dist/cli/chat/chatMetrics.d.ts +11 -0
  6. package/dist/cli/chat/chatMetrics.js +50 -0
  7. package/dist/cli/chat/inputSuggestions.d.ts +16 -0
  8. package/dist/cli/chat/inputSuggestions.js +55 -0
  9. package/dist/cli/chat/messages.d.ts +9 -0
  10. package/dist/cli/chat/messages.js +76 -0
  11. package/dist/cli/chat/sessionRecorder.d.ts +12 -0
  12. package/dist/cli/chat/sessionRecorder.js +21 -0
  13. package/dist/cli/chat/startupInfo.d.ts +4 -0
  14. package/dist/cli/chat/startupInfo.js +53 -0
  15. package/dist/cli/chat/turnState.d.ts +5 -0
  16. package/dist/cli/chat/turnState.js +20 -0
  17. package/dist/cli/commands/chat.d.ts +0 -1
  18. package/dist/cli/commands/chat.js +293 -894
  19. package/dist/cli/commands/chatModes.d.ts +8 -0
  20. package/dist/cli/commands/chatModes.js +44 -0
  21. package/dist/cli/commands/commandHelp.d.ts +6 -0
  22. package/dist/cli/commands/commandHelp.js +25 -0
  23. package/dist/cli/commands/commands.d.ts +1 -1
  24. package/dist/cli/commands/commands.js +41 -267
  25. package/dist/cli/commands/formatters.js +12 -4
  26. package/dist/cli/commands/initCommand.d.ts +2 -0
  27. package/dist/cli/commands/initCommand.js +19 -0
  28. package/dist/cli/commands/logsCommand.d.ts +2 -0
  29. package/dist/cli/commands/logsCommand.js +63 -0
  30. package/dist/cli/commands/lspWizard.d.ts +14 -0
  31. package/dist/cli/commands/lspWizard.js +44 -0
  32. package/dist/cli/commands/mcpWizard.d.ts +15 -0
  33. package/dist/cli/commands/mcpWizard.js +69 -0
  34. package/dist/cli/commands/modelCommand.d.ts +2 -0
  35. package/dist/cli/commands/modelCommand.js +36 -0
  36. package/dist/cli/commands/providerWizard.d.ts +30 -0
  37. package/dist/cli/commands/providerWizard.js +114 -0
  38. package/dist/cli/commands/runCommand.d.ts +16 -0
  39. package/dist/cli/commands/runCommand.js +170 -0
  40. package/dist/cli/commands/settingsSummary.d.ts +3 -0
  41. package/dist/cli/commands/settingsSummary.js +40 -0
  42. package/dist/cli/commands/skillConfirmRemove.d.ts +11 -0
  43. package/dist/cli/commands/skillConfirmRemove.js +19 -0
  44. package/dist/cli/commands/skillCreation.d.ts +12 -0
  45. package/dist/cli/commands/skillCreation.js +14 -0
  46. package/dist/cli/commands/skillWizard.d.ts +15 -0
  47. package/dist/cli/commands/skillWizard.js +38 -0
  48. package/dist/cli/commands/streaming/assistantText.d.ts +17 -0
  49. package/dist/cli/commands/streaming/assistantText.js +115 -0
  50. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +55 -0
  51. package/dist/cli/commands/streaming/toolGroupRenderer.js +102 -0
  52. package/dist/cli/commands/streaming/toolResultState.d.ts +13 -0
  53. package/dist/cli/commands/streaming/toolResultState.js +25 -0
  54. package/dist/cli/commands/streaming/turnRuntime.d.ts +78 -0
  55. package/dist/cli/commands/streaming/turnRuntime.js +86 -0
  56. package/dist/cli/commands/streaming.d.ts +9 -25
  57. package/dist/cli/commands/streaming.js +82 -347
  58. package/dist/cli/commands/wizardActions.d.ts +40 -0
  59. package/dist/cli/commands/wizardActions.js +40 -0
  60. package/dist/cli/commands/wizardInput.d.ts +4 -0
  61. package/dist/cli/commands/wizardInput.js +19 -0
  62. package/dist/cli/commands/wizardPrompts.d.ts +22 -0
  63. package/dist/cli/commands/wizardPrompts.js +52 -0
  64. package/dist/cli/commands/wizardSuggestions.d.ts +23 -0
  65. package/dist/cli/commands/wizardSuggestions.js +139 -0
  66. package/dist/cli/index.js +62 -4
  67. package/dist/config/contextFiles.d.ts +8 -1
  68. package/dist/config/contextFiles.js +25 -12
  69. package/dist/config/lspSettings.js +3 -6
  70. package/dist/config/mcpSettings.js +5 -5
  71. package/dist/config/providers.js +4 -4
  72. package/dist/config/skillSettings.js +4 -3
  73. package/dist/core/agent/budgets.d.ts +6 -0
  74. package/dist/core/agent/budgets.js +6 -0
  75. package/dist/core/agent/compaction.js +1 -1
  76. package/dist/core/agent/requestAssembly.d.ts +0 -7
  77. package/dist/core/agent/requestAssembly.js +27 -5
  78. package/dist/core/agent/toolOutputStore.js +5 -4
  79. package/dist/core/agent/toolResults.d.ts +31 -0
  80. package/dist/core/agent/toolResults.js +42 -0
  81. package/dist/core/agent/turnPolicy.d.ts +8 -0
  82. package/dist/core/agent/turnPolicy.js +23 -0
  83. package/dist/core/agent/workState.d.ts +18 -5
  84. package/dist/core/agent/workState.js +39 -20
  85. package/dist/core/bashOutput/reducers/content.d.ts +1 -0
  86. package/dist/core/bashOutput/reducers/content.js +1 -1
  87. package/dist/core/bashOutput/reducers/gh.d.ts +1 -0
  88. package/dist/core/bashOutput/reducers/gh.js +77 -0
  89. package/dist/core/bashOutput/registry.js +8 -0
  90. package/dist/core/goal/sessionGoal.d.ts +6 -30
  91. package/dist/core/goal/sessionGoal.js +3 -68
  92. package/dist/core/safety/bashClassifier.js +30 -0
  93. package/dist/core/safety/urlGuard.d.ts +1 -0
  94. package/dist/core/safety/urlGuard.js +6 -1
  95. package/dist/core/session/sessionSlimming.d.ts +5 -0
  96. package/dist/core/session/sessionSlimming.js +78 -0
  97. package/dist/core/session/sessionStore.d.ts +23 -3
  98. package/dist/core/session/sessionStore.js +30 -10
  99. package/dist/core/subagent/subagentRunner.d.ts +11 -1
  100. package/dist/core/subagent/subagentRunner.js +1 -0
  101. package/dist/llm/capabilities.d.ts +12 -0
  102. package/dist/llm/capabilities.js +10 -0
  103. package/dist/llm/client.d.ts +1 -0
  104. package/dist/llm/client.js +11 -2
  105. package/dist/llm/hazeTools.d.ts +31 -32
  106. package/dist/llm/hazeTools.js +40 -567
  107. package/dist/llm/lsp.d.ts +46 -1
  108. package/dist/llm/lsp.js +9 -9
  109. package/dist/llm/lspTools.d.ts +2 -20
  110. package/dist/llm/mcp.js +9 -0
  111. package/dist/llm/requestContext.js +7 -22
  112. package/dist/llm/systemPrompt.d.ts +1 -0
  113. package/dist/llm/systemPrompt.js +1 -1
  114. package/dist/llm/tools/bashTool.d.ts +5 -0
  115. package/dist/llm/tools/bashTool.js +81 -0
  116. package/dist/llm/tools/editMatch.d.ts +55 -0
  117. package/dist/llm/tools/editMatch.js +99 -0
  118. package/dist/llm/tools/failures.d.ts +36 -0
  119. package/dist/llm/tools/failures.js +38 -0
  120. package/dist/llm/tools/fetchTool.d.ts +65 -0
  121. package/dist/llm/tools/fetchTool.js +45 -0
  122. package/dist/llm/tools/fileToolShared.d.ts +10 -0
  123. package/dist/llm/tools/fileToolShared.js +43 -0
  124. package/dist/llm/tools/grepParse.d.ts +13 -0
  125. package/dist/llm/tools/grepParse.js +67 -0
  126. package/dist/llm/tools/outputCap.d.ts +53 -0
  127. package/dist/llm/tools/outputCap.js +67 -0
  128. package/dist/llm/tools/storedOutputTool.d.ts +10 -0
  129. package/dist/llm/tools/storedOutputTool.js +17 -0
  130. package/dist/llm/tools/taskTool.d.ts +28 -0
  131. package/dist/llm/tools/taskTool.js +41 -0
  132. package/dist/llm/tools/toolContext.d.ts +69 -0
  133. package/dist/llm/tools/toolContext.js +187 -0
  134. package/dist/llm/tools/workspaceFile.d.ts +33 -0
  135. package/dist/llm/tools/workspaceFile.js +27 -0
  136. package/dist/llm/webFetch.d.ts +13 -1
  137. package/dist/llm/webFetch.js +91 -7
  138. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  139. package/dist/skills/builder/SkillBuilder.js +1 -1
  140. package/dist/ui/components/TextInput.js +1 -99
  141. package/dist/ui/inputBuffer.d.ts +28 -0
  142. package/dist/ui/inputBuffer.js +99 -0
  143. package/dist/utils/collections.d.ts +6 -0
  144. package/dist/utils/collections.js +9 -0
  145. package/dist/utils/path.d.ts +2 -0
  146. package/dist/utils/path.js +40 -0
  147. package/package.json +1 -2
@@ -0,0 +1,8 @@
1
+ export type Mode = 'chat' | 'provider' | 'providerAction' | 'model' | 'providerAddPreset' | 'providerAddName' | 'providerAddUrl' | 'providerAddKey' | 'providerAddModels' | 'providerAppendModels' | 'providerSetKey' | 'providerRemoveModels' | 'providerConfirmRemove' | 'skills' | 'skillsAction' | 'skillsAddName' | 'skillsAddDescription' | 'skillsConfirmRemove' | 'lsp' | 'lspAction' | 'lspAddPreset' | 'lspAddName' | 'lspAddCommand' | 'lspConfirmRemove' | 'mcp' | 'mcpAction' | 'mcpAddPreset' | 'mcpAddName' | 'mcpAddTransport' | 'mcpAddUrl' | 'mcpAddCommand' | 'mcpAddKey' | 'mcpSetKey' | 'mcpConfirmRemove';
2
+ /** Modes that show an always-on suggestion picker (server/preset lists). */
3
+ export declare const PICKER_MODES: ReadonlySet<Mode>;
4
+ /** Modes that mask input (secrets/API keys). */
5
+ export declare const MASKED_MODES: ReadonlySet<Mode>;
6
+ /** Modes where submitting an empty value is valid (optional steps). */
7
+ export declare const SUBMIT_EMPTY_MODES: ReadonlySet<Mode>;
8
+ export declare function placeholderForMode(mode: Mode, busy: boolean): string;
@@ -0,0 +1,44 @@
1
+ /** Modes that show an always-on suggestion picker (server/preset lists). */
2
+ export const PICKER_MODES = new Set(['provider', 'providerAction', 'providerAddPreset', 'model', 'skills', 'skillsAction', 'lsp', 'lspAction', 'lspAddPreset', 'mcp', 'mcpAction', 'mcpAddPreset', 'mcpAddTransport']);
3
+ /** Modes that mask input (secrets/API keys). */
4
+ export const MASKED_MODES = new Set(['providerAddKey', 'providerSetKey', 'mcpAddKey', 'mcpSetKey']);
5
+ /** Modes where submitting an empty value is valid (optional steps). */
6
+ export const SUBMIT_EMPTY_MODES = new Set(['providerAddKey', 'mcpAddKey']);
7
+ const PLACEHOLDERS = {
8
+ provider: 'Choose provider',
9
+ providerAction: 'Choose provider action',
10
+ providerAddPreset: 'Choose a provider preset or custom',
11
+ model: 'Choose model',
12
+ providerAddName: 'Provider name',
13
+ providerAddUrl: 'https://example.com/v1',
14
+ providerAddKey: 'API key, or blank for local',
15
+ providerSetKey: 'API key',
16
+ providerAddModels: 'model-a, model-b',
17
+ providerAppendModels: 'model-a, model-b',
18
+ providerRemoveModels: 'model-a, model-b',
19
+ providerConfirmRemove: 'Type "yes" to confirm',
20
+ skills: 'Choose a skill or add skill',
21
+ skillsAction: 'show info, enable, disable, validate, or remove',
22
+ skillsAddName: 'Skill name (kebab-case, e.g. security-review)',
23
+ skillsAddDescription: 'Describe what the skill should do',
24
+ skillsConfirmRemove: 'Type "yes" to confirm',
25
+ lsp: 'Choose LSP server or add server',
26
+ lspAction: 'enable, disable, or remove server',
27
+ lspAddPreset: 'Choose an LSP preset or custom',
28
+ lspAddName: 'LSP server name (e.g. typescript)',
29
+ lspAddCommand: 'Command (e.g. typescript-language-server --stdio)',
30
+ lspConfirmRemove: 'Type "yes" to confirm',
31
+ mcp: 'Choose MCP server or add server',
32
+ mcpAction: 'enable, disable, remove, or set key',
33
+ mcpAddPreset: 'Choose an MCP preset or custom',
34
+ mcpAddName: 'MCP server name (e.g. context7)',
35
+ mcpAddTransport: 'http, sse, or stdio',
36
+ mcpAddUrl: 'https://mcp.example.com/mcp',
37
+ mcpAddCommand: 'Command (e.g. npx -y @pkg/server)',
38
+ mcpAddKey: 'API key, or blank to skip',
39
+ mcpSetKey: 'API key',
40
+ mcpConfirmRemove: 'Type "yes" to confirm',
41
+ };
42
+ export function placeholderForMode(mode, busy) {
43
+ return PLACEHOLDERS[mode] ?? (busy ? 'Queue a follow-up, or Esc to interrupt' : 'Ask Haze to help build your app');
44
+ }
@@ -0,0 +1,6 @@
1
+ export type CommandHelpEntry = {
2
+ usage: string;
3
+ description: string;
4
+ };
5
+ export declare const COMMAND_HELP_ENTRIES: CommandHelpEntry[];
6
+ export declare function formatCommandHelp(entries?: CommandHelpEntry[]): string;
@@ -0,0 +1,25 @@
1
+ export const COMMAND_HELP_ENTRIES = [
2
+ { usage: '/help', description: 'Show all available slash commands and what they do.' },
3
+ { usage: '/provider', description: 'Choose a provider, then use it, add/remove models, set API key, or remove it.' },
4
+ { usage: '/model', description: 'Choose a model from all configured providers.' },
5
+ { usage: '/model <name-or-provider:name>', description: 'Set a model directly. Selecting a model also sets its provider.' },
6
+ { usage: '/settings', description: 'Show the configured provider, model, API key status, LSP/MCP servers, skills, and loaded context files.' },
7
+ { usage: '/settings open', description: 'Open ~/.haze/settings.json with the OS default app.' },
8
+ { usage: '/skills', description: 'Manage Markdown skills: generate a custom skill, show info, enable/disable, validate, or remove.' },
9
+ { usage: '/init', description: 'Inspect the current workspace and create or update AGENTS.md project instructions.' },
10
+ { usage: '/context', description: 'Show a token breakdown of the current request: system prompt, project context, tools (incl. MCP), and chat messages.' },
11
+ { usage: '/session', description: 'Show the current durable session file.' },
12
+ { usage: '/resume', description: 'Resume the latest saved session for this workspace.' },
13
+ { usage: '/new', description: 'Start a fresh durable session.' },
14
+ { usage: '/logs', description: 'List recent log files with sizes and dates.' },
15
+ { usage: '/lsp', description: 'Configure Language Server Protocol navigation tools (interactive picker).' },
16
+ { usage: '/mcp', description: 'Configure Model Context Protocol servers like Context7 (interactive picker).' },
17
+ { usage: '/logs <id>', description: 'Show summary of a specific log: entry counts by type, total tokens, tool calls.' },
18
+ { usage: '/compact [instructions]', description: 'Summarize older model context and keep recent messages.' },
19
+ { usage: '/clear', description: 'Clear the current chat conversation history.' },
20
+ { usage: '/exit', description: 'Exit Haze.' },
21
+ { usage: '/quit', description: 'Exit Haze.' },
22
+ ];
23
+ export function formatCommandHelp(entries = COMMAND_HELP_ENTRIES) {
24
+ return ['Commands:', ...entries.flatMap(entry => [entry.usage, ` ${entry.description}`])].join('\n');
25
+ }
@@ -1,6 +1,6 @@
1
1
  import type { ContextFile } from '../../config/contextFiles.js';
2
2
  import { type HazeSettings } from '../../config/settings.js';
3
- import type { Mode } from './chat.js';
3
+ import type { Mode } from './chatModes.js';
4
4
  export type CommandContext = {
5
5
  settings: HazeSettings;
6
6
  contextFiles: ContextFile[];
@@ -1,15 +1,12 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import fs from 'fs-extra';
3
- import path from 'node:path';
4
- import { buildInitPrompt } from '../../llm/initPrompt.js';
5
- import { contextFileDiagnostics, summarizeContextDiagnostics, MAX_CONTEXT_FILE_CHARS } from '../../config/contextFiles.js';
6
3
  import { SETTINGS_FILE, writeSettings } from '../../config/settings.js';
7
- import { activeProvider, configuredProviders, modelSelector, providerHasKey, resolveModelSelector, upsertProvider } from '../../config/providers.js';
8
- import { configuredLspServers } from '../../config/lspSettings.js';
9
- import { configuredMcpServers } from '../../config/mcpSettings.js';
10
- import { isSkillEnabled } from '../../config/skillSettings.js';
11
4
  import { clearTasks } from '../../core/tasks/taskStorage.js';
12
- import { listLogs, readLogEntries } from '../../core/log/llmLog.js';
5
+ import { COMMAND_HELP_ENTRIES, formatCommandHelp } from './commandHelp.js';
6
+ import { handleInitCommand } from './initCommand.js';
7
+ import { handleLogsCommand } from './logsCommand.js';
8
+ import { handleModelCommand } from './modelCommand.js';
9
+ import { formatSettingsSummary } from './settingsSummary.js';
13
10
  async function ensureSettingsFile(settings) {
14
11
  if (!await fs.pathExists(SETTINGS_FILE))
15
12
  await writeSettings(settings);
@@ -24,272 +21,49 @@ function openPath(filePath) {
24
21
  child.on('error', () => undefined);
25
22
  child.unref();
26
23
  }
27
- function formatBytes(bytes) {
28
- if (bytes < 1024)
29
- return `${bytes} B`;
30
- if (bytes < 1024 * 1024)
31
- return `${(bytes / 1024).toFixed(1)} KB`;
32
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
24
+ const HANDLED = 'handled';
25
+ function exact(command) {
26
+ return value => value === command ? { args: '' } : false;
33
27
  }
34
- async function handleLogsCommand(args, ctx) {
35
- const id = args.trim();
36
- if (!id) {
37
- // List recent logs
38
- const logs = await listLogs();
39
- if (logs.length === 0) {
40
- ctx.addSystemMessage('No log files found.');
41
- return 'handled';
42
- }
43
- const lines = logs.slice(0, 20).map(log => {
44
- const date = log.modified.slice(0, 19).replace('T', ' ');
45
- return ` ${log.id} ${formatBytes(log.size).padStart(8)} ${date}`;
46
- });
47
- ctx.addSystemMessage(['Recent logs:', ' ID Size Modified', ...lines].join('\n'));
48
- return 'handled';
49
- }
50
- // Show summary for a specific log
51
- const entries = await readLogEntries(id);
52
- if (entries.length === 0) {
53
- ctx.addSystemMessage(`No log found with id ${id}.`);
54
- return 'handled';
55
- }
56
- const typeCounts = {};
57
- let totalInput = 0;
58
- let totalOutput = 0;
59
- const toolCallCounts = {};
60
- for (const entry of entries) {
61
- typeCounts[entry.type] = (typeCounts[entry.type] ?? 0) + 1;
62
- if (entry.usage) {
63
- totalInput += entry.usage.inputTokens ?? 0;
64
- totalOutput += entry.usage.outputTokens ?? 0;
65
- }
66
- if (entry.type === 'tool_call' && entry.toolCall) {
67
- toolCallCounts[entry.toolCall.name] = (toolCallCounts[entry.toolCall.name] ?? 0) + 1;
68
- }
69
- }
70
- const typeLines = Object.entries(typeCounts)
71
- .sort(([a], [b]) => a.localeCompare(b))
72
- .map(([type, count]) => ` ${type}: ${count}`);
73
- const toolLines = Object.entries(toolCallCounts)
74
- .sort(([, a], [, b]) => b - a)
75
- .map(([name, count]) => ` ${name}: ${count}`);
76
- const parts = [
77
- `Log: ${id}`,
78
- `Entries: ${entries.length}`,
79
- '',
80
- 'Entry counts by type:',
81
- ...typeLines,
82
- '',
83
- `Total token usage: in=${totalInput} out=${totalOutput}`,
84
- ];
85
- if (toolLines.length > 0) {
86
- parts.push('', 'Tool call counts:', ...toolLines);
87
- }
88
- ctx.addSystemMessage(parts.join('\n'));
89
- return 'handled';
28
+ function exactOrArgs(command) {
29
+ return value => value === command ? { args: '' } : value.startsWith(`${command} `) ? { args: value.slice(command.length).trim() } : false;
90
30
  }
91
- export async function handleSlashCommand(value, ctx) {
92
- if (value === '/exit' || value === '/quit')
93
- return 'exit';
94
- if (value === '/help') {
95
- ctx.addSystemMessage([
96
- 'Commands:',
97
- '/help',
98
- ' Show all available slash commands and what they do.',
99
- '/provider',
100
- ' Choose a provider, then use it, add/remove models, set API key, or remove it.',
101
- '/model',
102
- ' Choose a model from all configured providers.',
103
- '/model <name-or-provider:name>',
104
- ' Set a model directly. Selecting a model also sets its provider.',
105
- '/settings',
106
- ' Show the configured provider, model, API key status, LSP/MCP servers, skills, and loaded context files.',
107
- '/settings open',
108
- ' Open ~/.haze/settings.json with the OS default app.',
109
- '/skills',
110
- ' Manage Markdown skills: generate a custom skill, show info, enable/disable, validate, or remove.',
111
- '/init',
112
- ' Inspect the current workspace and create or update AGENTS.md project instructions.',
113
- '/context',
114
- ' Show a token breakdown of the current request: system prompt, project context, tools (incl. MCP), and chat messages.',
115
- '/session',
116
- ' Show the current durable session file.',
117
- '/resume',
118
- ' Resume the latest saved session for this workspace.',
119
- '/new',
120
- ' Start a fresh durable session.',
121
- '/logs',
122
- ' List recent log files with sizes and dates.',
123
- '/lsp',
124
- ' Configure Language Server Protocol navigation tools (interactive picker).',
125
- '/mcp',
126
- ' Configure Model Context Protocol servers like Context7 (interactive picker).',
127
- '/logs <id>',
128
- ' Show summary of a specific log: entry counts by type, total tokens, tool calls.',
129
- '/compact [instructions]',
130
- ' Summarize older model context and keep recent messages.',
131
- '/clear',
132
- ' Clear the current chat conversation history.',
133
- '/exit',
134
- ' Exit Haze.',
135
- '/quit',
136
- ' Exit Haze.',
137
- ].join('\n'));
138
- return 'handled';
139
- }
140
- if (value === '/context') {
141
- if (ctx.getContextReport)
142
- ctx.addSystemMessage(await ctx.getContextReport());
143
- else
144
- ctx.addSystemMessage('Context overview is unavailable.');
145
- return 'handled';
146
- }
147
- if (value === '/session') {
148
- ctx.addSystemMessage(ctx.sessionInfo?.() ?? 'Session persistence is unavailable.');
149
- return 'handled';
150
- }
151
- if (value === '/resume') {
152
- if (ctx.resumeSession)
31
+ const SLASH_COMMANDS = [
32
+ { match: value => value === '/exit' || value === '/quit' ? { args: '' } : false, run: () => 'exit' },
33
+ { match: exact('/help'), run: (_args, ctx) => { ctx.addSystemMessage(formatCommandHelp(COMMAND_HELP_ENTRIES)); return HANDLED; } },
34
+ { match: exact('/context'), run: async (_args, ctx) => { ctx.addSystemMessage(ctx.getContextReport ? await ctx.getContextReport() : 'Context overview is unavailable.'); return HANDLED; } },
35
+ { match: exact('/session'), run: (_args, ctx) => { ctx.addSystemMessage(ctx.sessionInfo?.() ?? 'Session persistence is unavailable.'); return HANDLED; } },
36
+ { match: exact('/resume'), run: async (_args, ctx) => { if (ctx.resumeSession)
153
37
  await ctx.resumeSession();
154
38
  else
155
- ctx.addSystemMessage('Session persistence is unavailable.');
156
- return 'handled';
157
- }
158
- if (value === '/new') {
159
- if (ctx.newSession)
39
+ ctx.addSystemMessage('Session persistence is unavailable.'); return HANDLED; } },
40
+ { match: exact('/new'), run: async (_args, ctx) => { if (ctx.newSession)
160
41
  await ctx.newSession();
161
42
  else
162
- ctx.addSystemMessage('Session persistence is unavailable.');
163
- return 'handled';
164
- }
165
- if (value === '/compact' || value.startsWith('/compact ')) {
166
- if (ctx.compactConversation)
167
- ctx.compactConversation(value.slice('/compact'.length).trim() || undefined);
43
+ ctx.addSystemMessage('Session persistence is unavailable.'); return HANDLED; } },
44
+ { match: exactOrArgs('/compact'), run: (args, ctx) => { if (ctx.compactConversation)
45
+ ctx.compactConversation(args || undefined);
168
46
  else
169
- ctx.addSystemMessage('Compaction is unavailable.');
170
- return 'handled';
171
- }
172
- if (value === '/clear') {
173
- ctx.clearConversation();
174
- await clearTasks();
175
- ctx.addSystemMessage('Cleared. The void is productive.');
176
- return 'handled';
177
- }
178
- if (value === '/logs' || value.startsWith('/logs ')) {
179
- const args = value.slice('/logs'.length).trim();
180
- return await handleLogsCommand(args, ctx);
181
- }
182
- if (value === '/lsp' || value.startsWith('/lsp ')) {
183
- ctx.setMode('lsp');
184
- ctx.addSystemMessage('Choose an LSP server to enable, disable, or remove it. Choose "add server" to add one from presets (e.g. typescript) or enter a custom command.');
185
- return 'handled';
186
- }
187
- if (value === '/mcp' || value.startsWith('/mcp ')) {
188
- ctx.setMode('mcp');
189
- ctx.addSystemMessage('Choose an MCP server to enable, disable, remove, or set a key for it. Choose "add server" to add one from presets (e.g. context7) or enter custom details.');
190
- return 'handled';
191
- }
192
- if (value === '/settings open' || value === '/settings edit') {
193
- const file = await ensureSettingsFile(ctx.settings);
194
- openPath(file);
195
- ctx.addSystemMessage(`Opened settings file: ${file}`);
196
- return 'handled';
197
- }
198
- if (value === '/settings') {
199
- const providers = configuredProviders(ctx.settings);
200
- const activeProvider = providers.find(provider => provider.name === ctx.settings.provider) ?? providers[0];
201
- const contextDiagnostics = contextFileDiagnostics(ctx.contextFiles);
202
- const contextTokens = contextDiagnostics.reduce((sum, file) => sum + file.estimatedTokens, 0);
203
- const summary = summarizeContextDiagnostics(ctx.contextFiles);
204
- const notes = [];
205
- if (summary.exceedsBudget === true && summary.windowSize) {
206
- const sharePct = Math.round((summary.budgetShare ?? 0) * 100);
207
- const thresholdPct = Math.round(summary.budgetThreshold * 100);
208
- notes.push(`project context exceeds ${thresholdPct}% budget (${sharePct}% of ${Math.round(summary.windowSize / 1000)}k window)`);
209
- }
210
- if (summary.duplicateGroups.length > 0) {
211
- const duplicateTotal = summary.duplicateFileCount;
212
- notes.push(`${summary.duplicateGroups.length} duplicate group${summary.duplicateGroups.length === 1 ? '' : 's'} (${duplicateTotal} file${duplicateTotal === 1 ? '' : 's'} with identical content)`);
213
- }
214
- const lspServers = configuredLspServers(ctx.settings);
215
- const { loadSkillRegistry } = await import('../../skills/SkillRegistry.js');
216
- const installedSkills = [...(await loadSkillRegistry()).skills.values()];
217
- const skillNames = installedSkills.map(skill => `${skill.name}${isSkillEnabled(ctx.settings, skill.name) ? '' : ' (disabled)'}`).join(', ');
218
- const lines = [
219
- `Provider: ${activeProvider?.name ?? 'not configured'}`,
220
- `Model: ${ctx.settings.model ?? 'not set'}`,
221
- `Base URL: ${activeProvider?.url ?? ctx.settings.baseURL ?? 'not configured'}`,
222
- `API key: ${activeProvider && providerHasKey(ctx.settings, activeProvider) ? 'saved' : 'missing'}`,
223
- `Configured providers: ${providers.map(provider => provider.name).join(', ') || 'none'}`,
224
- `LSP servers: ${lspServers.map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
225
- `MCP servers: ${configuredMcpServers(ctx.settings).map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
226
- `Skills: ${skillNames || 'none'}`,
227
- `Context files: ${ctx.contextFiles.length ? `${ctx.contextFiles.map(file => file.path).join(', ')} (~${contextTokens} tokens)` : 'none'}`,
228
- ];
229
- if (notes.length > 0)
230
- lines.push(`Context note: ${notes.join('; ')}`);
231
- ctx.addSystemMessage(lines.join(' | '));
232
- return 'handled';
233
- }
234
- if (value === '/provider') {
235
- ctx.setModelProviderFilter?.(undefined);
236
- ctx.setMode('provider');
237
- ctx.addSystemMessage('Choose a provider. Selecting one opens provider actions. Choose "add provider" to pick from presets or enter custom details.');
238
- return 'handled';
239
- }
240
- if (value === '/model') {
241
- ctx.setModelProviderFilter?.(undefined);
242
- ctx.setMode('model');
243
- ctx.addSystemMessage('Choose a model. Selecting a model also sets its provider.');
244
- return 'handled';
245
- }
246
- if (value === '/model list') {
247
- const providers = configuredProviders(ctx.settings);
248
- ctx.addSystemMessage(['Configured models:', ...providers.flatMap(provider => provider.models.map(model => `- ${modelSelector(provider, model)} - ${provider.name}`))].join('\n'));
249
- return 'handled';
250
- }
251
- if (value.startsWith('/model ')) {
252
- const selector = value.slice('/model '.length).trim();
253
- const resolved = resolveModelSelector(ctx.settings, selector);
254
- if (resolved.status === 'ambiguous') {
255
- ctx.addSystemMessage(`Model ${resolved.model} exists on multiple providers: ${resolved.providers.map(provider => modelSelector(provider, resolved.model)).join(', ')}`);
256
- return 'handled';
257
- }
258
- if (resolved.status === 'missing') {
259
- const provider = activeProvider(ctx.settings);
260
- if (!provider) {
261
- ctx.addSystemMessage('No provider configured. Run /provider to choose or add a provider before setting a model.');
262
- return 'handled';
263
- }
264
- const nextProvider = provider.models.includes(selector) ? provider : { ...provider, models: [...provider.models, selector] };
265
- await ctx.updateSettings({ provider: provider.name, model: selector, providers: upsertProvider(ctx.settings, nextProvider) });
266
- ctx.addSystemMessage(`Model set to ${selector} on ${provider.name}. Saved to ~/.haze/settings.json.`);
267
- return 'handled';
268
- }
269
- await ctx.updateSettings({ provider: resolved.provider.name, model: resolved.model });
270
- ctx.addSystemMessage(`Model set to ${resolved.model} on ${resolved.provider.name}. Saved to ~/.haze/settings.json.`);
271
- return 'handled';
272
- }
273
- if (value === '/init') {
274
- await ctx.runAgentTurn(buildInitPrompt(), '/init');
275
- await ctx.refreshContextFiles();
276
- const agentsMdPath = path.join(process.cwd(), 'AGENTS.md');
277
- if (await fs.pathExists(agentsMdPath)) {
278
- const content = await fs.readFile(agentsMdPath, 'utf8');
279
- const chars = content.length;
280
- const lines = content.split('\n').length;
281
- const msg = chars > MAX_CONTEXT_FILE_CHARS
282
- ? `AGENTS.md validation: ${chars.toLocaleString()} chars / ${lines} lines — exceeds the ${MAX_CONTEXT_FILE_CHARS.toLocaleString()}-char context budget and will be truncated. Trim it before relying on it.`
283
- : `AGENTS.md validation: ${chars.toLocaleString()} chars / ${lines} lines — within the ${MAX_CONTEXT_FILE_CHARS.toLocaleString()}-char context budget.`;
284
- ctx.addSystemMessage(msg);
285
- }
286
- return 'handled';
287
- }
288
- if (value === '/skills') {
289
- ctx.setMode('skills');
290
- ctx.addSystemMessage('Choose a skill to show info, enable/disable, or remove it. Choose "add skill" to generate a new one from a description.');
291
- return 'handled';
292
- }
47
+ ctx.addSystemMessage('Compaction is unavailable.'); return HANDLED; } },
48
+ { match: exact('/clear'), run: async (_args, ctx) => { ctx.clearConversation(); await clearTasks(); ctx.addSystemMessage('Cleared. The void is productive.'); return HANDLED; } },
49
+ { match: exactOrArgs('/logs'), run: async (args, ctx) => await handleLogsCommand(args, ctx) },
50
+ { match: exactOrArgs('/lsp'), run: (_args, ctx) => { ctx.setMode('lsp'); ctx.addSystemMessage('Choose an LSP server to enable, disable, or remove it. Choose "add server" to add one from presets (e.g. typescript) or enter a custom command.'); return HANDLED; } },
51
+ { match: exactOrArgs('/mcp'), run: (_args, ctx) => { ctx.setMode('mcp'); ctx.addSystemMessage('Choose an MCP server to enable, disable, remove, or set a key for it. Choose "add server" to add one from presets (e.g. context7) or enter custom details.'); return HANDLED; } },
52
+ { match: value => value === '/settings open' || value === '/settings edit' ? { args: '' } : false, run: async (_args, ctx) => { const file = await ensureSettingsFile(ctx.settings); openPath(file); ctx.addSystemMessage(`Opened settings file: ${file}`); return HANDLED; } },
53
+ { match: exact('/settings'), run: async (_args, ctx) => { ctx.addSystemMessage(await formatSettingsSummary(ctx.settings, ctx.contextFiles)); return HANDLED; } },
54
+ { match: exact('/provider'), run: (_args, ctx) => { ctx.setModelProviderFilter?.(undefined); ctx.setMode('provider'); ctx.addSystemMessage('Choose a provider. Selecting one opens provider actions. Choose "add provider" to pick from presets or enter custom details.'); return HANDLED; } },
55
+ { match: exact('/init'), run: async (_args, ctx) => await handleInitCommand(ctx) },
56
+ { match: exact('/skills'), run: (_args, ctx) => { ctx.setMode('skills'); ctx.addSystemMessage('Choose a skill to show info, enable/disable, or remove it. Choose "add skill" to generate a new one from a description.'); return HANDLED; } },
57
+ ];
58
+ export async function handleSlashCommand(value, ctx) {
59
+ for (const command of SLASH_COMMANDS) {
60
+ const match = command.match(value);
61
+ if (match)
62
+ return await command.run(match.args, ctx);
63
+ }
64
+ const modelResult = await handleModelCommand(value, ctx);
65
+ if (modelResult)
66
+ return modelResult;
293
67
  if (value.startsWith('/')) {
294
68
  ctx.addSystemMessage(`Unknown command: ${value}. Bold start.`);
295
69
  return 'handled';
@@ -9,8 +9,10 @@ export function compact(value, maxLength = 180) {
9
9
  else {
10
10
  text = JSON.stringify(value, (_key, nestedValue) => nestedValue instanceof Error ? nestedValue.message : nestedValue);
11
11
  }
12
- if (!text || text === '{}')
13
- return String(value);
12
+ if (!text)
13
+ return value === null ? 'null' : value === undefined ? 'undefined' : '';
14
+ if (text === '{}')
15
+ return ''; // empty object: nothing useful to render; avoid "[object Object]"
14
16
  return text.length > maxLength ? `${text.slice(0, maxLength)}…` : text;
15
17
  }
16
18
  export function toolCallSummary(toolName, input) {
@@ -26,14 +28,20 @@ export function toolCallSummary(toolName, input) {
26
28
  }
27
29
  if (toolName === 'listFiles' && typeof data?.path === 'string')
28
30
  return `listFiles ${data.path}`;
29
- if ((toolName === 'readFile' || toolName === 'writeFile') && typeof data?.path === 'string')
30
- return `${toolName} ${data.path}`;
31
+ if ((toolName === 'readFile' || toolName === 'writeFile')) {
32
+ if (typeof data?.path === 'string')
33
+ return `${toolName} ${data.path}`;
34
+ if (data == null || (typeof data === 'object' && Object.keys(data).length === 0))
35
+ return toolName; // input not yet streamed (tool-input-start) or empty
36
+ }
31
37
  if (toolName === 'editFile' && typeof data?.path === 'string') {
32
38
  const edits = Array.isArray(data.edits) ? ` (${data.edits.length} edit${data.edits.length === 1 ? '' : 's'})` : '';
33
39
  return `${toolName} ${data.path}${edits}`;
34
40
  }
35
41
  if (toolName === 'replaceLines' && typeof data?.path === 'string')
36
42
  return `replaceLines ${data.path}:${data.startLine}-${data.endLine}`;
43
+ if ((toolName === 'editFile' || toolName === 'replaceLines') && (data == null || (typeof data === 'object' && Object.keys(data).length === 0)))
44
+ return toolName;
37
45
  if (toolName === 'subagent' && typeof data?.task === 'string') {
38
46
  const taskPreview = data.task.length > 60 ? `${data.task.slice(0, 60).trimEnd()}…` : data.task;
39
47
  return `subagent "${taskPreview}"`;
@@ -0,0 +1,2 @@
1
+ import type { CommandContext, CommandResult } from './commands.js';
2
+ export declare function handleInitCommand(ctx: CommandContext): Promise<CommandResult>;
@@ -0,0 +1,19 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'node:path';
3
+ import { MAX_CONTEXT_FILE_CHARS } from '../../config/contextFiles.js';
4
+ import { buildInitPrompt } from '../../llm/initPrompt.js';
5
+ export async function handleInitCommand(ctx) {
6
+ await ctx.runAgentTurn(buildInitPrompt(), '/init');
7
+ await ctx.refreshContextFiles();
8
+ const agentsMdPath = path.join(process.cwd(), 'AGENTS.md');
9
+ if (await fs.pathExists(agentsMdPath)) {
10
+ const content = await fs.readFile(agentsMdPath, 'utf8');
11
+ const chars = content.length;
12
+ const lines = content.split('\n').length;
13
+ const msg = chars > MAX_CONTEXT_FILE_CHARS
14
+ ? `AGENTS.md validation: ${chars.toLocaleString()} chars / ${lines} lines — exceeds the ${MAX_CONTEXT_FILE_CHARS.toLocaleString()}-char context budget and will be truncated. Trim it before relying on it.`
15
+ : `AGENTS.md validation: ${chars.toLocaleString()} chars / ${lines} lines — within the ${MAX_CONTEXT_FILE_CHARS.toLocaleString()}-char context budget.`;
16
+ ctx.addSystemMessage(msg);
17
+ }
18
+ return 'handled';
19
+ }
@@ -0,0 +1,2 @@
1
+ import type { CommandContext, CommandResult } from './commands.js';
2
+ export declare function handleLogsCommand(args: string, ctx: CommandContext): Promise<CommandResult>;
@@ -0,0 +1,63 @@
1
+ import { listLogs, readLogEntries } from '../../core/log/llmLog.js';
2
+ function formatBytes(bytes) {
3
+ if (bytes < 1024)
4
+ return `${bytes} B`;
5
+ if (bytes < 1024 * 1024)
6
+ return `${(bytes / 1024).toFixed(1)} KB`;
7
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
8
+ }
9
+ export async function handleLogsCommand(args, ctx) {
10
+ const id = args.trim();
11
+ if (!id) {
12
+ const logs = await listLogs();
13
+ if (logs.length === 0) {
14
+ ctx.addSystemMessage('No log files found.');
15
+ return 'handled';
16
+ }
17
+ const lines = logs.slice(0, 20).map(log => {
18
+ const date = log.modified.slice(0, 19).replace('T', ' ');
19
+ return ` ${log.id} ${formatBytes(log.size).padStart(8)} ${date}`;
20
+ });
21
+ ctx.addSystemMessage(['Recent logs:', ' ID Size Modified', ...lines].join('\n'));
22
+ return 'handled';
23
+ }
24
+ const entries = await readLogEntries(id);
25
+ if (entries.length === 0) {
26
+ ctx.addSystemMessage(`No log found with id ${id}.`);
27
+ return 'handled';
28
+ }
29
+ const typeCounts = {};
30
+ let totalInput = 0;
31
+ let totalOutput = 0;
32
+ const toolCallCounts = {};
33
+ for (const entry of entries) {
34
+ typeCounts[entry.type] = (typeCounts[entry.type] ?? 0) + 1;
35
+ if (entry.usage) {
36
+ totalInput += entry.usage.inputTokens ?? 0;
37
+ totalOutput += entry.usage.outputTokens ?? 0;
38
+ }
39
+ if (entry.type === 'tool_call' && entry.toolCall) {
40
+ toolCallCounts[entry.toolCall.name] = (toolCallCounts[entry.toolCall.name] ?? 0) + 1;
41
+ }
42
+ }
43
+ const typeLines = Object.entries(typeCounts)
44
+ .sort(([a], [b]) => a.localeCompare(b))
45
+ .map(([type, count]) => ` ${type}: ${count}`);
46
+ const toolLines = Object.entries(toolCallCounts)
47
+ .sort(([, a], [, b]) => b - a)
48
+ .map(([name, count]) => ` ${name}: ${count}`);
49
+ const parts = [
50
+ `Log: ${id}`,
51
+ `Entries: ${entries.length}`,
52
+ '',
53
+ 'Entry counts by type:',
54
+ ...typeLines,
55
+ '',
56
+ `Total token usage: in=${totalInput} out=${totalOutput}`,
57
+ ];
58
+ if (toolLines.length > 0) {
59
+ parts.push('', 'Tool call counts:', ...toolLines);
60
+ }
61
+ ctx.addSystemMessage(parts.join('\n'));
62
+ return 'handled';
63
+ }
@@ -0,0 +1,14 @@
1
+ import { type HazeLspServer } from '../../config/lspSettings.js';
2
+ import type { HazeSettings } from '../../config/settings.js';
3
+ export type LspWizardResult = {
4
+ message?: string;
5
+ mode?: 'chat' | 'lsp' | 'lspAction' | 'lspAddName' | 'lspConfirmRemove';
6
+ selectedName?: string;
7
+ settingsPatch?: Partial<HazeSettings>;
8
+ server?: HazeLspServer;
9
+ clearDraft?: boolean;
10
+ };
11
+ export declare function selectLspServerResult(settings: HazeSettings, serverName: string): LspWizardResult;
12
+ export declare function selectLspPresetResult(settings: HazeSettings, presetId: string): LspWizardResult;
13
+ export declare function selectLspActionResult(settings: HazeSettings, selectedName: string | undefined, action: string): LspWizardResult;
14
+ export declare function finishLspCustomResult(settings: HazeSettings, draftName: string | undefined, commandLine: string): LspWizardResult;
@@ -0,0 +1,44 @@
1
+ import { configuredLspServers, lspPreset, upsertLspServer, setLspServerEnabled } from '../../config/lspSettings.js';
2
+ import { COMMON_ACTIONS, LSP_ACTIONS, SERVER_CHOICES } from './wizardActions.js';
3
+ import { commandParts } from './wizardInput.js';
4
+ export function selectLspServerResult(settings, serverName) {
5
+ if (serverName === SERVER_CHOICES.addServer)
6
+ return { mode: 'lspAddName', clearDraft: true, message: 'Choose an LSP preset, or select "custom" to enter a name and command manually.' };
7
+ const server = configuredLspServers(settings).find(candidate => candidate.name === serverName);
8
+ if (!server)
9
+ return { mode: 'chat', message: `No LSP server named ${serverName}. Use /lsp and choose add server.` };
10
+ return { mode: 'lspAction', selectedName: server.name, message: `${server.name}: choose an action.` };
11
+ }
12
+ export function selectLspPresetResult(settings, presetId) {
13
+ if (presetId === SERVER_CHOICES.custom)
14
+ return { mode: 'lspAddName', clearDraft: true, message: 'LSP server name? Example: typescript, rust, my-lsp.' };
15
+ const preset = lspPreset(presetId);
16
+ if (!preset)
17
+ return { message: `Unknown preset: ${presetId}.` };
18
+ if (configuredLspServers(settings).some(server => server.name === preset.name))
19
+ return { mode: 'chat', message: `LSP server ${preset.name} already exists. Use /lsp to manage existing servers.` };
20
+ return { mode: 'chat', server: preset, settingsPatch: { lspServers: upsertLspServer(settings, preset) }, message: `Added LSP preset ${preset.name}. Ensure ${preset.command} is installed and on PATH; tools appear once it is.` };
21
+ }
22
+ export function selectLspActionResult(settings, selectedName, action) {
23
+ if (!selectedName)
24
+ return { mode: 'lsp' };
25
+ const server = configuredLspServers(settings).find(candidate => candidate.name === selectedName);
26
+ if (!server)
27
+ return { mode: 'chat', selectedName: undefined, message: `LSP server ${selectedName} not found.` };
28
+ if (action === COMMON_ACTIONS.enable || action === COMMON_ACTIONS.disable) {
29
+ const enabled = action === COMMON_ACTIONS.enable;
30
+ return { mode: 'chat', selectedName: undefined, settingsPatch: { lspServers: setLspServerEnabled(settings, selectedName, enabled) }, message: `LSP server ${selectedName} ${enabled ? 'enabled' : 'disabled'}.` };
31
+ }
32
+ if (action === LSP_ACTIONS.removeServer)
33
+ return { mode: 'lspConfirmRemove', message: `Remove LSP server ${selectedName}? Type "yes" to confirm. Esc to cancel.` };
34
+ return { message: `Unknown LSP action: ${action}` };
35
+ }
36
+ export function finishLspCustomResult(settings, draftName, commandLine) {
37
+ const name = draftName?.trim();
38
+ const parts = commandParts(commandLine);
39
+ const command = parts[0];
40
+ if (!name || !command)
41
+ return { mode: 'chat', clearDraft: true, message: 'LSP server name and command are required.' };
42
+ const server = { name, command, args: parts.slice(1), extensions: [], rootPatterns: ['.git'], enabled: true };
43
+ return { mode: 'chat', clearDraft: true, server, settingsPatch: { lspServers: upsertLspServer(settings, server) }, message: `Added LSP server ${name} (${command}${parts.length > 1 ? ` ${parts.slice(1).join(' ')}` : ''}). Add extensions in ~/.haze/settings.json so tools can auto-select it.` };
44
+ }