@denizokcu/haze 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +50 -36
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +244 -94
  5. package/dist/cli/commands/commands.js +119 -114
  6. package/dist/cli/commands/streaming.d.ts +37 -5
  7. package/dist/cli/commands/streaming.js +455 -192
  8. package/dist/cli/contextReport.d.ts +1 -0
  9. package/dist/cli/contextReport.js +47 -0
  10. package/dist/config/contextFiles.d.ts +31 -0
  11. package/dist/config/contextFiles.js +97 -13
  12. package/dist/config/providers.d.ts +2 -5
  13. package/dist/config/providers.js +16 -12
  14. package/dist/core/agent/compaction.d.ts +3 -0
  15. package/dist/core/agent/compaction.js +23 -3
  16. package/dist/core/agent/contextBudget.d.ts +33 -0
  17. package/dist/core/agent/contextBudget.js +88 -0
  18. package/dist/core/agent/requestAssembly.d.ts +22 -0
  19. package/dist/core/agent/requestAssembly.js +157 -0
  20. package/dist/core/agent/toolOutputStore.d.ts +16 -0
  21. package/dist/core/agent/toolOutputStore.js +65 -0
  22. package/dist/core/agent/workState.d.ts +38 -0
  23. package/dist/core/agent/workState.js +89 -0
  24. package/dist/core/bashOutput/ansi.d.ts +1 -0
  25. package/dist/core/bashOutput/ansi.js +7 -0
  26. package/dist/core/bashOutput/command.d.ts +2 -0
  27. package/dist/core/bashOutput/command.js +62 -0
  28. package/dist/core/bashOutput/lineFilter.d.ts +25 -0
  29. package/dist/core/bashOutput/lineFilter.js +62 -0
  30. package/dist/core/bashOutput/reducers/content.d.ts +3 -0
  31. package/dist/core/bashOutput/reducers/content.js +134 -0
  32. package/dist/core/bashOutput/reducers/git.d.ts +1 -0
  33. package/dist/core/bashOutput/reducers/git.js +147 -0
  34. package/dist/core/bashOutput/reducers/search.d.ts +7 -0
  35. package/dist/core/bashOutput/reducers/search.js +76 -0
  36. package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
  37. package/dist/core/bashOutput/reducers/validation.js +41 -0
  38. package/dist/core/bashOutput/registry.d.ts +4 -0
  39. package/dist/core/bashOutput/registry.js +126 -0
  40. package/dist/core/bashOutput/types.d.ts +46 -0
  41. package/dist/core/bashOutput/types.js +1 -0
  42. package/dist/core/goal/completionPolicy.d.ts +1 -0
  43. package/dist/core/goal/completionPolicy.js +5 -1
  44. package/dist/core/goal/sessionGoal.d.ts +2 -0
  45. package/dist/core/goal/sessionGoal.js +8 -1
  46. package/dist/core/log/llmLog.d.ts +68 -0
  47. package/dist/core/log/llmLog.js +55 -0
  48. package/dist/core/safety/urlGuard.d.ts +37 -0
  49. package/dist/core/safety/urlGuard.js +206 -0
  50. package/dist/core/session/sessionStore.d.ts +6 -0
  51. package/dist/core/session/sessionStore.js +5 -0
  52. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  53. package/dist/core/subagent/subagentRunner.js +5 -15
  54. package/dist/core/toolOutput/reduction.d.ts +25 -0
  55. package/dist/core/toolOutput/reduction.js +23 -0
  56. package/dist/core/validation/outputParser.js +15 -2
  57. package/dist/llm/client.d.ts +40 -1
  58. package/dist/llm/client.js +51 -5
  59. package/dist/llm/hazeTools.d.ts +165 -23
  60. package/dist/llm/hazeTools.js +317 -65
  61. package/dist/llm/initPrompt.js +2 -1
  62. package/dist/llm/systemPrompt.d.ts +6 -1
  63. package/dist/llm/systemPrompt.js +44 -81
  64. package/dist/llm/toolResultTypes.d.ts +1 -1
  65. package/dist/llm/webFetch.d.ts +57 -0
  66. package/dist/llm/webFetch.js +270 -0
  67. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  68. package/dist/skills/builder/SkillBuilder.js +68 -65
  69. package/dist/skills/skillTools.d.ts +2 -19
  70. package/dist/skills/skillTools.js +28 -19
  71. package/dist/ui/components/MarkdownText.d.ts +2 -0
  72. package/dist/ui/components/MarkdownText.js +116 -3
  73. package/package.json +18 -10
@@ -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.";
@@ -79,7 +79,11 @@ export function completionDecision(input) {
79
79
  };
