@denizokcu/haze 0.2.0 → 0.4.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 (50) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +38 -22
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +411 -74
  5. package/dist/cli/commands/commands.js +122 -54
  6. package/dist/cli/commands/formatters.d.ts +2 -0
  7. package/dist/cli/commands/formatters.js +34 -0
  8. package/dist/cli/commands/streaming.d.ts +36 -1
  9. package/dist/cli/commands/streaming.js +312 -103
  10. package/dist/cli/contextReport.d.ts +1 -0
  11. package/dist/cli/contextReport.js +47 -0
  12. package/dist/config/contextFiles.d.ts +25 -0
  13. package/dist/config/contextFiles.js +53 -0
  14. package/dist/config/providerPresets.d.ts +23 -0
  15. package/dist/config/providerPresets.js +230 -0
  16. package/dist/core/agent/compaction.d.ts +3 -0
  17. package/dist/core/agent/compaction.js +23 -3
  18. package/dist/core/agent/contextBudget.d.ts +33 -0
  19. package/dist/core/agent/contextBudget.js +88 -0
  20. package/dist/core/agent/requestAssembly.d.ts +22 -0
  21. package/dist/core/agent/requestAssembly.js +146 -0
  22. package/dist/core/agent/toolOutputStore.d.ts +11 -0
  23. package/dist/core/agent/toolOutputStore.js +33 -0
  24. package/dist/core/agent/workState.d.ts +38 -0
  25. package/dist/core/agent/workState.js +89 -0
  26. package/dist/core/goal/completionPolicy.js +1 -1
  27. package/dist/core/goal/sessionGoal.d.ts +2 -0
  28. package/dist/core/goal/sessionGoal.js +8 -1
  29. package/dist/core/log/llmLog.d.ts +68 -0
  30. package/dist/core/log/llmLog.js +55 -0
  31. package/dist/core/session/sessionStore.d.ts +6 -0
  32. package/dist/core/session/sessionStore.js +5 -0
  33. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  34. package/dist/core/subagent/subagentRunner.js +5 -15
  35. package/dist/core/tasks/taskStorage.d.ts +13 -0
  36. package/dist/core/tasks/taskStorage.js +29 -0
  37. package/dist/core/validation/outputParser.js +15 -2
  38. package/dist/llm/client.d.ts +39 -0
  39. package/dist/llm/client.js +46 -2
  40. package/dist/llm/hazeTools.d.ts +53 -12
  41. package/dist/llm/hazeTools.js +170 -46
  42. package/dist/llm/systemPrompt.d.ts +6 -1
  43. package/dist/llm/systemPrompt.js +42 -79
  44. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  45. package/dist/skills/builder/SkillBuilder.js +68 -65
  46. package/dist/skills/skillTools.d.ts +2 -19
  47. package/dist/skills/skillTools.js +28 -19
  48. package/dist/ui/components/TextInput.d.ts +2 -1
  49. package/dist/ui/components/TextInput.js +6 -2
  50. package/package.json +2 -1
