@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,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
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ModelMessage } from 'ai';
2
+ import type { WorkState } from '../agent/workState.js';
2
3
  export type SessionEntry = {
3
4
  type: 'header';
4
5
  id: string;
@@ -14,6 +15,10 @@ export type SessionEntry = {
14
15
  type: 'conversation_snapshot';
15
16
  at: string;
16
17
  messages: ModelMessage[];
18
+ } | {
19
+ type: 'work_state_snapshot';
20
+ at: string;
21
+ state: WorkState;
17
22
  } | {
18
23
  type: 'event';
19
24
  at: string;
@@ -34,4 +39,5 @@ export declare function latestSession(cwd?: string, sessionsDir?: string): Promi
34
39
  export declare function appendSessionEntry(session: HazeSession, entry: SessionEntry): Promise<void>;
35
40
  export declare function readSessionEntries(session: HazeSession): Promise<SessionEntry[]>;
36
41
  export declare function restoreConversation(session: HazeSession): Promise<ModelMessage[]>;
42
+ export declare function restoreWorkState(session: HazeSession): Promise<WorkState | undefined>;
37
43
  export declare function formatSession(session: HazeSession): string;
@@ -54,6 +54,11 @@ export async function restoreConversation(session) {
54
54
  const snapshots = entries.filter((entry) => entry.type === 'conversation_snapshot');
55
55
  return snapshots.at(-1)?.messages ?? [];
56
56
  }
57
+ export async function restoreWorkState(session) {
58
+ const entries = await readSessionEntries(session);
59
+ const snapshots = entries.filter((entry) => entry.type === 'work_state_snapshot');
60
+ return snapshots.at(-1)?.state;
61
+ }
57
62
  export function formatSession(session) {
58
63
  return `${session.id} · ${session.file}`;
59
64
  }
@@ -1,4 +1,5 @@
1
1
  import { streamText } from 'ai';
2
+ import { type PromptSession } from '../../llm/systemPrompt.js';
2
3
  import type { ContextFile } from '../../config/contextFiles.js';
3
4
  export interface SubagentResult {
4
5
  status: 'ok' | 'error' | 'timeout' | 'cancelled';
@@ -22,12 +23,14 @@ export declare function runSubagent(task: string, options: {
22
23
  allowedTools?: readonly string[];
23
24
  maxSteps?: number;
24
25
  abortSignal?: AbortSignal;
26
+ session?: PromptSession;
25
27
  }): Promise<SubagentResult>;
26
28
  export declare function createSubagentTool(options: {
27
29
  model: Parameters<typeof streamText>[0]['model'];
28
30
  contextFiles: ContextFile[];
31
+ session?: PromptSession;
29
32
  }): import("ai").Tool<{
30
33
  task: string;
31
- tools?: ("listFiles" | "editFile" | "replaceLines" | "writeFile" | "readFile" | "grep" | "bash")[] | undefined;
34
+ tools?: ("listFiles" | "editFile" | "replaceLines" | "writeFile" | "readFile" | "grep" | "bash" | "fetch" | "readToolOutput")[] | undefined;
32
35
  maxSteps?: number | undefined;
33
36
  }, SubagentResult>;
@@ -1,19 +1,8 @@
1
1
  import { streamText, stepCountIs, tool } from 'ai';
2
2
  import { z } from 'zod';
3
- import { buildSystemPrompt } from '../../llm/systemPrompt.js';
3
+ import { buildSubagentPrompt } from '../../llm/systemPrompt.js';
4
4
  import { hazeTools } from '../../llm/hazeTools.js';
5
- const SUBAGENT_SYSTEM_PROMPT = `You are a focused subagent for a professional developer workflow. Complete the assigned task autonomously using the available tools, then return a clear summary.
6
-
7
- Rules:
8
- - Use whatever tools you need within the assigned scope. You have full access to file tools and bash.
9
- - If the task requires creating or modifying files, do it directly with file tools or an efficient non-destructive shell command; do not ask for permission for ordinary edits.
10
- - Assume expert users understand what they asked for. Do not ask for command confirmations; run relevant commands directly.
11
- - Destructive and ordinary professional workflows should proceed without extra ceremony when they are relevant to the assigned task.
12
- - If a file edit tool fails, read the exact file again and retry once with current content or line numbers.
13
- - After completing the task, summarize what you did, what files you created or changed, validation run, and important findings.
14
- - If you cannot complete the task, explain exactly what blocked you and what you tried.
15
- - Your summary is all the parent agent will see. Be specific: include file paths, function names, command results, and concrete next steps.`;
16
- const ALL_TOOLS = ['listFiles', 'readFile', 'grep', 'bash', 'editFile', 'replaceLines', 'writeFile'];
5
+ const ALL_TOOLS = ['listFiles', 'readFile', 'grep', 'bash', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'fetch'];
17
6
  const STEP_LIMIT = 25;
18
7
  const MAX_SUMMARY = 4000;
19
8
  const TOOL_ONLY_LIMIT = 12;
@@ -59,7 +48,7 @@ export async function runSubagent(task, options) {
59
48
  const result = streamText({
60
49
  model: options.model,
61
50
  maxOutputTokens: 4096,
62
- system: `${SUBAGENT_SYSTEM_PROMPT}\n\n${buildSystemPrompt(options.contextFiles)}`,
51
+ system: buildSubagentPrompt(options.contextFiles, options.session),
63
52
  messages: [{ role: 'user', content: task }],
64
53
  tools: scopedTools,
65
54
  stopWhen: stepCountIs(maxSteps),
@@ -127,7 +116,7 @@ export function createSubagentTool(options) {
127
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.',
128
117
  inputSchema: z.object({
129
118
  task: z.string().min(1).describe('Clear, specific task for the subagent to complete.'),
130
- tools: z.array(z.enum(['listFiles', 'readFile', 'grep', 'bash', 'editFile', 'replaceLines', 'writeFile'])).optional().describe('Tools the subagent can use. Defaults to all tools. Restrict to a subset only when the subagent should be read-only.'),
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.'),
131
120
  maxSteps: z.number().int().positive().max(50).optional().describe('Maximum tool-call rounds. Default 25.'),
132
121
  }),
133
122
  execute: async ({ task, tools, maxSteps }, context) => runSubagent(task, {
@@ -136,6 +125,7 @@ export function createSubagentTool(options) {
136
125
  allowedTools: tools,
137
126
  maxSteps,
138
127
  abortSignal: context.abortSignal,
128
+ session: options.session,
139
129
  }),
140
130
  });
141
131
  }
@@ -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
+ }
@@ -20,7 +20,6 @@ export function parseValidationOutput(input) {
20
20
  const failedTests = [];
21
21
  const failedFiles = [];
22
22
  const kind = inferKind(input.command, input.classification);
23
- const status = input.timedOut ? 'timed_out' : input.code === 0 ? 'passed' : input.code == null ? 'unknown' : 'failed';
24
23
  for (const line of lines) {
25
24
  const ts = line.match(/^(.+?\.(?:ts|tsx|js|jsx|mts|cts))\((\d+),(\d+)\):\s+(error|warning)\s+TS\d+:\s+(.+)$/);
26
25
  if (ts) {
@@ -45,7 +44,7 @@ export function parseValidationOutput(input) {
45
44
  const vitestFile = line.match(/^\s*(?:FAIL|FAILED|✓|✗|❯)?\s*([^\s]+\.(?:test|spec)\.(?:ts|tsx|js|jsx))/i);
46
45
  if (vitestFile)
47
46
  failedFiles.push(vitestFile[1] ?? '');
48
- const testName = line.match(/^\s*(?:FAIL|✗|×|●|-)\s+(.+)$/);
47
+ const testName = line.match(/^\s*(?:FAIL|✗|×|●)\s+(.+)$/);
49
48
  if (testName && !/^(FAIL|FAILED)\s+\S+\.(?:test|spec)\./i.test(line.trim()))
50
49
  failedTests.push((testName[1] ?? '').trim());
51
50
  const genericFile = line.match(/([^\s()]+\.(?:ts|tsx|js|jsx|mts|cts)):(\d+):(\d+)/);
@@ -59,6 +58,20 @@ export function parseValidationOutput(input) {
59
58
  const uniqueTests = uniq(failedTests).slice(0, 10);
60
59
  const diagCount = diagnostics.length;
61
60
  const rawOutputTruncated = Boolean(input.stdoutTruncated || input.stderrTruncated);
61
+ // Pipes (e.g. `npm test | tail`) and process substitutions can mask a
62
+ // non-zero exit code behind the final command in the pipeline. Treat
63
+ // parsed failure evidence as authoritative over `code` so a green exit
64
+ // status does not override real failures the parser already found.
65
+ const hasFailureEvidence = uniqueTests.length > 0 || diagCount > 0;
66
+ const status = input.timedOut
67
+ ? 'timed_out'
68
+ : hasFailureEvidence
69
+ ? 'failed'
70
+ : input.code === 0
71
+ ? 'passed'
72
+ : input.code == null
73
+ ? 'unknown'
74
+ : 'failed';
62
75
  let summaryText;
63
76
  if (status === 'passed')
64
77
  summaryText = `${kind} passed`;
@@ -1 +1,40 @@
1
- export declare function model(): Promise<import("@ai-sdk/provider").LanguageModelV3>;
1
+ export interface ProviderCapabilities {
2
+ reportsCacheUsage: boolean;
3
+ supportsPromptCacheKey: boolean;
4
+ supportsExtendedCacheRetention: boolean;
5
+ supportsStickySessionId: boolean;
6
+ supportsServerCompaction: boolean;
7
+ supportsTextVerbosity: boolean;
8
+ }
9
+ export interface ModelRuntimeConfig {
10
+ providerName: string;
11
+ baseURL: string;
12
+ modelName: string;
13
+ cacheKey: string;
14
+ capabilities: ProviderCapabilities;
15
+ }
16
+ export declare function modelWithConfig(session?: {
17
+ cwd?: string;
18
+ }): Promise<{
19
+ model: import("@ai-sdk/provider").LanguageModelV3;
20
+ config: {
21
+ providerName: string;
22
+ baseURL: string;
23
+ modelName: string;
24
+ cacheKey: string;
25
+ capabilities: ProviderCapabilities;
26
+ };
27
+ } | undefined>;
28
+ export declare function model(): Promise<import("@ai-sdk/provider").LanguageModelV3 | undefined>;
29
+ export declare function cacheKeyFor(name: string, cwd?: string): string;
30
+ export declare function providerRequestSettings(config: ModelRuntimeConfig): {
31
+ headers?: {
32
+ 'x-session-id': string;
33
+ } | undefined;
34
+ providerOptions?: {
35
+ openai: {
36
+ textVerbosity?: "low" | undefined;
37
+ promptCacheKey?: string | undefined;
38
+ };
39
+ } | undefined;
40
+ };
@@ -1,11 +1,57 @@
1
1
  import { createOpenAI } from '@ai-sdk/openai';
2
+ import crypto from 'node:crypto';
2
3
  import { readSettings } from '../config/settings.js';
3
4
  import { activeModel } from '../config/providers.js';
4
- export async function model() {
5
+ function capabilities(providerName, baseURL) {
6
+ const directOpenAI = providerName === 'openai' || /api\.openai\.com/i.test(baseURL);
7
+ const openRouter = providerName === 'openrouter' || /openrouter\.ai/i.test(baseURL);
8
+ return {
9
+ reportsCacheUsage: directOpenAI || openRouter,
10
+ supportsPromptCacheKey: directOpenAI,
11
+ supportsExtendedCacheRetention: false,
12
+ supportsStickySessionId: openRouter,
13
+ supportsServerCompaction: false,
14
+ supportsTextVerbosity: directOpenAI,
15
+ };
16
+ }
17
+ export async function modelWithConfig(session) {
5
18
  const settings = await readSettings();
6
19
  const selection = activeModel(settings);
7
- const baseURL = process.env.OPENAI_BASE_URL ?? selection.provider.url;
8
- const apiKey = process.env.OPENAI_API_KEY ?? selection.provider.key ?? settings.apiKey ?? 'not-needed';
9
- const name = process.env.HAZE_MODEL ?? selection.model;
10
- return createOpenAI({ apiKey, baseURL }).chat(name);
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;
25
+ const cacheSeed = session?.cwd ?? process.cwd();
26
+ const cacheKey = crypto.createHash('sha256').update(`${cacheSeed}\0${name}`).digest('hex').slice(0, 32);
27
+ return {
28
+ model: createOpenAI({ apiKey, baseURL }).chat(name),
29
+ config: {
30
+ providerName: selection.provider.name,
31
+ baseURL,
32
+ modelName: name,
33
+ cacheKey,
34
+ capabilities: capabilities(selection.provider.name, baseURL),
35
+ },
36
+ };
37
+ }
38
+ export async function model() {
39
+ return (await modelWithConfig())?.model;
40
+ }
41
+ export function cacheKeyFor(name, cwd) {
42
+ const seed = cwd ?? process.cwd();
43
+ return crypto.createHash('sha256').update(`${seed}\0${name}`).digest('hex').slice(0, 32);
44
+ }
45
+ export function providerRequestSettings(config) {
46
+ return {
47
+ ...(config.capabilities.supportsPromptCacheKey || config.capabilities.supportsTextVerbosity ? {
48
+ providerOptions: {
49
+ openai: {
50
+ ...(config.capabilities.supportsPromptCacheKey ? { promptCacheKey: config.cacheKey } : {}),
51
+ ...(config.capabilities.supportsTextVerbosity ? { textVerbosity: 'low' } : {}),
52
+ },
53
+ },
54
+ } : {}),
55
+ ...(config.capabilities.supportsStickySessionId ? { headers: { 'x-session-id': config.cacheKey } } : {}),
56
+ };
11
57
  }