@denizokcu/haze 0.0.1 → 0.0.3

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 (73) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +169 -70
  3. package/dist/cli/commands/chat.d.ts +4 -1
  4. package/dist/cli/commands/chat.js +606 -24
  5. package/dist/cli/commands/commands.d.ts +5 -0
  6. package/dist/cli/commands/commands.js +220 -11
  7. package/dist/cli/commands/formatters.d.ts +1 -0
  8. package/dist/cli/commands/formatters.js +23 -3
  9. package/dist/cli/commands/skills.d.ts +1 -1
  10. package/dist/cli/commands/skills.js +8 -5
  11. package/dist/cli/commands/streaming.d.ts +7 -1
  12. package/dist/cli/commands/streaming.js +533 -41
  13. package/dist/cli/index.js +5 -12
  14. package/dist/config/inputHistory.js +8 -0
  15. package/dist/config/paths.d.ts +0 -1
  16. package/dist/config/paths.js +0 -1
  17. package/dist/config/providers.d.ts +26 -0
  18. package/dist/config/providers.js +88 -0
  19. package/dist/config/settings.d.ts +9 -2
  20. package/dist/core/agent/compaction.d.ts +13 -0
  21. package/dist/core/agent/compaction.js +34 -0
  22. package/dist/core/agent/errors.d.ts +3 -0
  23. package/dist/core/agent/errors.js +13 -0
  24. package/dist/core/agent/events.d.ts +58 -0
  25. package/dist/core/agent/events.js +3 -0
  26. package/dist/core/goal/completionPolicy.d.ts +27 -0
  27. package/dist/core/goal/completionPolicy.js +67 -0
  28. package/dist/core/goal/requestClassifier.d.ts +6 -0
  29. package/dist/core/goal/requestClassifier.js +31 -0
  30. package/dist/core/goal/sessionGoal.d.ts +30 -0
  31. package/dist/core/goal/sessionGoal.js +88 -0
  32. package/dist/core/session/sessionStore.d.ts +37 -0
  33. package/dist/core/session/sessionStore.js +59 -0
  34. package/dist/llm/client.d.ts +1 -1
  35. package/dist/llm/client.js +6 -6
  36. package/dist/llm/hazeTools.d.ts +70 -0
  37. package/dist/llm/hazeTools.js +311 -97
  38. package/dist/llm/initPrompt.js +7 -5
  39. package/dist/llm/systemPrompt.js +25 -11
  40. package/dist/skills/SkillLoader.d.ts +12 -2
  41. package/dist/skills/SkillLoader.js +64 -18
  42. package/dist/skills/SkillRegistry.d.ts +1 -5
  43. package/dist/skills/SkillRegistry.js +10 -21
  44. package/dist/skills/builder/SkillBuilder.d.ts +31 -1
  45. package/dist/skills/builder/SkillBuilder.js +291 -20
  46. package/dist/skills/skillTools.d.ts +20 -0
  47. package/dist/skills/skillTools.js +25 -0
  48. package/dist/skills/types.d.ts +12 -51
  49. package/dist/ui/components/ErrorView.d.ts +2 -1
  50. package/dist/ui/components/Header.d.ts +4 -2
  51. package/dist/ui/components/Header.js +2 -2
  52. package/dist/ui/components/MarkdownText.d.ts +2 -1
  53. package/dist/ui/components/TextInput.d.ts +13 -2
  54. package/dist/ui/components/TextInput.js +125 -25
  55. package/dist/ui/theme.d.ts +2 -0
  56. package/dist/ui/theme.js +3 -1
  57. package/dist/utils/fs.d.ts +1 -0
  58. package/dist/utils/fs.js +10 -6
  59. package/examples/skills/files/SKILL.md +16 -0
  60. package/examples/skills/files/examples/file-editing.md +3 -0
  61. package/package.json +9 -9
  62. package/dist/skills/installer/SkillInstaller.d.ts +0 -1
  63. package/dist/skills/installer/SkillInstaller.js +0 -48
  64. package/dist/skills/manifestSchema.d.ts +0 -31
  65. package/dist/skills/manifestSchema.js +0 -23
  66. package/dist/tools/ToolExecutor.d.ts +0 -3
  67. package/dist/tools/ToolExecutor.js +0 -15
  68. package/dist/tools/types.d.ts +0 -9
  69. package/dist/tools/types.js +0 -1
  70. package/examples/skills/files/prompts/file_tasks.md +0 -1
  71. package/examples/skills/files/skill.yaml +0 -28
  72. package/examples/skills/files/tools/list_files.ts +0 -21
  73. package/examples/skills/files/tools/read_file.ts +0 -12
