@denizokcu/haze 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +68 -36
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +789 -106
  5. package/dist/cli/commands/commands.d.ts +2 -1
  6. package/dist/cli/commands/commands.js +77 -102
  7. package/dist/cli/commands/formatters.d.ts +27 -0
  8. package/dist/cli/commands/formatters.js +137 -0
  9. package/dist/cli/commands/streaming.d.ts +14 -13
  10. package/dist/cli/commands/streaming.js +399 -665
  11. package/dist/config/contextFiles.d.ts +6 -0
  12. package/dist/config/contextFiles.js +47 -16
  13. package/dist/config/lspSettings.d.ts +16 -0
  14. package/dist/config/lspSettings.js +98 -0
  15. package/dist/config/mcpSettings.d.ts +24 -0
  16. package/dist/config/mcpSettings.js +100 -0
  17. package/dist/config/providers.d.ts +2 -5
  18. package/dist/config/providers.js +16 -12
  19. package/dist/config/settings.d.ts +34 -0
  20. package/dist/config/skillSettings.d.ts +15 -0
  21. package/dist/config/skillSettings.js +31 -0
  22. package/dist/config/updateCheck.d.ts +44 -0
  23. package/dist/config/updateCheck.js +83 -0
  24. package/dist/core/agent/requestAssembly.js +12 -1
  25. package/dist/core/agent/toolOutputStore.d.ts +6 -1
  26. package/dist/core/agent/toolOutputStore.js +33 -1
  27. package/dist/core/bashOutput/ansi.d.ts +1 -0
  28. package/dist/core/bashOutput/ansi.js +7 -0
  29. package/dist/core/bashOutput/command.d.ts +2 -0
  30. package/dist/core/bashOutput/command.js +62 -0
  31. package/dist/core/bashOutput/lineFilter.d.ts +25 -0
  32. package/dist/core/bashOutput/lineFilter.js +62 -0
  33. package/dist/core/bashOutput/reducers/content.d.ts +3 -0
  34. package/dist/core/bashOutput/reducers/content.js +134 -0
  35. package/dist/core/bashOutput/reducers/git.d.ts +1 -0
  36. package/dist/core/bashOutput/reducers/git.js +147 -0
  37. package/dist/core/bashOutput/reducers/search.d.ts +7 -0
  38. package/dist/core/bashOutput/reducers/search.js +76 -0
  39. package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
  40. package/dist/core/bashOutput/reducers/validation.js +41 -0
  41. package/dist/core/bashOutput/registry.d.ts +4 -0
  42. package/dist/core/bashOutput/registry.js +126 -0
  43. package/dist/core/bashOutput/types.d.ts +46 -0
  44. package/dist/core/bashOutput/types.js +1 -0
  45. package/dist/core/goal/completionPolicy.d.ts +1 -0
  46. package/dist/core/goal/completionPolicy.js +4 -0
  47. package/dist/core/safety/urlGuard.d.ts +37 -0
  48. package/dist/core/safety/urlGuard.js +206 -0
  49. package/dist/core/subagent/subagentRunner.d.ts +1 -1
  50. package/dist/core/subagent/subagentRunner.js +2 -2
  51. package/dist/core/toolOutput/reduction.d.ts +25 -0
  52. package/dist/core/toolOutput/reduction.js +23 -0
  53. package/dist/llm/client.d.ts +2 -2
  54. package/dist/llm/client.js +6 -4
  55. package/dist/llm/hazeTools.d.ts +133 -16
  56. package/dist/llm/hazeTools.js +205 -31
  57. package/dist/llm/initPrompt.js +2 -1
  58. package/dist/llm/lsp.d.ts +64 -0
  59. package/dist/llm/lsp.js +241 -0
  60. package/dist/llm/lspTools.d.ts +122 -0
  61. package/dist/llm/lspTools.js +115 -0
  62. package/dist/llm/mcp.d.ts +19 -0
  63. package/dist/llm/mcp.js +64 -0
  64. package/dist/llm/requestContext.d.ts +28 -0
  65. package/dist/llm/requestContext.js +56 -0
  66. package/dist/llm/systemPrompt.d.ts +4 -1
  67. package/dist/llm/systemPrompt.js +11 -3
  68. package/dist/llm/toolResultTypes.d.ts +1 -1
  69. package/dist/llm/webFetch.d.ts +57 -0
  70. package/dist/llm/webFetch.js +270 -0
  71. package/dist/skills/builder/SkillBuilder.js +23 -44
  72. package/dist/ui/components/MarkdownText.d.ts +2 -0
  73. package/dist/ui/components/MarkdownText.js +116 -3
  74. package/dist/ui/components/TextInput.d.ts +1 -1
  75. package/dist/utils/version.d.ts +20 -0
  76. package/dist/utils/version.js +72 -0
  77. package/package.json +18 -10
  78. package/dist/cli/commands/skills.d.ts +0 -4
  79. package/dist/cli/commands/skills.js +0 -38
