@denizokcu/haze 0.4.0 → 0.6.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 (79) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +68 -36
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +789 -106
  5. package/dist/cli/commands/commands.d.ts +2 -1
  6. package/dist/cli/commands/commands.js +77 -102
  7. package/dist/cli/commands/formatters.d.ts +27 -0
  8. package/dist/cli/commands/formatters.js +137 -0
  9. package/dist/cli/commands/streaming.d.ts +14 -13
  10. package/dist/cli/commands/streaming.js +399 -665
  11. package/dist/config/contextFiles.d.ts +6 -0
  12. package/dist/config/contextFiles.js +47 -16
  13. package/dist/config/lspSettings.d.ts +16 -0
  14. package/dist/config/lspSettings.js +98 -0
  15. package/dist/config/mcpSettings.d.ts +24 -0
  16. package/dist/config/mcpSettings.js +100 -0
  17. package/dist/config/providers.d.ts +2 -5
  18. package/dist/config/providers.js +16 -12
  19. package/dist/config/settings.d.ts +34 -0
  20. package/dist/config/skillSettings.d.ts +15 -0
  21. package/dist/config/skillSettings.js +31 -0
  22. package/dist/config/updateCheck.d.ts +44 -0
  23. package/dist/config/updateCheck.js +83 -0
  24. package/dist/core/agent/requestAssembly.js +12 -1
  25. package/dist/core/agent/toolOutputStore.d.ts +6 -1
  26. package/dist/core/agent/toolOutputStore.js +33 -1
  27. package/dist/core/bashOutput/ansi.d.ts +1 -0
  28. package/dist/core/bashOutput/ansi.js +7 -0
  29. package/dist/core/bashOutput/command.d.ts +2 -0
  30. package/dist/core/bashOutput/command.js +62 -0
  31. package/dist/core/bashOutput/lineFilter.d.ts +25 -0
  32. package/dist/core/bashOutput/lineFilter.js +62 -0
  33. package/dist/core/bashOutput/reducers/content.d.ts +3 -0
  34. package/dist/core/bashOutput/reducers/content.js +134 -0
  35. package/dist/core/bashOutput/reducers/git.d.ts +1 -0
  36. package/dist/core/bashOutput/reducers/git.js +147 -0
  37. package/dist/core/bashOutput/reducers/search.d.ts +7 -0
  38. package/dist/core/bashOutput/reducers/search.js +76 -0
  39. package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
  40. package/dist/core/bashOutput/reducers/validation.js +41 -0
  41. package/dist/core/bashOutput/registry.d.ts +4 -0
  42. package/dist/core/bashOutput/registry.js +126 -0
  43. package/dist/core/bashOutput/types.d.ts +46 -0
  44. package/dist/core/bashOutput/types.js +1 -0
  45. package/dist/core/goal/completionPolicy.d.ts +1 -0
  46. package/dist/core/goal/completionPolicy.js +4 -0
  47. package/dist/core/safety/urlGuard.d.ts +37 -0
  48. package/dist/core/safety/urlGuard.js +206 -0
  49. package/dist/core/subagent/subagentRunner.d.ts +1 -1
  50. package/dist/core/subagent/subagentRunner.js +2 -2
  51. package/dist/core/toolOutput/reduction.d.ts +25 -0
  52. package/dist/core/toolOutput/reduction.js +23 -0
  53. package/dist/llm/client.d.ts +2 -2
  54. package/dist/llm/client.js +6 -4
  55. package/dist/llm/hazeTools.d.ts +133 -16
  56. package/dist/llm/hazeTools.js +205 -31
  57. package/dist/llm/initPrompt.js +2 -1
  58. package/dist/llm/lsp.d.ts +64 -0
  59. package/dist/llm/lsp.js +241 -0
  60. package/dist/llm/lspTools.d.ts +122 -0
  61. package/dist/llm/lspTools.js +115 -0
  62. package/dist/llm/mcp.d.ts +19 -0
  63. package/dist/llm/mcp.js +64 -0
  64. package/dist/llm/requestContext.d.ts +28 -0
  65. package/dist/llm/requestContext.js +56 -0
  66. package/dist/llm/systemPrompt.d.ts +4 -1
  67. package/dist/llm/systemPrompt.js +11 -3
  68. package/dist/llm/toolResultTypes.d.ts +1 -1
  69. package/dist/llm/webFetch.d.ts +57 -0
  70. package/dist/llm/webFetch.js +270 -0
  71. package/dist/skills/builder/SkillBuilder.js +23 -44
  72. package/dist/ui/components/MarkdownText.d.ts +2 -0
  73. package/dist/ui/components/MarkdownText.js +116 -3
  74. package/dist/ui/components/TextInput.d.ts +1 -1
  75. package/dist/utils/version.d.ts +20 -0
  76. package/dist/utils/version.js +72 -0
  77. package/package.json +18 -10
  78. package/dist/cli/commands/skills.d.ts +0 -4
  79. package/dist/cli/commands/skills.js +0 -38
