@denizokcu/haze 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +59 -12
  3. package/dist/cli/chat/TaskBar.d.ts +9 -0
  4. package/dist/cli/chat/TaskBar.js +40 -0
  5. package/dist/cli/chat/chatMetrics.d.ts +11 -0
  6. package/dist/cli/chat/chatMetrics.js +50 -0
  7. package/dist/cli/chat/inputSuggestions.d.ts +16 -0
  8. package/dist/cli/chat/inputSuggestions.js +55 -0
  9. package/dist/cli/chat/messages.d.ts +9 -0
  10. package/dist/cli/chat/messages.js +76 -0
  11. package/dist/cli/chat/sessionRecorder.d.ts +12 -0
  12. package/dist/cli/chat/sessionRecorder.js +21 -0
  13. package/dist/cli/chat/startupInfo.d.ts +4 -0
  14. package/dist/cli/chat/startupInfo.js +53 -0
  15. package/dist/cli/chat/turnState.d.ts +5 -0
  16. package/dist/cli/chat/turnState.js +20 -0
  17. package/dist/cli/commands/chat.d.ts +0 -1
  18. package/dist/cli/commands/chat.js +293 -894
  19. package/dist/cli/commands/chatModes.d.ts +8 -0
  20. package/dist/cli/commands/chatModes.js +44 -0
  21. package/dist/cli/commands/commandHelp.d.ts +6 -0
  22. package/dist/cli/commands/commandHelp.js +25 -0
  23. package/dist/cli/commands/commands.d.ts +1 -1
  24. package/dist/cli/commands/commands.js +41 -267
  25. package/dist/cli/commands/formatters.js +12 -4
  26. package/dist/cli/commands/initCommand.d.ts +2 -0
  27. package/dist/cli/commands/initCommand.js +19 -0
  28. package/dist/cli/commands/logsCommand.d.ts +2 -0
  29. package/dist/cli/commands/logsCommand.js +63 -0
  30. package/dist/cli/commands/lspWizard.d.ts +14 -0
  31. package/dist/cli/commands/lspWizard.js +44 -0
  32. package/dist/cli/commands/mcpWizard.d.ts +15 -0
  33. package/dist/cli/commands/mcpWizard.js +69 -0
  34. package/dist/cli/commands/modelCommand.d.ts +2 -0
  35. package/dist/cli/commands/modelCommand.js +36 -0
  36. package/dist/cli/commands/providerWizard.d.ts +30 -0
  37. package/dist/cli/commands/providerWizard.js +114 -0
  38. package/dist/cli/commands/runCommand.d.ts +16 -0
  39. package/dist/cli/commands/runCommand.js +170 -0
  40. package/dist/cli/commands/settingsSummary.d.ts +3 -0
  41. package/dist/cli/commands/settingsSummary.js +40 -0
  42. package/dist/cli/commands/skillConfirmRemove.d.ts +11 -0
  43. package/dist/cli/commands/skillConfirmRemove.js +19 -0
  44. package/dist/cli/commands/skillCreation.d.ts +12 -0
  45. package/dist/cli/commands/skillCreation.js +14 -0
  46. package/dist/cli/commands/skillWizard.d.ts +15 -0
  47. package/dist/cli/commands/skillWizard.js +38 -0
  48. package/dist/cli/commands/streaming/assistantText.d.ts +17 -0
  49. package/dist/cli/commands/streaming/assistantText.js +115 -0
  50. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +55 -0
  51. package/dist/cli/commands/streaming/toolGroupRenderer.js +102 -0
  52. package/dist/cli/commands/streaming/toolResultState.d.ts +13 -0
  53. package/dist/cli/commands/streaming/toolResultState.js +25 -0
  54. package/dist/cli/commands/streaming/turnRuntime.d.ts +78 -0
  55. package/dist/cli/commands/streaming/turnRuntime.js +86 -0
  56. package/dist/cli/commands/streaming.d.ts +9 -25
  57. package/dist/cli/commands/streaming.js +82 -347
  58. package/dist/cli/commands/wizardActions.d.ts +40 -0
  59. package/dist/cli/commands/wizardActions.js +40 -0
  60. package/dist/cli/commands/wizardInput.d.ts +4 -0
  61. package/dist/cli/commands/wizardInput.js +19 -0
  62. package/dist/cli/commands/wizardPrompts.d.ts +22 -0
  63. package/dist/cli/commands/wizardPrompts.js +52 -0
  64. package/dist/cli/commands/wizardSuggestions.d.ts +23 -0
  65. package/dist/cli/commands/wizardSuggestions.js +139 -0
  66. package/dist/cli/index.js +62 -4
  67. package/dist/config/contextFiles.d.ts +8 -1
  68. package/dist/config/contextFiles.js +25 -12
  69. package/dist/config/lspSettings.js +3 -6
  70. package/dist/config/mcpSettings.js +5 -5
  71. package/dist/config/providers.js +4 -4
  72. package/dist/config/skillSettings.js +4 -3
  73. package/dist/core/agent/budgets.d.ts +6 -0
  74. package/dist/core/agent/budgets.js +6 -0
  75. package/dist/core/agent/compaction.js +1 -1
  76. package/dist/core/agent/requestAssembly.d.ts +0 -7
  77. package/dist/core/agent/requestAssembly.js +27 -5
  78. package/dist/core/agent/toolOutputStore.js +5 -4
  79. package/dist/core/agent/toolResults.d.ts +31 -0
  80. package/dist/core/agent/toolResults.js +42 -0
  81. package/dist/core/agent/turnPolicy.d.ts +8 -0
  82. package/dist/core/agent/turnPolicy.js +23 -0
  83. package/dist/core/agent/workState.d.ts +18 -5
  84. package/dist/core/agent/workState.js +39 -20
  85. package/dist/core/bashOutput/reducers/content.d.ts +1 -0
  86. package/dist/core/bashOutput/reducers/content.js +1 -1
  87. package/dist/core/bashOutput/reducers/gh.d.ts +1 -0
  88. package/dist/core/bashOutput/reducers/gh.js +77 -0
  89. package/dist/core/bashOutput/registry.js +8 -0
  90. package/dist/core/goal/sessionGoal.d.ts +6 -30
  91. package/dist/core/goal/sessionGoal.js +3 -68
  92. package/dist/core/safety/bashClassifier.js +30 -0
  93. package/dist/core/safety/urlGuard.d.ts +1 -0
  94. package/dist/core/safety/urlGuard.js +6 -1
  95. package/dist/core/session/sessionSlimming.d.ts +5 -0
  96. package/dist/core/session/sessionSlimming.js +78 -0
  97. package/dist/core/session/sessionStore.d.ts +23 -3
  98. package/dist/core/session/sessionStore.js +30 -10
  99. package/dist/core/subagent/subagentRunner.d.ts +11 -1
  100. package/dist/core/subagent/subagentRunner.js +1 -0
  101. package/dist/llm/capabilities.d.ts +12 -0
  102. package/dist/llm/capabilities.js +10 -0
  103. package/dist/llm/client.d.ts +1 -0
  104. package/dist/llm/client.js +11 -2
  105. package/dist/llm/hazeTools.d.ts +31 -32
  106. package/dist/llm/hazeTools.js +40 -567
  107. package/dist/llm/lsp.d.ts +46 -1
  108. package/dist/llm/lsp.js +9 -9
  109. package/dist/llm/lspTools.d.ts +2 -20
  110. package/dist/llm/mcp.js +9 -0
  111. package/dist/llm/requestContext.js +7 -22
  112. package/dist/llm/systemPrompt.d.ts +1 -0
  113. package/dist/llm/systemPrompt.js +1 -1
  114. package/dist/llm/tools/bashTool.d.ts +5 -0
  115. package/dist/llm/tools/bashTool.js +81 -0
  116. package/dist/llm/tools/editMatch.d.ts +55 -0
  117. package/dist/llm/tools/editMatch.js +99 -0
  118. package/dist/llm/tools/failures.d.ts +36 -0
  119. package/dist/llm/tools/failures.js +38 -0
  120. package/dist/llm/tools/fetchTool.d.ts +65 -0
  121. package/dist/llm/tools/fetchTool.js +45 -0
  122. package/dist/llm/tools/fileToolShared.d.ts +10 -0
  123. package/dist/llm/tools/fileToolShared.js +43 -0
  124. package/dist/llm/tools/grepParse.d.ts +13 -0
  125. package/dist/llm/tools/grepParse.js +67 -0
  126. package/dist/llm/tools/outputCap.d.ts +53 -0
  127. package/dist/llm/tools/outputCap.js +67 -0
  128. package/dist/llm/tools/storedOutputTool.d.ts +10 -0
  129. package/dist/llm/tools/storedOutputTool.js +17 -0
  130. package/dist/llm/tools/taskTool.d.ts +28 -0
  131. package/dist/llm/tools/taskTool.js +41 -0
  132. package/dist/llm/tools/toolContext.d.ts +69 -0
  133. package/dist/llm/tools/toolContext.js +187 -0
  134. package/dist/llm/tools/workspaceFile.d.ts +33 -0
  135. package/dist/llm/tools/workspaceFile.js +27 -0
  136. package/dist/llm/webFetch.d.ts +13 -1
  137. package/dist/llm/webFetch.js +91 -7
  138. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  139. package/dist/skills/builder/SkillBuilder.js +1 -1
  140. package/dist/ui/components/TextInput.js +1 -99
  141. package/dist/ui/inputBuffer.d.ts +28 -0
  142. package/dist/ui/inputBuffer.js +99 -0
  143. package/dist/utils/collections.d.ts +6 -0
  144. package/dist/utils/collections.js +9 -0
  145. package/dist/utils/path.d.ts +2 -0
  146. package/dist/utils/path.js +40 -0
  147. package/package.json +1 -2
