@denizokcu/haze 0.8.0 → 0.9.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 (65) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/README.md +15 -13
  3. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  4. package/dist/cli/chat/sessionRecorder.js +23 -8
  5. package/dist/cli/commands/chat.js +90 -104
  6. package/dist/cli/commands/commands.d.ts +1 -1
  7. package/dist/cli/commands/commands.js +1 -1
  8. package/dist/cli/commands/formatters.js +3 -3
  9. package/dist/cli/commands/logsCommand.js +7 -21
  10. package/dist/cli/commands/mcpWizard.js +24 -2
  11. package/dist/cli/commands/providerWizard.js +18 -5
  12. package/dist/cli/commands/runCommand.js +7 -15
  13. package/dist/cli/commands/settingsSummary.js +3 -1
  14. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  15. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  16. package/dist/cli/commands/streaming.js +66 -29
  17. package/dist/cli/commands/wizardPrompts.js +1 -1
  18. package/dist/cli/commands/wizardSuggestions.js +2 -1
  19. package/dist/cli/commands/wizardTransition.d.ts +33 -0
  20. package/dist/cli/commands/wizardTransition.js +44 -0
  21. package/dist/config/contextFiles.js +6 -3
  22. package/dist/config/endpointSecurity.d.ts +2 -0
  23. package/dist/config/endpointSecurity.js +28 -0
  24. package/dist/config/inputHistory.js +4 -2
  25. package/dist/config/privateStorage.d.ts +6 -0
  26. package/dist/config/privateStorage.js +61 -0
  27. package/dist/config/settings.js +4 -4
  28. package/dist/config/updateCheck.js +4 -2
  29. package/dist/core/agent/toolOutputStore.d.ts +3 -0
  30. package/dist/core/agent/toolOutputStore.js +32 -11
  31. package/dist/core/goal/completionPolicy.d.ts +0 -28
  32. package/dist/core/goal/completionPolicy.js +0 -88
  33. package/dist/core/io/boundedRead.d.ts +15 -0
  34. package/dist/core/io/boundedRead.js +97 -0
  35. package/dist/core/limits/byteBudgets.d.ts +13 -0
  36. package/dist/core/limits/byteBudgets.js +13 -0
  37. package/dist/core/log/llmLog.d.ts +10 -0
  38. package/dist/core/log/llmLog.js +59 -13
  39. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  40. package/dist/core/persistence/orderedFileWriter.js +29 -0
  41. package/dist/core/process/runBoundedProcess.d.ts +27 -0
  42. package/dist/core/process/runBoundedProcess.js +80 -0
  43. package/dist/core/session/sessionStore.js +48 -25
  44. package/dist/core/subagent/subagentRunner.js +1 -1
  45. package/dist/llm/client.js +4 -1
  46. package/dist/llm/hazeTools.d.ts +410 -16
  47. package/dist/llm/hazeTools.js +36 -32
  48. package/dist/llm/lsp.d.ts +21 -3
  49. package/dist/llm/lsp.js +55 -13
  50. package/dist/llm/lspTools.d.ts +96 -48
  51. package/dist/llm/mcp.d.ts +1 -1
  52. package/dist/llm/mcp.js +65 -16
  53. package/dist/llm/requestContext.d.ts +1 -0
  54. package/dist/llm/requestContext.js +6 -3
  55. package/dist/llm/toolResultTypes.d.ts +1 -1
  56. package/dist/llm/tools/bashTool.d.ts +368 -16
  57. package/dist/llm/tools/bashTool.js +19 -57
  58. package/dist/llm/tools/grepRunner.d.ts +15 -0
  59. package/dist/llm/tools/grepRunner.js +85 -0
  60. package/dist/skills/SkillLoader.js +17 -5
  61. package/dist/skills/SkillRegistry.js +19 -6
  62. package/dist/skills/types.d.ts +5 -0
  63. package/dist/utils/path.d.ts +2 -0
  64. package/dist/utils/path.js +9 -4
  65. package/package.json +1 -1
