@denizokcu/haze 0.4.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 (51) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +31 -29
  3. package/dist/cli/commands/chat.js +106 -48
  4. package/dist/cli/commands/commands.js +15 -1
  5. package/dist/cli/commands/streaming.d.ts +4 -0
  6. package/dist/cli/commands/streaming.js +242 -111
  7. package/dist/config/contextFiles.d.ts +6 -0
  8. package/dist/config/contextFiles.js +47 -16
  9. package/dist/config/providers.d.ts +2 -5
  10. package/dist/config/providers.js +16 -12
  11. package/dist/core/agent/requestAssembly.js +12 -1
  12. package/dist/core/agent/toolOutputStore.d.ts +6 -1
  13. package/dist/core/agent/toolOutputStore.js +33 -1
  14. package/dist/core/bashOutput/ansi.d.ts +1 -0
  15. package/dist/core/bashOutput/ansi.js +7 -0
  16. package/dist/core/bashOutput/command.d.ts +2 -0
  17. package/dist/core/bashOutput/command.js +62 -0
  18. package/dist/core/bashOutput/lineFilter.d.ts +25 -0
  19. package/dist/core/bashOutput/lineFilter.js +62 -0
  20. package/dist/core/bashOutput/reducers/content.d.ts +3 -0
  21. package/dist/core/bashOutput/reducers/content.js +134 -0
  22. package/dist/core/bashOutput/reducers/git.d.ts +1 -0
  23. package/dist/core/bashOutput/reducers/git.js +147 -0
  24. package/dist/core/bashOutput/reducers/search.d.ts +7 -0
  25. package/dist/core/bashOutput/reducers/search.js +76 -0
  26. package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
  27. package/dist/core/bashOutput/reducers/validation.js +41 -0
  28. package/dist/core/bashOutput/registry.d.ts +4 -0
  29. package/dist/core/bashOutput/registry.js +126 -0
  30. package/dist/core/bashOutput/types.d.ts +46 -0
  31. package/dist/core/bashOutput/types.js +1 -0
  32. package/dist/core/goal/completionPolicy.d.ts +1 -0
  33. package/dist/core/goal/completionPolicy.js +4 -0
  34. package/dist/core/safety/urlGuard.d.ts +37 -0
  35. package/dist/core/safety/urlGuard.js +206 -0
  36. package/dist/core/subagent/subagentRunner.d.ts +1 -1
  37. package/dist/core/subagent/subagentRunner.js +2 -2
  38. package/dist/core/toolOutput/reduction.d.ts +25 -0
  39. package/dist/core/toolOutput/reduction.js +23 -0
  40. package/dist/llm/client.d.ts +2 -2
  41. package/dist/llm/client.js +6 -4
  42. package/dist/llm/hazeTools.d.ts +133 -16
  43. package/dist/llm/hazeTools.js +205 -31
  44. package/dist/llm/initPrompt.js +2 -1
  45. package/dist/llm/systemPrompt.js +3 -1
  46. package/dist/llm/toolResultTypes.d.ts +1 -1
  47. package/dist/llm/webFetch.d.ts +57 -0
  48. package/dist/llm/webFetch.js +270 -0
  49. package/dist/ui/components/MarkdownText.d.ts +2 -0
  50. package/dist/ui/components/MarkdownText.js +116 -3
  51. package/package.json +17 -10
