@denizokcu/haze 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +31 -19
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +144 -52
  5. package/dist/cli/commands/commands.js +105 -114
  6. package/dist/cli/commands/streaming.d.ts +33 -5
  7. package/dist/cli/commands/streaming.js +235 -103
  8. package/dist/cli/contextReport.d.ts +1 -0
  9. package/dist/cli/contextReport.js +47 -0
  10. package/dist/config/contextFiles.d.ts +25 -0
  11. package/dist/config/contextFiles.js +53 -0
  12. package/dist/core/agent/compaction.d.ts +3 -0
  13. package/dist/core/agent/compaction.js +23 -3
  14. package/dist/core/agent/contextBudget.d.ts +33 -0
  15. package/dist/core/agent/contextBudget.js +88 -0
  16. package/dist/core/agent/requestAssembly.d.ts +22 -0
  17. package/dist/core/agent/requestAssembly.js +146 -0
  18. package/dist/core/agent/toolOutputStore.d.ts +11 -0
  19. package/dist/core/agent/toolOutputStore.js +33 -0
  20. package/dist/core/agent/workState.d.ts +38 -0
  21. package/dist/core/agent/workState.js +89 -0
  22. package/dist/core/goal/completionPolicy.js +1 -1
  23. package/dist/core/goal/sessionGoal.d.ts +2 -0
  24. package/dist/core/goal/sessionGoal.js +8 -1
  25. package/dist/core/log/llmLog.d.ts +68 -0
  26. package/dist/core/log/llmLog.js +55 -0
  27. package/dist/core/session/sessionStore.d.ts +6 -0
  28. package/dist/core/session/sessionStore.js +5 -0
  29. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  30. package/dist/core/subagent/subagentRunner.js +5 -15
  31. package/dist/core/validation/outputParser.js +15 -2
  32. package/dist/llm/client.d.ts +39 -0
  33. package/dist/llm/client.js +46 -2
  34. package/dist/llm/hazeTools.d.ts +37 -12
  35. package/dist/llm/hazeTools.js +133 -55
  36. package/dist/llm/systemPrompt.d.ts +6 -1
  37. package/dist/llm/systemPrompt.js +42 -81
  38. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  39. package/dist/skills/builder/SkillBuilder.js +68 -65
  40. package/dist/skills/skillTools.d.ts +2 -19
  41. package/dist/skills/skillTools.js +28 -19
  42. package/package.json +2 -1
@@ -1,15 +1,15 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
3
  import { buildInitPrompt } from '../../llm/initPrompt.js';
4
+ import { contextFileDiagnostics, summarizeContextDiagnostics } from '../../config/contextFiles.js';
4
5
  import { activeProvider, configuredProviders, modelSelector, providerHasKey, resolveModelSelector, upsertProvider } from '../../config/providers.js';