@@ -1,10 +1,12 @@
1
1
  import type { ToolDiffLine, ToolFailureReasonCode } from './toolResultTypes.js';
2
+ import { type ContextFile } from '../config/contextFiles.js';
2
3
  export declare const hazeTools: {
3
4
  listFiles: import("ai").Tool<{
4
5
  path: string;
5
6
  recursive: boolean;
6
7
  maxEntries: number;
7
8
  includeIgnored: boolean;
9
+ includeSizes: boolean;
8
10
  cursor?: string | undefined;
9
11
  }, {
10
12
  ok: boolean;
@@ -21,22 +23,23 @@ export declare const hazeTools: {
21
23
  duplicateSkipped: true;
22
24
  toolName: string;
23
25
  reason: string;
24
- } | {
26
+ } | ({
25
27
  path: string;
26
28
  recursive: boolean;
27
29
  includeIgnored: boolean;
30
+ includeSizes: boolean;
28
31
  cursor: string | undefined;
29
32
  nextCursor: string | undefined;
30
33
  ignoredSkipped: number;
31
- entries: {
32
- path: string;
33
- type: "file" | "directory";
34
- size?: number;
35
- }[];
34
+ entryFormat: string;
35
+ entries: string[];
36
36
  truncated: boolean;
37
- }>;
37
+ } & {
38
+ applicableProjectInstructions?: ContextFile[];
39
+ })>;
38
40
  readFile: import("ai").Tool<{
39
41
  path: string;
42
+ mode: "exact" | "outline";
40
43
  allowIgnored: boolean;
41
44
  offset?: number | undefined;
42
45
  limit?: number | undefined;
@@ -55,8 +58,12 @@ export declare const hazeTools: {
55
58
  duplicateSkipped: true;
56
59
  toolName: string;
57
60
  reason: string;
58
- } | {
61
+ } | ({
62
+ outline?: boolean | undefined;
63
+ outlineEntries?: number | undefined;
64
+ warning?: string | undefined;
59
65
  path: string;
66
+ mode: "exact" | "outline";
60
67
  startLine: number;
61
68
  endLine: number;
62
69
  totalLines: number;
@@ -64,7 +71,9 @@ export declare const hazeTools: {
64
71
  nextOffset: number | undefined;
65
72
  truncated: boolean;
66
73
  lineTruncated: boolean;
67
- }>;
74
+ } & {
75
+ applicableProjectInstructions?: ContextFile[];
76
+ })>;
68
77
  grep: import("ai").Tool<{
69
78
  pattern: string;
70
79
  path: string;
@@ -87,7 +96,7 @@ export declare const hazeTools: {
87
96
  duplicateSkipped: true;
88
97
  toolName: string;
89
98
  reason: string;
90
- } | {
99
+ } | ({
91
100
  pattern: string;
92
101
  path: string;
93
102
  glob: string | null;
@@ -95,10 +104,17 @@ export declare const hazeTools: {
95
104
  matches: never[];
96
105
  totalMatches: number;
97
106
  truncated: boolean;
98
- returnedMatches?: undefined;
99
- omittedMatches?: undefined;
100
- suggestion?: undefined;
101
- } | {
107
+ } & {
108
+ applicableProjectInstructions?: ContextFile[];
109
+ }) | ({
110
+ suggestion: string | undefined;
111
+ omittedChars: number;
112
+ rawChars: number;
113
+ returnedChars: number;
114
+ rawTokensEstimate: number;
115
+ returnedTokensEstimate: number;
116
+ estimatedSavedTokens: number;
117
+ savingsPct: number;
102
118
  pattern: string;
103
119
  path: string;
104
120
  glob: string | null;
@@ -112,9 +128,16 @@ export declare const hazeTools: {
112
128
  totalMatches: number;
113
129
  returnedMatches: number;
114
130
  omittedMatches: number;
131
+ omittedResultLines: number;
132
+ lineTruncated: boolean;
115
133
  truncated: boolean;
116
- suggestion: string | undefined;
117
- }>;
134
+ reducerName: string;
135
+ contentKind: string;
136
+ lossy: boolean;
137
+ parseTier: string;
138
+ } & {
139
+ applicableProjectInstructions?: ContextFile[];
140
+ })>;
118
141
  replaceLines: import("ai").Tool<{
119
142
  path: string;
120
143
  startLine: number;
@@ -122,6 +145,15 @@ export declare const hazeTools: {
122
145
  content: string;
123
146
  allowIgnored: boolean;
124
147
  }, {
148
+ ok: boolean;
149
+ toolName: string;
150
+ path: string;
151
+ error: string;
152
+ reasonCode: "scoped_instructions_discovered";
153
+ recoverable: boolean;
154
+ suggestedNextStep: string;
155
+ applicableProjectInstructions: ContextFile[];
156
+ } | {
125
157
  ok: boolean;
126
158
  toolName: string;
127
159
  path: string | undefined;
@@ -156,6 +188,15 @@ export declare const hazeTools: {
156
188
  overwriteExisting: boolean;
157
189
  allowIgnored: boolean;
158
190
  }, {
191
+ ok: boolean;
192
+ toolName: string;
193
+ path: string;
194
+ error: string;
195
+ reasonCode: "scoped_instructions_discovered";
196
+ recoverable: boolean;
197
+ suggestedNextStep: string;
198
+ applicableProjectInstructions: ContextFile[];
199
+ } | {
159
200
  ok: boolean;
160
201
  toolName: string;
161
202
  path: string | undefined;
@@ -184,6 +225,15 @@ export declare const hazeTools: {
184
225
  }[];
185
226
  allowIgnored: boolean;
186
227
  }, {
228
+ ok: boolean;
229
+ toolName: string;
230
+ path: string;
231
+ error: string;
232
+ reasonCode: "scoped_instructions_discovered";
233
+ recoverable: boolean;
234
+ suggestedNextStep: string;
235
+ applicableProjectInstructions: ContextFile[];
236
+ } | {
187
237
  ok: boolean;
188
238
  toolName: string;
189
239
  path: string | undefined;
@@ -240,10 +290,77 @@ export declare const hazeTools: {
240
290
  handle: string;
241
291
  offset: number;
242
292
  limit: number;
293
+ contextLines: number;
294
+ query?: string | undefined;
243
295
  }, import("../core/agent/toolOutputStore.js").StoredToolOutputPage | {
244
296
  ok: boolean;
245
297
  error: string;
246
298
  }>;
299
+ fetch: import("ai").Tool<{
300
+ url: string;
301
+ format: "text" | "auto";
302
+ }, {
303
+ ok: boolean;
304
+ toolName: string;
305
+ path: string | undefined;
306
+ error: string;
307
+ reasonCode: ToolFailureReasonCode | undefined;
308
+ recoverable: boolean;
309
+ suggestedNextStep: string;
310
+ recoveryTool: string | undefined;
311
+ recoveryInput: unknown;
312
+ } | {
313
+ ok: true;
314
+ duplicateSkipped: true;
315
+ toolName: string;
316
+ reason: string;
317
+ } | {
318
+ handle: string;
319
+ rawHandle: string;
320
+ omittedChars: number;
321
+ rawChars: number;
322
+ returnedChars: number;
323
+ rawTokensEstimate: number;
324
+ returnedTokensEstimate: number;
325
+ estimatedSavedTokens: number;
326
+ savingsPct: number;
327
+ ok: boolean;
328
+ url: string;
329
+ status: number;
330
+ statusText: string;
331
+ contentType: string;
332
+ bytes: number;
333
+ redirected: boolean;
334
+ extractionMethod: "json" | "text" | "markdown";
335
+ truncated: boolean;
336
+ content: string;
337
+ reducerName: string;
338
+ contentKind: string;
339
+ lossy: boolean;
340
+ parseTier: string;
341
+ } | {
342
+ omittedChars: number;
343
+ rawChars: number;
344
+ returnedChars: number;
345
+ rawTokensEstimate: number;
346
+ returnedTokensEstimate: number;
347
+ estimatedSavedTokens: number;
348
+ savingsPct: number;
349
+ ok: boolean;
350
+ url: string;
351
+ status: number;
352
+ statusText: string;
353
+ contentType: string;
354
+ bytes: number;
355
+ redirected: boolean;
356
+ extractionMethod: "json" | "text" | "markdown";
357
+ truncated: boolean;
358
+ content: string;
359
+ reducerName: string;
360
+ contentKind: string;
361
+ lossy: boolean;
362
+ parseTier: string;
363
+ }>;
247
364
  bash: import("ai").Tool<{
248
365
  command: string;
249
366
  allowMutation: boolean;
@@ -10,11 +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';
13
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';
14
18
  const MAX_OUTPUT_CHARS = 50_000;
15
19
  const DEFAULT_READ_LINES = 300;
16
20
  const COMPACT_COMMAND_CHARS = 12_000;
17
21
  const SHORT_VALIDATION_CHARS = 2_000;
22
+ const GREP_MAX_OUTPUT_CHARS = 30_000;
23
+ const GREP_MAX_LINE_CHARS = 500;
18
24
  const execFile = promisify(execFileCallback);
19
25
  async function isGitIgnored(absolutePath) {
20
26
  const relative = workspaceRelativePath(absolutePath);
@@ -61,6 +67,31 @@ function compactStoredOutput(text, maxChars = COMPACT_COMMAND_CHARS) {
61
67
  handle,
62
68
  };
63
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
+ }
64
95
  function stripLineNumberPrefixes(text) {
65
96
  return text.replace(/^\s*\d+\s+\| ?/gm, '');
66
97
  }
@@ -123,12 +154,45 @@ function hazeContext(context) {
123
154
  ? context.experimental_context
124
155
  : undefined;
125
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
+ }
126
184
  function isMutatingTool(toolName) {
127
185
  return ['editFile', 'replaceLines', 'writeFile'].includes(toolName);
128
186
  }
129
187
  function isReadOnlyFileTool(toolName) {
130
188
  return ['listFiles', 'readFile', 'grep'].includes(toolName);
131
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
+ }
132
196
  function inputPath(input) {
133
197
  return typeof input === 'object' && input != null && 'path' in input && typeof input.path === 'string'
134
198
  ? input.path
@@ -153,6 +217,20 @@ function structuredToolFailure(toolName, error, suggestedNextStep, pathForError,
153
217
  };
154
218
  }
155
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
+ }
156
234
  function splitDiffLines(text) {
157
235
  const lines = text.split(/\r?\n/);
158
236
  if (text.endsWith('\n') || text.endsWith('\r\n'))
@@ -205,14 +283,16 @@ async function runDedupedTool(toolName, input, context, execute) {
205
283
  }
206
284
  const completedAt = ctx.completedToolCalls.get(key);
207
285
  const readAfterFailedMutation = toolName === 'readFile' && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput);
208
- if ((isReadOnlyFileTool(toolName) || toolName === 'bash') && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
286
+ if ((isDeduplicableReadOnlyTool(toolName)) && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
209
287
  return {
210
288
  ok: true,
211
289
  duplicateSkipped: true,
212
290
  toolName,
213
291
  reason: toolName === 'bash'
214
292
  ? 'Skipped duplicate bash command; no files changed since the previous run.'
215
- : '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.',
216
296
  };
217
297
  }
218
298
  if (ctx.inFlightToolCalls.has(key)) {
@@ -274,8 +354,9 @@ export const hazeTools = {
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
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,14 +394,15 @@ export const hazeTools = {
307
394
  }),
308
395
  }),
309
396
  readFile: tool({
310
- description: 'Read numbered lines from a UTF-8 workspace file. Defaults to 300 lines and returns nextOffset when more remain.',
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
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'),
315
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);
@@ -323,35 +411,45 @@ export const hazeTools = {
323
411
  const start = offset == null ? 0 : offset - 1;
324
412
  const requestedEnd = Math.min(lines.length, start + (limit ?? DEFAULT_READ_LINES));
325
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 }));
326
417
  const numberedLines = [];
327
418
  let includedLines = 0;
328
419
  let lineTruncated = false;
329
- for (const [index, line] of selectedLines.entries()) {
330
- const prefix = `${String(start + index + 1).padStart(4, ' ')} | `;
420
+ for (const entry of displayLines) {
421
+ const prefix = `${String(entry.lineNumber).padStart(4, ' ')} | `;
331
422
  const remaining = MAX_OUTPUT_CHARS - numberedLines.join('\n').length - (numberedLines.length > 0 ? 1 : 0);
332
423
  if (remaining <= prefix.length)
333
424
  break;
334
- if (prefix.length + line.length > remaining) {
335
- numberedLines.push(`${prefix}${line.slice(0, Math.max(0, remaining - prefix.length - 26))}[line content truncated]`);
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]`);
336
427
  includedLines += 1;
337
428
  lineTruncated = true;
338
429
  break;
339
430
  }
340
- numberedLines.push(`${prefix}${line}`);
431
+ numberedLines.push(`${prefix}${entry.text}`);
341
432
  includedLines += 1;
342
433
  }
343
- const endLine = start + includedLines;
344
- const hasMore = endLine < lines.length;
345
- return {
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({
346
442
  path: filePath,
443
+ mode,
347
444
  startLine: start + 1,
348
445
  endLine,
349
446
  totalLines: lines.length,
350
447
  content: numberedLines.join('\n'),
351
- nextOffset: hasMore ? endLine + 1 : undefined,
448
+ nextOffset: hasMore ? requestedEnd + 1 : undefined,
352
449
  truncated: hasMore || lineTruncated,
353
450
  lineTruncated,
354
- };
451
+ ...(mode === 'outline' ? { outline: true, outlineEntries: includedLines, warning: 'Outline mode is lossy discovery output. Use exact readFile around relevant lines before editing.' } : {}),
452
+ }, scopedContext);
355
453
  }
356
454
  catch (error) {
357
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);
@@ -395,8 +493,9 @@ export const hazeTools = {
395
493
  throw error;
396
494
  }
397
495
  }
496
+ const scopedContext = await discoverScopedContext(searchPath, context);
398
497
  if (!stdout) {
399
- 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);
400
499
  }
401
500
  const lines = stdout.split('\n').filter(Boolean);
402
501
  const matches = [];
@@ -448,18 +547,32 @@ export const hazeTools = {
448
547
  pendingContext = [];
449
548
  retainFollowingContext = true;
450
549
  }
451
- return {
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({
452
557
  pattern,
453
558
  path: searchPath,
454
559
  glob: glob ?? null,
455
560
  caseInsensitive,
456
- matches,
561
+ matches: compacted.matches,
457
562
  totalMatches,
458
563
  returnedMatches,
459
564
  omittedMatches,
460
- truncated: omittedMatches > 0,
461
- suggestion: omittedMatches > 0 ? 'Narrow the path, glob, or pattern to inspect omitted matches.' : undefined,
462
- };
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);
463
576
  }
464
577
  catch (error) {
465
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);
@@ -479,6 +592,10 @@ export const hazeTools = {
479
592
  try {
480
593
  const absolutePath = resolveWorkspacePath(filePath);
481
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;
482
599
  const original = await fs.readFile(absolutePath, 'utf8');
483
600
  const hasTrailingNewline = original.endsWith('\n');
484
601
  const lines = original.split(/\r?\n/);
@@ -525,6 +642,10 @@ export const hazeTools = {
525
642
  try {
526
643
  const absolutePath = resolveWorkspacePath(filePath);
527
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;
528
649
  try {
529
650
  await fs.access(absolutePath);
530
651
  if (!overwriteExisting) {
@@ -559,6 +680,10 @@ export const hazeTools = {
559
680
  try {
560
681
  const absolutePath = resolveWorkspacePath(filePath);
561
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;
562
687
  const original = await fs.readFile(absolutePath, 'utf8');
563
688
  const ranges = edits.map((edit, index) => {
564
689
  const match = findEditRange(original, edit.oldText);
@@ -651,12 +776,51 @@ export const hazeTools = {
651
776
  handle: z.string().min(1).describe('Output handle from a prior tool result'),
652
777
  offset: z.number().int().nonnegative().default(0).describe('Character offset to start reading'),
653
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'),
654
781
  }),
655
- execute: async ({ handle, offset, limit }) => {
656
- const page = readStoredToolOutput(handle, offset, limit);
782
+ execute: async ({ handle, offset, limit, query, contextLines }) => {
783
+ const page = readStoredToolOutput(handle, offset, limit, { query, contextLines });
657
784
  return page ?? { ok: false, error: `Unknown or expired tool output handle: ${handle}` };
658
785
  },
659
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
+ }),
660
824
  bash: tool({
661
825
  description: 'Run workspace tests, builds, validation, or inspection. Use file tools for edits.',
662
826
  inputSchema: z.object({
@@ -693,8 +857,18 @@ export const hazeTools = {
693
857
  ? parseValidationOutput({ command, code, stdout, stderr, timedOut, stdoutTruncated: stdout.length > COMPACT_COMMAND_CHARS, stderrTruncated: stderr.length > COMPACT_COMMAND_CHARS, classification })
694
858
  : undefined;
695
859
  const validationPassed = validationSummary?.status === 'passed';
696
- const stdoutResult = compactStoredOutput(stdout, validationPassed ? SHORT_VALIDATION_CHARS : COMPACT_COMMAND_CHARS);
697
- const stderrResult = compactStoredOutput(stderr, validationPassed ? SHORT_VALIDATION_CHARS : COMPACT_COMMAND_CHARS);
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
+ });
698
872
  resolve({
699
873
  ok: code === 0 && !timedOut,
700
874
  code,
@@ -703,8 +877,8 @@ export const hazeTools = {
703
877
  classification,
704
878
  durationMs: Date.now() - startedAt,
705
879
  timedOut,
706
- stdout: stdoutResult,
707
- stderr: stderrResult,
880
+ stdout: output.stdout,
881
+ stderr: output.stderr,
708
882
  validationSummary,
709
883
  });
710
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