@@ -0,0 +1,147 @@
1
+ import { commandCandidates } from '../command.js';
2
+ function gitSubcommand(command) {
3
+ for (const candidate of commandCandidates(command)) {
4
+ const words = candidate.toLowerCase().split(/\s+/).filter(Boolean);
5
+ const gitIndex = words.indexOf('git');
6
+ if (gitIndex === -1)
7
+ continue;
8
+ for (let index = gitIndex + 1; index < words.length; index++) {
9
+ const word = words[index] ?? '';
10
+ if (word === '-c' || word === '--git-dir' || word === '--work-tree') {
11
+ index += 1;
12
+ continue;
13
+ }
14
+ if (word.startsWith('-'))
15
+ continue;
16
+ return word;
17
+ }
18
+ }
19
+ return undefined;
20
+ }
21
+ export function reduceGitOutput(command, stdout, stderr) {
22
+ const text = stdout || stderr;
23
+ const subcommand = gitSubcommand(command);
24
+ if (subcommand === 'status')
25
+ return reduceGitStatus(text);
26
+ if (subcommand === 'log')
27
+ return reduceGitLog(text);
28
+ if (subcommand === 'diff' || subcommand === 'show')
29
+ return reduceGitDiff(text, subcommand);
30
+ return undefined;
31
+ }
32
+ function cleanStatusItem(line) {
33
+ return line.trim().replace(/^\t/, '').replace(/^\s*(modified:|deleted:|new file:|renamed:)\s+/, match => `${match.trim()} `);
34
+ }
35
+ function reduceGitStatus(text) {
36
+ const lines = text.split(/\r?\n/).filter(Boolean);
37
+ if (lines.length === 0)
38
+ return 'git status: clean';
39
+ const porcelain = lines.filter(line => /^(?:##|\?\?|[ MADRCU?!]{2})\s+/.test(line));
40
+ if (porcelain.length) {
41
+ const branchLine = porcelain.find(line => line.startsWith('## '));
42
+ const branch = branchLine?.replace(/^##\s+/, '').split('...')[0];
43
+ const items = porcelain.filter(line => !line.startsWith('## '));
44
+ const untracked = items.filter(line => line.startsWith('??')).length;
45
+ const changed = items.length - untracked;
46
+ const shown = items.slice(0, 30);
47
+ return [`git status: ${branch ? `branch ${branch}, ` : ''}${changed} changed, ${untracked} untracked`, ...shown.map(line => ` ${line}`), ...(items.length > shown.length ? [` ... ${items.length - shown.length} more`] : [])].join('\n');
48
+ }
49
+ const branch = lines.find(line => line.startsWith('On branch '))?.replace('On branch ', '');
50
+ if (lines.some(line => /nothing to commit|working tree clean/i.test(line)))
51
+ return `git status: ${branch ? `branch ${branch}, ` : ''}clean`;
52
+ const items = [];
53
+ let inUntracked = false;
54
+ for (const line of lines) {
55
+ if (/^Untracked files:/.test(line)) {
56
+ inUntracked = true;
57
+ continue;
58
+ }
59
+ if (/^Changes/.test(line)) {
60
+ inUntracked = false;
61
+ continue;
62
+ }
63
+ if (/^\s*(modified:|deleted:|new file:|renamed:)/.test(line) || (inUntracked && /^\s+\S/.test(line) && !/\(use /.test(line))) {
64
+ const item = cleanStatusItem(line);
65
+ if (item && !/^\(use /.test(item))
66
+ items.push(inUntracked && !/^\w+:/.test(item) ? `?? ${item}` : item);
67
+ }
68
+ }
69
+ const untracked = items.filter(line => line.startsWith('?? ')).length;
70
+ const changed = items.length - untracked;
71
+ const shown = items.slice(0, 30);
72
+ return [`git status: ${branch ? `branch ${branch}, ` : ''}${changed} changed, ${untracked} untracked`, ...shown.map(line => ` ${line}`), ...(items.length > shown.length ? [` ... ${items.length - shown.length} more`] : [])].join('\n');
73
+ }
74
+ function reduceGitLog(text) {
75
+ const lines = text.split(/\r?\n/).filter(Boolean);
76
+ if (lines.length === 0)
77
+ return 'git log: no commits shown';
78
+ const commits = [];
79
+ let currentHash;
80
+ for (const line of lines) {
81
+ const commit = line.match(/^commit\s+([a-f0-9]{7,40})/i);
82
+ if (commit) {
83
+ currentHash = commit[1]?.slice(0, 12);
84
+ continue;
85
+ }
86
+ if (currentHash && /^\s{4}\S/.test(line)) {
87
+ commits.push(`${currentHash} ${line.trim()}`);
88
+ currentHash = undefined;
89
+ continue;
90
+ }
91
+ if (/^[a-f0-9]{7,40}\s+\S/.test(line))
92
+ commits.push(line.length > 180 ? `${line.slice(0, 180)}…` : line);
93
+ }
94
+ const rows = (commits.length ? commits : lines).slice(0, 30);
95
+ return [`git log: ${rows.length} commit${rows.length === 1 ? '' : 's'} shown`, ...rows.map(line => ` ${line.length > 180 ? `${line.slice(0, 180)}…` : line}`), ...(lines.length > rows.length && commits.length === 0 ? [` ... ${lines.length - rows.length} more lines`] : [])].join('\n');
96
+ }
97
+ function reduceGitDiff(text, label = 'diff') {
98
+ const lines = text.split(/\r?\n/);
99
+ const statLines = lines.filter(line => /\|\s+\d+\s+[-+]+/.test(line) || /files? changed/.test(line)).slice(0, 40);
100
+ const files = [];
101
+ let current;
102
+ for (const line of lines) {
103
+ if (line.startsWith('diff --git ')) {
104
+ const file = line.replace(/^diff --git a\//, '').replace(/ b\/.*/, '');
105
+ current = { file, hunks: [], body: [], added: 0, removed: 0 };
106
+ files.push(current);
107
+ continue;
108
+ }
109
+ if (!current)
110
+ continue;
111
+ if (line.startsWith('@@')) {
112
+ current.hunks.push(line);
113
+ current.body.push(line);
114
+ continue;
115
+ }
116
+ if (/^(?:---|\+\+\+|index |new file mode|deleted file mode|similarity index|rename from|rename to)/.test(line))
117
+ continue;
118
+ if (line.startsWith('+') && !line.startsWith('+++'))
119
+ current.added += 1;
120
+ if (line.startsWith('-') && !line.startsWith('---'))
121
+ current.removed += 1;
122
+ if ((line.startsWith('+') || line.startsWith('-')) && current.body.length < 12)
123
+ current.body.push(line.length > 180 ? `${line.slice(0, 180)}…` : line);
124
+ }
125
+ if (files.length === 0) {
126
+ const compact = statLines.length ? statLines : lines.filter(Boolean).slice(0, 60);
127
+ return [`git ${label}: ${compact.length ? 'summary' : 'no changes'}`, ...compact].join('\n');
128
+ }
129
+ const totalAdded = files.reduce((sum, file) => sum + file.added, 0);
130
+ const totalRemoved = files.reduce((sum, file) => sum + file.removed, 0);
131
+ const shownFiles = files.slice(0, 30);
132
+ const output = [`git ${label}: ${files.length} file${files.length === 1 ? '' : 's'} changed, +${totalAdded}/-${totalRemoved}`];
133
+ for (const file of shownFiles) {
134
+ output.push(` ${file.file} +${file.added}/-${file.removed}${file.hunks.length ? ` (${file.hunks.length} hunk${file.hunks.length === 1 ? '' : 's'})` : ''}`);
135
+ for (const hunk of file.hunks.slice(0, 4))
136
+ output.push(` ${hunk}`);
137
+ for (const bodyLine of file.body.filter(line => !line.startsWith('@@')).slice(0, 6))
138
+ output.push(` ${bodyLine}`);
139
+ if (file.body.length > file.hunks.length + 6)
140
+ output.push(` ... ${file.body.length - file.hunks.length - 6} diff lines omitted for this file`);
141
+ }
142
+ if (files.length > shownFiles.length)
143
+ output.push(` ... ${files.length - shownFiles.length} more files`);
144
+ if (statLines.length)
145
+ output.push('', ...statLines);
146
+ return output.join('\n');
147
+ }
@@ -0,0 +1,7 @@
1
+ export interface SearchReductionOptions {
2
+ maxFiles?: number;
3
+ maxMatchesPerFile?: number;
4
+ maxTotalMatches?: number;
5
+ }
6
+ export declare function isSearchCommand(command: string): boolean;
7
+ export declare function reduceSearchOutput(command: string, stdout: string, stderr: string, options?: SearchReductionOptions): string | undefined;
@@ -0,0 +1,76 @@
1
+ import { commandMatches } from '../command.js';
2
+ const DEFAULT_OPTIONS = { maxFiles: 15, maxMatchesPerFile: 5, maxTotalMatches: 30 };
3
+ const SEARCH_COMMAND = /^(?:rg|grep|git\s+grep|ag|ack)(?:\s|$)/;
4
+ const SIGNAL_LINE = /\b(error|fail(?:ed|ure)?|warn(?:ing)?|exception|panic|fatal|todo|fixme)\b/i;
5
+ const MATCH_LINE = /^(.+?)([:-])(\d+)\2(.*)$/;
6
+ export function isSearchCommand(command) {
7
+ return commandMatches(command, SEARCH_COMMAND);
8
+ }
9
+ function parseSearchLine(line, index) {
10
+ const match = MATCH_LINE.exec(line);
11
+ if (!match)
12
+ return undefined;
13
+ const file = match[1]?.trim();
14
+ const separator = match[2];
15
+ const lineNumber = Number(match[3]);
16
+ if (!file || !separator || !Number.isInteger(lineNumber))
17
+ return undefined;
18
+ return { file, line: lineNumber, separator, content: match[4] ?? '', score: SIGNAL_LINE.test(line) ? 3 : separator === ':' ? 2 : 1, index };
19
+ }
20
+ function pickMatches(matches, max) {
21
+ if (matches.length <= max)
22
+ return matches;
23
+ const selected = new Map();
24
+ const add = (match) => { if (match)
25
+ selected.set(match.index, match); };
26
+ add(matches[0]);
27
+ add(matches[matches.length - 1]);
28
+ for (const match of [...matches].sort((a, b) => b.score - a.score || a.index - b.index)) {
29
+ if (selected.size >= max)
30
+ break;
31
+ add(match);
32
+ }
33
+ return [...selected.values()].sort((a, b) => a.index - b.index);
34
+ }
35
+ function clipLine(line, max = 220) {
36
+ return line.length <= max ? line : `${line.slice(0, max - 1)}…`;
37
+ }
38
+ export function reduceSearchOutput(command, stdout, stderr, options = {}) {
39
+ if (!isSearchCommand(command))
40
+ return undefined;
41
+ const text = stdout || stderr;
42
+ if (!text.trim())
43
+ return undefined;
44
+ const opts = { ...DEFAULT_OPTIONS, ...options };
45
+ const parsed = text.split(/\r?\n/).map(parseSearchLine).filter((match) => match != null);
46
+ if (parsed.length < 20)
47
+ return undefined;
48
+ if (parsed.length < Math.max(8, text.split(/\r?\n/).filter(Boolean).length * 0.6))
49
+ return undefined;
50
+ const grouped = new Map();
51
+ for (const match of parsed)
52
+ grouped.set(match.file, [...(grouped.get(match.file) ?? []), match]);
53
+ const files = [...grouped.entries()].map(([file, matches]) => ({ file, matches, total: matches.filter(match => match.separator === ':').length || matches.length }));
54
+ const shownFiles = files
55
+ .sort((a, b) => Math.max(...b.matches.map(match => match.score)) - Math.max(...a.matches.map(match => match.score)) || b.total - a.total || a.file.localeCompare(b.file))
56
+ .slice(0, opts.maxFiles);
57
+ let shownMatches = 0;
58
+ const output = [`Search results: ${parsed.filter(match => match.separator === ':').length || parsed.length} matches in ${files.length} files (showing up to ${opts.maxTotalMatches} matches across ${shownFiles.length} files)`];
59
+ for (const file of shownFiles) {
60
+ if (shownMatches >= opts.maxTotalMatches)
61
+ break;
62
+ const remaining = opts.maxTotalMatches - shownMatches;
63
+ const picked = pickMatches(file.matches, Math.min(opts.maxMatchesPerFile, remaining));
64
+ shownMatches += picked.length;
65
+ output.push('', `${file.file} (${file.total} match${file.total === 1 ? '' : 'es'}, showing ${picked.length})`);
66
+ for (const match of picked)
67
+ output.push(` ${match.line}${match.separator} ${clipLine(match.content.trim())}`);
68
+ const omitted = file.matches.length - picked.length;
69
+ if (omitted > 0)
70
+ output.push(` ... ${omitted} omitted in this file`);
71
+ }
72
+ const omittedFiles = files.length - shownFiles.length;
73
+ if (omittedFiles > 0)
74
+ output.push('', `... ${omittedFiles} more files omitted`);
75
+ return output.join('\n');
76
+ }
@@ -0,0 +1,2 @@
1
+ import type { ValidationSummary } from '../../../llm/toolResultTypes.js';
2
+ export declare function renderValidationReduction(summary: ValidationSummary, rawHandle?: string): string;
@@ -0,0 +1,41 @@
1
+ function groupDiagnostics(summary) {
2
+ const grouped = new Map();
3
+ for (const diagnostic of summary.diagnostics) {
4
+ const key = diagnostic.file ?? '(unknown file)';
5
+ grouped.set(key, [...(grouped.get(key) ?? []), diagnostic]);
6
+ }
7
+ return grouped;
8
+ }
9
+ export function renderValidationReduction(summary, rawHandle) {
10
+ const lines = [summary.summaryText];
11
+ if (summary.failedTests.length) {
12
+ lines.push('', 'failed tests:');
13
+ for (const test of summary.failedTests.slice(0, 10))
14
+ lines.push(` - ${test}`);
15
+ }
16
+ const grouped = groupDiagnostics(summary);
17
+ if (grouped.size) {
18
+ lines.push('', 'diagnostics:');
19
+ let emitted = 0;
20
+ for (const [file, diagnostics] of grouped) {
21
+ if (emitted >= 20)
22
+ break;
23
+ lines.push(file);
24
+ for (const diagnostic of diagnostics) {
25
+ if (emitted >= 20)
26
+ break;
27
+ const loc = diagnostic.line != null ? `${diagnostic.line}${diagnostic.column != null ? `:${diagnostic.column}` : ''}` : '?';
28
+ lines.push(` ${loc} ${diagnostic.severity} ${diagnostic.message}`);
29
+ emitted += 1;
30
+ }
31
+ }
32
+ }
33
+ if (summary.failedFiles.length && !grouped.size) {
34
+ lines.push('', `failed files: ${summary.failedFiles.join(', ')}`);
35
+ }
36
+ if (summary.suggestedNextStep)
37
+ lines.push('', `next: ${summary.suggestedNextStep}`);
38
+ if (rawHandle)
39
+ lines.push('', `raw output: use readToolOutput with handle ${rawHandle}`);
40
+ return lines.join('\n');
41
+ }
@@ -0,0 +1,4 @@
1
+ import type { BashOutputFilterInput, BashOutputFilterResult } from './types.js';
2
+ import type { LineFilterDefinition } from './lineFilter.js';
3
+ export declare const builtInLineFilters: LineFilterDefinition[];
4
+ export declare function filterBashOutput(input: BashOutputFilterInput): BashOutputFilterResult;
@@ -0,0 +1,126 @@
1
+ import { applyLineFilter, findLineFilter } from './lineFilter.js';
2
+ import { renderValidationReduction } from './reducers/validation.js';
3
+ import { reduceGitOutput } from './reducers/git.js';
4
+ import { reduceSearchOutput } from './reducers/search.js';
5
+ import { reduceGenericLogOutput, reduceJsonOutput, reduceUnifiedDiffOutput } from './reducers/content.js';
6
+ import { isInflating, reductionMetrics, retrievalHint } from '../toolOutput/reduction.js';
7
+ export const builtInLineFilters = [
8
+ { name: 'markdownlint', matchCommand: /(^|[;&|]\s*)markdownlint\b/, stripAnsi: true, truncateLinesAt: 200, maxLines: 80, onEmpty: 'markdownlint: ok' },
9
+ { name: 'shellcheck', matchCommand: /(^|[;&|]\s*)shellcheck\b/, stripAnsi: true, stripLinesMatching: [/^In .* line \d+:/], truncateLinesAt: 200, maxLines: 100, onEmpty: 'shellcheck: ok' },
10
+ { name: 'docker-list', matchCommand: /(^|[;&|]\s*)docker\s+(?:ps|images)\b/, stripAnsi: true, truncateLinesAt: 180, maxLines: 40, onEmpty: 'docker: no rows' },
11
+ { name: 'kubectl-get', matchCommand: /(^|[;&|]\s*)(?:kubectl|oc)\s+get\b/, stripAnsi: true, truncateLinesAt: 180, maxLines: 60, onEmpty: 'kubectl get: no rows' },
12
+ { name: 'terraform-plan', matchCommand: /(^|[;&|]\s*)terraform\s+plan\b/, stripAnsi: true, stripLinesMatching: [/^Refreshing Terraform state/, /^\s*$/, /^\s*# /], truncateLinesAt: 200, maxLines: 100, onEmpty: 'terraform plan: no significant changes' },
13
+ { name: 'make', matchCommand: /(^|[;&|]\s*)make\b/, stripAnsi: true, stripLinesMatching: [/^make\[\d+\]: Entering directory /, /^make\[\d+\]: Leaving directory /], truncateLinesAt: 180, maxLines: 80, onEmpty: 'make: no significant output' },
14
+ { name: 'system-list', matchCommand: /(^|[;&|]\s*)(?:du|df|ps)\b/, stripAnsi: true, truncateLinesAt: 180, maxLines: 50 },
15
+ ];
16
+ function makeReduction(raw, text, filtered, filterName, input, warning, contentKind = 'generic') {
17
+ let finalText = text;
18
+ let handle;
19
+ let truncated = false;
20
+ if (finalText.length > input.compactMaxChars) {
21
+ const compacted = input.fallbackCompact(finalText, input.compactMaxChars);
22
+ finalText = compacted.text;
23
+ handle = compacted.handle;
24
+ truncated = compacted.truncated;
25
+ }
26
+ const lossy = filtered && finalText !== raw;
27
+ const rawHandle = lossy && input.storeRawOutput ? input.storeRawOutput(raw) : handle;
28
+ if (filtered && contentKind !== 'validation' && raw.length > 2000 && isInflating(raw, finalText))
29
+ return passthroughReduction(raw, input);
30
+ if (lossy && rawHandle && !finalText.includes(rawHandle))
31
+ finalText = `${finalText}\n\n[${retrievalHint(rawHandle)}]`;
32
+ const metrics = reductionMetrics(raw, finalText);
33
+ return {
34
+ text: finalText,
35
+ truncated,
36
+ filtered,
37
+ ...(filterName ? { filterName, reducerName: filterName } : {}),
38
+ contentKind,
39
+ lossy,
40
+ parseTier: warning ? 'degraded' : filtered ? 'full' : 'passthrough',
41
+ ...(warning ? { warning } : {}),
42
+ ...(handle ?? rawHandle ? { handle: handle ?? rawHandle } : {}),
43
+ ...(rawHandle ? { rawHandle } : {}),
44
+ omittedChars: Math.max(0, raw.length - finalText.length),
45
+ ...metrics,
46
+ };
47
+ }
48
+ function passthroughReduction(raw, input) {
49
+ const compacted = input.fallbackCompact(raw, input.compactMaxChars);
50
+ return {
51
+ text: compacted.text,
52
+ truncated: compacted.truncated,
53
+ filtered: false,
54
+ reducerName: 'generic-cap',
55
+ contentKind: 'generic',
56
+ lossy: compacted.truncated,
57
+ parseTier: 'passthrough',
58
+ ...(compacted.handle ? { handle: compacted.handle, rawHandle: compacted.handle } : {}),
59
+ omittedChars: compacted.omittedChars ?? Math.max(0, raw.length - compacted.text.length),
60
+ ...reductionMetrics(raw, compacted.text),
61
+ };
62
+ }
63
+ export function filterBashOutput(input) {
64
+ try {
65
+ let stdout;
66
+ let stderr;
67
+ let filterName;
68
+ if (input.validationSummary && input.validationSummary.status !== 'passed') {
69
+ filterName = `validation-${input.validationSummary.kind}`;
70
+ const raw = `${input.stdout}${input.stderr ? `\n${input.stderr}` : ''}`;
71
+ const rawHandle = input.storeRawOutput?.(raw);
72
+ stdout = makeReduction(input.stdout, renderValidationReduction(input.validationSummary, rawHandle), true, filterName, input, undefined, 'validation');
73
+ stderr = makeReduction(input.stderr, '', input.stderr.length > 0, filterName, input, undefined, 'validation');
74
+ }
75
+ else {
76
+ const git = reduceGitOutput(input.command, input.stdout, input.stderr);
77
+ if (git != null) {
78
+ filterName = 'git';
79
+ const kind = /^git (?:diff|show):/.test(git) ? 'diff' : 'generic';
80
+ stdout = makeReduction(input.stdout, input.stdout ? git : '', true, filterName, input, undefined, kind);
81
+ stderr = makeReduction(input.stderr, input.stdout ? '' : git, true, filterName, input, undefined, kind);
82
+ }
83
+ else {
84
+ const search = reduceSearchOutput(input.command, input.stdout, input.stderr);
85
+ if (search != null) {
86
+ filterName = 'search';
87
+ stdout = makeReduction(input.stdout, input.stdout ? search : '', true, filterName, input, undefined, 'search');
88
+ stderr = makeReduction(input.stderr, input.stdout ? '' : search, true, filterName, input, undefined, 'search');
89
+ }
90
+ else {
91
+ const diff = reduceUnifiedDiffOutput(input.stdout, input.stderr);
92
+ const json = diff == null ? reduceJsonOutput(input.stdout, input.stderr) : undefined;
93
+ const log = diff == null && json == null ? reduceGenericLogOutput(input.stdout, input.stderr) : undefined;
94
+ const content = diff ?? json ?? log;
95
+ if (content != null) {
96
+ filterName = diff != null ? 'diff' : json != null ? 'json' : 'log';
97
+ const kind = diff != null ? 'diff' : json != null ? 'json' : 'log';
98
+ stdout = makeReduction(input.stdout, input.stdout ? content : '', true, filterName, input, undefined, kind);
99
+ stderr = makeReduction(input.stderr, input.stdout ? '' : content, input.stderr.length > 0, filterName, input, undefined, kind);
100
+ }
101
+ else {
102
+ const lineFilter = findLineFilter(builtInLineFilters, input.command);
103
+ if (lineFilter) {
104
+ filterName = lineFilter.name;
105
+ const out = input.stdout ? applyLineFilter(lineFilter, input.command, input.stdout) : undefined;
106
+ const err = input.stderr ? applyLineFilter(lineFilter, input.command, input.stderr) : undefined;
107
+ stdout = makeReduction(input.stdout, out?.text ?? input.stdout, out?.filtered ?? false, lineFilter.name, input, out?.warning, 'log');
108
+ stderr = makeReduction(input.stderr, err?.text ?? input.stderr, err?.filtered ?? false, lineFilter.name, input, err?.warning, 'log');
109
+ }
110
+ }
111
+ }
112
+ }
113
+ }
114
+ stdout ??= passthroughReduction(input.stdout, input);
115
+ stderr ??= passthroughReduction(input.stderr, input);
116
+ return { stdout, stderr, summary: input.validationSummary };
117
+ }
118
+ catch (error) {
119
+ const warning = error instanceof Error ? error.message : String(error);
120
+ const stdout = passthroughReduction(input.stdout, input);
121
+ const stderr = passthroughReduction(input.stderr, input);
122
+ stdout.warning = `bash output filter failed: ${warning}`;
123
+ stdout.parseTier = 'degraded';
124
+ return { stdout, stderr, summary: input.validationSummary };
125
+ }
126
+ }
@@ -0,0 +1,46 @@
1
+ import type { BashClassification } from '../safety/bashClassifier.js';
2
+ import type { ValidationSummary } from '../../llm/toolResultTypes.js';
3
+ import type { ReductionContentKind, ReductionParseTier } from '../toolOutput/reduction.js';
4
+ export type ParseTier = ReductionParseTier;
5
+ export interface BashOutputFilterInput {
6
+ command: string;
7
+ code: number | null;
8
+ stdout: string;
9
+ stderr: string;
10
+ timedOut: boolean;
11
+ classification?: BashClassification;
12
+ validationSummary?: ValidationSummary;
13
+ storeRawOutput?: (content: string) => string;
14
+ fallbackCompact: (text: string, maxChars?: number) => {
15
+ text: string;
16
+ truncated: boolean;
17
+ omittedChars?: number;
18
+ handle?: string;
19
+ };
20
+ compactMaxChars: number;
21
+ }
22
+ export interface StreamReduction {
23
+ text: string;
24
+ truncated: boolean;
25
+ filtered: boolean;
26
+ filterName?: string;
27
+ reducerName?: string;
28
+ contentKind?: ReductionContentKind;
29
+ lossy?: boolean;
30
+ parseTier?: ParseTier;
31
+ warning?: string;
32
+ handle?: string;
33
+ rawHandle?: string;
34
+ omittedChars: number;
35
+ rawChars?: number;
36
+ returnedChars?: number;
37
+ rawTokensEstimate?: number;
38
+ returnedTokensEstimate?: number;
39
+ estimatedSavedTokens?: number;
40
+ savingsPct?: number;
41
+ }
42
+ export interface BashOutputFilterResult {
43
+ stdout: StreamReduction;
44
+ stderr: StreamReduction;
45
+ summary?: ValidationSummary;
46
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -25,5 +25,6 @@ export interface CompletionDecision {
25
25
  }
26
26
  export declare function completionDecision(input: CompletionPolicyInput): CompletionDecision;
27
27
  export declare function toolLoopBudgetPrompt(): string;
28
+ export declare function repeatedToolCallPrompt(toolNames: string[]): string;
28
29
  export declare function postContinuationPrompt(): string;
29
30
  export declare function noTextAfterToolPrompt(allowTools: boolean): "Continue the original request now. If it asks for a change, edit or write the necessary files. If it asks to run or verify tests, run the command. Do not provide only a retrospective summary unless blocked or needing a user decision." | "Continue from the tool result and answer my original request. Do not call tools. Use the final status template for implementation-like requests; summarize only current-turn changes and validation; do not recap unrelated earlier tasks.";
@@ -81,6 +81,10 @@ export function completionDecision(input) {
81
81
  export function toolLoopBudgetPrompt() {
82
82
  return 'Tool slice reached for this model step — tools are no longer callable in this turn. Stop attempting to describe or announce tool calls (e.g. "Let me install", "Now I\'ll run", "Let me X"); those phrases imply tool use you cannot perform. Answer once: either the final status template (current-turn changes + validation evidence) or, if incomplete, a single short line stating the next concrete unfinished action so Haze can continue in a fresh tool slice. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
83
83
  }
84
+ export function repeatedToolCallPrompt(toolNames) {
85
+ const names = [...new Set(toolNames)].join(', ');
86
+ return `You already called ${names || 'a tool'} with identical input in this turn. Do not call the same tool again with the same arguments. Use the existing tool result already in the conversation, choose a different concrete tool/input if genuinely needed, or give the final/blocked status now.`;
87
+ }
84
88
  export function postContinuationPrompt() {
85
89
  return 'Your previous response still described unfinished work, missing validation, or a tool-budget issue. If tools are available, complete the remaining edit or run the final validation now. Only call something blocked for a concrete tool failure, missing dependency/permission, or unavoidable ambiguity.';
86
90
  }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * SSRF guard for the `fetch` tool.
3
+ *
4
+ * Network tools have no workspace path, so they need a *different* confinement
5
+ * than the file tools: scheme allowlist + private/loopback/link-local address
6
+ * blocking + DNS-resolution check (defeats DNS rebinding to internal IPs).
7
+ *
8
+ * This module is pure safety logic under `core/safety/`, parallel to
9
+ * `bashClassifier.ts`. It must not import anything from `ai`, `hazeTools`, or
10
+ * the UI — keep it auditable in one place.
11
+ */
12
+ export type UrlValidation = {
13
+ ok: true;
14
+ url: URL;
15
+ } | {
16
+ ok: false;
17
+ reasonCode: 'invalid_url' | 'blocked_scheme' | 'blocked_host' | 'blocked_address';
18
+ reason: string;
19
+ };
20
+ export type DnsLookupFn = (hostname: string) => Promise<string[]>;
21
+ /**
22
+ * Check whether a literal IP address (v4 or v6) is in a blocked range.
23
+ * Returns false for non-IP strings (hostnames are resolved separately).
24
+ */
25
+ export declare function isBlockedIp(ip: string): boolean;
26
+ /**
27
+ * Validate a URL for outbound fetching.
28
+ *
29
+ * Checks scheme allowlist, blocks well-known dangerous hostnames, blocks
30
+ * literal private/loopback/link-local IPs, and (if the host is a DNS name)
31
+ * resolves it to reject names that point at private/loopback/link-local IPs.
32
+ *
33
+ * `lookup` is injectable for deterministic offline tests.
34
+ */
35
+ export declare function validateUrl(input: string, options?: {
36
+ lookup?: DnsLookupFn;
37
+ }): Promise<UrlValidation>;