5
- import { clearTasks, generateTaskId, loadTasks, saveTasks } from '../../core/tasks/taskStorage.js';
6
+ import { clearTasks } from '../../core/tasks/taskStorage.js';
7
+ import { listLogs, readLogEntries } from '../../core/log/llmLog.js';
6
8
  function skillHelp() {
7
9
  return [
8
10
  'Skill commands:',
9
- '/create-skill <description>',
10
- ' Create a Markdown skill in ~/.haze/skills.',
11
- '/list-skills',
12
- ' List installed skills.',
11
+ '/create-skill',
12
+ ' Launch the 3-step skill wizard (name -> role -> description). Creates a Markdown skill in ~/.haze/skills.',
13
13
  '/skill-info <name>',
14
14
  ' Show a skill description and path.',
15
15
  '/validate-skill <name-or-dir>',
@@ -23,39 +23,23 @@ async function skillOverview() {
23
23
  const registry = await loadSkillRegistry();
24
24
  const skills = [...registry.skills.values()];
25
25
  const installed = skills.length === 0
26
- ? ['Installed skills:', '- None yet. Create one with /create-skill <description>.']
26
+ ? ['Installed skills:', '- None yet. Create one with /create-skill.']
27
27
  : ['Installed skills:', ...skills.map(s => `- /${s.name} - ${s.description}`)];
28
28
  return `${skillHelp()}\n\n${installed.join('\n')}`;
29
29
  }
30
- async function handleSkillCommand(value, ctx) {
31
- const parts = value.trim().split(/\s+/).filter(Boolean);
32
- const subcommand = parts[1];
33
- if (!subcommand || subcommand === 'help') {
30
+ async function handleSkillCommand(sub, args, ctx) {
31
+ if (sub === 'help') {
34
32
  ctx.addSystemMessage(await skillOverview());
35
33
  return 'handled';
36
34
  }
37
- if (subcommand === 'create') {
38
- const description = parts.slice(2).join(' ');
39
- if (!description) {
40
- ctx.addSystemMessage('Usage: /create-skill <description>');
41
- return 'handled';
42
- }
43
- const { createSkill } = await import('../../skills/builder/SkillBuilder.js');
44
- const result = await createSkill(description);
45
- ctx.addSystemMessage(`Created skill ${result.name} at ${result.file}. Invoke it with /${result.name}. Edit SKILL.md to refine its workflow.`);
46
- return 'handled';
47
- }
48
- if (subcommand === 'list') {
49
- const { loadSkillRegistry } = await import('../../skills/SkillRegistry.js');
50
- const registry = await loadSkillRegistry();
51
- const skills = [...registry.skills.values()];
52
- ctx.addSystemMessage(skills.length === 0
53
- ? 'No installed skills found. Create one with /create-skill <description>.'
54
- : ['Installed skills:', ...skills.map(s => `- /${s.name} - ${s.description}`)].join('\n'));
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.');
55
39
  return 'handled';
56
40
  }
57
- if (subcommand === 'info') {
58
- const name = parts[2];
41
+ if (sub === 'info') {
42
+ const name = args.trim();
59
43
  if (!name) {
60
44
  ctx.addSystemMessage('Usage: /skill-info <name>');
61
45
  return 'handled';
@@ -76,8 +60,8 @@ async function handleSkillCommand(value, ctx) {
76
60
  ].join('\n'));
77
61
  return 'handled';
78
62
  }
79
- if (subcommand === 'validate') {
80
- const target = parts[2];
63
+ if (sub === 'validate') {
64
+ const target = args.trim();
81
65
  if (!target) {
82
66
  ctx.addSystemMessage('Usage: /validate-skill <name-or-dir>');
83
67
  return 'handled';
@@ -90,8 +74,9 @@ async function handleSkillCommand(value, ctx) {
90
74
  ctx.addSystemMessage(skill ? `Valid: ${skill.name}` : 'No SKILL.md found');
91
75
  return 'handled';
92
76
  }
93
- if (subcommand === 'remove') {
94
- const name = parts[2];
77
+ if (sub === 'remove') {
78
+ const parts = args.split(/\s+/).filter(Boolean);
79
+ const name = parts[0];
95
80
  if (!name || !parts.includes('--yes')) {
96
81
  ctx.addSystemMessage('Usage: /remove-skill <name> --yes');
97
82
  return 'handled';
@@ -107,74 +92,70 @@ async function handleSkillCommand(value, ctx) {
107
92
  ctx.addSystemMessage(`Removed ${name} from ${skill.dir}.`);
108
93
  return 'handled';
109
94
  }
110
- ctx.addSystemMessage(`Unknown skill command: ${parts[0]} ${subcommand}\n\n${skillHelp()}`);
111
95
  return 'handled';
112
96
  }
113
- const STATUS_ICON = {
114
- pending: '○',
115
- in_progress: '◐',
116
- completed: '✓',
117
- };
118
- async function handleTasksCommand(args, ctx) {
119
- const parts = args.split(/\s+/).filter(Boolean);
120
- const subcommand = parts[0]?.toLowerCase();
121
- if (!subcommand || subcommand === 'help') {
122
- const tasks = await loadTasks();
123
- if (tasks.length === 0) {
124
- ctx.addSystemMessage('No tasks. Add one with /tasks add <title>.');
125
- }
126
- else {
127
- const list = tasks.map((t, i) => ` ${STATUS_ICON[t.status] ?? '○'} ${i + 1}. ${t.title}`).join('\n');
128
- ctx.addSystemMessage(`Tasks:\n${list}`);
97
+ function formatBytes(bytes) {
98
+ if (bytes < 1024)
99
+ return `${bytes} B`;
100
+ if (bytes < 1024 * 1024)
101
+ return `${(bytes / 1024).toFixed(1)} KB`;
102
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
103
+ }
104
+ async function handleLogsCommand(args, ctx) {
105
+ const id = args.trim();
106
+ if (!id) {
107
+ // List recent logs
108
+ const logs = await listLogs();
109
+ if (logs.length === 0) {
110
+ ctx.addSystemMessage('No log files found.');
111
+ return 'handled';
129
112
  }
113
+ const lines = logs.slice(0, 20).map(log => {
114
+ const date = log.modified.slice(0, 19).replace('T', ' ');
115
+ return ` ${log.id} ${formatBytes(log.size).padStart(8)} ${date}`;
116
+ });
117
+ ctx.addSystemMessage(['Recent logs:', ' ID Size Modified', ...lines].join('\n'));
130
118
  return 'handled';
131
119
  }
132
- if (subcommand === 'add') {
133
- const title = parts.slice(1).join(' ').trim();
134
- if (!title) {
135
- ctx.addSystemMessage('Usage: /tasks add <title>');
136
- return 'handled';
137
- }
138
- const tasks = await loadTasks();
139
- const now = new Date().toISOString();
140
- tasks.push({ id: generateTaskId(), title, status: 'pending', createdAt: now, updatedAt: now });
141
- await saveTasks(tasks);
142
- ctx.addSystemMessage(`Added: ${title}`);
120
+ // Show summary for a specific log
121
+ const entries = await readLogEntries(id);
122
+ if (entries.length === 0) {
123
+ ctx.addSystemMessage(`No log found with id ${id}.`);
143
124
  return 'handled';
144
125
  }
145
- if (subcommand === 'remove' || subcommand === 'rm') {
146
- const numStr = parts[1];
147
- if (!numStr) {
148
- ctx.addSystemMessage('Usage: /tasks remove <number>');
149
- return 'handled';
150
- }
151
- const num = parseInt(numStr, 10);
152
- if (isNaN(num) || num < 1) {
153
- ctx.addSystemMessage('Provide a valid task number (e.g., /tasks remove 1).');
154
- return 'handled';
126
+ const typeCounts = {};
127
+ let totalInput = 0;
128
+ let totalOutput = 0;
129
+ const toolCallCounts = {};
130
+ for (const entry of entries) {
131
+ typeCounts[entry.type] = (typeCounts[entry.type] ?? 0) + 1;
132
+ if (entry.usage) {
133
+ totalInput += entry.usage.inputTokens ?? 0;
134
+ totalOutput += entry.usage.outputTokens ?? 0;
155
135
  }
156
- const tasks = await loadTasks();
157
- if (num > tasks.length) {
158
- ctx.addSystemMessage(`Task ${num} not found. You have ${tasks.length} task(s).`);
159
- return 'handled';
136
+ if (entry.type === 'tool_call' && entry.toolCall) {
137
+ toolCallCounts[entry.toolCall.name] = (toolCallCounts[entry.toolCall.name] ?? 0) + 1;
160
138
  }
161
- const removed = tasks.splice(num - 1, 1)[0];
162
- await saveTasks(tasks);
163
- ctx.addSystemMessage(`Removed: ${removed.title}`);
164
- return 'handled';
165
139
  }
166
- if (subcommand === 'clear') {
167
- await clearTasks();
168
- ctx.addSystemMessage('All tasks cleared.');
169
- return 'handled';
140
+ const typeLines = Object.entries(typeCounts)
141
+ .sort(([a], [b]) => a.localeCompare(b))
142
+ .map(([type, count]) => ` ${type}: ${count}`);
143
+ const toolLines = Object.entries(toolCallCounts)
144
+ .sort(([, a], [, b]) => b - a)
145
+ .map(([name, count]) => ` ${name}: ${count}`);
146
+ const parts = [
147
+ `Log: ${id}`,
148
+ `Entries: ${entries.length}`,
149
+ '',
150
+ 'Entry counts by type:',
151
+ ...typeLines,
152
+ '',
153
+ `Total token usage: in=${totalInput} out=${totalOutput}`,
154
+ ];
155
+ if (toolLines.length > 0) {
156
+ parts.push('', 'Tool call counts:', ...toolLines);
170
157
  }
171
- // Unknown subcommand → treat as task title
172
- const title = args.trim();
173
- const tasks = await loadTasks();
174
- const now = new Date().toISOString();
175
- tasks.push({ id: generateTaskId(), title, status: 'pending', createdAt: now, updatedAt: now });
176
- await saveTasks(tasks);
177
- ctx.addSystemMessage(`Added: ${title}`);
158
+ ctx.addSystemMessage(parts.join('\n'));
178
159
  return 'handled';
179
160
  }
180
161
  export async function handleSlashCommand(value, ctx) {
@@ -193,8 +174,8 @@ export async function handleSlashCommand(value, ctx) {
193
174
  ' Set a model directly. Selecting a model also sets its provider.',
194
175
  '/settings',
195
176
  ' Show the configured provider, model, API key status, and loaded context files.',
196
- '/create-skill <description>',
197
- ' Create a reusable Markdown workflow from how you work.',
177
+ '/create-skill',
178
+ ' Launch the 3-step skill wizard (name, role, description).',
198
179
  '/skills',
199
180
  ' Show Markdown skill commands and installed skill slash commands.',
200
181
  '/init',
@@ -205,10 +186,10 @@ export async function handleSlashCommand(value, ctx) {
205
186
  ' Resume the latest saved session for this workspace.',
206
187
  '/new',
207
188
  ' Start a fresh durable session.',
208
- '/tasks',
209
- ' Manage your task list. Subcommands: add <title>, remove <number>, clear.',
210
- '/tasks',
211
- ' Show current task list.',
189
+ '/logs',
190
+ ' List recent log files with sizes and dates.',
191
+ '/logs <id>',
192
+ ' Show summary of a specific log: entry counts by type, total tokens, tool calls.',
212
193
  '/compact [instructions]',
213
194
  ' Summarize older model context and keep recent messages.',
214
195
  '/clear',
@@ -251,21 +232,37 @@ export async function handleSlashCommand(value, ctx) {
251
232
  ctx.addSystemMessage('Cleared. The void is productive.');
252
233
  return 'handled';
253
234
  }
254
- if (value === '/tasks' || value.startsWith('/tasks ')) {
255
- const args = value.slice('/tasks'.length).trim();
256
- return await handleTasksCommand(args, ctx);
235
+ if (value === '/logs' || value.startsWith('/logs ')) {
236
+ const args = value.slice('/logs'.length).trim();
237
+ return await handleLogsCommand(args, ctx);
257
238
  }
258
239
  if (value === '/settings') {
259
240
  const providers = configuredProviders(ctx.settings);
260
241
  const activeProvider = providers.find(provider => provider.name === ctx.settings.provider) ?? providers[0];
261
- ctx.addSystemMessage([
242
+ const contextDiagnostics = contextFileDiagnostics(ctx.contextFiles);
243
+ const contextTokens = contextDiagnostics.reduce((sum, file) => sum + file.estimatedTokens, 0);
244
+ const summary = summarizeContextDiagnostics(ctx.contextFiles);
245
+ const notes = [];
246
+ if (summary.exceedsBudget === true && summary.windowSize) {
247
+ const sharePct = Math.round((summary.budgetShare ?? 0) * 100);
248
+ const thresholdPct = Math.round(summary.budgetThreshold * 100);
249
+ notes.push(`project context exceeds ${thresholdPct}% budget (${sharePct}% of ${Math.round(summary.windowSize / 1000)}k window)`);
250
+ }
251
+ if (summary.duplicateGroups.length > 0) {
252
+ const duplicateTotal = summary.duplicateFileCount;
253
+ notes.push(`${summary.duplicateGroups.length} duplicate group${summary.duplicateGroups.length === 1 ? '' : 's'} (${duplicateTotal} file${duplicateTotal === 1 ? '' : 's'} with identical content)`);
254
+ }
255
+ const lines = [
262
256
  `Provider: ${activeProvider?.name ?? 'not configured'}`,
263
257
  `Model: ${ctx.settings.model ?? 'not set'}`,
264
258
  `Base URL: ${activeProvider?.url ?? ctx.settings.baseURL ?? 'not configured'}`,
265
259
  `API key: ${activeProvider && providerHasKey(ctx.settings, activeProvider) ? 'saved' : 'missing'}`,
266
260
  `Configured providers: ${providers.map(provider => provider.name).join(', ') || 'none'}`,
267
- `Context files: ${ctx.contextFiles.length ? ctx.contextFiles.map(file => file.path).join(', ') : 'none'}`,
268
- ].join(' | '));
261
+ `Context files: ${ctx.contextFiles.length ? `${ctx.contextFiles.map(file => file.path).join(', ')} (~${contextTokens} tokens)` : 'none'}`,
262
+ ];
263
+ if (notes.length > 0)
264
+ lines.push(`Context note: ${notes.join('; ')}`);
265
+ ctx.addSystemMessage(lines.join(' | '));
269
266
  return 'handled';
270
267
  }
271
268
  if (value === '/provider') {
@@ -309,21 +306,15 @@ export async function handleSlashCommand(value, ctx) {
309
306
  return 'handled';
310
307
  }
311
308
  if (value === '/skills')
312
- return await handleSkillCommand('/skill help', ctx);
313
- if (value === '/list-skills')
314
- return await handleSkillCommand('/skill list', ctx);
309
+ return await handleSkillCommand('help', '', ctx);
315
310
  if (value === '/create-skill' || value.startsWith('/create-skill '))
316
- return await handleSkillCommand(`/skill create${value.slice('/create-skill'.length)}`, ctx);
311
+ return await handleSkillCommand('create', '', ctx);
317
312
  if (value === '/skill-info' || value.startsWith('/skill-info '))
318
- return await handleSkillCommand(`/skill info${value.slice('/skill-info'.length)}`, ctx);
313
+ return await handleSkillCommand('info', value.slice('/skill-info '.length), ctx);
319
314
  if (value === '/validate-skill' || value.startsWith('/validate-skill '))
320
- return await handleSkillCommand(`/skill validate${value.slice('/validate-skill'.length)}`, ctx);
315
+ return await handleSkillCommand('validate', value.slice('/validate-skill '.length), ctx);
321
316
  if (value === '/remove-skill' || value.startsWith('/remove-skill '))
322
- return await handleSkillCommand(`/skill remove${value.slice('/remove-skill'.length)}`, ctx);
323
- if (value === '/skill' || value.startsWith('/skill ') || value.startsWith('/skills ')) {
324
- const normalized = value.replace(/^\/skills\b/, '/skill');
325
- return await handleSkillCommand(normalized, ctx);
326
- }
317
+ return await handleSkillCommand('remove', value.slice('/remove-skill '.length), ctx);
327
318
  if (value.startsWith('/')) {
328
319
  ctx.addSystemMessage(`Unknown command: ${value}. Bold start.`);
329
320
  return 'handled';
@@ -1,6 +1,9 @@
1
1
  import { type ModelMessage } from 'ai';
2
+ import type { LlmLog } from '../../core/log/llmLog.js';
3
+ import { type PromptSession } from '../../llm/systemPrompt.js';
2
4
  import type { ContextFile } from '../../config/contextFiles.js';
3
5
  import { type AgentEventSink } from '../../core/agent/events.js';
6
+ import { type WorkState } from '../../core/agent/workState.js';
4
7
  export type Message = {
5
8
  id?: string;
6
9
  role: 'system' | 'user' | 'assistant' | 'tool';
@@ -10,6 +13,32 @@ export type Message = {
10
13
  startedAt?: number;
11
14
  finishedAt?: number;
12
15
  };
16
+ export interface TokenUsage {
17
+ /** Precise input tokens from the provider (undefined if provider doesn't report). */
18
+ inputTokens: number | undefined;
19
+ /** Precise output tokens from the provider (undefined if provider doesn't report). */
20
+ outputTokens: number | undefined;
21
+ /** Estimated system prompt tokens. */
22
+ systemPrompt: number;
23
+ /** Estimated message history tokens. */
24
+ messages: number;
25
+ /** Estimated tool schema tokens. */
26
+ toolSchemas: number;
27
+ /** Estimated output tokens (from response messages). */
28
+ outputEstimate: number;
29
+ /** Cached input tokens (if provider reports). */
30
+ cacheReadTokens: number;
31
+ /** Cache write tokens (if provider reports). */
32
+ cacheWriteTokens: number;
33
+ /** Provider-reported input tokens that were not served from cache. */
34
+ noCacheTokens: number;
35
+ /** Reasoning tokens (if provider reports). */
36
+ reasoningTokens: number;
37
+ /** Estimated complete logical request size. */
38
+ logicalInputEstimate: number;
39
+ /** Provider input minus cache reads, when provider usage is available. */
40
+ effectiveNonCachedInput: number | undefined;
41
+ }
13
42
  export interface StreamCallbacks {
14
43
  addMessage: (msg: Message) => void;
15
44
  updateMessage: (id: string, update: Partial<Message>) => void;
@@ -24,10 +53,9 @@ export interface StreamCallbacks {
24
53
  setGoalStatus?: (status: string | undefined) => void;
25
54
  onEvent?: AgentEventSink;
26
55
  compactConversation?: (instructions?: string) => boolean;
27
- recordTokenEstimate?: (tokens: {
28
- input: number;
29
- output: number;
30
- }) => void;
56
+ recordTokenUsage?: (usage: TokenUsage) => void;
57
+ setWorkState?: (state: WorkState) => void;
31
58
  onTasksChanged?: () => void;
59
+ log?: LlmLog;
32
60
  }
33
- export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean): Promise<void>;
61
+ export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean, session?: PromptSession): Promise<void>;