@denizokcu/haze 0.3.0 → 0.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +50 -36
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +244 -94
  5. package/dist/cli/commands/commands.js +119 -114
  6. package/dist/cli/commands/streaming.d.ts +37 -5
  7. package/dist/cli/commands/streaming.js +455 -192
  8. package/dist/cli/contextReport.d.ts +1 -0
  9. package/dist/cli/contextReport.js +47 -0
  10. package/dist/config/contextFiles.d.ts +31 -0
  11. package/dist/config/contextFiles.js +97 -13
  12. package/dist/config/providers.d.ts +2 -5
  13. package/dist/config/providers.js +16 -12
  14. package/dist/core/agent/compaction.d.ts +3 -0
  15. package/dist/core/agent/compaction.js +23 -3
  16. package/dist/core/agent/contextBudget.d.ts +33 -0
  17. package/dist/core/agent/contextBudget.js +88 -0
  18. package/dist/core/agent/requestAssembly.d.ts +22 -0
  19. package/dist/core/agent/requestAssembly.js +157 -0
  20. package/dist/core/agent/toolOutputStore.d.ts +16 -0
  21. package/dist/core/agent/toolOutputStore.js +65 -0
  22. package/dist/core/agent/workState.d.ts +38 -0
  23. package/dist/core/agent/workState.js +89 -0
  24. package/dist/core/bashOutput/ansi.d.ts +1 -0
  25. package/dist/core/bashOutput/ansi.js +7 -0
  26. package/dist/core/bashOutput/command.d.ts +2 -0
  27. package/dist/core/bashOutput/command.js +62 -0
  28. package/dist/core/bashOutput/lineFilter.d.ts +25 -0
  29. package/dist/core/bashOutput/lineFilter.js +62 -0
  30. package/dist/core/bashOutput/reducers/content.d.ts +3 -0
  31. package/dist/core/bashOutput/reducers/content.js +134 -0
  32. package/dist/core/bashOutput/reducers/git.d.ts +1 -0
  33. package/dist/core/bashOutput/reducers/git.js +147 -0
  34. package/dist/core/bashOutput/reducers/search.d.ts +7 -0
  35. package/dist/core/bashOutput/reducers/search.js +76 -0
  36. package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
  37. package/dist/core/bashOutput/reducers/validation.js +41 -0
  38. package/dist/core/bashOutput/registry.d.ts +4 -0
  39. package/dist/core/bashOutput/registry.js +126 -0
  40. package/dist/core/bashOutput/types.d.ts +46 -0
  41. package/dist/core/bashOutput/types.js +1 -0
  42. package/dist/core/goal/completionPolicy.d.ts +1 -0
  43. package/dist/core/goal/completionPolicy.js +5 -1
  44. package/dist/core/goal/sessionGoal.d.ts +2 -0
  45. package/dist/core/goal/sessionGoal.js +8 -1
  46. package/dist/core/log/llmLog.d.ts +68 -0
  47. package/dist/core/log/llmLog.js +55 -0
  48. package/dist/core/safety/urlGuard.d.ts +37 -0
  49. package/dist/core/safety/urlGuard.js +206 -0
  50. package/dist/core/session/sessionStore.d.ts +6 -0
  51. package/dist/core/session/sessionStore.js +5 -0
  52. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  53. package/dist/core/subagent/subagentRunner.js +5 -15
  54. package/dist/core/toolOutput/reduction.d.ts +25 -0
  55. package/dist/core/toolOutput/reduction.js +23 -0
  56. package/dist/core/validation/outputParser.js +15 -2
  57. package/dist/llm/client.d.ts +40 -1
  58. package/dist/llm/client.js +51 -5
  59. package/dist/llm/hazeTools.d.ts +165 -23
  60. package/dist/llm/hazeTools.js +317 -65
  61. package/dist/llm/initPrompt.js +2 -1
  62. package/dist/llm/systemPrompt.d.ts +6 -1
  63. package/dist/llm/systemPrompt.js +44 -81
  64. package/dist/llm/toolResultTypes.d.ts +1 -1
  65. package/dist/llm/webFetch.d.ts +57 -0
  66. package/dist/llm/webFetch.js +270 -0
  67. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  68. package/dist/skills/builder/SkillBuilder.js +68 -65
  69. package/dist/skills/skillTools.d.ts +2 -19
  70. package/dist/skills/skillTools.js +28 -19
  71. package/dist/ui/components/MarkdownText.d.ts +2 -0
  72. package/dist/ui/components/MarkdownText.js +116 -3
  73. package/package.json +18 -10