@@ -1,4 +1,4 @@
1
- import { execFile as execFileCallback, spawn } from 'node:child_process';
1
+ import { execFile as execFileCallback } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
3
  import fs from 'node:fs/promises';
4
4
  import path from 'node:path';
@@ -6,345 +6,21 @@ import { tool } from 'ai';
6
6
  import { rgPath } from '@vscode/ripgrep';
7
7
  import { z } from 'zod';
8
8
  import { walkDir } from '../utils/fs.js';
9
- import { generateTaskId, saveTasks } from '../core/tasks/taskStorage.js';
10
- import { workspaceRoot, resolveWorkspacePath, workspaceRelativePath } from '../utils/path.js';
11
- import { classifyBashCommand, isValidationClassification } from '../core/safety/bashClassifier.js';
12
- import { parseValidationOutput } from '../core/validation/outputParser.js';
13
- import { filterBashOutput } from '../core/bashOutput/registry.js';
14
- import { readToolOutput as readStoredToolOutput, storeToolOutput } from '../core/agent/toolOutputStore.js';
15
- import { fetchUrlContent, BlockedUrlError } from './webFetch.js';
9
+ import { writeTasksTool } from './tools/taskTool.js';
10
+ import { readToolOutputTool } from './tools/storedOutputTool.js';
11
+ import { workspaceRoot } from '../utils/path.js';
12
+ import { storeToolOutput } from '../core/agent/toolOutputStore.js';
16
13
  import { reductionMetrics } from '../core/toolOutput/reduction.js';