@@ -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>;
@@ -0,0 +1,206 @@
1
+ import { promises as dns } from 'node:dns';
2
+ /**
3
+ * Blocked IPv4 and IPv6 ranges as CIDR strings. Centralized so the policy reads
4
+ * in one place. Covers loopback, link-local, private, and other non-routable /
5
+ * metadata-bearing ranges (e.g. 169.254.169.254 = AWS/cloud metadata).
6
+ */
7
+ const BLOCKED_IPV4_CIDRS = [
8
+ parseIpv4Cidr('0.0.0.0/8'), // "this network"
9
+ parseIpv4Cidr('10.0.0.0/8'), // private
10
+ parseIpv4Cidr('100.64.0.0/10'), // CGNAT
11
+ parseIpv4Cidr('127.0.0.0/8'), // loopback
12
+ parseIpv4Cidr('169.254.0.0/16'), // link-local / cloud metadata
13
+ parseIpv4Cidr('172.16.0.0/12'), // private
14
+ parseIpv4Cidr('192.0.0.0/24'), // IETF protocol assignments
15
+ parseIpv4Cidr('192.0.2.0/24'), // TEST-NET-1
16
+ parseIpv4Cidr('192.168.0.0/16'), // private
17
+ parseIpv4Cidr('198.18.0.0/15'), // benchmarking
18
+ parseIpv4Cidr('198.51.100.0/24'), // TEST-NET-2
19
+ parseIpv4Cidr('203.0.113.0/24'), // TEST-NET-3
20
+ parseIpv4Cidr('224.0.0.0/4'), // multicast
21
+ parseIpv4Cidr('240.0.0.0/4'), // reserved
22
+ ];
23
+ const BLOCKED_IPV6_CIDRS = [
24
+ parseIpv6Cidr('::/128'), // unspecified
25
+ parseIpv6Cidr('::1/128'), // loopback
26
+ parseIpv6Cidr('::ffff:0:0/96'), // IPv4-mapped (checked via v4 ranges too, but be explicit)
27
+ parseIpv6Cidr('64:ff9b::/96'), // NAT64
28
+ parseIpv6Cidr('100::/64'), // discard prefix
29
+ parseIpv6Cidr('fc00::/7'), // unique local
30
+ parseIpv6Cidr('fe80::/10'), // link-local
31
+ parseIpv6Cidr('ff00::/8'), // multicast
32
+ ];
33
+ /** Hostnames that are always blocked regardless of resolution. */
34
+ const BLOCKED_HOSTNAMES = new Set([
35
+ 'localhost',
36
+ 'localhost.localdomain',
37
+ 'ip6-localhost',
38
+ 'ip6-loopback',
39
+ 'broadcasthost',
40
+ ]);
41
+ function parseIpv4Cidr(cidr) {
42
+ const [ip, bitsStr] = cidr.split('/');
43
+ const bits = Number(bitsStr);
44
+ const octets = ip.split('.').map(Number);
45
+ const start = (((octets[0] << 24) >>> 0) + (octets[1] << 16) + (octets[2] << 8) + octets[3]) >>> 0;
46
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
47
+ return { start: (start & mask) >>> 0, mask, bits };
48
+ }
49
+ function parseIpv6Cidr(cidr) {
50
+ const [ip, bitsStr] = cidr.split('/');
51
+ const bits = Number(bitsStr);
52
+ const num = ipv6ToBigInt(ip);
53
+ const mask = bits === 0 ? 0n : ((0xffffffffffffffffffffffffffffffffn << BigInt(128 - bits)) & 0xffffffffffffffffffffffffffffffffn);
54
+ return { start: num & mask, mask, bits };
55
+ }
56
+ function ipv4ToInt(ip) {
57
+ const octets = ip.split('.');
58
+ if (octets.length !== 4)
59
+ return undefined;
60
+ const nums = octets.map(Number);
61
+ if (nums.some(n => !Number.isInteger(n) || n < 0 || n > 255))
62
+ return undefined;
63
+ return (((nums[0] << 24) >>> 0) + (nums[1] << 16) + (nums[2] << 8) + nums[3]) >>> 0;
64
+ }
65
+ function ipv6ToBigInt(ip) {
66
+ const normalized = normalizeIpv6(ip);
67
+ const parts = normalized.split(':');
68
+ const groups = parts.map(part => BigInt(parseInt(part || '0', 16)));
69
+ let result = 0n;
70
+ for (const group of groups) {
71
+ result = (result << 16n) + group;
72
+ }
73
+ return result;
74
+ }
75
+ function normalizeIpv6(ip) {
76
+ if (!ip.includes(':'))
77
+ return ip;
78
+ let expanded = ip;
79
+ // Handle IPv4-in-IPv6 dotted quad in the last group.
80
+ const lastColon = expanded.lastIndexOf(':');
81
+ const tail = expanded.slice(lastColon + 1);
82
+ if (tail.includes('.')) {
83
+ const v4 = ipv4ToInt(tail);
84
+ if (v4 != null) {
85
+ const g1 = (v4 >> 16) & 0xffff;
86
+ const g2 = v4 & 0xffff;
87
+ expanded = `${expanded.slice(0, lastColon + 1)}${g1.toString(16)}:${g2.toString(16)}`;
88
+ }
89
+ }
90
+ // Expand :: shorthand.
91
+ if (expanded.includes('::')) {
92
+ const [head, tail2] = expanded.split('::');
93
+ const headGroups = head ? head.split(':') : [];
94
+ const tailGroups = tail2 ? tail2.split(':') : [];
95
+ const missing = 8 - headGroups.length - tailGroups.length;
96
+ expanded = [...headGroups, ...Array.from({ length: missing }, () => '0'), ...tailGroups].join(':');
97
+ }
98
+ return expanded;
99
+ }
100
+ function isIpv6(ip) {
101
+ return ip.includes(':');
102
+ }
103
+ function ipv4InBlockedRange(ip) {
104
+ const value = ipv4ToInt(ip);
105
+ if (value == null)
106
+ return false;
107
+ for (const range of BLOCKED_IPV4_CIDRS) {
108
+ if ((value & range.mask) >>> 0 === range.start)
109
+ return true;
110
+ }
111
+ return false;
112
+ }
113
+ function ipv6InBlockedRange(ip) {
114
+ let num;
115
+ try {
116
+ num = ipv6ToBigInt(ip);
117
+ }
118
+ catch {
119
+ return false;
120
+ }
121
+ for (const range of BLOCKED_IPV6_CIDRS) {
122
+ if ((num & range.mask) === range.start)
123
+ return true;
124
+ }
125
+ return false;
126
+ }
127
+ /**
128
+ * Check whether a literal IP address (v4 or v6) is in a blocked range.
129
+ * Returns false for non-IP strings (hostnames are resolved separately).
130
+ */
131
+ export function isBlockedIp(ip) {
132
+ // Strip IPv6 bracket form for literal checks.
133
+ const cleaned = ip.replace(/^\[|\]$/g, '');
134
+ if (isIpv6(cleaned))
135
+ return ipv6InBlockedRange(cleaned);
136
+ return ipv4InBlockedRange(cleaned);
137
+ }
138
+ function hostLooksLikeIp(host) {
139
+ const cleaned = host.replace(/^\[|\]$/g, '');
140
+ if (cleaned.includes(':'))
141
+ return true; // IPv6
142
+ return /^\d{1,3}(\.\d{1,3}){3}$/.test(cleaned);
143
+ }
144
+ const defaultLookup = async (hostname) => {
145
+ const records = await dns.lookup(hostname, { all: true });
146
+ return records.map(record => record.address);
147
+ };
148
+ /**
149
+ * Validate a URL for outbound fetching.
150
+ *
151
+ * Checks scheme allowlist, blocks well-known dangerous hostnames, blocks
152
+ * literal private/loopback/link-local IPs, and (if the host is a DNS name)
153
+ * resolves it to reject names that point at private/loopback/link-local IPs.
154
+ *
155
+ * `lookup` is injectable for deterministic offline tests.
156
+ */
157
+ export async function validateUrl(input, options) {
158
+ let url;
159
+ try {
160
+ url = new URL(input);
161
+ }
162
+ catch {
163
+ return { ok: false, reasonCode: 'invalid_url', reason: `Not a valid URL: ${input}` };
164
+ }
165
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
166
+ return {
167
+ ok: false,
168
+ reasonCode: 'blocked_scheme',
169
+ reason: `Scheme '${url.protocol.replace(':', '')}' is not allowed; only http and https are permitted.`,
170
+ };
171
+ }
172
+ const host = url.hostname.toLowerCase();
173
+ if (BLOCKED_HOSTNAMES.has(host)) {
174
+ return { ok: false, reasonCode: 'blocked_host', reason: `Hostname '${host}' is blocked.` };
175
+ }
176
+ // Check userinfo/host confusion and empty host (e.g. "http:///").
177
+ if (!host) {
178
+ return { ok: false, reasonCode: 'blocked_host', reason: 'URL has no hostname.' };
179
+ }
180
+ // If the host is a literal IP, check ranges directly (no DNS needed).
181
+ if (hostLooksLikeIp(host)) {
182
+ if (isBlockedIp(host)) {
183
+ return { ok: false, reasonCode: 'blocked_address', reason: `Address '${host}' is private, loopback, link-local, or otherwise blocked.` };
184
+ }
185
+ return { ok: true, url };
186
+ }
187
+ // Hostname: resolve and reject if ANY resolved address is blocked.
188
+ // This defeats DNS rebinding (public hostname pointing at an internal IP).
189
+ const lookup = options?.lookup ?? defaultLookup;
190
+ let addresses;
191
+ try {
192
+ addresses = await lookup(host);
193
+ }
194
+ catch {
195
+ return { ok: false, reasonCode: 'blocked_host', reason: `Could not resolve hostname '${host}'.` };
196
+ }
197
+ if (addresses.length === 0) {
198
+ return { ok: false, reasonCode: 'blocked_host', reason: `Hostname '${host}' did not resolve to any address.` };
199
+ }
200
+ for (const address of addresses) {
201
+ if (isBlockedIp(address)) {
202
+ return { ok: false, reasonCode: 'blocked_address', reason: `Hostname '${host}' resolves to blocked address '${address}'.` };
203
+ }
204
+ }
205
+ return { ok: true, url };
206
+ }
@@ -31,6 +31,6 @@ export declare function createSubagentTool(options: {
31
31
  session?: PromptSession;
32
32
  }): import("ai").Tool<{
33
33
  task: string;
34
- tools?: ("listFiles" | "editFile" | "replaceLines" | "writeFile" | "readFile" | "grep" | "bash" | "readToolOutput")[] | undefined;
34
+ tools?: ("listFiles" | "editFile" | "replaceLines" | "writeFile" | "readFile" | "grep" | "bash" | "fetch" | "readToolOutput")[] | undefined;
35
35
  maxSteps?: number | undefined;
36
36
  }, SubagentResult>;
