@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,5 +1,5 @@
1
1
  import type { ContextFile } from '../../config/contextFiles.js';
2
- import type { HazeSettings } from '../../config/settings.js';
2
+ import { type HazeSettings } from '../../config/settings.js';
3
3
  import type { Mode } from './chat.js';
4
4
  export type CommandContext = {
5
5
  settings: HazeSettings;
@@ -15,6 +15,7 @@ export type CommandContext = {
15
15
  runAgentTurn: (prompt: string, displayValue?: string) => Promise<void>;
16
16
  refreshContextFiles: () => Promise<ContextFile[]>;
17
17
  updateSettings: (patch: Partial<HazeSettings>) => Promise<HazeSettings>;
18
+ getContextReport?: () => Promise<string>;
18
19
  };
19
20
  export type CommandResult = 'handled' | 'unhandled' | 'exit';
20
21
  export declare function handleSlashCommand(value: string, ctx: CommandContext): Promise<CommandResult>;
@@ -1,98 +1,28 @@
1
+ import { spawn } from 'node:child_process';
1
2
  import fs from 'fs-extra';
2
3
  import path from 'node:path';
3
4
  import { buildInitPrompt } from '../../llm/initPrompt.js';
4
- import { contextFileDiagnostics, summarizeContextDiagnostics } from '../../config/contextFiles.js';
5
+ import { contextFileDiagnostics, summarizeContextDiagnostics, MAX_CONTEXT_FILE_CHARS } from '../../config/contextFiles.js';
6
+ import { SETTINGS_FILE, writeSettings } from '../../config/settings.js';
5
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';
6
11
  import { clearTasks } from '../../core/tasks/taskStorage.js';
7
12
  import { listLogs, readLogEntries } from '../../core/log/llmLog.js';
8
- function skillHelp() {
9
- return [
10
- 'Skill commands:',
11
- '/create-skill',
12
- ' Launch the 3-step skill wizard (name -> role -> description). Creates a Markdown skill in ~/.haze/skills.',
13
- '/skill-info <name>',
14
- ' Show a skill description and path.',
15
- '/validate-skill <name-or-dir>',
16
- ' Validate a skill directory containing SKILL.md.',
17
- '/remove-skill <name> --yes',
18
- ' Remove an installed skill. Requires --yes because it deletes files.',
19
- ].join('\n');
13
+ async function ensureSettingsFile(settings) {
14
+ if (!await fs.pathExists(SETTINGS_FILE))
15
+ await writeSettings(settings);
16
+ return SETTINGS_FILE;
20
17
  }
21
- async function skillOverview() {
22
- const { loadSkillRegistry } = await import('../../skills/SkillRegistry.js');
23
- const registry = await loadSkillRegistry();
24
- const skills = [...registry.skills.values()];
25
- const installed = skills.length === 0
26
- ? ['Installed skills:', '- None yet. Create one with /create-skill.']
27
- : ['Installed skills:', ...skills.map(s => `- /${s.name} - ${s.description}`)];
28
- return `${skillHelp()}\n\n${installed.join('\n')}`;
29
- }
30
- async function handleSkillCommand(sub, args, ctx) {
31
- if (sub === 'help') {
32
- ctx.addSystemMessage(await skillOverview());
33
- return 'handled';
34
- }
35
- if (sub === 'create') {
36
- // Inline args are intentionally ignored — the wizard is the only path.
37
- ctx.setMode('skillCreateName');
38
- ctx.addSystemMessage('Skill wizard — step 1/3: Name the skill (kebab-case, e.g. security-review). ESC cancels.');
39
- return 'handled';
40
- }
41
- if (sub === 'info') {
42
- const name = args.trim();
43
- if (!name) {
44
- ctx.addSystemMessage('Usage: /skill-info <name>');
45
- return 'handled';
46
- }
47
- const { loadSkillRegistry } = await import('../../skills/SkillRegistry.js');
48
- const registry = await loadSkillRegistry();
49
- const skill = registry.skills.get(name);
50
- if (!skill) {
51
- ctx.addSystemMessage(`No skill named ${name}`);
52
- return 'handled';
53
- }
54
- ctx.addSystemMessage([
55
- `${skill.name}`,
56
- skill.description,
57
- '',
58
- `References: ${skill.references.length}`,
59
- `Path: ${skill.dir}`,
60
- ].join('\n'));
61
- return 'handled';
62
- }
63
- if (sub === 'validate') {
64
- const target = args.trim();
65
- if (!target) {
66
- ctx.addSystemMessage('Usage: /validate-skill <name-or-dir>');
67
- return 'handled';
68
- }
69
- const { GLOBAL_SKILLS_DIR } = await import('../../config/paths.js');
70
- const { loadSkill } = await import('../../skills/SkillLoader.js');
71
- const direct = path.resolve(target);
72
- const dir = await fs.pathExists(path.join(direct, 'SKILL.md')) ? direct : path.join(GLOBAL_SKILLS_DIR, target);
73
- const skill = await loadSkill(dir, 'global');
74
- ctx.addSystemMessage(skill ? `Valid: ${skill.name}` : 'No SKILL.md found');
75
- return 'handled';
76
- }
77
- if (sub === 'remove') {
78
- const parts = args.split(/\s+/).filter(Boolean);
79
- const name = parts[0];
80
- if (!name || !parts.includes('--yes')) {
81
- ctx.addSystemMessage('Usage: /remove-skill <name> --yes');
82
- return 'handled';
83
- }
84
- const { loadSkillRegistry } = await import('../../skills/SkillRegistry.js');
85
- const registry = await loadSkillRegistry();
86
- const skill = registry.skills.get(name);
87
- if (!skill) {
88
- ctx.addSystemMessage(`No skill named ${name}`);
89
- return 'handled';
90
- }
91
- await fs.remove(skill.dir);
92
- ctx.addSystemMessage(`Removed ${name} from ${skill.dir}.`);
93
- return 'handled';
94
- }
95
- return 'handled';
18
+ function openPath(filePath) {
19
+ if (process.env.VITEST || process.env.NODE_ENV === 'test')
20
+ return;
21
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
22
+ const args = process.platform === 'win32' ? ['/c', 'start', '', filePath] : [filePath];
23
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
24
+ child.on('error', () => undefined);
25
+ child.unref();
96
26
  }
97
27
  function formatBytes(bytes) {
98
28
  if (bytes < 1024)
@@ -173,13 +103,15 @@ export async function handleSlashCommand(value, ctx) {
173
103
  '/model <name-or-provider:name>',
174
104
  ' Set a model directly. Selecting a model also sets its provider.',
175
105
  '/settings',
176
- ' Show the configured provider, model, API key status, and loaded context files.',
177
- '/create-skill',
178
- ' Launch the 3-step skill wizard (name, role, description).',
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.',
179
109
  '/skills',
180
- ' Show Markdown skill commands and installed skill slash commands.',
110
+ ' Manage Markdown skills: generate a custom skill, show info, enable/disable, validate, or remove.',
181
111
  '/init',
182
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.',
183
115
  '/session',
184
116
  ' Show the current durable session file.',
185
117
  '/resume',
@@ -188,6 +120,10 @@ export async function handleSlashCommand(value, ctx) {
188
120
  ' Start a fresh durable session.',
189
121
  '/logs',
190
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).',
191
127
  '/logs <id>',
192
128
  ' Show summary of a specific log: entry counts by type, total tokens, tool calls.',
193
129
  '/compact [instructions]',
@@ -201,6 +137,13 @@ export async function handleSlashCommand(value, ctx) {
201
137
  ].join('\n'));
202
138
  return 'handled';
203
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
+ }
204
147
  if (value === '/session') {
205
148
  ctx.addSystemMessage(ctx.sessionInfo?.() ?? 'Session persistence is unavailable.');
206
149
  return 'handled';
@@ -236,6 +179,22 @@ export async function handleSlashCommand(value, ctx) {
236
179
  const args = value.slice('/logs'.length).trim();
237
180
  return await handleLogsCommand(args, ctx);
238
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
+ }
239
198
  if (value === '/settings') {
240
199
  const providers = configuredProviders(ctx.settings);
241
200
  const activeProvider = providers.find(provider => provider.name === ctx.settings.provider) ?? providers[0];
@@ -252,12 +211,19 @@ export async function handleSlashCommand(value, ctx) {
252
211
  const duplicateTotal = summary.duplicateFileCount;
253
212
  notes.push(`${summary.duplicateGroups.length} duplicate group${summary.duplicateGroups.length === 1 ? '' : 's'} (${duplicateTotal} file${duplicateTotal === 1 ? '' : 's'} with identical content)`);
254
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(', ');
255
218
  const lines = [
256
219
  `Provider: ${activeProvider?.name ?? 'not configured'}`,
257
220
  `Model: ${ctx.settings.model ?? 'not set'}`,
258
221
  `Base URL: ${activeProvider?.url ?? ctx.settings.baseURL ?? 'not configured'}`,
259
222
  `API key: ${activeProvider && providerHasKey(ctx.settings, activeProvider) ? 'saved' : 'missing'}`,
260
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'}`,
261
227
  `Context files: ${ctx.contextFiles.length ? `${ctx.contextFiles.map(file => file.path).join(', ')} (~${contextTokens} tokens)` : 'none'}`,
262
228
  ];
263
229
  if (notes.length > 0)
@@ -291,6 +257,10 @@ export async function handleSlashCommand(value, ctx) {
291
257
  }
292
258
  if (resolved.status === 'missing') {
293
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
+ }
294
264
  const nextProvider = provider.models.includes(selector) ? provider : { ...provider, models: [...provider.models, selector] };
295
265
  await ctx.updateSettings({ provider: provider.name, model: selector, providers: upsertProvider(ctx.settings, nextProvider) });
296
266
  ctx.addSystemMessage(`Model set to ${selector} on ${provider.name}. Saved to ~/.haze/settings.json.`);
@@ -303,18 +273,23 @@ export async function handleSlashCommand(value, ctx) {
303
273
  if (value === '/init') {
304
274
  await ctx.runAgentTurn(buildInitPrompt(), '/init');
305
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.');
306
291
  return 'handled';
307
292
  }
308
- if (value === '/skills')
309
- return await handleSkillCommand('help', '', ctx);
310
- if (value === '/create-skill' || value.startsWith('/create-skill '))
311
- return await handleSkillCommand('create', '', ctx);
312
- if (value === '/skill-info' || value.startsWith('/skill-info '))
313
- return await handleSkillCommand('info', value.slice('/skill-info '.length), ctx);
314
- if (value === '/validate-skill' || value.startsWith('/validate-skill '))
315
- return await handleSkillCommand('validate', value.slice('/validate-skill '.length), ctx);
316
- if (value === '/remove-skill' || value.startsWith('/remove-skill '))
317
- return await handleSkillCommand('remove', value.slice('/remove-skill '.length), ctx);
318
293
  if (value.startsWith('/')) {
319
294
  ctx.addSystemMessage(`Unknown command: ${value}. Bold start.`);
320
295
  return 'handled';
@@ -9,3 +9,30 @@ export declare function formatSeconds(milliseconds: number): string;
9
9
  export declare function formatElapsedTime(milliseconds: number): string;
10
10
  export declare function formatElapsedTimeWhole(milliseconds: number): string;
11
11
  export declare function toolOutputDetails(value: unknown): string;
12
+ export type ContextReportCategory = 'builtin' | 'lsp' | 'skill' | 'subagent' | 'mcp';
13
+ export interface ContextReportTool {
14
+ name: string;
15
+ tokens: number;
16
+ category: ContextReportCategory;
17
+ }
18
+ export interface ContextReportData {
19
+ modelLabel: string;
20
+ systemTokens: number;
21
+ projectContext: Array<{
22
+ path: string;
23
+ tokens: number;
24
+ }>;
25
+ tools: ContextReportTool[];
26
+ /** Full-message token totals by role (already includes tool call/result parts). */
27
+ messagesByRole: Record<string, number>;
28
+ /** Tool-result part tokens by tool name (subset of the messages total). */
29
+ toolResults: Record<string, number>;
30
+ /** Tool-call input part tokens by tool name (subset of the messages total). */
31
+ toolInputs: Record<string, number>;
32
+ syntheticControl: number;
33
+ logicalInputEstimate: number;
34
+ messageCount: number;
35
+ mcpErrors: string[];
36
+ }
37
+ /** Render a detailed, /context-style token breakdown. Pure for testability. */
38
+ export declare function formatContextReport(data: ContextReportData): string;
@@ -42,6 +42,12 @@ export function toolCallSummary(toolName, input) {
42
42
  const tasks = Array.isArray(data?.tasks) ? data.tasks : [];
43
43
  return `writeTasks (${tasks.length} task${tasks.length === 1 ? '' : 's'})`;
44
44
  }
45
+ if (toolName === 'lspWorkspaceSymbols' && typeof data?.query === 'string')
46
+ return `lspWorkspaceSymbols "${data.query}"`;
47
+ if (toolName === 'lspSymbols' && typeof data?.path === 'string')
48
+ return `lspSymbols ${data.path}`;
49
+ if ((toolName === 'lspDefinition' || toolName === 'lspReferences') && typeof data?.path === 'string')
50
+ return `${toolName} ${data.path}:${data.line}:${data.column}`;
45
51
  return `${toolName} ${compact(input)}`;
46
52
  }
47
53
  export function toolResultSummary(event) {
@@ -73,6 +79,14 @@ export function toolResultSummary(event) {
73
79
  const meta = calls > 0 ? ` (${calls} call${calls === 1 ? '' : 's'}${duration})` : '';
74
80
  return `${output.status}${meta}: ${preview}`;
75
81
  }
82
+ if (typeof output?.server === 'string' && Array.isArray(output.symbols)) {
83
+ const count = output.symbols.length;
84
+ return `${count} symbol${count === 1 ? '' : 's'} from ${output.server}`;
85
+ }
86
+ if (typeof output?.server === 'string' && Array.isArray(output.locations)) {
87
+ const count = output.locations.length;
88
+ return `${count} location${count === 1 ? '' : 's'} from ${output.server}`;
89
+ }
76
90
  if (typeof output?.ok === 'boolean') {
77
91
  // writeTasks result
78
92
  if (output.ok && typeof output.summary === 'string') {
@@ -141,3 +155,126 @@ export function toolOutputDetails(value) {
141
155
  const truncated = output.stdout?.truncated || output.stderr?.truncated;
142
156
  return `${parts.join('\n\n')}${truncated ? '\n… output truncated' : ''}`;
143
157
  }
158
+ const CONTEXT_CATEGORY_LABEL = {
159
+ builtin: 'Built-in',
160
+ lsp: 'LSP',
161
+ skill: 'Skills',
162
+ subagent: 'Subagent',
163
+ mcp: 'MCP',
164
+ };
165
+ const CONTEXT_CATEGORY_ORDER = ['builtin', 'lsp', 'skill', 'subagent', 'mcp'];
166
+ function num(n) {
167
+ return Math.round(n).toLocaleString('en-US');
168
+ }
169
+ // Bar chart glyphs: full block, 1/8..7/8 left-fill blocks, and a light track.
170
+ const BAR_FULL = '█';
171
+ const BAR_EMPTY = '░';
172
+ const BAR_PARTIAL = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉'];
173
+ /** A fixed-width horizontal bar; `value` vs `max` controls the filled fraction. */
174
+ function bar(value, max, width) {
175
+ if (width <= 0)
176
+ return '';
177
+ if (max <= 0 || value <= 0)
178
+ return BAR_EMPTY.repeat(width);
179
+ const scaled = Math.min(1, value / max) * width;
180
+ let whole = Math.floor(scaled);
181
+ let partial = Math.round((scaled - whole) * 8); // 0..8
182
+ if (partial >= 8) {
183
+ whole += 1;
184
+ partial = 0;
185
+ }
186
+ whole = Math.min(whole, width);
187
+ if (whole === 0 && partial === 0 && value > 0)
188
+ partial = 1; // ensure a sliver for any nonzero value
189
+ const partialGlyph = (whole < width && partial > 0) ? BAR_PARTIAL[partial] : '';
190
+ const filled = BAR_FULL.repeat(whole);
191
+ const emptyCount = width - filled.length - partialGlyph.length;
192
+ return `${filled}${partialGlyph}${emptyCount > 0 ? BAR_EMPTY.repeat(emptyCount) : ''}`;
193
+ }
194
+ function row(label, tokens, total, labelCol, numCol, barWidth, indent = 0) {
195
+ const prefix = `${' '.repeat(indent)}${label}`.padEnd(labelCol);
196
+ const pct = total > 0 ? `${Math.round((tokens / total) * 100)}%`.padStart(4) : ' -';
197
+ return `${prefix}${bar(tokens, total, barWidth)} ${num(tokens).padStart(numCol)} ${pct}`;
198
+ }
199
+ /** Render a detailed, /context-style token breakdown. Pure for testability. */
200
+ export function formatContextReport(data) {
201
+ const lines = [];
202
+ lines.push(`Context overview — model: ${data.modelLabel}`);
203
+ lines.push(`Estimated input: ~${num(data.logicalInputEstimate)} tokens (4 chars/token heuristic). Bars show each row's share of that total; tool results/inputs are subsets of the messages total.`);
204
+ lines.push('');
205
+ const projectTokens = data.projectContext.reduce((sum, file) => sum + file.tokens, 0);
206
+ const toolsTotal = data.tools.reduce((sum, tool) => sum + tool.tokens, 0);
207
+ const messagesTotal = Object.values(data.messagesByRole).reduce((sum, value) => sum + value, 0);
208
+ const resultsTotal = Object.values(data.toolResults).reduce((sum, value) => sum + value, 0);
209
+ const inputsTotal = Object.values(data.toolInputs).reduce((sum, value) => sum + value, 0);
210
+ const numberValues = [
211
+ data.systemTokens, toolsTotal, messagesTotal, data.logicalInputEstimate, projectTokens, resultsTotal, inputsTotal,
212
+ ...data.tools.map(tool => tool.tokens),
213
+ ...Object.values(data.toolResults), ...Object.values(data.toolInputs),
214
+ ...data.projectContext.map(file => file.tokens),
215
+ ...Object.values(data.messagesByRole),
216
+ ];
217
+ const numCol = Math.max(8, ...numberValues.map(value => num(value).length));
218
+ const labels = [
219
+ 'System prompt', 'project context', 'base instructions', '(no project context files)',
220
+ `Tools (${data.tools.length})`, `Chat messages (${data.messageCount})`,
221
+ 'tool results', 'tool inputs', 'synthetic control',
222
+ ...data.tools.map(tool => tool.name),
223
+ ...data.projectContext.map(file => file.path),
224
+ ...Object.keys(data.messagesByRole),
225
+ ...Object.keys(data.toolResults), ...Object.keys(data.toolInputs),
226
+ ];
227
+ // Indented labels gain up to 4 spaces of leading indent; padEnd accounts for that.
228
+ const labelCol = Math.max(28, ...labels.map(label => label.length + 4)) + 2;
229
+ const barWidth = 20;
230
+ const r = (label, tokens, indent = 0) => row(label, tokens, data.logicalInputEstimate, labelCol, numCol, barWidth, indent);
231
+ // System prompt
232
+ lines.push(r('System prompt', data.systemTokens));
233
+ if (data.projectContext.length > 0) {
234
+ lines.push(r('project context', projectTokens, 2));
235
+ for (const file of [...data.projectContext].sort((a, b) => b.tokens - a.tokens))
236
+ lines.push(r(file.path, file.tokens, 4));
237
+ lines.push(r('base instructions', data.systemTokens - projectTokens, 2));
238
+ }
239
+ else {
240
+ lines.push(r('(no project context files)', 0, 2));
241
+ }
242
+ lines.push('');
243
+ // Tools
244
+ lines.push(r(`Tools (${data.tools.length})`, toolsTotal));
245
+ for (const category of CONTEXT_CATEGORY_ORDER) {
246
+ const inCategory = data.tools.filter(tool => tool.category === category).sort((a, b) => b.tokens - a.tokens);
247
+ if (inCategory.length === 0)
248
+ continue;
249
+ const categoryTotal = inCategory.reduce((sum, tool) => sum + tool.tokens, 0);
250
+ lines.push(r(`${CONTEXT_CATEGORY_LABEL[category]} (${inCategory.length})`, categoryTotal, 2));
251
+ for (const tool of inCategory)
252
+ lines.push(r(tool.name, tool.tokens, 4));
253
+ }
254
+ if (data.mcpErrors.length > 0) {
255
+ lines.push('');
256
+ lines.push(`MCP errors: ${data.mcpErrors.join('; ')}`);
257
+ }
258
+ lines.push('');
259
+ // Messages
260
+ lines.push(r(`Chat messages (${data.messageCount})`, messagesTotal));
261
+ for (const role of Object.keys(data.messagesByRole).sort())
262
+ lines.push(r(role, data.messagesByRole[role], 2));
263
+ if (resultsTotal > 0 || inputsTotal > 0) {
264
+ lines.push('');
265
+ lines.push('Tool content inside messages (already counted above; bars are share of total input):');
266
+ if (resultsTotal > 0) {
267
+ lines.push(r('tool results', resultsTotal, 2));
268
+ for (const [name, value] of [...Object.entries(data.toolResults)].sort(([, a], [, b]) => b - a))
269
+ lines.push(r(name, value, 4));
270
+ }
271
+ if (inputsTotal > 0) {
272
+ lines.push(r('tool inputs', inputsTotal, 2));
273
+ for (const [name, value] of [...Object.entries(data.toolInputs)].sort(([, a], [, b]) => b - a))
274
+ lines.push(r(name, value, 4));
275
+ }
276
+ }
277
+ if (data.syntheticControl > 0)
278
+ lines.push(r('synthetic control', data.syntheticControl, 2));
279
+ return lines.join('\n');
280
+ }
@@ -3,7 +3,7 @@ import type { LlmLog } from '../../core/log/llmLog.js';
3
3
  import { type PromptSession } from '../../llm/systemPrompt.js';
4
4
  import type { ContextFile } from '../../config/contextFiles.js';
5
5
  import { type AgentEventSink } from '../../core/agent/events.js';
6
- import { type WorkState } from '../../core/agent/workState.js';
6
+ import type { WorkState } from '../../core/agent/workState.js';
7
7
  export type Message = {
8
8
  id?: string;
9
9
  role: 'system' | 'user' | 'assistant' | 'tool';
@@ -12,31 +12,32 @@ export type Message = {
12
12
  hidden?: boolean;
13
13
  startedAt?: number;
14
14
  finishedAt?: number;
15
+ tokensPerSecond?: number;
16
+ displayOrder?: number;
15
17
  };
18
+ export declare function uniqueRepeatedToolNames(toolCalls: Array<{
19
+ toolName: string;
20
+ input: unknown;
21
+ }>): string[];
22
+ export declare function toolOnlyStepCount(steps: Array<{
23
+ toolCalls: unknown[];
24
+ text: string;
25
+ }>): number;
26
+ export declare function isShortUnfinishedBridgeBeforeTool(text: string): boolean;
27
+ export declare function isHiddenUnstartedFinalText(text: string): boolean;
28
+ export declare function shouldStartAssistantStream(text: string, startedAt: number): boolean;
16
29
  export interface TokenUsage {
17
- /** Precise input tokens from the provider (undefined if provider doesn't report). */
18
30
  inputTokens: number | undefined;
19
- /** Precise output tokens from the provider (undefined if provider doesn't report). */
20
31
  outputTokens: number | undefined;
21
- /** Estimated system prompt tokens. */
22
32
  systemPrompt: number;
23
- /** Estimated message history tokens. */
24
33
  messages: number;
25
- /** Estimated tool schema tokens. */
26
34
  toolSchemas: number;
27
- /** Estimated output tokens (from response messages). */
28
35
  outputEstimate: number;
29
- /** Cached input tokens (if provider reports). */
30
36
  cacheReadTokens: number;
31
- /** Cache write tokens (if provider reports). */
32
37
  cacheWriteTokens: number;
33
- /** Provider-reported input tokens that were not served from cache. */
34
38
  noCacheTokens: number;
35
- /** Reasoning tokens (if provider reports). */
36
39
  reasoningTokens: number;
37
- /** Estimated complete logical request size. */
38
40
  logicalInputEstimate: number;
39
- /** Provider input minus cache reads, when provider usage is available. */
40
41
  effectiveNonCachedInput: number | undefined;
41
42
  }
42
43
  export interface StreamCallbacks {