@@ -10,7 +10,17 @@ import { generateTaskId, saveTasks } from '../core/tasks/taskStorage.js';
10
10
  import { workspaceRoot, resolveWorkspacePath, workspaceRelativePath } from '../utils/path.js';
11
11
  import { classifyBashCommand, isValidationClassification } from '../core/safety/bashClassifier.js';
12
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';
16
+ import { reductionMetrics } from '../core/toolOutput/reduction.js';
17
+ import { readScopedContextFilesForPath } from '../config/contextFiles.js';
13
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
24
  const execFile = promisify(execFileCallback);
15
25
  async function isGitIgnored(absolutePath) {
16
26
  const relative = workspaceRelativePath(absolutePath);
@@ -44,17 +54,43 @@ async function assertNotIgnored(absolutePath, inputPath, allowIgnored) {
44
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' });
45
55
  }
46
56
  }
47
- function truncate(text, maxChars = MAX_OUTPUT_CHARS) {
57
+ function compactStoredOutput(text, maxChars = COMPACT_COMMAND_CHARS) {
48
58
  if (text.length <= maxChars)
49
59
  return { text, truncated: false };
60
+ const handle = storeToolOutput(text);
61
+ const headChars = Math.floor(maxChars * 0.4);
62
+ const tailChars = maxChars - headChars;
50
63
  return {
51
- text: text.slice(0, maxChars),
64
+ text: `${text.slice(0, headChars)}\n\n[... ${text.length - maxChars} characters omitted; use readToolOutput with handle ${handle} ...]\n\n${text.slice(-tailChars)}`,
52
65
  truncated: true,
53
66
  omittedChars: text.length - maxChars,
67
+ handle,
54
68
  };
55
69
  }
56
- function numberLines(lines, startLine) {
57
- return lines.map((line, index) => `${String(startLine + index).padStart(4, ' ')} | ${line}`).join('\n');
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 };
58
94
  }
59
95
  function stripLineNumberPrefixes(text) {
60
96
  return text.replace(/^\s*\d+\s+\| ?/gm, '');
@@ -118,12 +154,45 @@ function hazeContext(context) {
118
154
  ? context.experimental_context
119
155
  : undefined;
120
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
+ }
121
184
  function isMutatingTool(toolName) {
122
185
  return ['editFile', 'replaceLines', 'writeFile'].includes(toolName);
123
186
  }
124
187
  function isReadOnlyFileTool(toolName) {
125
188
  return ['listFiles', 'readFile', 'grep'].includes(toolName);
126
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
+ }
127
196
  function inputPath(input) {
128
197
  return typeof input === 'object' && input != null && 'path' in input && typeof input.path === 'string'
129
198
  ? input.path
@@ -148,6 +217,20 @@ function structuredToolFailure(toolName, error, suggestedNextStep, pathForError,
148
217
  };
149
218
  }
150
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
+ }
151
234
  function splitDiffLines(text) {
152
235
  const lines = text.split(/\r?\n/);
153
236
  if (text.endsWith('\n') || text.endsWith('\r\n'))
@@ -200,14 +283,16 @@ async function runDedupedTool(toolName, input, context, execute) {
200
283
  }
201
284
  const completedAt = ctx.completedToolCalls.get(key);
202
285
  const readAfterFailedMutation = toolName === 'readFile' && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput);