@@ -2,7 +2,7 @@ import { streamText, stepCountIs, tool } from 'ai';
2
2
  import { z } from 'zod';
3
3
  import { buildSubagentPrompt } from '../../llm/systemPrompt.js';
4
4
  import { hazeTools } from '../../llm/hazeTools.js';
5
- const ALL_TOOLS = ['listFiles', 'readFile', 'grep', 'bash', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile'];
5
+ const ALL_TOOLS = ['listFiles', 'readFile', 'grep', 'bash', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'fetch'];
6
6
  const STEP_LIMIT = 25;
7
7
  const MAX_SUMMARY = 4000;
8
8
  const TOOL_ONLY_LIMIT = 12;
@@ -116,7 +116,7 @@ export function createSubagentTool(options) {
116
116
  description: 'Spawn subagents to run independent tasks in parallel. ONLY use when a request clearly decomposes into 2+ independent subtasks that can run concurrently — spawn all of them in one step. Do NOT use for single tasks, sequential work, or anything that benefits from conversation context; do those directly instead. Subagents have no conversation history and return a summary.',
117
117
  inputSchema: z.object({
118
118
  task: z.string().min(1).describe('Clear, specific task for the subagent to complete.'),
119
- tools: z.array(z.enum(['listFiles', 'readFile', 'grep', 'bash', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile'])).optional().describe('Tools the subagent can use. Defaults to all tools.'),
119
+ tools: z.array(z.enum(['listFiles', 'readFile', 'grep', 'bash', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'fetch'])).optional().describe('Tools the subagent can use. Defaults to all tools.'),
120
120
  maxSteps: z.number().int().positive().max(50).optional().describe('Maximum tool-call rounds. Default 25.'),
121
121
  }),
122
122
  execute: async ({ task, tools, maxSteps }, context) => runSubagent(task, {
@@ -0,0 +1,25 @@
1
+ export type ReductionPressure = 'conservative' | 'normal' | 'aggressive';
2
+ export type ReductionContentKind = 'validation' | 'log' | 'search' | 'diff' | 'json' | 'table' | 'web' | 'source-outline' | 'generic';
3
+ export type ReductionParseTier = 'full' | 'degraded' | 'passthrough';
4
+ export interface ReductionMetrics {
5
+ rawChars: number;
6
+ returnedChars: number;
7
+ rawTokensEstimate: number;
8
+ returnedTokensEstimate: number;
9
+ estimatedSavedTokens: number;
10
+ savingsPct: number;
11
+ }
12
+ export interface ToolOutputReductionMetadata extends ReductionMetrics {
13
+ reducerName: string;
14
+ contentKind: ReductionContentKind;
15
+ lossy: boolean;
16
+ parseTier: ReductionParseTier;
17
+ rawHandle?: string;
18
+ handle?: string;
19
+ omittedChars: number;
20
+ warning?: string;
21
+ }
22
+ export declare function estimateReductionTokens(text: string): number;
23
+ export declare function reductionMetrics(raw: string, returned: string): ReductionMetrics;
24
+ export declare function retrievalHint(handle: string): string;
25
+ export declare function isInflating(raw: string, returned: string): boolean;
@@ -0,0 +1,23 @@
1
+ export function estimateReductionTokens(text) {
2
+ return Math.ceil(text.length / 4);
3
+ }
4
+ export function reductionMetrics(raw, returned) {
5
+ const rawTokensEstimate = estimateReductionTokens(raw);
6
+ const returnedTokensEstimate = estimateReductionTokens(returned);
7
+ const estimatedSavedTokens = Math.max(0, rawTokensEstimate - returnedTokensEstimate);
8
+ const savingsPct = rawTokensEstimate === 0 ? 0 : Number(((estimatedSavedTokens / rawTokensEstimate) * 100).toFixed(1));
9
+ return {
10
+ rawChars: raw.length,
11
+ returnedChars: returned.length,
12
+ rawTokensEstimate,
13
+ returnedTokensEstimate,
14
+ estimatedSavedTokens,
15
+ savingsPct,
16
+ };
17
+ }
18
+ export function retrievalHint(handle) {
19
+ return `Use readToolOutput with handle ${handle} for the original output.`;
20
+ }
21
+ export function isInflating(raw, returned) {
22
+ return raw.trim().length > 0 && returned.length > raw.length;
23
+ }
@@ -24,8 +24,8 @@ export declare function modelWithConfig(session?: {
24
24
  cacheKey: string;
25
25
  capabilities: ProviderCapabilities;
26
26
  };
27
- }>;
28
- export declare function model(): Promise<import("@ai-sdk/provider").LanguageModelV3>;
27
+ } | undefined>;
28
+ export declare function model(): Promise<import("@ai-sdk/provider").LanguageModelV3 | undefined>;
29
29
  export declare function cacheKeyFor(name: string, cwd?: string): string;
30
30
  export declare function providerRequestSettings(config: ModelRuntimeConfig): {
31
31
  headers?: {
@@ -17,9 +17,11 @@ function capabilities(providerName, baseURL) {
17
17
  export async function modelWithConfig(session) {
18
18
  const settings = await readSettings();
19
19
  const selection = activeModel(settings);
20
- const baseURL = process.env.OPENAI_BASE_URL ?? selection.provider.url;
21
- const apiKey = process.env.OPENAI_API_KEY ?? selection.provider.key ?? settings.apiKey ?? 'not-needed';
22
- const name = process.env.HAZE_MODEL ?? selection.model;
20
+ if (!selection)
21
+ return undefined;
22
+ const baseURL = selection.provider.url;
23
+ const apiKey = selection.provider.key ?? settings.apiKey ?? 'not-needed';
24
+ const name = selection.model;
23
25
  const cacheSeed = session?.cwd ?? process.cwd();
24
26
  const cacheKey = crypto.createHash('sha256').update(`${cacheSeed}\0${name}`).digest('hex').slice(0, 32);
25
27
  return {
@@ -34,7 +36,7 @@ export async function modelWithConfig(session) {
34
36
  };
35
37
  }
36
38
  export async function model() {
37
- return (await modelWithConfig()).model;
39
+ return (await modelWithConfig())?.model;
38
40
  }
39
41
  export function cacheKeyFor(name, cwd) {
40
42
  const seed = cwd ?? process.cwd();