@@ -40,6 +40,172 @@ function truncate(text, maxChars = MAX_OUTPUT_CHARS) {
40
40
  function numberLines(lines, startLine) {
41
41
  return lines.map((line, index) => `${String(startLine + index).padStart(4, ' ')} | ${line}`).join('\n');
42
42
  }
43
+ function stripLineNumberPrefixes(text) {
44
+ return text.replace(/^\s*\d+\s+\| ?/gm, '');
45
+ }
46
+ function lineStartOffsets(text) {
47
+ const offsets = [0];
48
+ for (let index = 0; index < text.length; index++) {
49
+ if (text[index] === '\n')
50
+ offsets.push(index + 1);
51
+ }
52
+ return offsets;
53
+ }
54
+ function findLineTrimmedRange(original, oldText) {
55
+ const wantedLines = oldText.replace(/\r\n/g, '\n').split('\n').map(line => line.trimEnd());
56
+ if (wantedLines.at(-1) === '')
57
+ wantedLines.pop();
58
+ if (wantedLines.length === 0)
59
+ return undefined;
60
+ const originalLines = original.replace(/\r\n/g, '\n').split('\n');
61
+ const hasTrailingNewline = original.endsWith('\n');
62
+ if (hasTrailingNewline)
63
+ originalLines.pop();
64
+ const offsets = lineStartOffsets(original);
65
+ const matches = [];
66
+ for (let lineIndex = 0; lineIndex <= originalLines.length - wantedLines.length; lineIndex++) {
67
+ const window = originalLines.slice(lineIndex, lineIndex + wantedLines.length).map(line => line.trimEnd());
68
+ if (window.every((line, index) => line === wantedLines[index])) {
69
+ const start = offsets[lineIndex] ?? 0;
70
+ const endLineIndex = lineIndex + wantedLines.length;
71
+ const end = endLineIndex < offsets.length ? (offsets[endLineIndex] ?? original.length) : original.length;
72
+ matches.push({ start, end });
73
+ }
74
+ }
75
+ if (matches.length !== 1)
76
+ return undefined;
77
+ return matches[0];
78
+ }
79
+ function findEditRange(original, oldText) {
80
+ const candidates = [oldText, stripLineNumberPrefixes(oldText)].filter((candidate, index, all) => candidate.length > 0 && all.indexOf(candidate) === index);
81
+ for (const candidate of candidates) {
82
+ const first = original.indexOf(candidate);
83
+ if (first !== -1) {
84
+ const second = original.indexOf(candidate, first + candidate.length);
85
+ if (second !== -1)
86
+ return { kind: 'multiple' };
87
+ return { kind: 'found', start: first, end: first + candidate.length, approximate: candidate !== oldText };
88
+ }
89
+ }
90
+ for (const candidate of candidates) {
91
+ const range = findLineTrimmedRange(original, candidate);
92
+ if (range)
93
+ return { kind: 'found', ...range, approximate: true };
94
+ }
95
+ return { kind: 'missing' };
96
+ }
97
+ function toolCallKey(toolName, input) {
98
+ return `${toolName}:${JSON.stringify(input)}`;
99
+ }
100
+ function hazeContext(context) {
101
+ return typeof context.experimental_context === 'object' && context.experimental_context != null
102
+ ? context.experimental_context
103
+ : undefined;
104
+ }
105
+ function isMutatingTool(toolName) {
106
+ return ['editFile', 'replaceLines', 'writeFile'].includes(toolName);
107
+ }
108
+ function isReadOnlyFileTool(toolName) {
109
+ return ['listFiles', 'readFile'].includes(toolName);
110
+ }
111
+ function inputPath(input) {
112
+ return typeof input === 'object' && input != null && 'path' in input && typeof input.path === 'string'
113
+ ? input.path
114
+ : undefined;
115
+ }
116
+ function isStructuredFailure(value) {
117
+ return typeof value === 'object' && value != null && 'ok' in value && value.ok === false;
118
+ }
119
+ function structuredToolFailure(toolName, error, suggestedNextStep, pathForError) {
120
+ const message = error instanceof Error ? error.message : String(error);
121
+ return { ok: false, toolName, path: pathForError, error: message, recoverable: true, suggestedNextStep };
122
+ }
123
+ async function runDedupedTool(toolName, input, context, execute) {
124
+ const ctx = hazeContext(context);
125
+ if (!ctx)
126
+ return execute();
127
+ ctx.inFlightToolCalls ??= new Map();
128
+ ctx.completedToolCalls ??= new Map();
129
+ ctx.failedMutationPaths ??= new Set();
130
+ ctx.pathsReadAfterFailedMutation ??= new Set();
131
+ ctx.inFlightMutationPaths ??= new Set();
132
+ ctx.mutationEpoch ??= 0;
133
+ const key = toolCallKey(toolName, input);
134
+ const pathForInput = inputPath(input);
135
+ if (isMutatingTool(toolName) && pathForInput && ctx.inFlightMutationPaths.has(pathForInput)) {
136
+ return {
137
+ ok: true,
138
+ duplicateSkipped: true,
139
+ toolName,
140
+ reason: `Skipped concurrent mutation for ${pathForInput}. Read the file again, then make one editFile call with all non-overlapping replacements or one replaceLines call based on the latest line numbers.`,
141
+ };
142
+ }
143
+ if (isMutatingTool(toolName) && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput)) {
144
+ throw new Error(`Read ${pathForInput} before attempting another edit after the previous edit failure.`);
145
+ }
146
+ const completedAt = ctx.completedToolCalls.get(key);
147
+ const readAfterFailedMutation = toolName === 'readFile' && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput);
148
+ if ((isReadOnlyFileTool(toolName) || toolName === 'bash') && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
149
+ return {
150
+ ok: true,
151
+ duplicateSkipped: true,
152
+ toolName,
153
+ reason: toolName === 'bash'
154
+ ? 'Skipped duplicate bash command; no files changed since the previous run.'
155
+ : 'Skipped duplicate read-only tool call with identical input; no files changed since the previous call.',
156
+ };
157
+ }
158
+ if (ctx.inFlightToolCalls.has(key)) {
159
+ return {
160
+ ok: true,
161
+ duplicateSkipped: true,
162
+ toolName,
163
+ reason: 'Skipped duplicate in-flight tool call with identical input.',
164
+ };
165
+ }
166
+ if (isMutatingTool(toolName) && pathForInput)
167
+ ctx.inFlightMutationPaths.add(pathForInput);
168
+ const promise = execute();
169
+ ctx.inFlightToolCalls.set(key, promise);
170
+ try {
171
+ const result = await promise;
172
+ if (isStructuredFailure(result)) {
173
+ if (isMutatingTool(toolName) && pathForInput) {
174
+ ctx.failedMutationPaths.add(pathForInput);
175
+ ctx.pathsReadAfterFailedMutation.delete(pathForInput);
176
+ }
177
+ return result;
178
+ }
179
+ if (toolName === 'readFile' && pathForInput)
180
+ ctx.pathsReadAfterFailedMutation.add(pathForInput);
181
+ if (isMutatingTool(toolName)) {
182
+ ctx.mutationEpoch += 1;
183
+ if (pathForInput) {
184
+ ctx.failedMutationPaths.delete(pathForInput);
185
+ ctx.pathsReadAfterFailedMutation.delete(pathForInput);
186
+ }
187
+ }
188
+ ctx.completedToolCalls.set(key, ctx.mutationEpoch);
189
+ return result;
190
+ }
191
+ catch (error) {
192
+ if (isMutatingTool(toolName) && pathForInput) {
193
+ ctx.failedMutationPaths.add(pathForInput);
194
+ ctx.pathsReadAfterFailedMutation.delete(pathForInput);
195
+ }
196
+ throw error;
197
+ }
198
+ finally {
199
+ ctx.inFlightToolCalls.delete(key);
200
+ if (isMutatingTool(toolName) && pathForInput)
201
+ ctx.inFlightMutationPaths?.delete(pathForInput);
202
+ }
203
+ }
204
+ function looksLikeShellFileMutation(command) {
205
+ return /(^|[;&|]\s*)(sed\s+-i|perl\s+-pi|tee\b|chmod\b|mv\b|cp\b|rm\b|mkdir\b|touch\b)/.test(command)
206
+ || /(^|\s)(>|>>)(\s|\S)/.test(command)
207
+ || /\b(File\.write|writeFileSync|writeFile|appendFileSync|appendFile)\b/.test(command);
208
+ }
43
209
  export const hazeTools = {
44
210
  listFiles: tool({
45
211
  description: 'List files and directories in the current workspace. Prefer this over bash ls/find for discovering project structure.',
@@ -47,31 +213,39 @@ export const hazeTools = {
47
213
  path: z.string().default('.').describe('Directory path relative to the current workspace'),
48
214
  recursive: z.boolean().default(false).describe('Whether to list files recursively'),
49
215
  maxEntries: z.number().int().positive().max(500).default(100).describe('Maximum number of entries to return'),
216
+ cursor: z.string().optional().describe('Pagination cursor from a previous listFiles result. Continue after that entry.'),
50
217
  includeIgnored: z.boolean().default(false).describe('Include files ignored by .gitignore. Use only when explicitly needed.'),
51
218
  }),
52
- execute: async ({ path: dirPath, recursive, maxEntries, includeIgnored }) => {
53
- const absolutePath = resolveWorkspacePath(dirPath);
54
- await assertNotIgnored(absolutePath, dirPath, includeIgnored);
55
- const entries = [];
56
- let ignoredSkipped = 0;
57
- const walked = await walkDir(absolutePath, { recursive, maxEntries, filter: async (entry) => {
58
- if (!includeIgnored && await isGitIgnored(entry.absolutePath)) {
59
- ignoredSkipped++;
60
- return false;
219
+ execute: async ({ path: dirPath, recursive, maxEntries, cursor, includeIgnored }, context) => runDedupedTool('listFiles', { path: dirPath, recursive, maxEntries, cursor, includeIgnored }, context, async () => {
220
+ try {
221
+ const absolutePath = resolveWorkspacePath(dirPath);
222
+ await assertNotIgnored(absolutePath, dirPath, includeIgnored);
223
+ const entries = [];
224
+ let ignoredSkipped = 0;
225
+ const walked = await walkDir(absolutePath, { recursive, maxEntries: maxEntries + 1, cursor, filter: async (entry) => {
226
+ if (!includeIgnored && await isGitIgnored(entry.absolutePath)) {
227
+ ignoredSkipped++;
228
+ return false;
229
+ }
230
+ return true;
231
+ } });
232
+ const page = walked.slice(0, maxEntries);
233
+ const hasMore = walked.length > maxEntries;
234
+ for (const entry of page) {
235
+ if (entry.isDirectory) {
236
+ entries.push({ path: entry.path, type: 'directory' });
237
+ }
238
+ else if (entry.isFile) {
239
+ const stat = await fs.stat(entry.absolutePath);
240
+ entries.push({ path: entry.path, type: 'file', size: stat.size });
61
241
  }
62
- return true;
63
- } });
64
- for (const entry of walked) {
65
- if (entry.isDirectory) {
66
- entries.push({ path: entry.path, type: 'directory' });
67
- }
68
- else if (entry.isFile) {
69
- const stat = await fs.stat(entry.absolutePath);
70
- entries.push({ path: entry.path, type: 'file', size: stat.size });
71
242
  }
243
+ return { path: dirPath, recursive, includeIgnored, cursor, nextCursor: hasMore ? page.at(-1)?.path : undefined, ignoredSkipped, entries, truncated: hasMore };
72
244
  }
73
- return { path: dirPath, recursive, includeIgnored, ignoredSkipped, entries, truncated: entries.length >= maxEntries };
74
- },
245
+ catch (error) {
246
+ return structuredToolFailure('listFiles', error, 'Check that the directory exists and is not ignored, or retry with a narrower path.', dirPath);
247
+ }
248
+ }),
75
249
  }),
76
250
  readFile: tool({
77
251
  description: 'Read a UTF-8 text file from the current workspace. Supports optional 1-based line offset and line limit.',
@@ -81,72 +255,104 @@ export const hazeTools = {
81
255
  limit: z.number().int().positive().max(2000).optional().describe('Maximum number of lines to return'),
82
256
  allowIgnored: z.boolean().default(false).describe('Read the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
83
257
  }),
84
- execute: async ({ path: filePath, offset, limit, allowIgnored }) => {
85
- const absolutePath = resolveWorkspacePath(filePath);
86
- await assertNotIgnored(absolutePath, filePath, allowIgnored);
87
- const content = await fs.readFile(absolutePath, 'utf8');
88
- const lines = content.split(/\r?\n/);
89
- const start = offset == null ? 0 : offset - 1;
90
- const end = limit == null ? lines.length : start + limit;
91
- const selectedLines = lines.slice(start, end);
92
- const selected = selectedLines.join('\n');
93
- return {
94
- path: filePath,
95
- startLine: start + 1,
96
- endLine: Math.min(end, lines.length),
97
- totalLines: lines.length,
98
- lineNumberedText: numberLines(selectedLines, start + 1),
99
- ...truncate(selected),
100
- };
101
- },
258
+ execute: async ({ path: filePath, offset, limit, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, allowIgnored }, context, async () => {
259
+ try {
260
+ const absolutePath = resolveWorkspacePath(filePath);
261
+ await assertNotIgnored(absolutePath, filePath, allowIgnored);
262
+ const content = await fs.readFile(absolutePath, 'utf8');
263
+ const lines = content.split(/\r?\n/);
264
+ const start = offset == null ? 0 : offset - 1;
265
+ const end = limit == null ? lines.length : start + limit;
266
+ const selectedLines = lines.slice(start, end);
267
+ const selected = selectedLines.join('\n');
268
+ return {
269
+ path: filePath,
270
+ startLine: start + 1,
271
+ endLine: Math.min(end, lines.length),
272
+ totalLines: lines.length,
273
+ lineNumberedText: numberLines(selectedLines, start + 1),
274
+ ...truncate(selected),
275
+ };
276
+ }
277
+ catch (error) {
278
+ return structuredToolFailure('readFile', error, 'Check the path with listFiles, or set allowIgnored=true only if the user explicitly asked to inspect an ignored file.', filePath);
279
+ }
280
+ }),
102
281
  }),
103
282
  replaceLines: tool({
104
- description: 'Replace a 1-based inclusive line range in an existing UTF-8 text file. Prefer this after reading a file when exact editFile replacements are ambiguous or fail.',
283
+ description: 'Replace a 1-based inclusive line range in an existing UTF-8 text file. Prefer this after reading a file when exact editFile replacements are ambiguous or fail. If endLine is slightly beyond EOF, it is clamped to the current last line.',
105
284
  inputSchema: z.object({
106
285
  path: z.string().describe('File path relative to the current workspace'),
107
286
  startLine: z.number().int().positive().describe('First 1-based line number to replace'),
108
- endLine: z.number().int().positive().describe('Last 1-based line number to replace, inclusive'),
287
+ endLine: z.number().int().nonnegative().describe('Last 1-based line number to replace, inclusive. To append at EOF, use startLine=totalLines+1 and endLine=totalLines.'),
109
288
  content: z.string().describe('Replacement content for the line range'),
110
289
  allowIgnored: z.boolean().default(false).describe('Edit the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
111
290
  }),
112
- execute: async ({ path: filePath, startLine, endLine, content, allowIgnored }) => {
113
- if (endLine < startLine)
114
- throw new Error('endLine must be greater than or equal to startLine');
115
- const absolutePath = resolveWorkspacePath(filePath);
116
- await assertNotIgnored(absolutePath, filePath, allowIgnored);
117
- const original = await fs.readFile(absolutePath, 'utf8');
118
- const hasTrailingNewline = original.endsWith('\n');
119
- const lines = original.split(/\r?\n/);
120
- if (hasTrailingNewline)
121
- lines.pop();
122
- if (startLine > lines.length + 1)
123
- throw new Error(`startLine ${startLine} is beyond end of file (${lines.length} lines)`);
124
- if (endLine > lines.length)
125
- throw new Error(`endLine ${endLine} is beyond end of file (${lines.length} lines)`);
126
- const replacementLines = content.length === 0 ? [] : content.split(/\r?\n/);
127
- lines.splice(startLine - 1, endLine - startLine + 1, ...replacementLines);
128
- const updated = lines.join('\n') + (hasTrailingNewline ? '\n' : '');
129
- await fs.writeFile(absolutePath, updated, 'utf8');
130
- return { ok: true, path: filePath, startLine, endLine, replacementLines: replacementLines.length };
131
- },
291
+ execute: async ({ path: filePath, startLine, endLine, content, allowIgnored }, context) => runDedupedTool('replaceLines', { path: filePath, startLine, endLine, content, allowIgnored }, context, async () => {
292
+ try {
293
+ const absolutePath = resolveWorkspacePath(filePath);
294
+ await assertNotIgnored(absolutePath, filePath, allowIgnored);
295
+ const original = await fs.readFile(absolutePath, 'utf8');
296
+ const hasTrailingNewline = original.endsWith('\n');
297
+ const lines = original.split(/\r?\n/);
298
+ if (hasTrailingNewline)
299
+ lines.pop();
300
+ const isAppend = startLine === lines.length + 1 && endLine === lines.length;
301
+ if (!isAppend && endLine < startLine)
302
+ throw new Error('endLine must be greater than or equal to startLine, except when appending at EOF with startLine=totalLines+1 and endLine=totalLines');
303
+ if (startLine > lines.length + 1)
304
+ throw new Error(`startLine ${startLine} is beyond end of file (${lines.length} lines)`);
305
+ const effectiveEndLine = !isAppend && endLine > lines.length ? lines.length : endLine;
306
+ const replacementLines = content.length === 0 ? [] : content.split(/\r?\n/);
307
+ if (isAppend) {
308
+ lines.push(...replacementLines);
309
+ }
310
+ else {
311
+ lines.splice(startLine - 1, effectiveEndLine - startLine + 1, ...replacementLines);
312
+ }
313
+ const updated = lines.join('\n') + (hasTrailingNewline ? '\n' : '');
314
+ await fs.writeFile(absolutePath, updated, 'utf8');
315
+ return { ok: true, path: filePath, startLine, endLine: effectiveEndLine, requestedEndLine: endLine, endLineClamped: effectiveEndLine !== endLine, replacementLines: replacementLines.length, appended: isAppend };
316
+ }
317
+ catch (error) {
318
+ return structuredToolFailure('replaceLines', error, 'Read the file again for current line numbers, then retry replaceLines with a valid range.', filePath);
319
+ }
320
+ }),
132
321
  }),
133
322
  writeFile: tool({
134
- description: 'Create or overwrite a UTF-8 text file in the current workspace. Creates parent directories as needed. Use for new files or after smaller edit tools are not suitable.',
323
+ description: 'Create a UTF-8 text file in the current workspace. For existing files, prefer editFile/replaceLines; set overwriteExisting=true only for an intentional complete rewrite.',
135
324
  inputSchema: z.object({
136
325
  path: z.string().describe('File path relative to the current workspace'),
137
326
  content: z.string().describe('Complete file contents to write'),
327
+ overwriteExisting: z.boolean().default(false).describe('Required to overwrite an existing file. Prefer editFile or replaceLines for existing files unless a complete rewrite is intentional.'),
138
328
  allowIgnored: z.boolean().default(false).describe('Write the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
139
329
  }),
140
- execute: async ({ path: filePath, content, allowIgnored }) => {
141
- const absolutePath = resolveWorkspacePath(filePath);
142
- await assertNotIgnored(absolutePath, filePath, allowIgnored);
143
- await fs.mkdir(path.dirname(absolutePath), { recursive: true });
144
- await fs.writeFile(absolutePath, content, 'utf8');
145
- return { ok: true, path: filePath, bytes: Buffer.byteLength(content, 'utf8') };
146
- },
330
+ execute: async ({ path: filePath, content, overwriteExisting, allowIgnored }, context) => runDedupedTool('writeFile', { path: filePath, content, overwriteExisting, allowIgnored }, context, async () => {
331
+ try {
332
+ const absolutePath = resolveWorkspacePath(filePath);
333
+ await assertNotIgnored(absolutePath, filePath, allowIgnored);
334
+ try {
335
+ await fs.access(absolutePath);
336
+ if (!overwriteExisting) {
337
+ throw new Error(`Refusing to overwrite existing file: ${filePath}. Use editFile/replaceLines for targeted edits, or set overwriteExisting=true for an intentional complete rewrite.`);
338
+ }
339
+ }
340
+ catch (error) {
341
+ const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
342
+ if (code !== 'ENOENT')
343
+ throw error;
344
+ }
345
+ await fs.mkdir(path.dirname(absolutePath), { recursive: true });
346
+ await fs.writeFile(absolutePath, content, 'utf8');
347
+ return { ok: true, path: filePath, bytes: Buffer.byteLength(content, 'utf8'), overwritten: overwriteExisting };
348
+ }
349
+ catch (error) {
350
+ return structuredToolFailure('writeFile', error, 'Use editFile/replaceLines for existing files, set overwriteExisting=true only for an intentional rewrite, or check the path/ignored-file setting.', filePath);
351
+ }
352
+ }),
147
353
  }),
148
354
  editFile: tool({
149
- description: 'Edit a text file using exact replacements. Each oldText must match exactly once in the original file and edits must not overlap. If this fails because text is missing or not unique, do not retry; use replaceLines instead.',
355
+ description: 'Edit a text file using unique replacements. Each oldText should match the current file; line-number prefixes from readFile output and trailing-whitespace-only differences are tolerated when the match is still unique. Put multiple edits to the same file in one call. If this fails because text is missing or not unique, read the file again and use replaceLines.',
150
356
  inputSchema: z.object({
151
357
  path: z.string().describe('File path relative to the current workspace'),
152
358
  edits: z.array(z.object({
@@ -155,39 +361,47 @@ export const hazeTools = {
155
361
  })).min(1).describe('One or more non-overlapping exact replacements'),
156
362
  allowIgnored: z.boolean().default(false).describe('Edit the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
157
363
  }),
158
- execute: async ({ path: filePath, edits, allowIgnored }) => {
159
- const absolutePath = resolveWorkspacePath(filePath);
160
- await assertNotIgnored(absolutePath, filePath, allowIgnored);
161
- const original = await fs.readFile(absolutePath, 'utf8');
162
- const ranges = edits.map((edit, index) => {
163
- const first = original.indexOf(edit.oldText);
164
- if (first === -1)
165
- throw new Error(`edit ${index}: oldText was not found`);
166
- const second = original.indexOf(edit.oldText, first + edit.oldText.length);
167
- if (second !== -1)
168
- throw new Error(`edit ${index}: oldText is not unique`);
169
- return { index, start: first, end: first + edit.oldText.length, edit };
170
- }).sort((a, b) => a.start - b.start);
171
- for (let i = 1; i < ranges.length; i++) {
172
- if (ranges[i].start < ranges[i - 1].end) {
173
- throw new Error(`edits ${ranges[i - 1].index} and ${ranges[i].index} overlap`);
364
+ execute: async ({ path: filePath, edits, allowIgnored }, context) => runDedupedTool('editFile', { path: filePath, edits, allowIgnored }, context, async () => {
365
+ try {
366
+ const absolutePath = resolveWorkspacePath(filePath);
367
+ await assertNotIgnored(absolutePath, filePath, allowIgnored);
368
+ const original = await fs.readFile(absolutePath, 'utf8');
369
+ const ranges = edits.map((edit, index) => {
370
+ const match = findEditRange(original, edit.oldText);
371
+ if (match.kind === 'missing')
372
+ throw new Error(`edit ${index}: oldText was not found. Read the file again and use the exact current text, or use replaceLines with the latest line numbers.`);
373
+ if (match.kind === 'multiple')
374
+ throw new Error(`edit ${index}: oldText is not unique`);
375
+ return { index, start: match.start, end: match.end, edit, approximate: match.approximate };
376
+ }).sort((a, b) => a.start - b.start);
377
+ for (let i = 1; i < ranges.length; i++) {
378
+ if (ranges[i].start < ranges[i - 1].end) {
379
+ throw new Error(`edits ${ranges[i - 1].index} and ${ranges[i].index} overlap`);
380
+ }
381
+ }
382
+ let updated = original;
383
+ for (const range of [...ranges].sort((a, b) => b.start - a.start)) {
384
+ updated = updated.slice(0, range.start) + range.edit.newText + updated.slice(range.end);
174
385
  }
386
+ await fs.writeFile(absolutePath, updated, 'utf8');
387
+ return { ok: true, path: filePath, edits: edits.length, approximateMatches: ranges.filter(range => range.approximate).length };
175
388
  }
176
- let updated = original;
177
- for (const range of [...ranges].sort((a, b) => b.start - a.start)) {
178
- updated = updated.slice(0, range.start) + range.edit.newText + updated.slice(range.end);
389
+ catch (error) {
390
+ return structuredToolFailure('editFile', error, 'Read the file again, then retry with exact current text or use replaceLines with the latest line numbers.', filePath);
179
391
  }
180
- await fs.writeFile(absolutePath, updated, 'utf8');
181
- return { ok: true, path: filePath, edits: edits.length };
182
- },
392
+ }),
183
393
  }),
184
394
  bash: tool({
185
- description: 'Run a bash command in the current workspace. Use for inspecting files, running tests, builds, and other shell tasks. Avoid destructive commands unless the user explicitly asked.',
395
+ description: 'Run a bash command in the current workspace. Use for tests, builds, validation, and inspection. Do not use bash to edit files; use file tools instead unless the user explicitly requested a shell mutation.',
186
396
  inputSchema: z.object({
187
397
  command: z.string().min(1).describe('Command to execute with bash -lc'),
188
398
  timeoutSeconds: z.number().int().positive().max(600).optional().describe('Timeout in seconds; defaults to 60'),
399
+ allowMutation: z.boolean().default(false).describe('Allow shell commands that mutate files (chmod, redirection, tee, sed -i, File.write, etc.). Use only when explicitly requested or when file tools cannot do the job.'),
189
400
  }),
190
- execute: async ({ command, timeoutSeconds }, { abortSignal }) => {
401
+ execute: async ({ command, timeoutSeconds, allowMutation }, context) => runDedupedTool('bash', { command, timeoutSeconds, allowMutation }, context, async () => {
402
+ if (!allowMutation && looksLikeShellFileMutation(command)) {
403
+ return structuredToolFailure('bash', 'Refusing to mutate files via bash. Use writeFile/editFile/replaceLines, or set allowMutation=true only when shell mutation is explicitly required.', 'Use writeFile/editFile/replaceLines for file changes, or retry bash with allowMutation=true only when shell mutation is explicitly required.');
404
+ }
191
405
  const timeoutMs = (timeoutSeconds ?? 60) * 1000;
192
406
  return await new Promise(resolve => {
193
407
  const child = spawn('bash', ['-lc', command], { cwd: workspaceRoot(), stdio: ['ignore', 'pipe', 'pipe'] });
@@ -199,13 +413,13 @@ export const hazeTools = {
199
413
  child.kill('SIGTERM');
200
414
  }, timeoutMs);
201
415
  const abort = () => child.kill('SIGTERM');
202
- abortSignal?.addEventListener('abort', abort, { once: true });
416
+ context.abortSignal?.addEventListener('abort', abort, { once: true });
203
417
  child.stdout.on('data', data => stdout += data.toString());
204
418
  child.stderr.on('data', data => stderr += data.toString());
205
419
  child.on('close', code => {
206
420
  settled = true;
207
421
  clearTimeout(timer);
208
- abortSignal?.removeEventListener('abort', abort);
422
+ context.abortSignal?.removeEventListener('abort', abort);
209
423
  resolve({
210
424
  ok: code === 0,
211
425
  code,
@@ -217,10 +431,10 @@ export const hazeTools = {
217
431
  child.on('error', error => {
218
432
  settled = true;
219
433
  clearTimeout(timer);
220
- abortSignal?.removeEventListener('abort', abort);
434
+ context.abortSignal?.removeEventListener('abort', abort);
221
435
  resolve({ ok: false, command, error: error.message });
222
436
  });
223
437
  });
224
- },
438
+ }),
225
439
  }),
226
440
  };
@@ -1,10 +1,12 @@
1
1
  export function buildInitPrompt() {
2
2
  return `Initialize this repository for Haze by creating a best-practice AGENTS.md file.
3
3
 
4
- Explore the codebase first, respecting .gitignore:
5
- 1. Use listFiles recursively from the workspace root.
6
- 2. Read only the files needed to understand project conventions, commands, architecture, and release workflow. Usually read package/config files, README, and key source entrypoints.
7
- 3. Do not read ignored files unless truly necessary.
4
+ Explore the codebase first, respecting .gitignore, but keep this quick and minimal:
5
+ 1. Start with exactly one listFiles call from the workspace root. Do not announce that you are starting before the tool call.
6
+ 2. Do not use bash for discovery unless package metadata is missing. Do not grep/find the tree for this command.
7
+ 3. After listFiles returns, read only the small set needed to understand conventions: package/config files, README, existing AGENTS.md if present, and at most three key source entrypoints/directories.
8
+ 4. Do not call listFiles with the same input twice. Do not read the same path repeatedly. Do not read speculative files; list the parent first if unsure.
9
+ 5. Aim to finish in 12 tool calls or fewer. Do not read ignored files unless truly necessary.
8
10
 
9
11
  Create or update AGENTS.md at the workspace root. It should be concise and useful for future coding agents. Include sections when known:
10
12
  - Project overview
@@ -15,5 +17,5 @@ Create or update AGENTS.md at the workspace root. It should be concise and usefu
15
17
  - Testing/validation expectations
16
18
  - Safety notes or files/directories to avoid
17
19
 
18
- If AGENTS.md already exists, preserve useful existing instructions and improve them. After writing it, summarize what you learned and what you wrote.`;
20
+ If AGENTS.md already exists, preserve useful existing instructions and improve them with targeted editFile/replaceLines edits. Do not rewrite the entire file unless it is missing or unusable. After writing it, summarize only the change and validation status.`;
19
21
  }
@@ -5,26 +5,40 @@ export function buildSystemPrompt(contextFiles = []) {
5
5
  return `You are Haze, an expert coding assistant operating inside a terminal-based agent CLI. You help users build apps by understanding the current conversation, inspecting projects, running commands, and editing files.
6
6
 
7
7
  Available tools:
8
- - listFiles: List files and directories in the current workspace. Prefer this over bash ls/find for project discovery.
8
+ - listFiles: List files and directories in the current workspace. Supports recursive listings and cursor pagination. Prefer this over bash ls/find for project discovery.
9
9
  - readFile: Read UTF-8 files with optional line ranges. Returns lineNumberedText for line-based edits.
10
- - editFile: Edit files with exact unique text replacements. Use only for small, unambiguous replacements.
11
- - replaceLines: Replace a 1-based inclusive line range. Use when editFile is ambiguous or has failed once.
12
- - writeFile: Create or overwrite files. Use for new files or intentional complete rewrites.
13
- - bash: Run shell commands for tests, builds, scripts, and inspection that cannot be done with file tools.
10
+ - editFile: Edit files with unique text replacements. Use only for small, unambiguous replacements. Put multiple edits to the same file in one editFile call; do not issue parallel separate edits for the same file.
11
+ - replaceLines: Replace a 1-based inclusive line range. Use when editFile is ambiguous or has failed once. To append at EOF, use startLine=totalLines+1 and endLine=totalLines from the latest readFile result. Slightly-too-large endLine values are clamped to EOF.
12
+ - writeFile: Create files, or overwrite existing files only when overwriteExisting=true is intentionally set for a complete rewrite. Prefer editFile/replaceLines for existing files.
13
+ - bash: Run shell commands for tests, builds, scripts, and inspection that cannot be done with file tools. Do not use bash to mutate files unless explicitly requested or file tools cannot do the job.
14
+ - skill_*: Markdown skills installed in ~/.haze/skills. Use a skill tool when its description matches the user's request; it returns workflow instructions and explicitly referenced files.
14
15
 
15
16
  Guidelines:
16
17
  - Be concise, technical, and practical.
18
+ - You have access to the tools listed above. Never claim that you cannot inspect files, run shell commands, or make file changes when an available tool can do it.
19
+ - Skills are optional instruction bundles. Call a skill tool only when relevant, then follow the returned SKILL.md instructions and references.
20
+ - If answering requires current workspace information, inspect it with tools instead of guessing or saying you cannot access it.
21
+ - When the user asks you to run a command, inspect command output, or reason about local project state, use bash or file tools rather than only explaining what the user could run.
17
22
  - Preserve user-provided content exactly. When the user asks to add, modify, or use "this", "that", "it", or previous content, refer to the current conversation and do not substitute different text.
18
- - Use listFiles for project discovery instead of bash ls/find.
23
+ - Use listFiles for project discovery instead of bash ls/find. Start non-recursive, use recursive for focused directories, and follow nextCursor only when more listing is genuinely needed.
19
24
  - Do not list or read the same path repeatedly unless the file changed or the previous result was insufficient.
20
25
  - Read only directly relevant files, usually once. Do not read README/package files unless needed for the task.
21
26
  - File tools follow .gitignore by default. Only set includeIgnored/allowIgnored when the user explicitly asks or the task truly requires ignored files, and say why.
22
- - Prefer editFile for existing files when one small exact replacement is unique.
27
+ - Prefer editFile for existing files when one small replacement is unique. For multiple edits in one file, use one editFile call with multiple non-overlapping edits instead of parallel tool calls.
23
28
  - If editFile fails because oldText is missing or not unique, do not retry editFile for the same change; use replaceLines with lineNumberedText from readFile.
24
- - Use writeFile only for new files or complete rewrites.
25
- - Use bash mainly for tests, builds, package scripts, and commands that are not covered by file tools.
26
- - After making changes, validate with the project's relevant test/typecheck/build command when practical.
27
- - After tool use, always respond with a concise summary of what changed or what failed.
29
+ - Use writeFile for new files. For existing files, prefer editFile or replaceLines; only set writeFile overwriteExisting=true when a complete rewrite is intentional and safer than targeted edits.
30
+ - Use bash mainly for tests, builds, package scripts, and commands that are not covered by file tools. Do not combine validation with file mutation in one shell command; use file tools for edits and bash only for validation/inspection.
31
+ - After making changes, validate with the project's relevant test/typecheck/build command when practical. After editing source or test files in languages with syntax checkers, run the syntax check before the full test command when practical. Once a requested change is edited and validation passes, summarize; do not continue inspecting files.
32
+ - For action requests such as "add", "create", "write", "implement", "update", "fix", "test", or "document", do not stop after only inspecting files. Make the requested file/code changes unless blocked or clarification is required.
33
+ - Requests like "create a plan", "make a plan", or "outline a plan" are planning requests, not implementation requests. If you create a plan document, summarize it; do not start implementing or validating unless asked.
34
+ - If editFile or replaceLines fails, read the affected file again with readFile before another edit attempt, then make one smaller targeted change; do not batch speculative replacements. Bash/cat does not satisfy this recovery step.
35
+ - For plan-only requests, stop after creating/updating the plan artifact and summarize it; do not edit source files or run validation in the same turn.
36
+ - When asked to implement a plan, identify the concrete required checklist items first and compare them with the current files. Do not edit source or tests when the required behavior is already present. Implement the smallest clearly required phase or required items, skip optional/design-question items unless explicitly requested, prefer adding tests over exploratory one-off scripts, validate once after code/test edits, and do not edit the plan file itself unless asked or unless marking completed items after validation passes.
37
+ - After tool use, always respond with a concise summary of what changed or what failed for the current user request only. Do not recap unrelated earlier tasks unless directly relevant.
38
+ - Do not call ordinary unfinished work or unresolved optional scope a blocker. A blocker is a concrete tool failure, missing/ambiguous requirement, permission problem, or unavailable dependency.
39
+ - For Ruby ad-hoc checks, prefer adding/running Minitest tests. If a one-liner is truly useful, use ruby -I. -e with require "file" rather than require_relative from -e.
40
+ - Do not say tools are unavailable just because a tool budget or loop guard was mentioned; if you can still call tools in the current turn, continue the requested work.
41
+ - Do not claim tests passed or commands succeeded unless you actually ran them in the current turn and saw success.
28
42
  - Ask before destructive actions.
29
43
  - Show file paths clearly when working with files.${projectContext}
30
44
 
@@ -1,2 +1,12 @@
1
- import type { LoadedSkill } from './types.js';
2
- export declare function loadSkill(dir: string, source: 'global' | 'local'): Promise<LoadedSkill | null>;
1
+ import type { LoadedSkill, SkillFrontmatter } from './types.js';
2
+ declare function parseSkillMarkdown(content: string): {
3
+ frontmatter: SkillFrontmatter;
4
+ body: string;
5
+ };
6
+ declare function referencedPaths(body: string): string[];
7
+ export declare function loadSkill(dir: string, source?: 'global'): Promise<LoadedSkill | null>;
8
+ export declare const internals: {
9
+ parseSkillMarkdown: typeof parseSkillMarkdown;
10
+ referencedPaths: typeof referencedPaths;
11
+ };
12
+ export {};