203
- if ((isReadOnlyFileTool(toolName) || toolName === 'bash') && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
286
+ if ((isDeduplicableReadOnlyTool(toolName)) && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
204
287
  return {
205
288
  ok: true,
206
289
  duplicateSkipped: true,
207
290
  toolName,
208
291
  reason: toolName === 'bash'
209
292
  ? 'Skipped duplicate bash command; no files changed since the previous run.'
210
- : 'Skipped duplicate read-only tool call with identical input; no files changed since the previous call.',
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.',
211
296
  };
212
297
  }
213
298
  if (ctx.inFlightToolCalls.has(key)) {
@@ -260,22 +345,18 @@ async function runDedupedTool(toolName, input, context, execute) {
260
345
  ctx.inFlightMutationPaths?.delete(pathForInput);
261
346
  }
262
347
  }
263
- const STATUS_ICON = {
264
- pending: '○',
265
- in_progress: '◐',
266
- completed: '✓',
267
- };
268
348
  export const hazeTools = {
269
349
  listFiles: tool({
270
- description: 'List files and directories in the current workspace. Prefer this over bash ls/find for discovering project structure.',
350
+ description: 'List workspace files/directories with pagination. Prefer this to bash for discovery.',
271
351
  inputSchema: z.object({
272
352
  path: z.string().default('.').describe('Directory path relative to the current workspace'),
273
353
  recursive: z.boolean().default(false).describe('Whether to list files recursively'),
274
354
  maxEntries: z.number().int().positive().max(500).default(100).describe('Maximum number of entries to return'),
275
355
  cursor: z.string().optional().describe('Pagination cursor from a previous listFiles result. Continue after that entry.'),
276
- includeIgnored: z.boolean().default(false).describe('Include files ignored by .gitignore. Use only when explicitly needed.'),
356
+ includeIgnored: z.boolean().default(false).describe('Include .gitignored paths only when needed'),
357
+ includeSizes: z.boolean().default(false).describe('Include file byte sizes only when needed; omitted by default for compact output'),
277
358
  }),
278
- execute: async ({ path: dirPath, recursive, maxEntries, cursor, includeIgnored }, context) => runDedupedTool('listFiles', { path: dirPath, recursive, maxEntries, cursor, includeIgnored }, context, async () => {
359
+ execute: async ({ path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context) => runDedupedTool('listFiles', { path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context, async () => {
279
360
  try {
280
361
  const absolutePath = resolveWorkspacePath(dirPath);
281
362
  await assertNotIgnored(absolutePath, dirPath, includeIgnored);
@@ -292,14 +373,20 @@ export const hazeTools = {
292
373
  const hasMore = walked.length > maxEntries;
293
374
  for (const entry of page) {
294
375
  if (entry.isDirectory) {
295
- entries.push({ path: entry.path, type: 'directory' });
376
+ entries.push(`${entry.path}/`);
296
377
  }
297
378
  else if (entry.isFile) {
298
- const stat = await fs.stat(entry.absolutePath);
299
- entries.push({ path: entry.path, type: 'file', size: stat.size });
379
+ if (includeSizes) {
380
+ const stat = await fs.stat(entry.absolutePath);
381
+ entries.push(`${entry.path} (${stat.size} bytes)`);
382
+ }
383
+ else {
384
+ entries.push(entry.path);
385
+ }
300
386
  }
301
387
  }
302
- return { path: dirPath, recursive, includeIgnored, cursor, nextCursor: hasMore ? page.at(-1)?.path : undefined, ignoredSkipped, entries, truncated: hasMore };
388
+ const scopedContext = await discoverScopedContext(dirPath, context);
389
+ 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);
303
390
  }
304
391
  catch (error) {
305
392
  return structuredToolFailure('listFiles', error, 'Check that the directory exists and is not ignored, or retry with a narrower path.', dirPath);
@@ -307,31 +394,62 @@ export const hazeTools = {
307
394
  }),
308
395
  }),
309
396
  readFile: tool({
310
- description: 'Read a UTF-8 text file from the current workspace. Supports optional 1-based line offset and line limit.',
397
+ 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.',
311
398
  inputSchema: z.object({
312
399
  path: z.string().describe('File path relative to the current workspace'),
313
400
  offset: z.number().int().positive().optional().describe('1-based line number to start reading from'),
314
- limit: z.number().int().positive().max(2000).optional().describe('Maximum number of lines to return'),
315
- allowIgnored: z.boolean().default(false).describe('Read the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
401
+ limit: z.number().int().positive().max(2000).optional().describe('Maximum lines to return; defaults to 300'),
402
+ mode: z.enum(['exact', 'outline']).default('exact').describe('exact returns source lines; outline returns imports/includes and top-level declarations for discovery only'),
403
+ allowIgnored: z.boolean().default(false).describe('Read a .gitignored file only when needed'),
316
404
  }),
317
- execute: async ({ path: filePath, offset, limit, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, allowIgnored }, context, async () => {
405
+ execute: async ({ path: filePath, offset, limit, mode, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, mode, allowIgnored }, context, async () => {
318
406
  try {
319
407
  const absolutePath = resolveWorkspacePath(filePath);
320
408
  await assertNotIgnored(absolutePath, filePath, allowIgnored);
321
409
  const content = await fs.readFile(absolutePath, 'utf8');
322
410
  const lines = content.split(/\r?\n/);
323
411
  const start = offset == null ? 0 : offset - 1;
324
- const end = limit == null ? lines.length : start + limit;
325
- const selectedLines = lines.slice(start, end);
326
- const selected = selectedLines.join('\n');
327
- return {
412
+ const requestedEnd = Math.min(lines.length, start + (limit ?? DEFAULT_READ_LINES));
413
+ const selectedLines = lines.slice(start, requestedEnd);
414
+ const outlineEntries = mode === 'outline' ? sourceOutlineEntries(selectedLines, start + 1) : undefined;
415
+ const displayLines = outlineEntries?.map(entry => ({ lineNumber: entry.lineNumber, text: entry.text }))
416
+ ?? selectedLines.map((line, index) => ({ lineNumber: start + index + 1, text: line }));
417
+ const numberedLines = [];
418
+ let includedLines = 0;
419
+ let lineTruncated = false;
420
+ for (const entry of displayLines) {
421
+ const prefix = `${String(entry.lineNumber).padStart(4, ' ')} | `;
422
+ const remaining = MAX_OUTPUT_CHARS - numberedLines.join('\n').length - (numberedLines.length > 0 ? 1 : 0);
423
+ if (remaining <= prefix.length)
424
+ break;
425
+ 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]`);
427
+ includedLines += 1;
428
+ lineTruncated = true;
429
+ break;
430
+ }
431
+ numberedLines.push(`${prefix}${entry.text}`);
432
+ includedLines += 1;
433
+ }
434
+ const endLine = mode === 'outline'
435
+ ? displayLines[Math.max(0, includedLines - 1)]?.lineNumber ?? start + 1
436
+ : start + includedLines;
437
+ const hasMore = mode === 'outline'
438
+ ? requestedEnd < lines.length
439
+ : endLine < lines.length;
440
+ const scopedContext = await discoverScopedContext(filePath, context);
441
+ return withScopedContext({
328
442
  path: filePath,
443
+ mode,
329
444
  startLine: start + 1,
330
- endLine: Math.min(end, lines.length),
445
+ endLine,
331
446
  totalLines: lines.length,
332
- lineNumberedText: numberLines(selectedLines, start + 1),
333
- ...truncate(selected),
334
- };
447
+ content: numberedLines.join('\n'),
448
+ nextOffset: hasMore ? requestedEnd + 1 : undefined,
449
+ truncated: hasMore || lineTruncated,
450
+ lineTruncated,
451
+ ...(mode === 'outline' ? { outline: true, outlineEntries: includedLines, warning: 'Outline mode is lossy discovery output. Use exact readFile around relevant lines before editing.' } : {}),
452
+ }, scopedContext);
335
453
  }
336
454
  catch (error) {
337
455
  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);
@@ -339,20 +457,20 @@ export const hazeTools = {
339
457
  }),
340
458
  }),
341
459
  grep: tool({
342
- description: 'Search file contents with a regex pattern using ripgrep. Use this to find symbol definitions, usages, string literals, import paths, and code patterns across the workspace. Much faster and more targeted than reading files one by one with readFile. Respects .gitignore by default.',
460
+ description: 'Regex search workspace files with structured, globally capped results. Prefer this to reading files one by one.',
343
461
  inputSchema: z.object({
344
- pattern: z.string().min(1).describe('Regex pattern to search for (PCRE-compatible). Examples: "function handleClick", "import.*from.*react", "class UserService", "TODO|FIXME"'),
345
- path: z.string().default('.').describe('Directory or file path to search in, relative to the workspace. Narrow this to focus results.'),
346
- glob: z.string().optional().describe('File glob filter. Examples: "*.ts", "*.{js,jsx}", "src/**/*.py". Narrows search to matching files.'),
347
- contextLines: z.number().int().nonnegative().max(5).default(2).describe('Number of context lines before and after each match (0-5). Use 0 for compact output, 2-3 for understanding surrounding code.'),
348
- maxMatches: z.number().int().positive().max(200).default(50).describe('Maximum number of matches to return. Increase for broad searches, decrease for focused lookups.'),
349
- caseInsensitive: z.boolean().default(false).describe('Case-insensitive matching. Useful for symbol names that may vary in casing.'),
462
+ pattern: z.string().min(1).describe('Regex pattern'),
463
+ path: z.string().default('.').describe('Workspace-relative file or directory'),
464
+ glob: z.string().optional().describe('Optional file glob, e.g. "*.ts"'),
465
+ contextLines: z.number().int().nonnegative().max(5).default(2).describe('Context lines before/after each match'),
466
+ maxMatches: z.number().int().positive().max(200).default(50).describe('Global match limit'),
467
+ caseInsensitive: z.boolean().default(false).describe('Ignore case'),
350
468
  }),
351
469
  execute: async ({ pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context) => runDedupedTool('grep', { pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context, async () => {
352
470
  try {
353
471
  const absolutePath = resolveWorkspacePath(searchPath);
354
472
  const args = [
355
- '--no-heading', '--line-number', '--color=never',
473
+ '--json', '--color=never',
356
474
  '--max-count', String(maxMatches),
357
475
  '--context', String(contextLines),
358
476
  ];
@@ -375,24 +493,86 @@ export const hazeTools = {
375
493
  throw error;
376
494
  }
377
495
  }
496
+ const scopedContext = await discoverScopedContext(searchPath, context);
378
497
  if (!stdout) {
379
- return { pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches: [], totalMatches: 0, truncated: false };
498
+ return withScopedContext({ pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches: [], totalMatches: 0, truncated: false }, scopedContext);
380
499
  }
381
- const { text: output, truncated } = truncate(stdout);
382
- const lines = output.split('\n').filter(Boolean);
500
+ const lines = stdout.split('\n').filter(Boolean);
383
501
  const matches = [];
502
+ let totalMatches = 0;
503
+ let returnedMatches = 0;
504
+ let omittedMatches = 0;
505
+ let pendingContext = [];
506
+ let retainFollowingContext = false;
384
507
  for (const line of lines) {
385
- const match = line.match(/^(\S+?):(\d+)[-:](.*)$/);
386
- if (!match)
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;
387
518
  continue;
388
- const [, file, lineStr, content] = match;
389
- if (file && lineStr && content !== undefined) {
390
- const isContext = line.includes('-');
391
- const relativePath = path.relative(workspaceRoot(), file);
392
- matches.push({ file: relativePath, line: Number(lineStr), content, isContext });
393
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;
394
549
  }
395
- return { pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches, totalMatches: matches.filter(m => !m.isContext).length, truncated };
550
+ const compacted = compactGrepMatches(matches);
551
+ const outputTruncated = compacted.outputTruncated;
552
+ const rawRenderedMatches = renderGrepMatches(matches);
553
+ const returnedRenderedMatches = renderGrepMatches(compacted.matches);
554
+ const grepMetrics = reductionMetrics(rawRenderedMatches, returnedRenderedMatches);
555
+ const fullOutputHandle = outputTruncated ? storeToolOutput(rawRenderedMatches) : undefined;
556
+ return withScopedContext({
557
+ pattern,
558
+ path: searchPath,
559
+ glob: glob ?? null,
560
+ caseInsensitive,
561
+ matches: compacted.matches,
562
+ totalMatches,
563
+ returnedMatches,
564
+ omittedMatches,
565
+ omittedResultLines: compacted.omittedResultLines,
566
+ lineTruncated: compacted.lineTruncated,
567
+ truncated: omittedMatches > 0 || outputTruncated,
568
+ reducerName: 'grep-structured',
569
+ contentKind: 'search',
570
+ lossy: omittedMatches > 0 || outputTruncated,
571
+ parseTier: 'full',
572
+ ...grepMetrics,
573
+ ...(fullOutputHandle ? { handle: fullOutputHandle, rawHandle: fullOutputHandle, omittedChars: Math.max(0, rawRenderedMatches.length - returnedRenderedMatches.length) } : { omittedChars: 0 }),
574
+ suggestion: omittedMatches > 0 || outputTruncated ? 'Narrow the path, glob, or pattern to inspect omitted results, or use readToolOutput with the handle when present.' : undefined,
575
+ }, scopedContext);
396
576
  }
397
577
  catch (error) {
398
578
  return structuredToolFailure('grep', error, 'Check that the search path exists and the pattern is valid regex. Try a narrower path or simpler pattern.', searchPath);
@@ -400,7 +580,7 @@ export const hazeTools = {
400
580
  }),
401
581
  }),
402
582
  replaceLines: tool({
403
- 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.',
583
+ description: 'Replace a 1-based inclusive line range. Use after readFile when exact editFile text is ambiguous or stale.',
404
584
  inputSchema: z.object({
405
585
  path: z.string().describe('File path relative to the current workspace'),
406
586
  startLine: z.number().int().positive().describe('First 1-based line number to replace'),
@@ -412,6 +592,10 @@ export const hazeTools = {
412
592
  try {
413
593
  const absolutePath = resolveWorkspacePath(filePath);
414
594
  await assertNotIgnored(absolutePath, filePath, allowIgnored);
595
+ const scopedContext = await discoverScopedContext(filePath, context);
596
+ const scopedStop = scopedContextMutationStop('replaceLines', filePath, scopedContext);
597
+ if (scopedStop)
598
+ return scopedStop;
415
599
  const original = await fs.readFile(absolutePath, 'utf8');
416
600
  const hasTrailingNewline = original.endsWith('\n');
417
601
  const lines = original.split(/\r?\n/);
@@ -447,17 +631,21 @@ export const hazeTools = {
447
631
  }),
448
632
  }),
449
633
  writeFile: tool({
450
- 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.',
634
+ description: 'Create a UTF-8 file. Existing files require explicit full-rewrite approval.',
451
635
  inputSchema: z.object({
452
636
  path: z.string().describe('File path relative to the current workspace'),
453
637
  content: z.string().describe('Complete file contents to write'),
454
- 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.'),
455
- allowIgnored: z.boolean().default(false).describe('Write the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
638
+ overwriteExisting: z.boolean().default(false).describe('Approve intentional full rewrite of an existing file'),
639
+ allowIgnored: z.boolean().default(false).describe('Write a .gitignored file only when needed'),
456
640
  }),
457
641
  execute: async ({ path: filePath, content, overwriteExisting, allowIgnored }, context) => runDedupedTool('writeFile', { path: filePath, content, overwriteExisting, allowIgnored }, context, async () => {
458
642
  try {
459
643
  const absolutePath = resolveWorkspacePath(filePath);
460
644
  await assertNotIgnored(absolutePath, filePath, allowIgnored);
645
+ const scopedContext = await discoverScopedContext(filePath, context);
646
+ const scopedStop = scopedContextMutationStop('writeFile', filePath, scopedContext);
647
+ if (scopedStop)
648
+ return scopedStop;
461
649
  try {
462
650
  await fs.access(absolutePath);
463
651
  if (!overwriteExisting) {
@@ -479,19 +667,23 @@ export const hazeTools = {
479
667
  }),
480
668
  }),
481
669
  editFile: tool({
482
- 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.',
670
+ description: 'Apply unique text replacements. Batch same-file edits; reread and use replaceLines if matching fails.',
483
671
  inputSchema: z.object({
484
672
  path: z.string().describe('File path relative to the current workspace'),
485
673
  edits: z.array(z.object({
486
674
  oldText: z.string().min(1).describe('Exact text to replace; must appear exactly once'),
487
675
  newText: z.string().describe('Replacement text'),
488
676
  })).min(1).describe('One or more non-overlapping exact replacements'),
489
- allowIgnored: z.boolean().default(false).describe('Edit the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
677
+ allowIgnored: z.boolean().default(false).describe('Edit a .gitignored file only when needed'),
490
678
  }),
491
679
  execute: async ({ path: filePath, edits, allowIgnored }, context) => runDedupedTool('editFile', { path: filePath, edits, allowIgnored }, context, async () => {
492
680
  try {
493
681
  const absolutePath = resolveWorkspacePath(filePath);
494
682
  await assertNotIgnored(absolutePath, filePath, allowIgnored);
683
+ const scopedContext = await discoverScopedContext(filePath, context);
684
+ const scopedStop = scopedContextMutationStop('editFile', filePath, scopedContext);
685
+ if (scopedStop)
686
+ return scopedStop;
495
687
  const original = await fs.readFile(absolutePath, 'utf8');
496
688
  const ranges = edits.map((edit, index) => {
497
689
  const match = findEditRange(original, edit.oldText);
@@ -541,7 +733,7 @@ export const hazeTools = {
541
733
  }),
542
734
  }),
543
735
  writeTasks: tool({
544
- description: 'Create or replace your task list for multi-step work (3+ steps). Pass the COMPLETE list every time — this REPLACES the entire list. Mark one task in_progress, then completed. Keep at most one in_progress. Leave completed tasks when done — do not clear the list automatically.',
736
+ description: 'Replace the task list for substantial work. Update at meaningful phase changes, blockers, and completion; pass the complete list.',
545
737
  inputSchema: z.object({
546
738
  tasks: z.array(z.object({
547
739
  title: z.string().max(200).describe('Short task description'),
@@ -575,13 +767,62 @@ export const hazeTools = {
575
767
  in_progress: tasks.filter(t => t.status === 'in_progress').length,
576
768
  completed: tasks.filter(t => t.status === 'completed').length,
577
769
  };
578
- const list = tasks.map(t => ` ${STATUS_ICON[t.status]} ${t.title}`).join('\n');
579
- const summary = `Tasks (${counts.pending} pending, ${counts.in_progress} in progress, ${counts.completed} completed):\n${list}`;
580
- return { ok: true, taskCount: tasks.length, summary };
770
+ return { ok: true, taskCount: tasks.length, counts, summary: `Tasks: ${counts.pending} pending, ${counts.in_progress} in progress, ${counts.completed} completed.` };
581
771
  },
582
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
+ }),
583
824
  bash: tool({
584
- 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.',
825
+ description: 'Run workspace tests, builds, validation, or inspection. Use file tools for edits.',
585
826
  inputSchema: z.object({
586
827
  command: z.string().min(1).describe('Command to execute with bash -lc'),
587
828
  timeoutSeconds: z.number().int().positive().max(600).optional().describe('Timeout in seconds; defaults to 60'),
@@ -612,11 +853,22 @@ export const hazeTools = {
612
853
  settled = true;
613
854
  clearTimeout(timer);
614
855
  context.abortSignal?.removeEventListener('abort', abort);
615
- const truncatedStdout = truncate(stdout);
616
- const truncatedStderr = truncate(stderr);
617
856
  const validationSummary = isValidationClassification(classification)
618
- ? parseValidationOutput({ command, code, stdout, stderr, timedOut, stdoutTruncated: truncatedStdout.truncated, stderrTruncated: truncatedStderr.truncated, classification })
857
+ ? parseValidationOutput({ command, code, stdout, stderr, timedOut, stdoutTruncated: stdout.length > COMPACT_COMMAND_CHARS, stderrTruncated: stderr.length > COMPACT_COMMAND_CHARS, classification })
619
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
+ });
620
872
  resolve({
621
873
  ok: code === 0 && !timedOut,
622
874
  code,
@@ -625,8 +877,8 @@ export const hazeTools = {
625
877
  classification,
626
878
  durationMs: Date.now() - startedAt,
627
879
  timedOut,
628
- stdout: truncatedStdout,
629
- stderr: truncatedStderr,
880
+ stdout: output.stdout,
881
+ stderr: output.stderr,
630
882
  validationSummary,
631
883
  });
632
884
  });
@@ -1,3 +1,4 @@
1
+ import { MAX_CONTEXT_FILE_CHARS } from '../config/contextFiles.js';
1
2
  export function buildInitPrompt() {
2
3
  return `Initialize this repository for Haze by creating a best-practice AGENTS.md file.
3
4
 
@@ -8,7 +9,7 @@ Explore the codebase first, respecting .gitignore, but keep this quick and minim
8
9
  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
10
  5. Aim to finish in 12 tool calls or fewer. Do not read ignored files unless truly necessary.
10
11
 
11
- Create or update AGENTS.md at the workspace root. It should be concise and useful for future coding agents. Include sections when known:
12
+ Create or update AGENTS.md at the workspace root. It should be concise and useful for future coding agents. Keep it compact: the full file is injected into every request's system context and is truncated at ${MAX_CONTEXT_FILE_CHARS} characters, so prefer a target under ~${Math.round(MAX_CONTEXT_FILE_CHARS / 80 / 10) * 10} lines and omit anything an agent could discover by reading the source. Include sections when known:
12
13
  - Project overview
13
14
  - Common commands for install, development, typecheck, build, test, lint, release
14
15
  - Architecture and important directories
@@ -1,2 +1,7 @@
1
1
  import type { ContextFile } from '../config/contextFiles.js';
2
- export declare function buildSystemPrompt(contextFiles?: ContextFile[]): string;
2
+ export interface PromptSession {
3
+ start?: Date;
4
+ cwd?: string;
5
+ }
6
+ export declare function buildSystemPrompt(contextFiles?: ContextFile[], session?: PromptSession): string;
7
+ export declare function buildSubagentPrompt(contextFiles?: ContextFile[], session?: PromptSession): string;