80
80
  }
81
81
  export function toolLoopBudgetPrompt() {
82
- return 'Tool slice reached for this model step. Do not output XML, JSON tool-call syntax, <tool_call> blocks, or function-call markup. If the current request is complete, answer with the final status template using only current-turn changes and validation evidence. If incomplete, state the single next concrete unfinished action so Haze can continue autonomously in a fresh tool slice. Do not claim tools are unavailable, recap unrelated earlier tasks, or provide a generic remains list.';
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
+ }
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.`;
83
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.';
@@ -1,4 +1,5 @@
1
1
  import { type RequestIntent } from './requestClassifier.js';
2
+ import { type WorkState } from '../agent/workState.js';
2
3
  export type SessionGoalStatus = 'active' | 'needs-user' | 'blocked' | 'complete' | 'aborted';
3
4
  export type ValidationStatus = 'pending' | 'passed' | 'failed';
4
5
  export interface SessionGoal {
@@ -16,6 +17,7 @@ export interface SessionGoal {
16
17
  phase: 'starting' | 'inspecting' | 'editing' | 'validating' | 'summarizing' | 'done';
17
18
  blocker?: string;
18
19
  lastProgressAt: number;
20
+ workState: WorkState;
19
21
  }
20
22
  export interface GoalToolEvent {
21
23
  toolName: string;
@@ -1,4 +1,5 @@
1
1
  import { classifyRequestIntent } from './requestClassifier.js';
2
+ import { createWorkState, observeWorkToolEvent } from '../agent/workState.js';
2
3
  function shortRequest(value) {
3
4
  return value.replace(/\s+/g, ' ').trim().slice(0, 160) || 'current request';
4
5
  }
@@ -27,26 +28,30 @@ export function createSessionGoal(request, now = Date.now()) {
27
28
  : intent === 'answer'
28
29
  ? ['Answer the user using current project context when needed']
29
30
  : ['Inspect the relevant files', 'Make the requested change when needed', 'Validate the change when practical', 'Summarize only current-task changes and validation'];
31
+ const successCriteria = criteria;
30
32
  return {
31
33
  id: `goal-${now}-${Math.random().toString(36).slice(2)}`,
32
34
  originalUserRequest: request,
33
35
  normalizedIntent: intent,
34
- successCriteria: criteria,
36
+ successCriteria,
35
37
  constraints: [],
36
38
  touchedFiles: [],
37
39
  validationCommands: [],
38
40
  status: 'active',
39
41
  phase: 'starting',
40
42
  lastProgressAt: now,
43
+ workState: createWorkState(request, intent, successCriteria),
41
44
  };
42
45
  }
43
46
  export function observeGoalToolEvent(goal, event, now = Date.now()) {
44
47
  if (event.duplicateSkipped)
45
48
  return goal;
49
+ observeWorkToolEvent(goal.workState, event);
46
50
  if (event.success && ['listFiles', 'readFile'].includes(event.toolName)) {
47
51
  goal.phase = goal.phase === 'editing' || goal.phase === 'validating' ? goal.phase : 'inspecting';
48
52
  goal.lastProgressAt = now;
49
53
  }
54
+ goal.workState.phase = goal.phase;
50
55
  if (['editFile', 'replaceLines', 'writeFile'].includes(event.toolName)) {
51
56
  const path = inputPath(event.input);
52
57
  if (path)
@@ -59,6 +64,7 @@ export function observeGoalToolEvent(goal, event, now = Date.now()) {
59
64
  goal.blocker = `File edit failed${path ? ` for ${path}` : ''}; recovery read is required before retry.`;
60
65
  }
61
66
  }
67
+ goal.workState.phase = goal.phase;
62
68
  if (event.toolName === 'bash') {
63
69
  const command = bashCommand(event.input);
64
70
  if (command) {
@@ -75,6 +81,7 @@ export function observeGoalToolEvent(goal, event, now = Date.now()) {
75
81
  goal.blocker = `Validation command failed: ${command}`;
76
82
  }
77
83
  }
84
+ goal.workState.phase = goal.phase;
78
85
  return goal;
79
86
  }
80
87
  export function formatGoalStatus(goal) {
@@ -0,0 +1,68 @@
1
+ import type { ModelMessage } from 'ai';
2
+ import type { ContextBreakdown } from '../agent/contextBudget.js';
3
+ export interface LlmLogEntry {
4
+ /** ISO timestamp. */
5
+ at: string;
6
+ /** Entry type. */
7
+ type: 'request' | 'response' | 'step' | 'tool_call' | 'tool_result' | 'error' | 'warning';
8
+ /** Which stream this belongs to: 'main' or 'continuation'. */
9
+ stream: string;
10
+ /** Step number within the stream. */
11
+ step?: number;
12
+ /** System prompt sent to the model (request entries only). */
13
+ system?: string;
14
+ /** Messages sent to the model (request entries only). */
15
+ messages?: ModelMessage[];
16
+ /** Tool names available (request entries only). */
17
+ tools?: string[];
18
+ /** Size-only request composition metrics. */
19
+ context?: ContextBreakdown;
20
+ /** Model response text. */
21
+ text?: string;
22
+ /** Finish reason from the model. */
23
+ finishReason?: string;
24
+ /** Token usage from the provider. */
25
+ usage?: {
26
+ inputTokens?: number;
27
+ outputTokens?: number;
28
+ cacheReadTokens?: number;
29
+ cacheWriteTokens?: number;
30
+ noCacheTokens?: number;
31
+ reasoningTokens?: number;
32
+ logicalInputEstimate?: number;
33
+ effectiveNonCachedInput?: number;
34
+ /** cacheReadTokens / inputTokens. Undefined when either is missing or input is 0. */
35
+ cacheHitRatio?: number;
36
+ };
37
+ /** Tool call details. */
38
+ toolCall?: {
39
+ id: string;
40
+ name: string;
41
+ input: unknown;
42
+ };
43
+ /** Tool result details. */
44
+ toolResult?: {
45
+ id: string;
46
+ name: string;
47
+ success: boolean;
48
+ output?: unknown;
49
+ error?: unknown;
50
+ durationMs?: number;
51
+ };
52
+ /** Error message. */
53
+ error?: string;
54
+ }
55
+ export interface LlmLog {
56
+ id: string;
57
+ file: string;
58
+ }
59
+ export declare function createLog(): Promise<LlmLog>;
60
+ export declare function appendLogEntry(log: LlmLog, entry: LlmLogEntry): Promise<void>;
61
+ export declare function endLog(log: LlmLog): Promise<void>;
62
+ export declare function listLogs(): Promise<Array<{
63
+ id: string;
64
+ file: string;
65
+ size: number;
66
+ modified: string;
67
+ }>>;
68
+ export declare function readLogEntries(id: string): Promise<LlmLogEntry[]>;
@@ -0,0 +1,55 @@
1
+ import path from 'node:path';
2
+ import fs from 'fs-extra';
3
+ import { HAZE_DIR } from '../../config/paths.js';
4
+ const LOGS_DIR = path.join(HAZE_DIR, 'logs');
5
+ function logFileId(now = new Date()) {
6
+ return now.toISOString().replace(/[:.]/g, '-');
7
+ }
8
+ function logFilePath(id) {
9
+ return path.join(LOGS_DIR, `${id}.jsonl`);
10
+ }
11
+ export async function createLog() {
12
+ await fs.ensureDir(LOGS_DIR);
13
+ const id = logFileId();
14
+ const file = logFilePath(id);
15
+ await fs.writeFile(file, '');
16
+ return { id, file };
17
+ }
18
+ export async function appendLogEntry(log, entry) {
19
+ const line = JSON.stringify(entry) + '\n';
20
+ await fs.appendFile(log.file, line);
21
+ }
22
+ export async function endLog(log) {
23
+ const entry = {
24
+ at: new Date().toISOString(),
25
+ type: 'response',
26
+ stream: 'main',
27
+ finishReason: 'log-ended',
28
+ };
29
+ await appendLogEntry(log, entry);
30
+ }
31
+ export async function listLogs() {
32
+ await fs.ensureDir(LOGS_DIR);
33
+ const files = await fs.readdir(LOGS_DIR);
34
+ const logs = [];
35
+ for (const name of files) {
36
+ if (!name.endsWith('.jsonl'))
37
+ continue;
38
+ const file = path.join(LOGS_DIR, name);
39
+ const stat = await fs.stat(file);
40
+ logs.push({ id: name.replace(/\.jsonl$/, ''), file, size: stat.size, modified: stat.mtime.toISOString() });
41
+ }
42
+ return logs.sort((a, b) => b.modified.localeCompare(a.modified));
43
+ }
44
+ export async function readLogEntries(id) {
45
+ const file = logFilePath(id);
46
+ const raw = await fs.readFile(file, 'utf8').catch(() => '');
47
+ return raw.split('\n').filter(Boolean).flatMap(line => {
48
+ try {
49
+ return [JSON.parse(line)];
50
+ }
51
+ catch {
52
+ return [];
53
+ }
54
+ });
55
+ }
@@ -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>;