17
- import { readScopedContextFilesForPath } from '../config/contextFiles.js';
18
- const MAX_OUTPUT_CHARS = 50_000;
19
- const DEFAULT_READ_LINES = 300;
20
- const COMPACT_COMMAND_CHARS = 12_000;
21
- const SHORT_VALIDATION_CHARS = 2_000;
22
- const GREP_MAX_OUTPUT_CHARS = 30_000;
23
- const GREP_MAX_LINE_CHARS = 500;
14
+ import { HazeToolError, structuredToolFailure } from './tools/failures.js';
15
+ import { compactGrepMatches, renderGrepMatches } from './tools/outputCap.js';
16
+ import { parseRipgrepJsonStream } from './tools/grepParse.js';
17
+ import { findEditRange, splitDiffLines, lineNumberAtOffset, replacementDiff } from './tools/editMatch.js';
18
+ import { runDedupedTool, discoverScopedContext, withScopedContext } from './tools/toolContext.js';
19
+ import { prepareWorkspaceExisting, prepareWorkspaceMutation, prepareWorkspaceRead, prepareWorkspaceWritePath } from './tools/workspaceFile.js';
20
+ import { fetchTool } from './tools/fetchTool.js';
21
+ import { bashTool } from './tools/bashTool.js';
22
+ import { DEFAULT_READ_LINES, INLINE_DIFF_LINE_LIMIT, isGitIgnored, MAX_OUTPUT_CHARS, sourceOutlineEntries } from './tools/fileToolShared.js';
24
23
  const execFile = promisify(execFileCallback);