@@ -1,5 +1,3 @@
1
- import { execFile as execFileCallback } from 'node:child_process';
2
- import { promisify } from 'node:util';
3
1
  import fs from 'node:fs/promises';
4
2
  import path from 'node:path';
5
3
  import { tool } from 'ai';
@@ -16,11 +14,13 @@ import { compactGrepMatches, renderGrepMatches } from './tools/outputCap.js';
16
14
  import { parseRipgrepJsonStream } from './tools/grepParse.js';
17
15
  import { findEditRange, splitDiffLines, lineNumberAtOffset, replacementDiff } from './tools/editMatch.js';
18
16
  import { runDedupedTool, discoverScopedContext, withScopedContext, hazeToolContextSchema } from './tools/toolContext.js';
19
- import { prepareWorkspaceExisting, prepareWorkspaceMutation, prepareWorkspaceRead, prepareWorkspaceWritePath } from './tools/workspaceFile.js';
17
+ import { prepareWorkspaceMutation, prepareWorkspaceRead, prepareWorkspaceWritePath } from './tools/workspaceFile.js';
20
18
  import { fetchTool } from './tools/fetchTool.js';
21
19
  import { bashTool } from './tools/bashTool.js';
22
20
  import { DEFAULT_READ_LINES, INLINE_DIFF_LINE_LIMIT, isGitIgnored, MAX_OUTPUT_CHARS, sourceOutlineEntries } from './tools/fileToolShared.js';
