@denizokcu/haze 1.4.0 → 1.5.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.
- package/CHANGELOG.md +33 -1
- package/README.md +13 -8
- package/SECURITY.md +1 -1
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/BusyBar.d.ts +7 -0
- package/dist/cli/chat/BusyBar.js +8 -0
- package/dist/cli/chat/DynamicFrame.d.ts +37 -0
- package/dist/cli/chat/DynamicFrame.js +43 -0
- package/dist/cli/chat/busyIndicator.d.ts +3 -1
- package/dist/cli/chat/busyIndicator.js +11 -9
- package/dist/cli/chat/chatMetrics.d.ts +1 -1
- package/dist/cli/chat/chatMetrics.js +3 -3
- package/dist/cli/chat/inputSuggestions.js +2 -1
- package/dist/cli/chat/liveRegion.js +1 -1
- package/dist/cli/chat/messages.js +27 -16
- package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
- package/dist/cli/chat/sessionLifecycle.js +13 -2
- package/dist/cli/chat/sessionRecorder.d.ts +2 -1
- package/dist/cli/chat/sessionRecorder.js +8 -0
- package/dist/cli/chat/shutdown.d.ts +27 -0
- package/dist/cli/chat/shutdown.js +79 -0
- package/dist/cli/chat/terminalControl.d.ts +45 -0
- package/dist/cli/chat/terminalControl.js +107 -0
- package/dist/cli/chat/tips.js +1 -0
- package/dist/cli/chat/userInput.d.ts +43 -0
- package/dist/cli/chat/userInput.js +63 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +14 -6
- package/dist/cli/chat/wizard/types.d.ts +8 -1
- package/dist/cli/chat/wizardDispatch.js +1 -1
- package/dist/cli/commands/chat.js +251 -172
- package/dist/cli/commands/commandHelp.js +6 -2
- package/dist/cli/commands/commands.d.ts +8 -0
- package/dist/cli/commands/commands.js +11 -0
- package/dist/cli/commands/formatters.d.ts +1 -1
- package/dist/cli/commands/formatters.js +20 -2
- package/dist/cli/commands/logsCommand.js +21 -2
- package/dist/cli/commands/reasoningCommand.d.ts +23 -14
- package/dist/cli/commands/reasoningCommand.js +53 -20
- package/dist/cli/commands/runCommand.js +19 -11
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
- package/dist/cli/commands/streaming/attemptOutcome.js +11 -6
- package/dist/cli/commands/streaming/attemptSetup.d.ts +1 -0
- package/dist/cli/commands/streaming/attemptSetup.js +11 -5
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +8 -1
- package/dist/cli/commands/streaming/goalCheckpoint.js +3 -2
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +4 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +43 -7
- package/dist/cli/commands/streaming/prepareStep.js +7 -3
- package/dist/cli/commands/streaming/streamLoop.d.ts +5 -0
- package/dist/cli/commands/streaming/streamLoop.js +3 -0
- package/dist/cli/commands/streaming/toolPartHandlers.js +6 -0
- package/dist/cli/commands/streaming.d.ts +1 -1
- package/dist/cli/commands/streaming.js +23 -17
- package/dist/cli/commands/wizardFlow.d.ts +5 -2
- package/dist/cli/commands/wizardFlow.js +17 -10
- package/dist/cli/index.js +17 -1
- package/dist/config/contextFiles.d.ts +9 -0
- package/dist/config/contextFiles.js +21 -1
- package/dist/config/modelCatalog.d.ts +3 -0
- package/dist/config/modelCatalog.js +29 -0
- package/dist/config/providerPresets.d.ts +1 -1
- package/dist/config/providerPresets.js +42 -3
- package/dist/config/settings.d.ts +7 -3
- package/dist/config/settings.js +8 -0
- package/dist/core/agent/budgets.d.ts +13 -15
- package/dist/core/agent/budgets.js +15 -17
- package/dist/core/agent/completionController.d.ts +6 -2
- package/dist/core/agent/completionController.js +16 -3
- package/dist/core/agent/goalPolicy.d.ts +10 -0
- package/dist/core/agent/goalPolicy.js +44 -6
- package/dist/core/agent/projectPreflight.d.ts +2 -0
- package/dist/core/agent/projectPreflight.js +56 -0
- package/dist/core/agent/reasoningPolicy.d.ts +34 -4
- package/dist/core/agent/reasoningPolicy.js +27 -4
- package/dist/core/agent/workState.d.ts +8 -0
- package/dist/core/agent/workState.js +191 -8
- package/dist/core/providerContracts.d.ts +29 -0
- package/dist/core/providerContracts.js +1 -0
- package/dist/core/session/sessionReport.d.ts +33 -0
- package/dist/core/session/sessionReport.js +121 -0
- package/dist/core/session/sessionSlimming.js +9 -3
- package/dist/core/session/sessionStore.d.ts +12 -0
- package/dist/core/session/sessionStore.js +20 -4
- package/dist/core/subagent/contracts.d.ts +3 -25
- package/dist/core/subagent/executionProfiles.js +4 -4
- package/dist/core/validation/outputParser.d.ts +6 -1
- package/dist/core/validation/outputParser.js +6 -2
- package/dist/llm/client.d.ts +4 -2
- package/dist/llm/client.js +17 -10
- package/dist/llm/hazeTools.d.ts +8553 -8550
- package/dist/llm/hazeTools.js +6 -503
- package/dist/llm/lspTools.d.ts +120 -120
- package/dist/llm/mcp.js +3 -0
- package/dist/llm/requestContext.d.ts +1 -1
- package/dist/llm/requestContext.js +1 -1
- package/dist/{core/subagent → llm}/subagentRunner.d.ts +9 -9
- package/dist/{core/subagent → llm}/subagentRunner.js +22 -25
- package/dist/llm/systemPrompt.d.ts +11 -1
- package/dist/llm/systemPrompt.js +2 -11
- package/dist/llm/tools/fetchTool.d.ts +30 -30
- package/dist/llm/tools/fileTools.d.ts +7768 -0
- package/dist/llm/tools/fileTools.js +510 -0
- package/dist/llm/tools/processTool.d.ts +30 -30
- package/dist/llm/tools/shellTool.d.ts +30 -30
- package/dist/llm/tools/shellTool.js +8 -4
- package/dist/llm/tools/toolContext.d.ts +3 -32
- package/dist/llm/tools/toolContext.js +33 -52
- package/dist/llm/tools/toolContextState.d.ts +40 -0
- package/dist/llm/tools/toolContextState.js +34 -0
- package/dist/llm/workerContext.d.ts +7 -0
- package/dist/llm/workerContext.js +18 -1
- package/dist/skills/SkillLoader.js +3 -3
- package/dist/skills/SkillRegistry.js +3 -3
- package/dist/skills/builder/SkillBuilder.js +3 -3
- package/dist/skills/confinement.d.ts +7 -0
- package/dist/skills/confinement.js +15 -0
- package/dist/ui/codeHighlight.js +4 -4
- package/dist/ui/components/MarkdownText.js +7 -8
- package/dist/ui/components/NativeIndicators.d.ts +15 -0
- package/dist/ui/components/NativeIndicators.js +32 -0
- package/dist/ui/components/StreamingMarkdownText.d.ts +9 -0
- package/dist/ui/components/StreamingMarkdownText.js +38 -0
- package/dist/ui/components/TextInput.d.ts +7 -2
- package/dist/ui/components/TextInput.js +103 -46
- package/dist/ui/components/WizardChoices.d.ts +18 -0
- package/dist/ui/components/WizardChoices.js +32 -0
- package/dist/ui/inputBuffer.js +12 -6
- package/dist/ui/textGeometry.d.ts +14 -0
- package/dist/ui/textGeometry.js +31 -0
- package/package.json +14 -13
- /package/dist/cli/{contextReport.d.ts → contextReportCli.d.ts} +0 -0
- /package/dist/cli/{contextReport.js → contextReportCli.js} +0 -0
package/dist/llm/hazeTools.js
CHANGED
|
@@ -1,512 +1,15 @@
|
|
|
1
|
-
import fs from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { tool } from 'ai';
|
|
4
|
-
import { rgPath } from '@vscode/ripgrep';
|
|
5
|
-
import { z } from 'zod';
|
|
6
|
-
import { walkDir } from '../utils/fs.js';
|
|
7
1
|
import { writeTasksTool } from './tools/taskTool.js';
|
|
8
2
|
import { readToolOutputTool } from './tools/storedOutputTool.js';
|
|
9
|
-
import {
|
|
10
|
-
import { storeToolOutput } from '../core/agent/toolOutputStore.js';
|
|
11
|
-
import { reductionMetrics } from '../core/toolOutput/reduction.js';
|
|
12
|
-
import { HazeToolError, structuredToolFailure } from './tools/failures.js';
|
|
13
|
-
import { compactGrepMatches, renderGrepMatches } from './tools/outputCap.js';
|
|
14
|
-
import { parseRipgrepJsonStream } from './tools/grepParse.js';
|
|
15
|
-
import { boundedDiff, fileDiff, findEditRange, splitDiffLines, lineNumberAtOffset, renderToolDiff, replacementDiff } from './tools/editMatch.js';
|
|
16
|
-
import { runDedupedTool, discoverScopedContext, withScopedContext, hazeToolContextSchema } from './tools/toolContext.js';
|
|
17
|
-
import { prepareWorkspaceMutation, prepareWorkspaceRead, prepareWorkspaceWritePath } from './tools/workspaceFile.js';
|
|
3
|
+
import { fileTools } from './tools/fileTools.js';
|
|
18
4
|
import { fetchTool } from './tools/fetchTool.js';
|
|
19
5
|
import { shellTool } from './tools/shellTool.js';
|
|
20
6
|
import { processTool } from './tools/processTool.js';
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
import { EXACT_MUTATION_BYTES } from '../core/limits.js';
|
|
26
|
-
import { WRITE_FILE_CHUNK_BYTES } from '../core/agent/budgets.js';
|
|
27
|
-
import { readUtf8LinesPage, readUtf8Prefix } from '../core/io/boundedRead.js';
|
|
28
|
-
import { assertReadableTextFile, readFailureRecovery } from './tools/readRecovery.js';
|
|
29
|
-
import { replaceInFiles } from './tools/replaceInFiles.js';
|
|
30
|
-
function mutationDiffFields(filePath, fullDiff) {
|
|
31
|
-
const preview = boundedDiff(fullDiff, INLINE_DIFF_LINE_LIMIT);
|
|
32
|
-
const diffHandle = preview.truncated ? storeToolOutput(renderToolDiff(filePath, fullDiff)) : undefined;
|
|
33
|
-
return {
|
|
34
|
-
diffLineCount: fullDiff.length,
|
|
35
|
-
diff: preview.diff,
|
|
36
|
-
diffTruncated: preview.truncated,
|
|
37
|
-
diffOmittedLines: preview.omittedLines,
|
|
38
|
-
...(diffHandle ? { diffHandle } : {}),
|
|
39
|
-
};
|
|
40
|
-
}
|
|
7
|
+
/**
|
|
8
|
+
* The public built-in tool catalog. Implementations live in `tools/`
|
|
9
|
+
* (`fileTools.ts` holds the workspace file tools); this file only composes.
|
|
10
|
+
*/
|
|
41
11
|
export const hazeTools = {
|
|
42
|
-
|
|
43
|
-
description: 'List workspace files/directories with pagination. Prefer this to shell for discovery.',
|
|
44
|
-
contextSchema: hazeToolContextSchema,
|
|
45
|
-
inputSchema: z.object({
|
|
46
|
-
path: z.string().default('.').describe('Directory path relative to the current workspace'),
|
|
47
|
-
recursive: z.boolean().default(false).describe('Whether to list files recursively'),
|
|
48
|
-
maxEntries: z.number().int().positive().max(500).default(100).describe('Maximum number of entries to return'),
|
|
49
|
-
cursor: z.string().optional().describe('Pagination cursor from a previous listFiles result. Continue after that entry.'),
|
|
50
|
-
includeIgnored: z.boolean().default(false).describe('Include .gitignored paths only when needed'),
|
|
51
|
-
includeSizes: z.boolean().default(false).describe('Include file byte sizes only when needed; omitted by default for compact output'),
|
|
52
|
-
}),
|
|
53
|
-
execute: async ({ path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context) => runDedupedTool('listFiles', { path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context, async () => {
|
|
54
|
-
try {
|
|
55
|
-
let absolutePath;
|
|
56
|
-
try {
|
|
57
|
-
absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored, context);
|
|
58
|
-
}
|
|
59
|
-
catch (error) {
|
|
60
|
-
// RT-06: an out-of-workspace path must refuse honestly instead of
|
|
61
|
-
// returning a success-shaped empty listing, which the model reads as
|
|
62
|
-
// "directory is empty" and can report as a false fact. Reuse the
|
|
63
|
-
// shared structured failure shape (readFile/grep already do).
|
|
64
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
65
|
-
if (message.includes('outside the workspace')) {
|
|
66
|
-
return { ok: false, toolName: 'listFiles', path: dirPath, error: message, reasonCode: 'outside_workspace', recoverable: true, suggestedNextStep: 'Use a workspace-relative path, or ask the user to mention the outside path explicitly so it can be read directly.' };
|
|
67
|
-
}
|
|
68
|
-
throw error;
|
|
69
|
-
}
|
|
70
|
-
const entries = [];
|
|
71
|
-
let ignoredSkipped = 0;
|
|
72
|
-
// One persistent classifier owns the whole listing so rule files are
|
|
73
|
-
// cached across directory frontiers. Walk entries include absolute paths,
|
|
74
|
-
// allowing subtree listings to classify workspace-relative identities.
|
|
75
|
-
const ignoreClassifier = includeIgnored ? undefined : createIgnoreClassifier(workspaceRoot());
|
|
76
|
-
const ignoreBatch = ignoreClassifier ? (entries) => ignoreClassifier.classify(entries).then(ignored => {
|
|
77
|
-
ignoredSkipped += ignored.size;
|
|
78
|
-
return ignored;
|
|
79
|
-
}) : undefined;
|
|
80
|
-
const walked = await walkDir(absolutePath, { recursive, maxEntries: maxEntries + 1, cursor, ignoreBatch });
|
|
81
|
-
const page = walked.slice(0, maxEntries);
|
|
82
|
-
const hasMore = walked.length > maxEntries;
|
|
83
|
-
for (const entry of page) {
|
|
84
|
-
if (entry.isDirectory) {
|
|
85
|
-
entries.push(`${entry.path}/`);
|
|
86
|
-
}
|
|
87
|
-
else if (entry.isFile) {
|
|
88
|
-
if (includeSizes) {
|
|
89
|
-
const stat = await fs.stat(entry.absolutePath);
|
|
90
|
-
entries.push(`${entry.path} (${stat.size} bytes)`);
|
|
91
|
-
}
|
|
92
|
-
else {
|
|
93
|
-
entries.push(entry.path);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
const scopedContext = await discoverScopedContext(dirPath, context);
|
|
98
|
-
return withScopedContext({ path: dirPath, recursive, includeIgnored, includeSizes, cursor, nextCursor: hasMore ? page.at(-1)?.path : undefined, ignoredSkipped, entryFormat: includeSizes ? 'directories end with /; files may include byte size in parentheses' : 'directories end with /', entries, truncated: hasMore }, scopedContext);
|
|
99
|
-
}
|
|
100
|
-
catch (error) {
|
|
101
|
-
return structuredToolFailure('listFiles', error, 'Check that the directory exists and is not ignored, or retry with a narrower path.', dirPath);
|
|
102
|
-
}
|
|
103
|
-
}),
|
|
104
|
-
}),
|
|
105
|
-
readFile: tool({
|
|
106
|
-
description: 'Read numbered lines from a UTF-8 workspace file. Defaults to exact mode; outline mode is for discovery only and must be followed by exact reads before editing.',
|
|
107
|
-
contextSchema: hazeToolContextSchema,
|
|
108
|
-
inputSchema: z.object({
|
|
109
|
-
path: z.string().describe('File path relative to the current workspace'),
|
|
110
|
-
offset: z.number().int().positive().optional().describe('1-based line number to start reading from'),
|
|
111
|
-
limit: z.number().int().positive().max(2000).optional().describe('Maximum lines to return; defaults to 300'),
|
|
112
|
-
mode: z.enum(['exact', 'outline']).default('exact').describe('exact returns source lines; outline returns imports/includes and top-level declarations for discovery only'),
|
|
113
|
-
allowIgnored: z.boolean().default(false).describe('Read a .gitignored file only when needed'),
|
|
114
|
-
}),
|
|
115
|
-
execute: async ({ path: filePath, offset, limit, mode, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, mode, allowIgnored }, context, async () => {
|
|
116
|
-
try {
|
|
117
|
-
const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored, context);
|
|
118
|
-
await assertReadableTextFile(absolutePath, filePath);
|
|
119
|
-
const start = offset == null ? 0 : offset - 1;
|
|
120
|
-
const pageLimit = limit ?? DEFAULT_READ_LINES;
|
|
121
|
-
const page = await readUtf8LinesPage(absolutePath, start + 1, pageLimit);
|
|
122
|
-
if (offset != null && offset > page.totalLines) {
|
|
123
|
-
throw new HazeToolError(`offset ${offset} is beyond end of file (${page.totalLines} lines)`, 'invalid_line_range', { recoveryTool: 'readFile', recoveryInput: { path: filePath, offset: Math.max(1, page.totalLines) } });
|
|
124
|
-
}
|
|
125
|
-
const lines = page.lines;
|
|
126
|
-
const totalLines = page.totalLines;
|
|
127
|
-
const requestedEnd = Math.min(totalLines, start + pageLimit);
|
|
128
|
-
const selectedLines = lines;
|
|
129
|
-
const outlineEntries = mode === 'outline' ? sourceOutlineEntries(selectedLines, start + 1) : undefined;
|
|
130
|
-
const displayLines = outlineEntries?.map(entry => ({ lineNumber: entry.lineNumber, text: entry.text }))
|
|
131
|
-
?? selectedLines.map((line, index) => ({ lineNumber: start + index + 1, text: line }));
|
|
132
|
-
const numberedLines = [];
|
|
133
|
-
let includedLines = 0;
|
|
134
|
-
let lineTruncated = false;
|
|
135
|
-
let outputChars = 0;
|
|
136
|
-
for (const entry of displayLines) {
|
|
137
|
-
const prefix = `${String(entry.lineNumber).padStart(4, ' ')} | `;
|
|
138
|
-
const separatorChars = numberedLines.length > 0 ? 1 : 0;
|
|
139
|
-
const remaining = MAX_OUTPUT_CHARS - outputChars - separatorChars;
|
|
140
|
-
if (remaining <= prefix.length)
|
|
141
|
-
break;
|
|
142
|
-
if (prefix.length + entry.text.length > remaining) {
|
|
143
|
-
const line = `${prefix}${entry.text.slice(0, Math.max(0, remaining - prefix.length - 26))}[line content truncated]`;
|
|
144
|
-
numberedLines.push(line);
|
|
145
|
-
outputChars += separatorChars + line.length;
|
|
146
|
-
includedLines += 1;
|
|
147
|
-
lineTruncated = true;
|
|
148
|
-
break;
|
|
149
|
-
}
|
|
150
|
-
const line = `${prefix}${entry.text}`;
|
|
151
|
-
numberedLines.push(line);
|
|
152
|
-
outputChars += separatorChars + line.length;
|
|
153
|
-
includedLines += 1;
|
|
154
|
-
}
|
|
155
|
-
const endLine = mode === 'outline'
|
|
156
|
-
? displayLines[Math.max(0, includedLines - 1)]?.lineNumber ?? start + 1
|
|
157
|
-
: start + includedLines;
|
|
158
|
-
const outlineDroppedEntries = mode === 'outline' ? displayLines.length - includedLines : 0;
|
|
159
|
-
const hasMore = mode === 'outline'
|
|
160
|
-
? requestedEnd < totalLines || outlineDroppedEntries > 0
|
|
161
|
-
: endLine < totalLines;
|
|
162
|
-
// Outline pages resume after the last *included* entry: the output cap can
|
|
163
|
-
// stop a page before requestedEnd, and jumping to requestedEnd + 1 would
|
|
164
|
-
// silently skip the entries in between (CR-028).
|
|
165
|
-
const nextOffset = hasMore
|
|
166
|
-
? (mode === 'outline' && includedLines > 0 ? endLine + 1 : requestedEnd + 1)
|
|
167
|
-
: undefined;
|
|
168
|
-
const scopedContext = await discoverScopedContext(filePath, context);
|
|
169
|
-
return withScopedContext({
|
|
170
|
-
path: filePath,
|
|
171
|
-
mode,
|
|
172
|
-
startLine: start + 1,
|
|
173
|
-
endLine,
|
|
174
|
-
totalLines,
|
|
175
|
-
content: numberedLines.join('\n'),
|
|
176
|
-
nextOffset,
|
|
177
|
-
truncated: hasMore || lineTruncated,
|
|
178
|
-
lineTruncated,
|
|
179
|
-
...(mode === 'outline' ? { outline: true, outlineEntries: includedLines, ...(outlineDroppedEntries > 0 ? { outlineDroppedEntries } : {}), warning: 'Outline mode is lossy discovery output. Use exact readFile around relevant lines before editing.' } : {}),
|
|
180
|
-
}, scopedContext);
|
|
181
|
-
}
|
|
182
|
-
catch (error) {
|
|
183
|
-
const recovery = await readFailureRecovery(filePath, error);
|
|
184
|
-
return structuredToolFailure('readFile', error, recovery.suggestedNextStep, filePath, { reasonCode: recovery.reasonCode, suggestedPaths: recovery.suggestedPaths });
|
|
185
|
-
}
|
|
186
|
-
}),
|
|
187
|
-
}),
|
|
188
|
-
grep: tool({
|
|
189
|
-
description: 'Regex search workspace files with structured, globally capped results. Prefer this to reading files one by one.',
|
|
190
|
-
contextSchema: hazeToolContextSchema,
|
|
191
|
-
inputSchema: z.object({
|
|
192
|
-
pattern: z.string().min(1).describe('Regex pattern'),
|
|
193
|
-
path: z.string().default('.').describe('Workspace-relative file or directory'),
|
|
194
|
-
glob: z.string().optional().describe('Optional file glob, e.g. "*.ts"'),
|
|
195
|
-
contextLines: z.number().int().nonnegative().max(5).default(2).describe('Context lines before/after each match'),
|
|
196
|
-
maxMatches: z.number().int().positive().max(200).default(50).describe('Global match limit (enforced by the runner; ripgrep also applies it as a per-file cap)'),
|
|
197
|
-
caseInsensitive: z.boolean().default(false).describe('Ignore case'),
|
|
198
|
-
includeIgnored: z.boolean().default(false).describe('Search ignored paths only when explicitly needed'),
|
|
199
|
-
}),
|
|
200
|
-
execute: async ({ pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive, includeIgnored }, context) => runDedupedTool('grep', { pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive, includeIgnored }, context, async () => {
|
|
201
|
-
try {
|
|
202
|
-
const absolutePath = await prepareWorkspaceRead(searchPath, includeIgnored, context);
|
|
203
|
-
const args = [
|
|
204
|
-
'--json', '--color=never',
|
|
205
|
-
'--max-count', String(maxMatches),
|
|
206
|
-
'--context', String(contextLines),
|
|
207
|
-
];
|
|
208
|
-
if (caseInsensitive)
|
|
209
|
-
args.push('--ignore-case');
|
|
210
|
-
if (includeIgnored)
|
|
211
|
-
args.push('--no-ignore', '--hidden');
|
|
212
|
-
if (glob)
|
|
213
|
-
args.push('--glob', glob);
|
|
214
|
-
// Secret-file exclusions come after any model-supplied glob: later
|
|
215
|
-
// ripgrep globs take precedence, and an explicit glob (which also
|
|
216
|
-
// re-enables hidden-file search) must never re-include secrets.
|
|
217
|
-
for (const secretGlob of secretSearchExcludeGlobs())
|
|
218
|
-
args.push('--iglob', secretGlob);
|
|
219
|
-
args.push('--glob', '!**/.git/**', '--glob', '!**/node_modules/**');
|
|
220
|
-
args.push('--', pattern, absolutePath);
|
|
221
|
-
const result = await runRipgrepBounded({ executable: rgPath, args, cwd: workspaceRoot(), maxMatches, signal: context.abortSignal });
|
|
222
|
-
const stdout = result.stdout;
|
|
223
|
-
if (result.aborted)
|
|
224
|
-
throw new Error('ripgrep aborted');
|
|
225
|
-
if (result.timedOut)
|
|
226
|
-
throw new Error('ripgrep timed out');
|
|
227
|
-
if (result.code !== 0 && result.code !== 1 && !result.capped)
|
|
228
|
-
throw new Error(result.stderr || `ripgrep exited with code ${result.code}`);
|
|
229
|
-
const scopedContext = await discoverScopedContext(searchPath, context);
|
|
230
|
-
if (!stdout) {
|
|
231
|
-
return withScopedContext({ pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches: [], totalMatches: 0, truncated: false }, scopedContext);
|
|
232
|
-
}
|
|
233
|
-
const parsed = parseRipgrepJsonStream(stdout, maxMatches, contextLines, absolute => path.relative(workspaceRoot(), absolute));
|
|
234
|
-
const matches = parsed.matches;
|
|
235
|
-
const totalMatches = parsed.totalMatches;
|
|
236
|
-
const returnedMatches = parsed.returnedMatches;
|
|
237
|
-
const omittedMatches = parsed.omittedMatches;
|
|
238
|
-
const compacted = compactGrepMatches(matches);
|
|
239
|
-
const outputTruncated = compacted.outputTruncated;
|
|
240
|
-
const rawRenderedMatches = renderGrepMatches(matches);
|
|
241
|
-
const returnedRenderedMatches = renderGrepMatches(compacted.matches);
|
|
242
|
-
const grepMetrics = reductionMetrics(rawRenderedMatches, returnedRenderedMatches);
|
|
243
|
-
const fullOutputHandle = outputTruncated ? storeToolOutput(rawRenderedMatches) : undefined;
|
|
244
|
-
return withScopedContext({
|
|
245
|
-
pattern,
|
|
246
|
-
path: searchPath,
|
|
247
|
-
glob: glob ?? null,
|
|
248
|
-
caseInsensitive,
|
|
249
|
-
matches: compacted.matches,
|
|
250
|
-
totalMatches,
|
|
251
|
-
returnedMatches,
|
|
252
|
-
omittedMatches,
|
|
253
|
-
omittedResultLines: compacted.omittedResultLines,
|
|
254
|
-
lineTruncated: compacted.lineTruncated,
|
|
255
|
-
truncated: result.capped || omittedMatches > 0 || outputTruncated,
|
|
256
|
-
matchCountIsLowerBound: result.capped,
|
|
257
|
-
reducerName: 'grep-structured',
|
|
258
|
-
contentKind: 'search',
|
|
259
|
-
lossy: result.capped || omittedMatches > 0 || outputTruncated,
|
|
260
|
-
parseTier: 'full',
|
|
261
|
-
...grepMetrics,
|
|
262
|
-
...(fullOutputHandle ? { handle: fullOutputHandle, rawHandle: fullOutputHandle, omittedChars: Math.max(0, rawRenderedMatches.length - returnedRenderedMatches.length) } : { omittedChars: 0 }),
|
|
263
|
-
suggestion: result.capped || omittedMatches > 0 || outputTruncated ? 'Narrow the path, glob, or pattern to inspect omitted results, or use readToolOutput with the handle when present.' : undefined,
|
|
264
|
-
}, scopedContext);
|
|
265
|
-
}
|
|
266
|
-
catch (error) {
|
|
267
|
-
return structuredToolFailure('grep', error, 'Check that the search path exists and the pattern is valid regex. Try a narrower path or simpler pattern.', searchPath);
|
|
268
|
-
}
|
|
269
|
-
}),
|
|
270
|
-
}),
|
|
271
|
-
replaceInFiles: tool({
|
|
272
|
-
description: 'Preview or apply guarded literal/regex replacements across files. Use dryRun and occurrence IDs when unintended matches are possible.',
|
|
273
|
-
contextSchema: hazeToolContextSchema,
|
|
274
|
-
inputSchema: z.object({
|
|
275
|
-
path: z.string().default('.').describe('Workspace-relative file or directory scope'),
|
|
276
|
-
needle: z.string().min(1).describe('Literal text or JavaScript regular expression'),
|
|
277
|
-
replacement: z.string().describe('Replacement text; regex mode supports $1-style capture substitutions'),
|
|
278
|
-
mode: z.enum(['literal', 'regex']).default('literal'),
|
|
279
|
-
includeGlob: z.string().optional().describe('Optional workspace-relative include glob'),
|
|
280
|
-
excludeGlob: z.string().optional().describe('Optional workspace-relative exclude glob'),
|
|
281
|
-
dryRun: z.boolean().default(true).describe('Preview changes without writing'),
|
|
282
|
-
occurrenceIds: z.array(z.string()).optional().describe('Apply only stable IDs returned by a dry run; stale IDs abort all changes'),
|
|
283
|
-
expectedCount: z.number().int().nonnegative().optional().describe('Abort all changes unless this many occurrences are currently found'),
|
|
284
|
-
}),
|
|
285
|
-
execute: async (input, context) => runDedupedTool('replaceInFiles', input, context, async () => {
|
|
286
|
-
try {
|
|
287
|
-
return await replaceInFiles(input, context);
|
|
288
|
-
}
|
|
289
|
-
catch (error) {
|
|
290
|
-
return structuredToolFailure('replaceInFiles', error, 'Run a dry run with a narrower path/glob or corrected pattern, then apply current occurrence IDs.', input.path);
|
|
291
|
-
}
|
|
292
|
-
}),
|
|
293
|
-
}),
|
|
294
|
-
replaceLines: tool({
|
|
295
|
-
description: 'Replace a 1-based inclusive line range. Use after readFile when exact editFile text is ambiguous or stale.',
|
|
296
|
-
contextSchema: hazeToolContextSchema,
|
|
297
|
-
inputSchema: z.object({
|
|
298
|
-
path: z.string().describe('File path relative to the current workspace'),
|
|
299
|
-
startLine: z.number().int().positive().describe('First 1-based line number to replace'),
|
|
300
|
-
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.'),
|
|
301
|
-
content: z.string().describe('Replacement content for the line range'),
|
|
302
|
-
allowIgnored: z.boolean().default(false).describe('Edit the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
|
|
303
|
-
}),
|
|
304
|
-
execute: async ({ path: filePath, startLine, endLine, content, allowIgnored }, context) => runDedupedTool('replaceLines', { path: filePath, startLine, endLine, content, allowIgnored }, context, async () => {
|
|
305
|
-
try {
|
|
306
|
-
const { absolutePath, scopedStop } = await prepareWorkspaceMutation('replaceLines', filePath, allowIgnored, context);
|
|
307
|
-
if (scopedStop)
|
|
308
|
-
return scopedStop;
|
|
309
|
-
const file = await readUtf8Prefix(absolutePath, EXACT_MUTATION_BYTES);
|
|
310
|
-
if (file.truncated)
|
|
311
|
-
throw new HazeToolError(`File exceeds ${EXACT_MUTATION_BYTES} byte exact-mutation limit`, 'file_too_large');
|
|
312
|
-
const original = file.content;
|
|
313
|
-
const hasTrailingNewline = original.endsWith('\n');
|
|
314
|
-
const lines = original.split(/\r?\n/);
|
|
315
|
-
if (hasTrailingNewline)
|
|
316
|
-
lines.pop();
|
|
317
|
-
const isAppend = startLine === lines.length + 1 && endLine === lines.length;
|
|
318
|
-
if (!isAppend && endLine < startLine)
|
|
319
|
-
throw new HazeToolError('endLine must be greater than or equal to startLine, except when appending at EOF with startLine=totalLines+1 and endLine=totalLines', 'invalid_line_range', { recoveryTool: 'readFile', recoveryInput: { path: filePath } });
|
|
320
|
-
if (startLine > lines.length + 1)
|
|
321
|
-
throw new HazeToolError(`startLine ${startLine} is beyond end of file (${lines.length} lines)`, 'invalid_line_range', { recoveryTool: 'readFile', recoveryInput: { path: filePath } });
|
|
322
|
-
const effectiveEndLine = !isAppend && endLine > lines.length ? lines.length : endLine;
|
|
323
|
-
const replacementLines = content.length === 0 ? [] : content.split(/\r?\n/);
|
|
324
|
-
const removedText = isAppend ? '' : lines.slice(startLine - 1, effectiveEndLine).join('\n');
|
|
325
|
-
const beforeContext = startLine > 1 ? { oldLine: startLine - 1, newLine: startLine - 1, text: lines[startLine - 2] ?? '' } : undefined;
|
|
326
|
-
const afterContext = !isAppend && effectiveEndLine < lines.length
|
|
327
|
-
? { oldLine: effectiveEndLine + 1, newLine: startLine + replacementLines.length, text: lines[effectiveEndLine] ?? '' }
|
|
328
|
-
: undefined;
|
|
329
|
-
if (isAppend) {
|
|
330
|
-
lines.push(...replacementLines);
|
|
331
|
-
}
|
|
332
|
-
else {
|
|
333
|
-
lines.splice(startLine - 1, effectiveEndLine - startLine + 1, ...replacementLines);
|
|
334
|
-
}
|
|
335
|
-
const updated = lines.join('\n') + (hasTrailingNewline ? '\n' : '');
|
|
336
|
-
const replacement = replacementDiff(removedText, content, startLine, startLine, { before: beforeContext, after: afterContext });
|
|
337
|
-
const changed = updated !== original;
|
|
338
|
-
await fs.writeFile(absolutePath, updated, 'utf8');
|
|
339
|
-
return {
|
|
340
|
-
ok: true,
|
|
341
|
-
path: filePath,
|
|
342
|
-
startLine,
|
|
343
|
-
endLine: effectiveEndLine,
|
|
344
|
-
requestedEndLine: endLine,
|
|
345
|
-
endLineClamped: effectiveEndLine !== endLine,
|
|
346
|
-
replacementLines: replacementLines.length,
|
|
347
|
-
appended: isAppend,
|
|
348
|
-
noChange: !changed,
|
|
349
|
-
addedLines: changed ? replacement.addedLines : 0,
|
|
350
|
-
removedLines: changed ? replacement.removedLines : 0,
|
|
351
|
-
...mutationDiffFields(filePath, changed ? replacement.diff : []),
|
|
352
|
-
};
|
|
353
|
-
}
|
|
354
|
-
catch (error) {
|
|
355
|
-
return structuredToolFailure('replaceLines', error, 'Read the file again for current line numbers, then retry replaceLines with a valid range.', filePath);
|
|
356
|
-
}
|
|
357
|
-
}),
|
|
358
|
-
}),
|
|
359
|
-
writeFile: tool({
|
|
360
|
-
description: `Create, rewrite, or append a UTF-8 file in chunks of at most ${WRITE_FILE_CHUNK_BYTES} bytes. Existing files require explicit rewrite or append approval.`,
|
|
361
|
-
contextSchema: hazeToolContextSchema,
|
|
362
|
-
inputSchema: z.object({
|
|
363
|
-
path: z.string().describe('File path relative to the current workspace'),
|
|
364
|
-
// Size policy lives in execute (write_chunk_too_large with chunking
|
|
365
|
-
// guidance), not in the schema: a Zod .max() would shadow that error
|
|
366
|
-
// with a cryptic AI_TypeValidationError before execute can run.
|
|
367
|
-
content: z.string().describe(`File content chunk, at most ${WRITE_FILE_CHUNK_BYTES} UTF-8 bytes`),
|
|
368
|
-
overwriteExisting: z.boolean().default(false).describe('Approve replacing an existing file with the first chunk of an intentional full rewrite'),
|
|
369
|
-
append: z.boolean().default(false).describe('Append this chunk to an existing file; use after creating or replacing the file with the first chunk'),
|
|
370
|
-
allowIgnored: z.boolean().default(false).describe('Write a .gitignored file only when needed'),
|
|
371
|
-
}),
|
|
372
|
-
execute: async ({ path: filePath, content, overwriteExisting, append, allowIgnored }, context) => runDedupedTool('writeFile', { path: filePath, content, overwriteExisting, append, allowIgnored }, context, async () => {
|
|
373
|
-
try {
|
|
374
|
-
const contentBytes = Buffer.byteLength(content, 'utf8');
|
|
375
|
-
if (contentBytes > WRITE_FILE_CHUNK_BYTES) {
|
|
376
|
-
throw new HazeToolError(`Content is ${contentBytes} UTF-8 bytes; writeFile accepts at most ${WRITE_FILE_CHUNK_BYTES} bytes per call. Write the first chunk normally, then use append=true for later chunks.`, 'write_chunk_too_large');
|
|
377
|
-
}
|
|
378
|
-
if (append && overwriteExisting) {
|
|
379
|
-
throw new HazeToolError('append=true and overwriteExisting=true are mutually exclusive', 'conflicting_write_modes');
|
|
380
|
-
}
|
|
381
|
-
const { absolutePath, scopedStop, assertExistingInsideWorkspace, assertWritableInsideWorkspace } = await prepareWorkspaceWritePath('writeFile', filePath, allowIgnored, context);
|
|
382
|
-
if (scopedStop)
|
|
383
|
-
return scopedStop;
|
|
384
|
-
let targetExisted = false;
|
|
385
|
-
let previousContent = '';
|
|
386
|
-
let previousContentTruncated = false;
|
|
387
|
-
let previousContentOmittedBytes = 0;
|
|
388
|
-
try {
|
|
389
|
-
await fs.access(absolutePath);
|
|
390
|
-
targetExisted = true;
|
|
391
|
-
await assertExistingInsideWorkspace();
|
|
392
|
-
if (!overwriteExisting && !append) {
|
|
393
|
-
throw new HazeToolError(`Refusing to overwrite existing file: ${filePath}. Use editFile/replaceLines for targeted edits, set append=true for a later chunk, or set overwriteExisting=true for an intentional rewrite.`, 'existing_file_requires_overwrite', { recoveryTool: 'readFile', recoveryInput: { path: filePath } });
|
|
394
|
-
}
|
|
395
|
-
const previous = await readUtf8Prefix(absolutePath, EXACT_MUTATION_BYTES);
|
|
396
|
-
previousContent = previous.content;
|
|
397
|
-
previousContentTruncated = previous.truncated;
|
|
398
|
-
previousContentOmittedBytes = Math.max(0, previous.totalBytes - Buffer.byteLength(previous.content, 'utf8'));
|
|
399
|
-
}
|
|
400
|
-
catch (error) {
|
|
401
|
-
const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
|
|
402
|
-
if (code !== 'ENOENT')
|
|
403
|
-
throw error;
|
|
404
|
-
if (append)
|
|
405
|
-
throw new HazeToolError(`Cannot append to missing file: ${filePath}. Create its first chunk with append=false.`, 'append_target_missing');
|
|
406
|
-
await assertWritableInsideWorkspace();
|
|
407
|
-
}
|
|
408
|
-
await fs.mkdir(path.dirname(absolutePath), { recursive: true });
|
|
409
|
-
const updated = append ? `${previousContent}${content}` : content;
|
|
410
|
-
const writeDiff = fileDiff(previousContent, updated);
|
|
411
|
-
if (append)
|
|
412
|
-
await fs.appendFile(absolutePath, content, 'utf8');
|
|
413
|
-
else
|
|
414
|
-
await fs.writeFile(absolutePath, content, 'utf8');
|
|
415
|
-
return {
|
|
416
|
-
ok: true,
|
|
417
|
-
path: filePath,
|
|
418
|
-
bytes: contentBytes,
|
|
419
|
-
overwritten: overwriteExisting,
|
|
420
|
-
appended: append,
|
|
421
|
-
noChange: targetExisted && !previousContentTruncated && previousContent === updated,
|
|
422
|
-
addedLines: writeDiff.addedLines,
|
|
423
|
-
removedLines: writeDiff.removedLines,
|
|
424
|
-
diffComplete: !previousContentTruncated,
|
|
425
|
-
...(previousContentTruncated ? { previousContentOmittedBytes } : {}),
|
|
426
|
-
...mutationDiffFields(filePath, writeDiff.diff),
|
|
427
|
-
};
|
|
428
|
-
}
|
|
429
|
-
catch (error) {
|
|
430
|
-
return structuredToolFailure('writeFile', error, `Keep each content chunk at or below ${WRITE_FILE_CHUNK_BYTES} UTF-8 bytes. Create or replace the first chunk, then continue with append=true.`, filePath);
|
|
431
|
-
}
|
|
432
|
-
}),
|
|
433
|
-
}),
|
|
434
|
-
editFile: tool({
|
|
435
|
-
description: 'Apply unique text replacements. Batch same-file edits; reread and use replaceLines if matching fails.',
|
|
436
|
-
contextSchema: hazeToolContextSchema,
|
|
437
|
-
inputSchema: z.object({
|
|
438
|
-
path: z.string().describe('File path relative to the current workspace'),
|
|
439
|
-
edits: z.array(z.object({
|
|
440
|
-
oldText: z.string().min(1).describe('Exact text to replace; must appear exactly once'),
|
|
441
|
-
newText: z.string().describe('Replacement text'),
|
|
442
|
-
})).min(1).describe('One or more non-overlapping exact replacements'),
|
|
443
|
-
allowIgnored: z.boolean().default(false).describe('Edit a .gitignored file only when needed'),
|
|
444
|
-
}),
|
|
445
|
-
execute: async ({ path: filePath, edits, allowIgnored }, context) => runDedupedTool('editFile', { path: filePath, edits, allowIgnored }, context, async () => {
|
|
446
|
-
try {
|
|
447
|
-
const { absolutePath, scopedStop } = await prepareWorkspaceMutation('editFile', filePath, allowIgnored, context);
|
|
448
|
-
if (scopedStop)
|
|
449
|
-
return scopedStop;
|
|
450
|
-
const file = await readUtf8Prefix(absolutePath, EXACT_MUTATION_BYTES);
|
|
451
|
-
if (file.truncated)
|
|
452
|
-
throw new HazeToolError(`File exceeds ${EXACT_MUTATION_BYTES} byte exact-mutation limit`, 'file_too_large');
|
|
453
|
-
const original = file.content;
|
|
454
|
-
const ranges = edits.map((edit, index) => {
|
|
455
|
-
const match = findEditRange(original, edit.oldText);
|
|
456
|
-
if (match.kind === 'missing')
|
|
457
|
-
throw new HazeToolError(`edit ${index}: oldText was not found. Read the file again and use the exact current text, or use replaceLines with the latest line numbers.`, 'old_text_missing', { recoveryTool: 'readFile', recoveryInput: { path: filePath } });
|
|
458
|
-
if (match.kind === 'multiple')
|
|
459
|
-
throw new HazeToolError(`edit ${index}: oldText is not unique`, 'old_text_not_unique', { recoveryTool: 'readFile', recoveryInput: { path: filePath } });
|
|
460
|
-
return { index, start: match.start, end: match.end, edit, approximate: match.approximate };
|
|
461
|
-
}).sort((a, b) => a.start - b.start);
|
|
462
|
-
for (let i = 1; i < ranges.length; i++) {
|
|
463
|
-
if (ranges[i].start < ranges[i - 1].end) {
|
|
464
|
-
throw new HazeToolError(`edits ${ranges[i - 1].index} and ${ranges[i].index} overlap`, 'overlapping_edits', { recoveryTool: 'readFile', recoveryInput: { path: filePath } });
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
let updated = original;
|
|
468
|
-
for (const range of [...ranges].sort((a, b) => b.start - a.start)) {
|
|
469
|
-
updated = updated.slice(0, range.start) + range.edit.newText + updated.slice(range.end);
|
|
470
|
-
}
|
|
471
|
-
const originalLines = splitDiffLines(original);
|
|
472
|
-
let lineDelta = 0;
|
|
473
|
-
let addedLines = 0;
|
|
474
|
-
let removedLines = 0;
|
|
475
|
-
const diff = [];
|
|
476
|
-
for (const range of ranges) {
|
|
477
|
-
const oldStartLine = lineNumberAtOffset(original, range.start);
|
|
478
|
-
const newStartLine = oldStartLine + lineDelta;
|
|
479
|
-
const oldLineCount = splitDiffLines(range.edit.oldText).length;
|
|
480
|
-
const newLineCount = splitDiffLines(range.edit.newText).length;
|
|
481
|
-
const beforeContext = oldStartLine > 1 ? { oldLine: oldStartLine - 1, newLine: newStartLine - 1, text: originalLines[oldStartLine - 2] ?? '' } : undefined;
|
|
482
|
-
const afterOldLine = oldStartLine + oldLineCount;
|
|
483
|
-
const afterContext = afterOldLine <= originalLines.length
|
|
484
|
-
? { oldLine: afterOldLine, newLine: newStartLine + newLineCount, text: originalLines[afterOldLine - 1] ?? '' }
|
|
485
|
-
: undefined;
|
|
486
|
-
const rangeDiff = replacementDiff(range.edit.oldText, range.edit.newText, oldStartLine, newStartLine, { before: beforeContext, after: afterContext });
|
|
487
|
-
diff.push(...rangeDiff.diff);
|
|
488
|
-
addedLines += rangeDiff.addedLines;
|
|
489
|
-
removedLines += rangeDiff.removedLines;
|
|
490
|
-
lineDelta += rangeDiff.addedLines - rangeDiff.removedLines;
|
|
491
|
-
}
|
|
492
|
-
const changed = updated !== original;
|
|
493
|
-
await fs.writeFile(absolutePath, updated, 'utf8');
|
|
494
|
-
return {
|
|
495
|
-
ok: true,
|
|
496
|
-
path: filePath,
|
|
497
|
-
edits: edits.length,
|
|
498
|
-
approximateMatches: ranges.filter(range => range.approximate).length,
|
|
499
|
-
noChange: !changed,
|
|
500
|
-
addedLines: changed ? addedLines : 0,
|
|
501
|
-
removedLines: changed ? removedLines : 0,
|
|
502
|
-
...mutationDiffFields(filePath, changed ? diff : []),
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
catch (error) {
|
|
506
|
-
return structuredToolFailure('editFile', error, 'Read the file again, then retry with exact current text or use replaceLines with the latest line numbers.', filePath);
|
|
507
|
-
}
|
|
508
|
-
}),
|
|
509
|
-
}),
|
|
12
|
+
...fileTools,
|
|
510
13
|
writeTasks: writeTasksTool,
|
|
511
14
|
readToolOutput: readToolOutputTool,
|
|
512
15
|
fetch: fetchTool,
|