@@ -0,0 +1,29 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { resolveWorkspacePath } from '../../utils/path.js';
5
+ const TASKS_DIR = '.haze';
6
+ const TASKS_FILE = 'tasks.json';
7
+ export function getTasksFilePath() {
8
+ return resolveWorkspacePath(path.join(TASKS_DIR, TASKS_FILE));
9
+ }
10
+ export function generateTaskId() {
11
+ return randomUUID().slice(0, 8);
12
+ }
13
+ export async function loadTasks() {
14
+ try {
15
+ const content = await fs.readFile(getTasksFilePath(), 'utf-8');
16
+ return JSON.parse(content);
17
+ }
18
+ catch {
19
+ return [];
20
+ }
21
+ }
22
+ export async function saveTasks(tasks) {
23
+ const filePath = getTasksFilePath();
24
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
25
+ await fs.writeFile(filePath, JSON.stringify(tasks, null, 2), 'utf-8');
26
+ }
27
+ export async function clearTasks() {
28
+ await saveTasks([]);
29
+ }
@@ -20,7 +20,6 @@ export function parseValidationOutput(input) {
20
20
  const failedTests = [];
21
21
  const failedFiles = [];
22
22
  const kind = inferKind(input.command, input.classification);
23
- const status = input.timedOut ? 'timed_out' : input.code === 0 ? 'passed' : input.code == null ? 'unknown' : 'failed';
24
23
  for (const line of lines) {
25
24
  const ts = line.match(/^(.+?\.(?:ts|tsx|js|jsx|mts|cts))\((\d+),(\d+)\):\s+(error|warning)\s+TS\d+:\s+(.+)$/);
26
25
  if (ts) {
@@ -45,7 +44,7 @@ export function parseValidationOutput(input) {
45
44
  const vitestFile = line.match(/^\s*(?:FAIL|FAILED|✓|✗|❯)?\s*([^\s]+\.(?:test|spec)\.(?:ts|tsx|js|jsx))/i);
46
45
  if (vitestFile)
47
46
  failedFiles.push(vitestFile[1] ?? '');
48
- const testName = line.match(/^\s*(?:FAIL|✗|×|●|-)\s+(.+)$/);
47
+ const testName = line.match(/^\s*(?:FAIL|✗|×|●)\s+(.+)$/);
49
48
  if (testName && !/^(FAIL|FAILED)\s+\S+\.(?:test|spec)\./i.test(line.trim()))
50
49
  failedTests.push((testName[1] ?? '').trim());
51
50
  const genericFile = line.match(/([^\s()]+\.(?:ts|tsx|js|jsx|mts|cts)):(\d+):(\d+)/);
@@ -59,6 +58,20 @@ export function parseValidationOutput(input) {
59
58
  const uniqueTests = uniq(failedTests).slice(0, 10);
60
59
  const diagCount = diagnostics.length;
61
60
  const rawOutputTruncated = Boolean(input.stdoutTruncated || input.stderrTruncated);
61
+ // Pipes (e.g. `npm test | tail`) and process substitutions can mask a
62
+ // non-zero exit code behind the final command in the pipeline. Treat
63
+ // parsed failure evidence as authoritative over `code` so a green exit
64
+ // status does not override real failures the parser already found.
65
+ const hasFailureEvidence = uniqueTests.length > 0 || diagCount > 0;
66
+ const status = input.timedOut
67
+ ? 'timed_out'
68
+ : hasFailureEvidence
69
+ ? 'failed'
70
+ : input.code === 0
71
+ ? 'passed'
72
+ : input.code == null
73
+ ? 'unknown'
74
+ : 'failed';
62
75
  let summaryText;
63
76
  if (status === 'passed')
64
77
  summaryText = `${kind} passed`;
@@ -1 +1,40 @@
1
+ export interface ProviderCapabilities {
2
+ reportsCacheUsage: boolean;
3
+ supportsPromptCacheKey: boolean;
4
+ supportsExtendedCacheRetention: boolean;
5
+ supportsStickySessionId: boolean;
6
+ supportsServerCompaction: boolean;
7
+ supportsTextVerbosity: boolean;
8
+ }
9
+ export interface ModelRuntimeConfig {
10
+ providerName: string;
11
+ baseURL: string;
12
+ modelName: string;
13
+ cacheKey: string;
14
+ capabilities: ProviderCapabilities;
15
+ }
16
+ export declare function modelWithConfig(session?: {
17
+ cwd?: string;
18
+ }): Promise<{
19
+ model: import("@ai-sdk/provider").LanguageModelV3;
20
+ config: {
21
+ providerName: string;
22
+ baseURL: string;
23
+ modelName: string;
24
+ cacheKey: string;
25
+ capabilities: ProviderCapabilities;
26
+ };
27
+ }>;
1
28
  export declare function model(): Promise<import("@ai-sdk/provider").LanguageModelV3>;
29
+ export declare function cacheKeyFor(name: string, cwd?: string): string;
30
+ export declare function providerRequestSettings(config: ModelRuntimeConfig): {
31
+ headers?: {
32
+ 'x-session-id': string;
33
+ } | undefined;
34
+ providerOptions?: {
35
+ openai: {
36
+ textVerbosity?: "low" | undefined;
37
+ promptCacheKey?: string | undefined;
38
+ };
39
+ } | undefined;
40
+ };
@@ -1,11 +1,55 @@
1
1
  import { createOpenAI } from '@ai-sdk/openai';
2
+ import crypto from 'node:crypto';
2
3
  import { readSettings } from '../config/settings.js';
3
4
  import { activeModel } from '../config/providers.js';
4
- export async function model() {
5
+ function capabilities(providerName, baseURL) {
6
+ const directOpenAI = providerName === 'openai' || /api\.openai\.com/i.test(baseURL);
7
+ const openRouter = providerName === 'openrouter' || /openrouter\.ai/i.test(baseURL);
8
+ return {
9
+ reportsCacheUsage: directOpenAI || openRouter,
10
+ supportsPromptCacheKey: directOpenAI,
11
+ supportsExtendedCacheRetention: false,
12
+ supportsStickySessionId: openRouter,
13
+ supportsServerCompaction: false,
14
+ supportsTextVerbosity: directOpenAI,
15
+ };
16
+ }
17
+ export async function modelWithConfig(session) {
5
18
  const settings = await readSettings();
6
19
  const selection = activeModel(settings);
7
20
  const baseURL = process.env.OPENAI_BASE_URL ?? selection.provider.url;
8
21
  const apiKey = process.env.OPENAI_API_KEY ?? selection.provider.key ?? settings.apiKey ?? 'not-needed';
9
22
  const name = process.env.HAZE_MODEL ?? selection.model;
10
- return createOpenAI({ apiKey, baseURL }).chat(name);
23
+ const cacheSeed = session?.cwd ?? process.cwd();
24
+ const cacheKey = crypto.createHash('sha256').update(`${cacheSeed}\0${name}`).digest('hex').slice(0, 32);
25
+ return {
26
+ model: createOpenAI({ apiKey, baseURL }).chat(name),
27
+ config: {
28
+ providerName: selection.provider.name,
29
+ baseURL,
30
+ modelName: name,
31
+ cacheKey,
32
+ capabilities: capabilities(selection.provider.name, baseURL),
33
+ },
34
+ };
35
+ }
36
+ export async function model() {
37
+ return (await modelWithConfig()).model;
38
+ }
39
+ export function cacheKeyFor(name, cwd) {
40
+ const seed = cwd ?? process.cwd();
41
+ return crypto.createHash('sha256').update(`${seed}\0${name}`).digest('hex').slice(0, 32);
42
+ }
43
+ export function providerRequestSettings(config) {
44
+ return {
45
+ ...(config.capabilities.supportsPromptCacheKey || config.capabilities.supportsTextVerbosity ? {
46
+ providerOptions: {
47
+ openai: {
48
+ ...(config.capabilities.supportsPromptCacheKey ? { promptCacheKey: config.cacheKey } : {}),
49
+ ...(config.capabilities.supportsTextVerbosity ? { textVerbosity: 'low' } : {}),
50
+ },
51
+ },
52
+ } : {}),
53
+ ...(config.capabilities.supportsStickySessionId ? { headers: { 'x-session-id': config.cacheKey } } : {}),
54
+ };
11
55
  }
@@ -56,23 +56,14 @@ export declare const hazeTools: {
56
56
  toolName: string;
57
57
  reason: string;
58
58
  } | {
59
- text: string;
60
- truncated: boolean;
61
- omittedChars?: undefined;
62
59
  path: string;
63
60
  startLine: number;
64
61
  endLine: number;
65
62
  totalLines: number;
66
- lineNumberedText: string;
67
- } | {
68
- text: string;
63
+ content: string;
64
+ nextOffset: number | undefined;
69
65
  truncated: boolean;
70
- omittedChars: number;
71
- path: string;
72
- startLine: number;
73
- endLine: number;
74
- totalLines: number;
75
- lineNumberedText: string;
66
+ lineTruncated: boolean;
76
67
  }>;
77
68
  grep: import("ai").Tool<{
78
69
  pattern: string;
@@ -96,6 +87,17 @@ export declare const hazeTools: {
96
87
  duplicateSkipped: true;
97
88
  toolName: string;
98
89
  reason: string;
90
+ } | {
91
+ pattern: string;
92
+ path: string;
93
+ glob: string | null;
94
+ caseInsensitive: boolean;
95
+ matches: never[];
96
+ totalMatches: number;
97
+ truncated: boolean;
98
+ returnedMatches?: undefined;
99
+ omittedMatches?: undefined;
100
+ suggestion?: undefined;
99
101
  } | {
100
102
  pattern: string;
101
103
  path: string;
@@ -108,7 +110,10 @@ export declare const hazeTools: {
108
110
  isContext: boolean;
109
111
  }[];
110
112
  totalMatches: number;
113
+ returnedMatches: number;
114
+ omittedMatches: number;
111
115
  truncated: boolean;
116
+ suggestion: string | undefined;
112
117
  }>;
113
118
  replaceLines: import("ai").Tool<{
114
119
  path: string;
@@ -203,6 +208,42 @@ export declare const hazeTools: {
203
208
  diffLineCount: number;
204
209
  diff: ToolDiffLine[] | undefined;
205
210
  }>;
211
+ writeTasks: import("ai").Tool<{
212
+ tasks: {
213
+ title: string;
214
+ status?: "pending" | "in_progress" | "completed" | undefined;
215
+ }[];
216
+ }, {
217
+ ok: boolean;
218
+ error: string;
219
+ taskCount?: undefined;
220
+ summary?: undefined;
221
+ counts?: undefined;
222
+ } | {
223
+ ok: boolean;
224
+ taskCount: number;
225
+ summary: string;
226
+ error?: undefined;
227
+ counts?: undefined;
228
+ } | {
229
+ ok: boolean;
230
+ taskCount: number;
231
+ counts: {
232
+ pending: number;
233
+ in_progress: number;
234
+ completed: number;
235
+ };
236
+ summary: string;
237
+ error?: undefined;
238
+ }>;
239
+ readToolOutput: import("ai").Tool<{
240
+ handle: string;
241
+ offset: number;
242
+ limit: number;
243
+ }, import("../core/agent/toolOutputStore.js").StoredToolOutputPage | {
244
+ ok: boolean;
245
+ error: string;
246
+ }>;
206
247
  bash: import("ai").Tool<{
207
248
  command: string;
208
249
  allowMutation: boolean;
@@ -6,10 +6,15 @@ import { tool } from 'ai';
6
6
  import { rgPath } from '@vscode/ripgrep';
7
7
  import { z } from 'zod';
8
8
  import { walkDir } from '../utils/fs.js';
9
+ import { generateTaskId, saveTasks } from '../core/tasks/taskStorage.js';
9
10
  import { workspaceRoot, resolveWorkspacePath, workspaceRelativePath } from '../utils/path.js';
10
11
  import { classifyBashCommand, isValidationClassification } from '../core/safety/bashClassifier.js';
11
12
  import { parseValidationOutput } from '../core/validation/outputParser.js';
13
+ import { readToolOutput as readStoredToolOutput, storeToolOutput } from '../core/agent/toolOutputStore.js';
12
14
  const MAX_OUTPUT_CHARS = 50_000;
15
+ const DEFAULT_READ_LINES = 300;
16
+ const COMPACT_COMMAND_CHARS = 12_000;
17
+ const SHORT_VALIDATION_CHARS = 2_000;
13
18
  const execFile = promisify(execFileCallback);
14
19
  async function isGitIgnored(absolutePath) {
15
20
  const relative = workspaceRelativePath(absolutePath);
@@ -43,18 +48,19 @@ async function assertNotIgnored(absolutePath, inputPath, allowIgnored) {
43
48
  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' });
44
49
  }
45
50
  }
46
- function truncate(text, maxChars = MAX_OUTPUT_CHARS) {
51
+ function compactStoredOutput(text, maxChars = COMPACT_COMMAND_CHARS) {
47
52
  if (text.length <= maxChars)
48
53
  return { text, truncated: false };
54
+ const handle = storeToolOutput(text);
55
+ const headChars = Math.floor(maxChars * 0.4);
56
+ const tailChars = maxChars - headChars;
49
57
  return {
50
- text: text.slice(0, maxChars),
58
+ text: `${text.slice(0, headChars)}\n\n[... ${text.length - maxChars} characters omitted; use readToolOutput with handle ${handle} ...]\n\n${text.slice(-tailChars)}`,
51
59
  truncated: true,
52
60
  omittedChars: text.length - maxChars,
61
+ handle,
53
62
  };
54
63
  }
55
- function numberLines(lines, startLine) {
56
- return lines.map((line, index) => `${String(startLine + index).padStart(4, ' ')} | ${line}`).join('\n');
57
- }
58
64
  function stripLineNumberPrefixes(text) {
59
65
  return text.replace(/^\s*\d+\s+\| ?/gm, '');
60
66
  }
@@ -261,13 +267,13 @@ async function runDedupedTool(toolName, input, context, execute) {
261
267
  }
262
268
  export const hazeTools = {
263
269
  listFiles: tool({
264
- description: 'List files and directories in the current workspace. Prefer this over bash ls/find for discovering project structure.',
270
+ description: 'List workspace files/directories with pagination. Prefer this to bash for discovery.',
265
271
  inputSchema: z.object({
266
272
  path: z.string().default('.').describe('Directory path relative to the current workspace'),
267
273
  recursive: z.boolean().default(false).describe('Whether to list files recursively'),
268
274
  maxEntries: z.number().int().positive().max(500).default(100).describe('Maximum number of entries to return'),
269
275
  cursor: z.string().optional().describe('Pagination cursor from a previous listFiles result. Continue after that entry.'),
270
- includeIgnored: z.boolean().default(false).describe('Include files ignored by .gitignore. Use only when explicitly needed.'),
276
+ includeIgnored: z.boolean().default(false).describe('Include .gitignored paths only when needed'),
271
277
  }),
272
278
  execute: async ({ path: dirPath, recursive, maxEntries, cursor, includeIgnored }, context) => runDedupedTool('listFiles', { path: dirPath, recursive, maxEntries, cursor, includeIgnored }, context, async () => {
273
279
  try {
@@ -301,12 +307,12 @@ export const hazeTools = {
301
307
  }),
302
308
  }),
303
309
  readFile: tool({
304
- description: 'Read a UTF-8 text file from the current workspace. Supports optional 1-based line offset and line limit.',
310
+ description: 'Read numbered lines from a UTF-8 workspace file. Defaults to 300 lines and returns nextOffset when more remain.',
305
311
  inputSchema: z.object({
306
312
  path: z.string().describe('File path relative to the current workspace'),
307
313
  offset: z.number().int().positive().optional().describe('1-based line number to start reading from'),
308
- limit: z.number().int().positive().max(2000).optional().describe('Maximum number of lines to return'),
309
- allowIgnored: z.boolean().default(false).describe('Read the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
314
+ limit: z.number().int().positive().max(2000).optional().describe('Maximum lines to return; defaults to 300'),
315
+ allowIgnored: z.boolean().default(false).describe('Read a .gitignored file only when needed'),
310
316
  }),
311
317
  execute: async ({ path: filePath, offset, limit, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, allowIgnored }, context, async () => {
312
318
  try {
@@ -315,16 +321,36 @@ export const hazeTools = {
315
321
  const content = await fs.readFile(absolutePath, 'utf8');
316
322
  const lines = content.split(/\r?\n/);
317
323
  const start = offset == null ? 0 : offset - 1;
318
- const end = limit == null ? lines.length : start + limit;
319
- const selectedLines = lines.slice(start, end);
320
- const selected = selectedLines.join('\n');
324
+ const requestedEnd = Math.min(lines.length, start + (limit ?? DEFAULT_READ_LINES));
325
+ const selectedLines = lines.slice(start, requestedEnd);
326
+ const numberedLines = [];
327
+ let includedLines = 0;
328
+ let lineTruncated = false;
329
+ for (const [index, line] of selectedLines.entries()) {
330
+ const prefix = `${String(start + index + 1).padStart(4, ' ')} | `;
331
+ const remaining = MAX_OUTPUT_CHARS - numberedLines.join('\n').length - (numberedLines.length > 0 ? 1 : 0);
332
+ if (remaining <= prefix.length)
333
+ 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]`);
336
+ includedLines += 1;
337
+ lineTruncated = true;
338
+ break;
339
+ }
340
+ numberedLines.push(`${prefix}${line}`);
341
+ includedLines += 1;
342
+ }
343
+ const endLine = start + includedLines;
344
+ const hasMore = endLine < lines.length;
321
345
  return {
322
346
  path: filePath,
323
347
  startLine: start + 1,
324
- endLine: Math.min(end, lines.length),
348
+ endLine,
325
349
  totalLines: lines.length,
326
- lineNumberedText: numberLines(selectedLines, start + 1),
327
- ...truncate(selected),
350
+ content: numberedLines.join('\n'),
351
+ nextOffset: hasMore ? endLine + 1 : undefined,
352
+ truncated: hasMore || lineTruncated,
353
+ lineTruncated,
328
354
  };
329
355
  }
330
356
  catch (error) {
@@ -333,20 +359,20 @@ export const hazeTools = {
333
359
  }),
334
360
  }),
335
361
  grep: tool({
336
- 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.',
362
+ description: 'Regex search workspace files with structured, globally capped results. Prefer this to reading files one by one.',
337
363
  inputSchema: z.object({
338
- pattern: z.string().min(1).describe('Regex pattern to search for (PCRE-compatible). Examples: "function handleClick", "import.*from.*react", "class UserService", "TODO|FIXME"'),
339
- path: z.string().default('.').describe('Directory or file path to search in, relative to the workspace. Narrow this to focus results.'),
340
- glob: z.string().optional().describe('File glob filter. Examples: "*.ts", "*.{js,jsx}", "src/**/*.py". Narrows search to matching files.'),
341
- 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.'),
342
- maxMatches: z.number().int().positive().max(200).default(50).describe('Maximum number of matches to return. Increase for broad searches, decrease for focused lookups.'),
343
- caseInsensitive: z.boolean().default(false).describe('Case-insensitive matching. Useful for symbol names that may vary in casing.'),
364
+ pattern: z.string().min(1).describe('Regex pattern'),
365
+ path: z.string().default('.').describe('Workspace-relative file or directory'),
366
+ glob: z.string().optional().describe('Optional file glob, e.g. "*.ts"'),
367
+ contextLines: z.number().int().nonnegative().max(5).default(2).describe('Context lines before/after each match'),
368
+ maxMatches: z.number().int().positive().max(200).default(50).describe('Global match limit'),
369
+ caseInsensitive: z.boolean().default(false).describe('Ignore case'),
344
370
  }),
345
371
  execute: async ({ pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context) => runDedupedTool('grep', { pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context, async () => {
346
372
  try {
347
373
  const absolutePath = resolveWorkspacePath(searchPath);
348
374
  const args = [
349
- '--no-heading', '--line-number', '--color=never',
375
+ '--json', '--color=never',
350
376
  '--max-count', String(maxMatches),
351
377
  '--context', String(contextLines),
352
378
  ];
@@ -372,21 +398,68 @@ export const hazeTools = {
372
398
  if (!stdout) {
373
399
  return { pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches: [], totalMatches: 0, truncated: false };
374
400
  }
375
- const { text: output, truncated } = truncate(stdout);
376
- const lines = output.split('\n').filter(Boolean);
401
+ const lines = stdout.split('\n').filter(Boolean);
377
402
  const matches = [];
403
+ let totalMatches = 0;
404
+ let returnedMatches = 0;
405
+ let omittedMatches = 0;
406
+ let pendingContext = [];
407
+ let retainFollowingContext = false;
378
408
  for (const line of lines) {
379
- const match = line.match(/^(\S+?):(\d+)[-:](.*)$/);
380
- if (!match)
409
+ let event;
410
+ try {
411
+ event = JSON.parse(line);
412
+ }
413
+ catch {
414
+ continue;
415
+ }
416
+ if (event.type === 'begin' || event.type === 'end') {
417
+ pendingContext = [];
418
+ retainFollowingContext = false;
419
+ continue;
420
+ }
421
+ if (event.type !== 'match' && event.type !== 'context')
422
+ continue;
423
+ const file = event.data?.path?.text;
424
+ const lineNumber = event.data?.line_number;
425
+ const content = event.data?.lines?.text?.replace(/\r?\n$/, '');
426
+ if (!file || lineNumber == null || content == null)
427
+ continue;
428
+ const item = { file: path.relative(workspaceRoot(), file), line: lineNumber, content };
429
+ if (event.type === 'context') {
430
+ if (retainFollowingContext) {
431
+ matches.push({ ...item, isContext: true });
432
+ continue;
433
+ }
434
+ pendingContext.push({ ...item, isContext: true });
435
+ if (pendingContext.length > contextLines)
436
+ pendingContext.shift();
437
+ continue;
438
+ }
439
+ totalMatches += 1;
440
+ if (returnedMatches >= maxMatches) {
441
+ omittedMatches += 1;
442
+ pendingContext = [];
443
+ retainFollowingContext = false;
381
444
  continue;
382
- const [, file, lineStr, content] = match;
383
- if (file && lineStr && content !== undefined) {
384
- const isContext = line.includes('-');
385
- const relativePath = path.relative(workspaceRoot(), file);
386
- matches.push({ file: relativePath, line: Number(lineStr), content, isContext });
387
445
  }
446
+ matches.push(...pendingContext, { ...item, isContext: false });
447
+ returnedMatches += 1;
448
+ pendingContext = [];
449
+ retainFollowingContext = true;
388
450
  }
389
- return { pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches, totalMatches: matches.filter(m => !m.isContext).length, truncated };
451
+ return {
452
+ pattern,
453
+ path: searchPath,
454
+ glob: glob ?? null,
455
+ caseInsensitive,
456
+ matches,
457
+ totalMatches,
458
+ returnedMatches,
459
+ omittedMatches,
460
+ truncated: omittedMatches > 0,
461
+ suggestion: omittedMatches > 0 ? 'Narrow the path, glob, or pattern to inspect omitted matches.' : undefined,
462
+ };
390
463
  }
391
464
  catch (error) {
392
465
  return structuredToolFailure('grep', error, 'Check that the search path exists and the pattern is valid regex. Try a narrower path or simpler pattern.', searchPath);
@@ -394,7 +467,7 @@ export const hazeTools = {
394
467
  }),
395
468
  }),
396
469
  replaceLines: tool({
397
- 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.',
470
+ description: 'Replace a 1-based inclusive line range. Use after readFile when exact editFile text is ambiguous or stale.',
398
471
  inputSchema: z.object({
399
472
  path: z.string().describe('File path relative to the current workspace'),
400
473
  startLine: z.number().int().positive().describe('First 1-based line number to replace'),
@@ -441,12 +514,12 @@ export const hazeTools = {
441
514
  }),
442
515
  }),
443
516
  writeFile: tool({
444
- 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.',
517
+ description: 'Create a UTF-8 file. Existing files require explicit full-rewrite approval.',
445
518
  inputSchema: z.object({
446
519
  path: z.string().describe('File path relative to the current workspace'),
447
520
  content: z.string().describe('Complete file contents to write'),
448
- 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.'),
449
- allowIgnored: z.boolean().default(false).describe('Write the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
521
+ overwriteExisting: z.boolean().default(false).describe('Approve intentional full rewrite of an existing file'),
522
+ allowIgnored: z.boolean().default(false).describe('Write a .gitignored file only when needed'),
450
523
  }),
451
524
  execute: async ({ path: filePath, content, overwriteExisting, allowIgnored }, context) => runDedupedTool('writeFile', { path: filePath, content, overwriteExisting, allowIgnored }, context, async () => {
452
525
  try {
@@ -473,14 +546,14 @@ export const hazeTools = {
473
546
  }),
474
547
  }),
475
548
  editFile: tool({
476
- 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.',
549
+ description: 'Apply unique text replacements. Batch same-file edits; reread and use replaceLines if matching fails.',
477
550
  inputSchema: z.object({
478
551
  path: z.string().describe('File path relative to the current workspace'),
479
552
  edits: z.array(z.object({
480
553
  oldText: z.string().min(1).describe('Exact text to replace; must appear exactly once'),
481
554
  newText: z.string().describe('Replacement text'),
482
555
  })).min(1).describe('One or more non-overlapping exact replacements'),
483
- allowIgnored: z.boolean().default(false).describe('Edit the file even if it is ignored by .gitignore. Use only when explicitly needed.'),
556
+ allowIgnored: z.boolean().default(false).describe('Edit a .gitignored file only when needed'),
484
557
  }),
485
558
  execute: async ({ path: filePath, edits, allowIgnored }, context) => runDedupedTool('editFile', { path: filePath, edits, allowIgnored }, context, async () => {
486
559
  try {
@@ -534,8 +607,58 @@ export const hazeTools = {
534
607
  }
535
608
  }),
536
609
  }),
610
+ writeTasks: tool({
611
+ description: 'Replace the task list for substantial work. Update at meaningful phase changes, blockers, and completion; pass the complete list.',
612
+ inputSchema: z.object({
613
+ tasks: z.array(z.object({
614
+ title: z.string().max(200).describe('Short task description'),
615
+ status: z.enum(['pending', 'in_progress', 'completed']).optional().describe('Task status (defaults to pending)'),
616
+ })).describe('Complete task list. Replaces any existing tasks. Pass an empty array to clear.'),
617
+ }),
618
+ execute: async ({ tasks: inputTasks }) => {
619
+ if (!Array.isArray(inputTasks)) {
620
+ return { ok: false, error: 'Tasks must be an array. Pass an empty array to clear the list.' };
621
+ }
622
+ for (let i = 0; i < inputTasks.length; i++) {
623
+ const title = inputTasks[i]?.title?.trim();
624
+ if (!title)
625
+ return { ok: false, error: `Task ${i + 1}: title cannot be empty.` };
626
+ if (title.length > 200)
627
+ return { ok: false, error: `Task ${i + 1}: title is too long (max 200 characters).` };
628
+ }
629
+ const now = new Date().toISOString();
630
+ const tasks = inputTasks.map((input) => ({
631
+ id: generateTaskId(),
632
+ title: input.title.trim(),
633
+ status: input.status ?? 'pending',
634
+ createdAt: now,
635
+ updatedAt: now,
636
+ }));
637
+ await saveTasks(tasks);
638
+ if (tasks.length === 0)
639
+ return { ok: true, taskCount: 0, summary: 'Task list cleared.' };
640
+ const counts = {
641
+ pending: tasks.filter(t => t.status === 'pending').length,
642
+ in_progress: tasks.filter(t => t.status === 'in_progress').length,
643
+ completed: tasks.filter(t => t.status === 'completed').length,
644
+ };
645
+ return { ok: true, taskCount: tasks.length, counts, summary: `Tasks: ${counts.pending} pending, ${counts.in_progress} in progress, ${counts.completed} completed.` };
646
+ },
647
+ }),
648
+ readToolOutput: tool({
649
+ description: 'Read another page of oversized output previously returned by a tool handle.',
650
+ inputSchema: z.object({
651
+ handle: z.string().min(1).describe('Output handle from a prior tool result'),
652
+ offset: z.number().int().nonnegative().default(0).describe('Character offset to start reading'),
653
+ limit: z.number().int().positive().max(20_000).default(12_000).describe('Maximum characters to return'),
654
+ }),
655
+ execute: async ({ handle, offset, limit }) => {
656
+ const page = readStoredToolOutput(handle, offset, limit);
657
+ return page ?? { ok: false, error: `Unknown or expired tool output handle: ${handle}` };
658
+ },
659
+ }),
537
660
  bash: tool({
538
- 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.',
661
+ description: 'Run workspace tests, builds, validation, or inspection. Use file tools for edits.',
539
662
  inputSchema: z.object({
540
663
  command: z.string().min(1).describe('Command to execute with bash -lc'),
541
664
  timeoutSeconds: z.number().int().positive().max(600).optional().describe('Timeout in seconds; defaults to 60'),
@@ -566,11 +689,12 @@ export const hazeTools = {
566
689
  settled = true;
567
690
  clearTimeout(timer);
568
691
  context.abortSignal?.removeEventListener('abort', abort);
569
- const truncatedStdout = truncate(stdout);
570
- const truncatedStderr = truncate(stderr);
571
692
  const validationSummary = isValidationClassification(classification)
572
- ? parseValidationOutput({ command, code, stdout, stderr, timedOut, stdoutTruncated: truncatedStdout.truncated, stderrTruncated: truncatedStderr.truncated, classification })
693
+ ? parseValidationOutput({ command, code, stdout, stderr, timedOut, stdoutTruncated: stdout.length > COMPACT_COMMAND_CHARS, stderrTruncated: stderr.length > COMPACT_COMMAND_CHARS, classification })
573
694
  : undefined;
695
+ 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);
574
698
  resolve({
575
699
  ok: code === 0 && !timedOut,
576
700
  code,
@@ -579,8 +703,8 @@ export const hazeTools = {
579
703
  classification,
580
704
  durationMs: Date.now() - startedAt,
581
705
  timedOut,
582
- stdout: truncatedStdout,
583
- stderr: truncatedStderr,
706
+ stdout: stdoutResult,
707
+ stderr: stderrResult,
584
708
  validationSummary,
585
709
  });
586
710
  });
@@ -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;