23
- const execFile = promisify(execFileCallback);
21
+ import { runRipgrepBounded } from './tools/grepRunner.js';
22
+ import { EXACT_MUTATION_BYTES } from '../core/limits/byteBudgets.js';
23
+ import { readUtf8LinesPage, readUtf8Prefix } from '../core/io/boundedRead.js';
24
24
  export const hazeTools = {
25
25
  listFiles: tool({
26
26
  description: 'List workspace files/directories with pagination. Prefer this to bash for discovery.',
@@ -82,11 +82,13 @@ export const hazeTools = {
82
82
  execute: async ({ path: filePath, offset, limit, mode, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, mode, allowIgnored }, context, async () => {
83
83
  try {
84
84
  const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored);
85
- const content = await fs.readFile(absolutePath, 'utf8');
86
- const lines = content.split(/\r?\n/);
87
85
  const start = offset == null ? 0 : offset - 1;
88
- const requestedEnd = Math.min(lines.length, start + (limit ?? DEFAULT_READ_LINES));
89
- const selectedLines = lines.slice(start, requestedEnd);
86
+ const pageLimit = limit ?? DEFAULT_READ_LINES;
87
+ const page = await readUtf8LinesPage(absolutePath, start + 1, pageLimit);
88
+ const lines = page.lines;
89
+ const totalLines = page.totalLines;
90
+ const requestedEnd = Math.min(totalLines, start + pageLimit);
91
+ const selectedLines = lines;
90
92
  const outlineEntries = mode === 'outline' ? sourceOutlineEntries(selectedLines, start + 1) : undefined;
91
93
  const displayLines = outlineEntries?.map(entry => ({ lineNumber: entry.lineNumber, text: entry.text }))
92
94
  ?? selectedLines.map((line, index) => ({ lineNumber: start + index + 1, text: line }));
@@ -117,15 +119,15 @@ export const hazeTools = {
117
119
  ? displayLines[Math.max(0, includedLines - 1)]?.lineNumber ?? start + 1
118
120
  : start + includedLines;
119
121
  const hasMore = mode === 'outline'
120
- ? requestedEnd < lines.length
121
- : endLine < lines.length;
122
+ ? requestedEnd < totalLines
123
+ : endLine < totalLines;
122
124
  const scopedContext = await discoverScopedContext(filePath, context);
123
125
  return withScopedContext({
124
126
  path: filePath,
125
127
  mode,
126
128
  startLine: start + 1,
127
129
  endLine,
128
- totalLines: lines.length,
130
+ totalLines,
129
131
  content: numberedLines.join('\n'),
130
132
  nextOffset: hasMore ? requestedEnd + 1 : undefined,
131
133
  truncated: hasMore || lineTruncated,
@@ -148,10 +150,11 @@ export const hazeTools = {
148
150
  contextLines: z.number().int().nonnegative().max(5).default(2).describe('Context lines before/after each match'),
149
151
  maxMatches: z.number().int().positive().max(200).default(50).describe('Global match limit'),
150
152
  caseInsensitive: z.boolean().default(false).describe('Ignore case'),
153
+ includeIgnored: z.boolean().default(false).describe('Search ignored paths only when explicitly needed'),
151
154
  }),
152
- execute: async ({ pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context) => runDedupedTool('grep', { pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context, async () => {
155
+ execute: async ({ pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive, includeIgnored }, context) => runDedupedTool('grep', { pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive, includeIgnored }, context, async () => {
153
156
  try {
154
- const absolutePath = await prepareWorkspaceExisting(searchPath);
157
+ const absolutePath = await prepareWorkspaceRead(searchPath, includeIgnored);
155
158
  const args = [
156
159
  '--json', '--color=never',
157
160
  '--max-count', String(maxMatches),
@@ -162,20 +165,14 @@ export const hazeTools = {
162
165
  if (glob)
163
166
  args.push('--glob', glob);
164
167
  args.push('--', pattern, absolutePath);
165
- let stdout = '';
166
- try {
167
- const result = await execFile(rgPath, args, { cwd: workspaceRoot(), timeout: 30_000 });
168
- stdout = result.stdout;
169
- }
170
- catch (error) {
171
- const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
172
- if (code === 1) {
173
- stdout = '';
174
- }
175
- else {
176
- throw error;
177
- }
178
- }
168
+ const result = await runRipgrepBounded({ executable: rgPath, args, cwd: workspaceRoot(), maxMatches, signal: context.abortSignal });
169
+ const stdout = result.stdout;
170
+ if (result.aborted)
171
+ throw new Error('ripgrep aborted');
172
+ if (result.timedOut)
173
+ throw new Error('ripgrep timed out');
174
+ if (result.code !== 0 && result.code !== 1 && !result.capped)
175
+ throw new Error(result.stderr || `ripgrep exited with code ${result.code}`);
179
176
  const scopedContext = await discoverScopedContext(searchPath, context);
180
177
  if (!stdout) {
181
178
  return withScopedContext({ pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches: [], totalMatches: 0, truncated: false }, scopedContext);
@@ -202,14 +199,15 @@ export const hazeTools = {
202
199
  omittedMatches,
203
200
  omittedResultLines: compacted.omittedResultLines,
204
201
  lineTruncated: compacted.lineTruncated,
205
- truncated: omittedMatches > 0 || outputTruncated,
202
+ truncated: result.capped || omittedMatches > 0 || outputTruncated,
203
+ matchCountIsLowerBound: result.capped,
206
204
  reducerName: 'grep-structured',
207
205
  contentKind: 'search',
208
- lossy: omittedMatches > 0 || outputTruncated,
206
+ lossy: result.capped || omittedMatches > 0 || outputTruncated,
209
207
  parseTier: 'full',
210
208
  ...grepMetrics,
211
209
  ...(fullOutputHandle ? { handle: fullOutputHandle, rawHandle: fullOutputHandle, omittedChars: Math.max(0, rawRenderedMatches.length - returnedRenderedMatches.length) } : { omittedChars: 0 }),
212
- suggestion: omittedMatches > 0 || outputTruncated ? 'Narrow the path, glob, or pattern to inspect omitted results, or use readToolOutput with the handle when present.' : undefined,
210
+ suggestion: result.capped || omittedMatches > 0 || outputTruncated ? 'Narrow the path, glob, or pattern to inspect omitted results, or use readToolOutput with the handle when present.' : undefined,
213
211
  }, scopedContext);
214
212
  }
215
213
  catch (error) {
@@ -232,7 +230,10 @@ export const hazeTools = {
232
230
  const { absolutePath, scopedStop } = await prepareWorkspaceMutation('replaceLines', filePath, allowIgnored, context);
233
231
  if (scopedStop)
234
232
  return scopedStop;
235
- const original = await fs.readFile(absolutePath, 'utf8');
233
+ const file = await readUtf8Prefix(absolutePath, EXACT_MUTATION_BYTES);
234
+ if (file.truncated)
235
+ throw new HazeToolError(`File exceeds ${EXACT_MUTATION_BYTES} byte exact-mutation limit`, 'file_too_large');
236
+ const original = file.content;
236
237
  const hasTrailingNewline = original.endsWith('\n');
237
238
  const lines = original.split(/\r?\n/);
238
239
  if (hasTrailingNewline)
@@ -318,7 +319,10 @@ export const hazeTools = {
318
319
  const { absolutePath, scopedStop } = await prepareWorkspaceMutation('editFile', filePath, allowIgnored, context);
319
320
  if (scopedStop)
320
321
  return scopedStop;
321
- const original = await fs.readFile(absolutePath, 'utf8');
322
+ const file = await readUtf8Prefix(absolutePath, EXACT_MUTATION_BYTES);
323
+ if (file.truncated)
324
+ throw new HazeToolError(`File exceeds ${EXACT_MUTATION_BYTES} byte exact-mutation limit`, 'file_too_large');
325
+ const original = file.content;
322
326
  const ranges = edits.map((edit, index) => {
323
327
  const match = findEditRange(original, edit.oldText);
324
328
  if (match.kind === 'missing')
package/dist/llm/lsp.d.ts CHANGED
@@ -21,6 +21,7 @@ export declare function asRange(value: unknown): {
21
21
  };
22
22
  } | undefined;
23
23
  export declare function locationToResult(value: unknown): {
24
+ external?: boolean | undefined;
24
25
  path: string;
25
26
  range: {
26
27
  start: {
@@ -33,6 +34,20 @@ export declare function locationToResult(value: unknown): {
33
34
  };
34
35
  };
35
36
  } | undefined;
37
+ export declare function locationToWorkspaceResult(value: unknown): Promise<{
38
+ external?: boolean | undefined;
39
+ path: string;
40
+ range: {
41
+ start: {
42
+ line: number;
43
+ character: number;
44
+ };
45
+ end: {
46
+ line: number;
47
+ character: number;
48
+ };
49
+ };
50
+ } | undefined>;
36
51
  export declare function flattenSymbols(symbols: unknown[], filePath: string, limit: number): {
37
52
  name: string;
38
53
  kind?: number;
@@ -66,6 +81,7 @@ export declare function lspDocumentSymbols(server: HazeLspServer, filePath: stri
66
81
  selectionRange?: ReturnType<typeof asRange>;
67
82
  }[]>;
68
83
  export declare function lspDefinition(server: HazeLspServer, filePath: string, line: number, character: number, limit: number): Promise<{
84
+ external?: boolean | undefined;
69
85
  path: string;
70
86
  range: {
71
87
  start: {
@@ -79,6 +95,7 @@ export declare function lspDefinition(server: HazeLspServer, filePath: string, l
79
95
  };
80
96
  }[]>;
81
97
  export declare function lspReferences(server: HazeLspServer, filePath: string, line: number, character: number, limit: number): Promise<{
98
+ external?: boolean | undefined;
82
99
  path: string;
83
100
  range: {
84
101
  start: {
@@ -92,8 +109,9 @@ export declare function lspReferences(server: HazeLspServer, filePath: string, l
92
109
  };
93
110
  }[]>;
94
111
  export declare function lspWorkspaceSymbols(server: HazeLspServer, query: string, limit: number): Promise<{
95
- path?: string | undefined;
96
- range?: {
112
+ external?: boolean | undefined;
113
+ path: string;
114
+ range: {
97
115
  start: {
98
116
  line: number;
99
117
  character: number;
@@ -102,7 +120,7 @@ export declare function lspWorkspaceSymbols(server: HazeLspServer, query: string
102
120
  line: number;
103
121
  character: number;
104
122
  };
105
- } | undefined;
123
+ };
106
124
  name: string;
107
125
  kind: number | undefined;
108
126
  }[]>;
package/dist/llm/lsp.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { spawn } from 'node:child_process';
2
- import fs from 'node:fs/promises';
3
2
  import path from 'node:path';
4
- import { pathToFileURL } from 'node:url';
5
- import { resolveWorkspacePath, workspaceRelativePath, workspaceRoot } from '../utils/path.js';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { assertRealPathInsideWorkspace, workspaceRelativePath, workspaceRoot } from '../utils/path.js';
5
+ import { prepareWorkspaceRead } from './tools/workspaceFile.js';
6
+ import { LSP_BUFFER_BYTES, LSP_DOCUMENT_BYTES, LSP_FRAME_BYTES, LSP_HEADER_BYTES } from '../core/limits/byteBudgets.js';
7
+ import { readUtf8Prefix } from '../core/io/boundedRead.js';
6
8
  export class LspError extends Error {
7
9
  constructor(message) {
8
10
  super(message);
@@ -33,7 +35,12 @@ export function toUri(absolutePath) {
33
35
  export function fromUri(uri) {
34
36
  if (!uri.startsWith('file://'))
35
37
  return uri;
36
- return workspaceRelativePath(new URL(uri).pathname);
38
+ try {
39
+ return workspaceRelativePath(fileURLToPath(uri));
40
+ }
41
+ catch {
42
+ return uri;
43
+ }
37
44
  }
38
45
  export function isObject(value) {
39
46
  return typeof value === 'object' && value != null && !Array.isArray(value);
@@ -55,7 +62,27 @@ export function locationToResult(value) {
55
62
  const range = asRange(value.range ?? value.targetSelectionRange ?? value.targetRange);
56
63
  if (!uri || !range)
57
64
  return undefined;
58
- return { path: fromUri(uri), range };
65
+ const resultPath = fromUri(uri);
66
+ const external = !uri.startsWith('file://') || resultPath.startsWith('..') || path.isAbsolute(resultPath);
67
+ return { path: resultPath, range, ...(external ? { external: true } : {}) };
68
+ }
69
+ export async function locationToWorkspaceResult(value) {
70
+ const result = locationToResult(value);
71
+ if (!result || result.external)
72
+ return result;
73
+ if (!isObject(value))
74
+ return undefined;
75
+ const uri = typeof value.uri === 'string' ? value.uri : (typeof value.targetUri === 'string' ? value.targetUri : undefined);
76
+ if (!uri?.startsWith('file://'))
77
+ return result;
78
+ try {
79
+ const absolutePath = fileURLToPath(uri);
80
+ await assertRealPathInsideWorkspace(absolutePath, uri);
81
+ return result;
82
+ }
83
+ catch {
84
+ return { ...result, path: uri, external: true };
85
+ }
59
86
  }
60
87
  export function flattenSymbols(symbols, filePath, limit) {
61
88
  const out = [];
@@ -120,16 +147,25 @@ export class StdioLspClient {
120
147
  this.pending.clear();
121
148
  }
122
149
  onData(chunk) {
150
+ if (this.buffer.length + chunk.length > LSP_BUFFER_BYTES)
151
+ throw new LspError(`LSP receive buffer exceeds ${LSP_BUFFER_BYTES} bytes.`);
123
152
  this.buffer = Buffer.concat([this.buffer, chunk]);
124
153
  while (true) {
125
154
  const headerEnd = this.buffer.indexOf('\r\n\r\n');
126
- if (headerEnd === -1)
155
+ if (headerEnd === -1) {
156
+ if (this.buffer.length > LSP_HEADER_BYTES)
157
+ throw new LspError(`LSP header exceeds ${LSP_HEADER_BYTES} bytes.`);
127
158
  return;
159
+ }
160
+ if (headerEnd > LSP_HEADER_BYTES)
161
+ throw new LspError(`LSP header exceeds ${LSP_HEADER_BYTES} bytes.`);
128
162
  const header = this.buffer.slice(0, headerEnd).toString('utf8');
129
163
  const match = /Content-Length: (\d+)/i.exec(header);
130
164
  if (!match)
131
165
  throw new LspError('Malformed LSP response: missing Content-Length.');
132
166
  const length = Number(match[1]);
167
+ if (!Number.isSafeInteger(length) || length < 0 || length > LSP_FRAME_BYTES)
168
+ throw new LspError(`LSP frame exceeds ${LSP_FRAME_BYTES} bytes.`);
133
169
  const bodyStart = headerEnd + 4;
134
170
  if (this.buffer.length < bodyStart + length)
135
171
  return;
@@ -183,7 +219,10 @@ export class StdioLspClient {
183
219
  this.notify('initialized', {});
184
220
  }
185
221
  async openDocument(absolutePath) {
186
- const text = await fs.readFile(absolutePath, 'utf8');
222
+ const document = await readUtf8Prefix(absolutePath, LSP_DOCUMENT_BYTES);
223
+ if (document.truncated)
224
+ throw new LspError(`LSP document exceeds ${LSP_DOCUMENT_BYTES} byte limit.`);
225
+ const text = document.content;
187
226
  this.notify('textDocument/didOpen', {
188
227
  textDocument: { uri: toUri(absolutePath), languageId: languageId(absolutePath), version: 1, text },
189
228
  });
@@ -199,7 +238,7 @@ export class StdioLspClient {
199
238
  }
200
239
  }
201
240
  async function withLsp(server, filePath, fn) {
202
- const absolutePath = resolveWorkspacePath(filePath);
241
+ const absolutePath = await prepareWorkspaceRead(filePath, false);
203
242
  const client = StdioLspClient.start(server);
204
243
  try {
205
244
  await client.initialize();
@@ -221,14 +260,14 @@ export async function lspDefinition(server, filePath, line, character, limit) {
221
260
  return await withLsp(server, filePath, async (client, absolutePath) => {
222
261
  const result = await client.request('textDocument/definition', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 } });
223
262
  const values = Array.isArray(result) ? result : result ? [result] : [];
224
- return values.map(locationToResult).filter(result => result != null).slice(0, limit);
263
+ return (await Promise.all(values.map(locationToWorkspaceResult))).filter(result => result != null).slice(0, limit);
225
264
  });
226
265
  }
227
266
  export async function lspReferences(server, filePath, line, character, limit) {
228
267
  return await withLsp(server, filePath, async (client, absolutePath) => {
229
268
  const result = await client.request('textDocument/references', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 }, context: { includeDeclaration: true } });
230
269
  const values = Array.isArray(result) ? result : [];
231
- return values.map(locationToResult).filter(result => result != null).slice(0, limit);
270
+ return (await Promise.all(values.map(locationToWorkspaceResult))).filter(result => result != null).slice(0, limit);
232
271
  });
233
272
  }
234
273
  export async function lspWorkspaceSymbols(server, query, limit) {
@@ -237,12 +276,15 @@ export async function lspWorkspaceSymbols(server, query, limit) {
237
276
  await client.initialize();
238
277
  const result = await client.request('workspace/symbol', { query });
239
278
  const values = Array.isArray(result) ? result : [];
240
- return values.flatMap(value => {
279
+ const locations = await Promise.all(values.map(async (value) => {
241
280
  if (!isObject(value) || typeof value.name !== 'string')
242
281
  return [];
243
- const location = locationToResult(value.location);
282
+ const location = await locationToWorkspaceResult(value.location);
283
+ if (!location)
284
+ return [];
244
285
  return [{ name: value.name, kind: typeof value.kind === 'number' ? value.kind : undefined, ...location }];
245
- }).slice(0, limit);
286
+ }));
287
+ return locations.flat().slice(0, limit);
246
288
  }
247
289
  finally {
248
290
  await client.close();