25
- async function isGitIgnored(absolutePath) {
26
- const relative = workspaceRelativePath(absolutePath);
27
- if (relative === '.')
28
- return false;
29
- try {
30
- await execFile('git', ['-C', workspaceRoot(), 'check-ignore', '-q', '--', relative]);
31
- return true;
32
- }
33
- catch (error) {
34
- const status = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
35
- if (status === 1 || status === 128)
36
- return false;
37
- return false;
38
- }
39
- }
40
- class HazeToolError extends Error {
41
- reasonCode;
42
- recoveryTool;
43
- recoveryInput;
44
- constructor(message, reasonCode, options) {
45
- super(message);
46
- this.name = 'HazeToolError';
47
- this.reasonCode = reasonCode;
48
- this.recoveryTool = options?.recoveryTool;
49
- this.recoveryInput = options?.recoveryInput;
50
- }
51
- }
52
- async function assertNotIgnored(absolutePath, inputPath, allowIgnored) {
53
- if (!allowIgnored && await isGitIgnored(absolutePath)) {
54
- throw new HazeToolError(`Path is ignored by .gitignore: ${inputPath}. Set allowIgnored=true only if you explicitly need to access ignored files.`, 'ignored_path', { recoveryTool: 'listFiles' });
55
- }
56
- }
57
- function compactStoredOutput(text, maxChars = COMPACT_COMMAND_CHARS) {
58
- if (text.length <= maxChars)
59
- return { text, truncated: false };
60
- const handle = storeToolOutput(text);
61
- const headChars = Math.floor(maxChars * 0.4);
62
- const tailChars = maxChars - headChars;
63
- return {
64
- text: `${text.slice(0, headChars)}\n\n[... ${text.length - maxChars} characters omitted; use readToolOutput with handle ${handle} ...]\n\n${text.slice(-tailChars)}`,
65
- truncated: true,
66
- omittedChars: text.length - maxChars,
67
- handle,
68
- };
69
- }
70
- function compactLine(text, maxChars = GREP_MAX_LINE_CHARS) {
71
- if (text.length <= maxChars)
72
- return { text, truncated: false };
73
- return { text: `${text.slice(0, Math.max(0, maxChars - 22))}[line truncated]`, truncated: true };
74
- }
75
- function renderGrepMatches(matches) {
76
- return matches.map(match => `${match.file}:${match.line}:${match.isContext ? '-' : ''}${match.content}`).join('\n');
77
- }
78
- function compactGrepMatches(matches, maxChars = GREP_MAX_OUTPUT_CHARS) {
79
- const compacted = [];
80
- let lineTruncated = false;
81
- let omittedResultLines = 0;
82
- for (const match of matches) {
83
- const line = compactLine(match.content);
84
- lineTruncated = lineTruncated || line.truncated;
85
- const next = { ...match, content: line.text };
86
- const estimated = JSON.stringify([...compacted, next]).length;
87
- if (estimated > maxChars) {
88
- omittedResultLines = matches.length - compacted.length;
89
- break;
90
- }
91
- compacted.push(next);
92
- }
93
- return { matches: compacted, lineTruncated, omittedResultLines, outputTruncated: omittedResultLines > 0 || lineTruncated };
94
- }
95
- function stripLineNumberPrefixes(text) {
96
- return text.replace(/^\s*\d+\s+\| ?/gm, '');
97
- }
98
- function lineStartOffsets(text) {
99
- const offsets = [0];
100
- for (let index = 0; index < text.length; index++) {
101
- if (text[index] === '\n')
102
- offsets.push(index + 1);
103
- }
104
- return offsets;
105
- }
106
- function findLineTrimmedRange(original, oldText) {
107
- const wantedLines = oldText.replace(/\r\n/g, '\n').split('\n').map(line => line.trimEnd());
108
- if (wantedLines.at(-1) === '')
109
- wantedLines.pop();
110
- if (wantedLines.length === 0)
111
- return undefined;
112
- const originalLines = original.replace(/\r\n/g, '\n').split('\n');
113
- const hasTrailingNewline = original.endsWith('\n');
114
- if (hasTrailingNewline)
115
- originalLines.pop();
116
- const offsets = lineStartOffsets(original);
117
- const matches = [];
118
- for (let lineIndex = 0; lineIndex <= originalLines.length - wantedLines.length; lineIndex++) {
119
- const window = originalLines.slice(lineIndex, lineIndex + wantedLines.length).map(line => line.trimEnd());
120
- if (window.every((line, index) => line === wantedLines[index])) {
121
- const start = offsets[lineIndex] ?? 0;
122
- const endLineIndex = lineIndex + wantedLines.length;
123
- const end = endLineIndex < offsets.length ? (offsets[endLineIndex] ?? original.length) : original.length;
124
- matches.push({ start, end });
125
- }
126
- }
127
- if (matches.length !== 1)
128
- return undefined;
129
- return matches[0];
130
- }
131
- function findEditRange(original, oldText) {
132
- const candidates = [oldText, stripLineNumberPrefixes(oldText)].filter((candidate, index, all) => candidate.length > 0 && all.indexOf(candidate) === index);
133
- for (const candidate of candidates) {
134
- const first = original.indexOf(candidate);
135
- if (first !== -1) {
136
- const second = original.indexOf(candidate, first + candidate.length);
137
- if (second !== -1)
138
- return { kind: 'multiple' };
139
- return { kind: 'found', start: first, end: first + candidate.length, approximate: candidate !== oldText };
140
- }
141
- }
142
- for (const candidate of candidates) {
143
- const range = findLineTrimmedRange(original, candidate);
144
- if (range)
145
- return { kind: 'found', ...range, approximate: true };
146
- }
147
- return { kind: 'missing' };
148
- }
149
- function toolCallKey(toolName, input) {
150
- return `${toolName}:${JSON.stringify(input)}`;
151
- }
152
- function hazeContext(context) {
153
- return typeof context.experimental_context === 'object' && context.experimental_context != null
154
- ? context.experimental_context
155
- : undefined;
156
- }
157
- async function discoverScopedContext(filePath, context) {
158
- const ctx = hazeContext(context);
159
- const loaded = ctx?.loadedContextFilePaths ?? new Set();
160
- const files = await readScopedContextFilesForPath(filePath, { cwd: workspaceRoot(), alreadyLoadedPaths: loaded });
161
- if (ctx && !ctx.loadedContextFilePaths)
162
- ctx.loadedContextFilePaths = loaded;
163
- for (const file of files)
164
- loaded.add(file.path);
165
- return files;
166
- }
167
- function withScopedContext(result, files) {
168
- return files.length > 0 ? { ...result, applicableProjectInstructions: files } : result;
169
- }
170
- function scopedContextMutationStop(toolName, filePath, files) {
171
- if (files.length === 0)
172
- return undefined;
173
- return {
174
- ok: false,
175
- toolName,
176
- path: filePath,
177
- error: `Scoped project instructions apply to ${filePath}: ${files.map(file => file.path).join(', ')}. Review them before mutating this path.`,
178
- reasonCode: 'scoped_instructions_discovered',
179
- recoverable: true,
180
- suggestedNextStep: `Read the applicableProjectInstructions returned in this result, then retry ${toolName} only if the change follows those scoped instructions.`,
181
- applicableProjectInstructions: files,
182
- };
183
- }
184
- function isMutatingTool(toolName) {
185
- return ['editFile', 'replaceLines', 'writeFile'].includes(toolName);
186
- }
187
- function isReadOnlyFileTool(toolName) {
188
- return ['listFiles', 'readFile', 'grep'].includes(toolName);
189
- }
190
- function isDeduplicableReadOnlyTool(toolName) {
191
- // Read-only tools that participate in completed-call deduplication within a
192
- // turn (no side effects). File tools + bash + fetch; fetch has no path and is
193
- // network-side-effect-free for the agent's purposes.
194
- return isReadOnlyFileTool(toolName) || toolName === 'bash' || toolName === 'fetch';
195
- }
196
- function inputPath(input) {
197
- return typeof input === 'object' && input != null && 'path' in input && typeof input.path === 'string'
198
- ? input.path
199
- : undefined;
200
- }
201
- function isStructuredFailure(value) {
202
- return typeof value === 'object' && value != null && 'ok' in value && value.ok === false;
203
- }
204
- function structuredToolFailure(toolName, error, suggestedNextStep, pathForError, options) {
205
- const message = error instanceof Error ? error.message : String(error);
206
- const hazeError = error instanceof HazeToolError ? error : undefined;
207
- return {
208
- ok: false,
209
- toolName,
210
- path: pathForError,
211
- error: message,
212
- reasonCode: options?.reasonCode ?? hazeError?.reasonCode,
213
- recoverable: true,
214
- suggestedNextStep,
215
- recoveryTool: options?.recoveryTool ?? hazeError?.recoveryTool,
216
- recoveryInput: options?.recoveryInput ?? hazeError?.recoveryInput,
217
- };
218
- }
219
- const INLINE_DIFF_LINE_LIMIT = 20;
220
- const SOURCE_OUTLINE_PATTERNS = [
221
- /^\s*(?:import|from|export|package|namespace|module|using)\b/,
222
- /^\s*#\s*include\b/,
223
- /^\s*(?:public|private|protected|internal|static|async|final|open|sealed|abstract|export\s+)?\s*(?:class|interface|struct|enum|type|trait|record|protocol)\b/,
224
- /^\s*(?:export\s+)?(?:async\s+)?function\b/,
225
- /^\s*(?:def|func|fn)\s+[A-Za-z_]/,
226
- /^\s*(?:pub\s+)?(?:async\s+)?fn\s+[A-Za-z_]/,
227
- /^\s*(?:public|private|protected|internal|static|async|final|override|virtual|abstract)\s+[^=;{}]+\([^)]*\)\s*(?:\{|;|=>)?\s*$/,
228
- ];
229
- function sourceOutlineEntries(lines, startLine) {
230
- return lines
231
- .map((line, index) => ({ lineNumber: startLine + index, text: line }))
232
- .filter(entry => SOURCE_OUTLINE_PATTERNS.some(pattern => pattern.test(entry.text)));
233
- }
234
- function splitDiffLines(text) {
235
- const lines = text.split(/\r?\n/);
236
- if (text.endsWith('\n') || text.endsWith('\r\n'))
237
- lines.pop();
238
- return lines;
239
- }
240
- function lineNumberAtOffset(text, offset) {
241
- let line = 1;
242
- for (let index = 0; index < offset; index++) {
243
- if (text.charCodeAt(index) === 10)
244
- line += 1;
245
- }
246
- return line;
247
- }
248
- function replacementDiff(oldText, newText, oldStartLine, newStartLine, context) {
249
- const oldLines = splitDiffLines(oldText);
250
- const newLines = splitDiffLines(newText);
251
- const diff = [];
252
- if (context?.before)
253
- diff.push({ type: 'context', ...context.before });
254
- diff.push(...oldLines.map((text, index) => ({ type: 'remove', oldLine: oldStartLine + index, text })), ...newLines.map((text, index) => ({ type: 'add', newLine: newStartLine + index, text })));
255
- if (context?.after)
256
- diff.push({ type: 'context', ...context.after });
257
- return { diff, addedLines: newLines.length, removedLines: oldLines.length };
258
- }
259
- async function runDedupedTool(toolName, input, context, execute) {
260
- const ctx = hazeContext(context);
261
- if (!ctx)
262
- return execute();
263
- ctx.inFlightToolCalls ??= new Map();
264
- ctx.completedToolCalls ??= new Map();
265
- ctx.failedMutationPaths ??= new Set();
266
- ctx.failedMutationReasons ??= new Map();
267
- ctx.pathsReadAfterFailedMutation ??= new Set();
268
- ctx.inFlightMutationPaths ??= new Set();
269
- ctx.mutationEpoch ??= 0;
270
- const key = toolCallKey(toolName, input);
271
- const pathForInput = inputPath(input);
272
- if (isMutatingTool(toolName) && pathForInput && ctx.inFlightMutationPaths.has(pathForInput)) {
273
- return {
274
- ok: true,
275
- duplicateSkipped: true,
276
- toolName,
277
- 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.`,
278
- };
279
- }
280
- if (isMutatingTool(toolName) && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput)) {
281
- const reason = ctx.failedMutationReasons.get(pathForInput);
282
- throw new HazeToolError(`Read ${pathForInput} before attempting another edit after the previous edit failure${reason ? ` (${reason})` : ''}.`, reason ?? 'io_error', { recoveryTool: 'readFile', recoveryInput: { path: pathForInput } });
283
- }
284
- const completedAt = ctx.completedToolCalls.get(key);
285
- const readAfterFailedMutation = toolName === 'readFile' && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput);
286
- if ((isDeduplicableReadOnlyTool(toolName)) && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
287
- return {
288
- ok: true,
289
- duplicateSkipped: true,
290
- toolName,
291
- reason: toolName === 'bash'
292
- ? 'Skipped duplicate bash command; no files changed since the previous run.'
293
- : toolName === 'fetch'
294
- ? 'Skipped duplicate fetch with identical URL; no files changed since the previous call.'
295
- : 'Skipped duplicate read-only tool call with identical input; no files changed since the previous call.',
296
- };
297
- }
298
- if (ctx.inFlightToolCalls.has(key)) {
299
- return {
300
- ok: true,
301
- duplicateSkipped: true,
302
- toolName,
303
- reason: 'Skipped duplicate in-flight tool call with identical input.',
304
- };
305
- }
306
- if (isMutatingTool(toolName) && pathForInput)
307
- ctx.inFlightMutationPaths.add(pathForInput);
308
- const promise = execute();
309
- ctx.inFlightToolCalls.set(key, promise);
310
- try {
311
- const result = await promise;
312
- if (isStructuredFailure(result)) {
313
- if (isMutatingTool(toolName) && pathForInput) {
314
- ctx.failedMutationPaths.add(pathForInput);
315
- const reasonCode = typeof result === 'object' && result != null && 'reasonCode' in result ? result.reasonCode : undefined;
316
- ctx.failedMutationReasons.set(pathForInput, reasonCode);
317
- ctx.pathsReadAfterFailedMutation.delete(pathForInput);
318
- }
319
- return result;
320
- }
321
- if (toolName === 'readFile' && pathForInput)
322
- ctx.pathsReadAfterFailedMutation.add(pathForInput);
323
- if (isMutatingTool(toolName)) {
324
- ctx.mutationEpoch += 1;
325
- if (pathForInput) {
326
- ctx.failedMutationPaths.delete(pathForInput);
327
- ctx.failedMutationReasons.delete(pathForInput);
328
- ctx.pathsReadAfterFailedMutation.delete(pathForInput);
329
- }
330
- }
331
- ctx.completedToolCalls.set(key, ctx.mutationEpoch);
332
- return result;
333
- }
334
- catch (error) {
335
- if (isMutatingTool(toolName) && pathForInput) {
336
- ctx.failedMutationPaths.add(pathForInput);
337
- ctx.failedMutationReasons.set(pathForInput, error instanceof HazeToolError ? error.reasonCode : undefined);
338
- ctx.pathsReadAfterFailedMutation.delete(pathForInput);
339
- }
340
- throw error;
341
- }
342
- finally {
343
- ctx.inFlightToolCalls.delete(key);
344
- if (isMutatingTool(toolName) && pathForInput)
345
- ctx.inFlightMutationPaths?.delete(pathForInput);
346
- }
347
- }
348
24
  export const hazeTools = {
349
25
  listFiles: tool({
350
26
  description: 'List workspace files/directories with pagination. Prefer this to bash for discovery.',
@@ -358,8 +34,7 @@ export const hazeTools = {
358
34
  }),
359
35
  execute: async ({ path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context) => runDedupedTool('listFiles', { path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context, async () => {
360
36
  try {
361
- const absolutePath = resolveWorkspacePath(dirPath);
362
- await assertNotIgnored(absolutePath, dirPath, includeIgnored);
37
+ const absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored);
363
38
  const entries = [];
364
39
  let ignoredSkipped = 0;
365
40
  const walked = await walkDir(absolutePath, { recursive, maxEntries: maxEntries + 1, cursor, filter: async (entry) => {
@@ -404,8 +79,7 @@ export const hazeTools = {
404
79
  }),
405
80
  execute: async ({ path: filePath, offset, limit, mode, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, mode, allowIgnored }, context, async () => {
406
81
  try {
407
- const absolutePath = resolveWorkspacePath(filePath);
408
- await assertNotIgnored(absolutePath, filePath, allowIgnored);
82
+ const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored);
409
83
  const content = await fs.readFile(absolutePath, 'utf8');
410
84
  const lines = content.split(/\r?\n/);
411
85
  const start = offset == null ? 0 : offset - 1;
@@ -417,18 +91,24 @@ export const hazeTools = {
417
91
  const numberedLines = [];
418
92
  let includedLines = 0;
419
93
  let lineTruncated = false;
94
+ let outputChars = 0;
420
95
  for (const entry of displayLines) {
421
96
  const prefix = `${String(entry.lineNumber).padStart(4, ' ')} | `;
422
- const remaining = MAX_OUTPUT_CHARS - numberedLines.join('\n').length - (numberedLines.length > 0 ? 1 : 0);
97
+ const separatorChars = numberedLines.length > 0 ? 1 : 0;
98
+ const remaining = MAX_OUTPUT_CHARS - outputChars - separatorChars;
423
99
  if (remaining <= prefix.length)
424
100
  break;
425
101
  if (prefix.length + entry.text.length > remaining) {
426
- numberedLines.push(`${prefix}${entry.text.slice(0, Math.max(0, remaining - prefix.length - 26))}[line content truncated]`);
102
+ const line = `${prefix}${entry.text.slice(0, Math.max(0, remaining - prefix.length - 26))}[line content truncated]`;
103
+ numberedLines.push(line);
104
+ outputChars += separatorChars + line.length;
427
105
  includedLines += 1;
428
106
  lineTruncated = true;
429
107
  break;
430
108
  }
431
- numberedLines.push(`${prefix}${entry.text}`);
109
+ const line = `${prefix}${entry.text}`;
110
+ numberedLines.push(line);
111
+ outputChars += separatorChars + line.length;
432
112
  includedLines += 1;
433
113
  }
434
114
  const endLine = mode === 'outline'
@@ -468,7 +148,7 @@ export const hazeTools = {
468
148
  }),
469
149
  execute: async ({ pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context) => runDedupedTool('grep', { pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context, async () => {
470
150
  try {
471
- const absolutePath = resolveWorkspacePath(searchPath);
151
+ const absolutePath = await prepareWorkspaceExisting(searchPath);
472
152
  const args = [
473
153
  '--json', '--color=never',
474
154
  '--max-count', String(maxMatches),
@@ -497,56 +177,11 @@ export const hazeTools = {
497
177
  if (!stdout) {
498
178
  return withScopedContext({ pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches: [], totalMatches: 0, truncated: false }, scopedContext);
499
179
  }
500
- const lines = stdout.split('\n').filter(Boolean);
501
- const matches = [];
502
- let totalMatches = 0;
503
- let returnedMatches = 0;
504
- let omittedMatches = 0;
505
- let pendingContext = [];
506
- let retainFollowingContext = false;
507
- for (const line of lines) {
508
- let event;
509
- try {
510
- event = JSON.parse(line);
511
- }
512
- catch {
513
- continue;
514
- }
515
- if (event.type === 'begin' || event.type === 'end') {
516
- pendingContext = [];
517
- retainFollowingContext = false;
518
- continue;
519
- }
520
- if (event.type !== 'match' && event.type !== 'context')
521
- continue;
522
- const file = event.data?.path?.text;
523
- const lineNumber = event.data?.line_number;
524
- const content = event.data?.lines?.text?.replace(/\r?\n$/, '');
525
- if (!file || lineNumber == null || content == null)
526
- continue;
527
- const item = { file: path.relative(workspaceRoot(), file), line: lineNumber, content };
528
- if (event.type === 'context') {
529
- if (retainFollowingContext) {
530
- matches.push({ ...item, isContext: true });
531
- continue;
532
- }
533
- pendingContext.push({ ...item, isContext: true });
534
- if (pendingContext.length > contextLines)
535
- pendingContext.shift();
536
- continue;
537
- }
538
- totalMatches += 1;
539
- if (returnedMatches >= maxMatches) {
540
- omittedMatches += 1;
541
- pendingContext = [];
542
- retainFollowingContext = false;
543
- continue;
544
- }
545
- matches.push(...pendingContext, { ...item, isContext: false });
546
- returnedMatches += 1;
547
- pendingContext = [];
548
- retainFollowingContext = true;
549
- }
180
+ const parsed = parseRipgrepJsonStream(stdout, maxMatches, contextLines, absolute => path.relative(workspaceRoot(), absolute));
181
+ const matches = parsed.matches;
182
+ const totalMatches = parsed.totalMatches;
183
+ const returnedMatches = parsed.returnedMatches;
184
+ const omittedMatches = parsed.omittedMatches;
550
185
  const compacted = compactGrepMatches(matches);
551
186
  const outputTruncated = compacted.outputTruncated;
552
187
  const rawRenderedMatches = renderGrepMatches(matches);
@@ -590,10 +225,7 @@ export const hazeTools = {
590
225
  }),
591
226
  execute: async ({ path: filePath, startLine, endLine, content, allowIgnored }, context) => runDedupedTool('replaceLines', { path: filePath, startLine, endLine, content, allowIgnored }, context, async () => {
592
227
  try {
593
- const absolutePath = resolveWorkspacePath(filePath);
594
- await assertNotIgnored(absolutePath, filePath, allowIgnored);
595
- const scopedContext = await discoverScopedContext(filePath, context);
596
- const scopedStop = scopedContextMutationStop('replaceLines', filePath, scopedContext);
228
+ const { absolutePath, scopedStop } = await prepareWorkspaceMutation('replaceLines', filePath, allowIgnored, context);
597
229
  if (scopedStop)
598
230
  return scopedStop;
599
231
  const original = await fs.readFile(absolutePath, 'utf8');
@@ -640,14 +272,12 @@ export const hazeTools = {
640
272
  }),
641
273
  execute: async ({ path: filePath, content, overwriteExisting, allowIgnored }, context) => runDedupedTool('writeFile', { path: filePath, content, overwriteExisting, allowIgnored }, context, async () => {
642
274
  try {
643
- const absolutePath = resolveWorkspacePath(filePath);
644
- await assertNotIgnored(absolutePath, filePath, allowIgnored);
645
- const scopedContext = await discoverScopedContext(filePath, context);
646
- const scopedStop = scopedContextMutationStop('writeFile', filePath, scopedContext);
275
+ const { absolutePath, scopedStop, assertExistingInsideWorkspace, assertWritableInsideWorkspace } = await prepareWorkspaceWritePath('writeFile', filePath, allowIgnored, context);
647
276
  if (scopedStop)
648
277
  return scopedStop;
649
278
  try {
650
279
  await fs.access(absolutePath);
280
+ await assertExistingInsideWorkspace();
651
281
  if (!overwriteExisting) {
652
282
  throw new HazeToolError(`Refusing to overwrite existing file: ${filePath}. Use editFile/replaceLines for targeted edits, or set overwriteExisting=true for an intentional complete rewrite.`, 'existing_file_requires_overwrite', { recoveryTool: 'readFile', recoveryInput: { path: filePath } });
653
283
  }
@@ -656,6 +286,7 @@ export const hazeTools = {
656
286
  const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
657
287
  if (code !== 'ENOENT')
658
288
  throw error;
289
+ await assertWritableInsideWorkspace();
659
290
  }
660
291
  await fs.mkdir(path.dirname(absolutePath), { recursive: true });
661
292
  await fs.writeFile(absolutePath, content, 'utf8');
@@ -678,10 +309,7 @@ export const hazeTools = {
678
309
  }),
679
310
  execute: async ({ path: filePath, edits, allowIgnored }, context) => runDedupedTool('editFile', { path: filePath, edits, allowIgnored }, context, async () => {
680
311
  try {
681
- const absolutePath = resolveWorkspacePath(filePath);
682
- await assertNotIgnored(absolutePath, filePath, allowIgnored);
683
- const scopedContext = await discoverScopedContext(filePath, context);
684
- const scopedStop = scopedContextMutationStop('editFile', filePath, scopedContext);
312
+ const { absolutePath, scopedStop } = await prepareWorkspaceMutation('editFile', filePath, allowIgnored, context);
685
313
  if (scopedStop)
686
314
  return scopedStop;
687
315
  const original = await fs.readFile(absolutePath, 'utf8');
@@ -732,163 +360,8 @@ export const hazeTools = {
732
360
  }
733
361
  }),
734
362
  }),
735
- writeTasks: tool({
736
- description: 'Replace the task list for substantial work. Update at meaningful phase changes, blockers, and completion; pass the complete list.',
737
- inputSchema: z.object({
738
- tasks: z.array(z.object({
739
- title: z.string().max(200).describe('Short task description'),
740
- status: z.enum(['pending', 'in_progress', 'completed']).optional().describe('Task status (defaults to pending)'),
741
- })).describe('Complete task list. Replaces any existing tasks. Pass an empty array to clear.'),
742
- }),
743
- execute: async ({ tasks: inputTasks }) => {
744
- if (!Array.isArray(inputTasks)) {
745
- return { ok: false, error: 'Tasks must be an array. Pass an empty array to clear the list.' };
746
- }
747
- for (let i = 0; i < inputTasks.length; i++) {
748
- const title = inputTasks[i]?.title?.trim();
749
- if (!title)
750
- return { ok: false, error: `Task ${i + 1}: title cannot be empty.` };
751
- if (title.length > 200)
752
- return { ok: false, error: `Task ${i + 1}: title is too long (max 200 characters).` };
753
- }
754
- const now = new Date().toISOString();
755
- const tasks = inputTasks.map((input) => ({
756
- id: generateTaskId(),
757
- title: input.title.trim(),
758
- status: input.status ?? 'pending',
759
- createdAt: now,
760
- updatedAt: now,
761
- }));
762
- await saveTasks(tasks);
763
- if (tasks.length === 0)
764
- return { ok: true, taskCount: 0, summary: 'Task list cleared.' };
765
- const counts = {
766
- pending: tasks.filter(t => t.status === 'pending').length,
767
- in_progress: tasks.filter(t => t.status === 'in_progress').length,
768
- completed: tasks.filter(t => t.status === 'completed').length,
769
- };
770
- return { ok: true, taskCount: tasks.length, counts, summary: `Tasks: ${counts.pending} pending, ${counts.in_progress} in progress, ${counts.completed} completed.` };
771
- },
772
- }),
773
- readToolOutput: tool({
774
- description: 'Read another page of oversized output previously returned by a tool handle.',
775
- inputSchema: z.object({
776
- handle: z.string().min(1).describe('Output handle from a prior tool result'),
777
- offset: z.number().int().nonnegative().default(0).describe('Character offset to start reading'),
778
- limit: z.number().int().positive().max(20_000).default(12_000).describe('Maximum characters to return'),
779
- query: z.string().optional().describe('Optional case-insensitive substring search within the stored output instead of reading by offset'),
780
- contextLines: z.number().int().nonnegative().max(20).default(2).describe('Lines of context around query matches'),
781
- }),
782
- execute: async ({ handle, offset, limit, query, contextLines }) => {
783
- const page = readStoredToolOutput(handle, offset, limit, { query, contextLines });
784
- return page ?? { ok: false, error: `Unknown or expired tool output handle: ${handle}` };
785
- },
786
- }),
787
- fetch: tool({
788
- description: 'Fetch a public http(s) URL and return readable content. Use for current docs, API references, error lookups, or CI logs. Private/loopback/metadata hosts are blocked.',
789
- inputSchema: z.object({
790
- url: z.string().url().describe('Absolute http(s) URL to fetch'),
791
- format: z.enum(['auto', 'text']).default('auto').describe('auto = markdown for HTML, pretty for JSON, passthrough for text; text = raw text only'),
792
- }),
793
- execute: async ({ url, format }, context) => runDedupedTool('fetch', { url, format }, context, async () => {
794
- try {
795
- const result = await fetchUrlContent(url, { signal: context.abortSignal, format });
796
- const capped = compactStoredOutput(result.content, MAX_OUTPUT_CHARS);
797
- const extractionMethod = format === 'text' ? 'text' : result.extractionMethod;
798
- const fetchMetrics = reductionMetrics(result.content, capped.text);
799
- return {
800
- ok: true,
801
- url: result.url,
802
- status: result.status,
803
- statusText: result.statusText,
804
- contentType: result.contentType,
805
- bytes: result.bytes,
806
- redirected: result.redirected,
807
- extractionMethod,
808
- truncated: capped.truncated,
809
- content: capped.text,
810
- reducerName: extractionMethod === 'markdown' ? 'web-html-extract' : 'web-content-cap',
811
- contentKind: 'web',
812
- lossy: capped.truncated || extractionMethod === 'markdown',
813
- parseTier: 'full',
814
- ...fetchMetrics,
815
- ...(capped.handle ? { handle: capped.handle, rawHandle: capped.handle, omittedChars: capped.omittedChars } : { omittedChars: 0 }),
816
- };
817
- }
818
- catch (error) {
819
- const reasonCode = error instanceof BlockedUrlError ? 'blocked_url' : undefined;
820
- return structuredToolFailure('fetch', error, 'Check the URL is correct and public. Private/localhost/metadata hosts and non-http(s) schemes are blocked.', url, { reasonCode });
821
- }
822
- }),
823
- }),
824
- bash: tool({
825
- description: 'Run workspace tests, builds, validation, or inspection. Use file tools for edits.',
826
- inputSchema: z.object({
827
- command: z.string().min(1).describe('Command to execute with bash -lc'),
828
- timeoutSeconds: z.number().int().positive().max(600).optional().describe('Timeout in seconds; defaults to 60'),
829
- allowMutation: z.boolean().default(false).describe('Deprecated compatibility flag. Commands run without confirmation; retained for compatibility.'),
830
- }),
831
- execute: async ({ command, timeoutSeconds, allowMutation }, context) => runDedupedTool('bash', { command, timeoutSeconds, allowMutation }, context, async () => {
832
- const cwd = workspaceRoot();
833
- const classification = classifyBashCommand(command);
834
- const timeoutMs = (timeoutSeconds ?? 60) * 1000;
835
- const startedAt = Date.now();
836
- return await new Promise(resolve => {
837
- const child = spawn('bash', ['-lc', command], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
838
- let stdout = '';
839
- let stderr = '';
840
- let settled = false;
841
- let timedOut = false;
842
- const timer = setTimeout(() => {
843
- if (!settled) {
844
- timedOut = true;
845
- child.kill('SIGTERM');
846
- }
847
- }, timeoutMs);
848
- const abort = () => child.kill('SIGTERM');
849
- context.abortSignal?.addEventListener('abort', abort, { once: true });
850
- child.stdout.on('data', data => stdout += data.toString());
851
- child.stderr.on('data', data => stderr += data.toString());
852
- child.on('close', code => {
853
- settled = true;
854
- clearTimeout(timer);
855
- context.abortSignal?.removeEventListener('abort', abort);
856
- const validationSummary = isValidationClassification(classification)
857
- ? parseValidationOutput({ command, code, stdout, stderr, timedOut, stdoutTruncated: stdout.length > COMPACT_COMMAND_CHARS, stderrTruncated: stderr.length > COMPACT_COMMAND_CHARS, classification })
858
- : undefined;
859
- const validationPassed = validationSummary?.status === 'passed';
860
- const output = filterBashOutput({
861
- command,
862
- code,
863
- stdout,
864
- stderr,
865
- timedOut,
866
- classification,
867
- validationSummary,
868
- storeRawOutput: storeToolOutput,
869
- fallbackCompact: compactStoredOutput,
870
- compactMaxChars: validationPassed ? SHORT_VALIDATION_CHARS : COMPACT_COMMAND_CHARS,
871
- });
872
- resolve({
873
- ok: code === 0 && !timedOut,
874
- code,
875
- command,
876
- cwd,
877
- classification,
878
- durationMs: Date.now() - startedAt,
879
- timedOut,
880
- stdout: output.stdout,
881
- stderr: output.stderr,
882
- validationSummary,
883
- });
884
- });
885
- child.on('error', error => {
886
- settled = true;
887
- clearTimeout(timer);
888
- context.abortSignal?.removeEventListener('abort', abort);
889
- resolve({ ok: false, command, cwd, classification, durationMs: Date.now() - startedAt, error: error.message });
890
- });
891
- });
892
- }),
893
- }),
363
+ writeTasks: writeTasksTool,
364
+ readToolOutput: readToolOutputTool,
365
+ fetch: fetchTool,
366
+ bash: bashTool,
894
367
  };