@denizokcu/haze 0.7.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 (96) hide show
  1. package/CHANGELOG.md +35 -9
  2. package/README.md +37 -35
  3. package/dist/cli/chat/inputSuggestions.js +2 -2
  4. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  5. package/dist/cli/chat/sessionRecorder.js +23 -8
  6. package/dist/cli/commands/chat.js +136 -124
  7. package/dist/cli/commands/chatModes.js +1 -1
  8. package/dist/cli/commands/commandHelp.js +2 -2
  9. package/dist/cli/commands/commands.d.ts +1 -1
  10. package/dist/cli/commands/commands.js +1 -1
  11. package/dist/cli/commands/formatters.d.ts +6 -0
  12. package/dist/cli/commands/formatters.js +41 -3
  13. package/dist/cli/commands/logsCommand.js +7 -21
  14. package/dist/cli/commands/mcpWizard.js +24 -2
  15. package/dist/cli/commands/providerWizard.js +18 -5
  16. package/dist/cli/commands/runCommand.js +7 -15
  17. package/dist/cli/commands/settingsSummary.js +3 -1
  18. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  19. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  20. package/dist/cli/commands/streaming.js +99 -51
  21. package/dist/cli/commands/wizardPrompts.js +1 -1
  22. package/dist/cli/commands/wizardSuggestions.js +3 -2
  23. package/dist/cli/commands/wizardTransition.d.ts +33 -0
  24. package/dist/cli/commands/wizardTransition.js +44 -0
  25. package/dist/config/contextFiles.js +6 -3
  26. package/dist/config/endpointSecurity.d.ts +2 -0
  27. package/dist/config/endpointSecurity.js +28 -0
  28. package/dist/config/inputHistory.js +4 -2
  29. package/dist/config/privateStorage.d.ts +6 -0
  30. package/dist/config/privateStorage.js +61 -0
  31. package/dist/config/providers.js +5 -9
  32. package/dist/config/settings.d.ts +1 -0
  33. package/dist/config/settings.js +55 -3
  34. package/dist/config/updateCheck.js +4 -2
  35. package/dist/core/agent/compaction.js +2 -2
  36. package/dist/core/agent/errors.js +1 -1
  37. package/dist/core/agent/requestAssembly.d.ts +1 -0
  38. package/dist/core/agent/requestAssembly.js +13 -0
  39. package/dist/core/agent/toolOutputStore.d.ts +3 -0
  40. package/dist/core/agent/toolOutputStore.js +32 -11
  41. package/dist/core/bashOutput/registry.js +11 -9
  42. package/dist/core/goal/completionPolicy.d.ts +0 -28
  43. package/dist/core/goal/completionPolicy.js +1 -89
  44. package/dist/core/io/boundedRead.d.ts +15 -0
  45. package/dist/core/io/boundedRead.js +97 -0
  46. package/dist/core/limits/byteBudgets.d.ts +13 -0
  47. package/dist/core/limits/byteBudgets.js +13 -0
  48. package/dist/core/log/llmLog.d.ts +10 -0
  49. package/dist/core/log/llmLog.js +59 -13
  50. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  51. package/dist/core/persistence/orderedFileWriter.js +29 -0
  52. package/dist/core/process/runBoundedProcess.d.ts +27 -0
  53. package/dist/core/process/runBoundedProcess.js +80 -0
  54. package/dist/core/session/sessionStore.js +48 -25
  55. package/dist/core/subagent/subagentRunner.d.ts +252 -9
  56. package/dist/core/subagent/subagentRunner.js +14 -19
  57. package/dist/core/toolOutput/reduction.d.ts +2 -0
  58. package/dist/core/toolOutput/reduction.js +12 -0
  59. package/dist/core/validation/outputParser.js +5 -3
  60. package/dist/llm/client.d.ts +2 -2
  61. package/dist/llm/client.js +19 -3
  62. package/dist/llm/hazeTools.d.ts +8103 -364
  63. package/dist/llm/hazeTools.js +43 -33
  64. package/dist/llm/initPrompt.js +1 -1
  65. package/dist/llm/lsp.d.ts +21 -3
  66. package/dist/llm/lsp.js +65 -14
  67. package/dist/llm/lspTools.d.ts +2358 -101
  68. package/dist/llm/mcp.d.ts +1 -1
  69. package/dist/llm/mcp.js +65 -16
  70. package/dist/llm/requestContext.d.ts +1 -0
  71. package/dist/llm/requestContext.js +6 -3
  72. package/dist/llm/systemPrompt.js +2 -2
  73. package/dist/llm/toolResultTypes.d.ts +1 -1
  74. package/dist/llm/tools/bashTool.d.ts +603 -5
  75. package/dist/llm/tools/bashTool.js +23 -60
  76. package/dist/llm/tools/fetchTool.d.ts +1201 -65
  77. package/dist/llm/tools/fetchTool.js +2 -1
  78. package/dist/llm/tools/grepRunner.d.ts +15 -0
  79. package/dist/llm/tools/grepRunner.js +85 -0
  80. package/dist/llm/tools/storedOutputTool.d.ts +351 -10
  81. package/dist/llm/tools/taskTool.d.ts +629 -28
  82. package/dist/llm/tools/toolContext.d.ts +7 -2
  83. package/dist/llm/tools/toolContext.js +11 -2
  84. package/dist/llm/webFetch.js +31 -21
  85. package/dist/skills/SkillLoader.js +17 -5
  86. package/dist/skills/SkillRegistry.js +19 -6
  87. package/dist/skills/builder/SkillBuilder.js +7 -7
  88. package/dist/skills/types.d.ts +5 -0
  89. package/dist/ui/components/TextInput.d.ts +7 -0
  90. package/dist/ui/components/TextInput.js +10 -0
  91. package/dist/utils/modelName.d.ts +2 -0
  92. package/dist/utils/modelName.js +15 -0
  93. package/dist/utils/path.d.ts +2 -0
  94. package/dist/utils/path.js +9 -4
  95. package/examples/skills/files/SKILL.md +1 -1
  96. package/package.json +14 -14
@@ -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';
@@ -15,15 +13,18 @@ import { HazeToolError, structuredToolFailure } from './tools/failures.js';
15
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
- import { runDedupedTool, discoverScopedContext, withScopedContext } from './tools/toolContext.js';
19
- import { prepareWorkspaceExisting, prepareWorkspaceMutation, prepareWorkspaceRead, prepareWorkspaceWritePath } from './tools/workspaceFile.js';
16
+ import { runDedupedTool, discoverScopedContext, withScopedContext, hazeToolContextSchema } from './tools/toolContext.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.',
27
+ contextSchema: hazeToolContextSchema,
27
28
  inputSchema: z.object({
28
29
  path: z.string().default('.').describe('Directory path relative to the current workspace'),
29
30
  recursive: z.boolean().default(false).describe('Whether to list files recursively'),
@@ -70,6 +71,7 @@ export const hazeTools = {
70
71
  }),
71
72
  readFile: tool({
72
73
  description: 'Read numbered lines from a UTF-8 workspace file. Defaults to exact mode; outline mode is for discovery only and must be followed by exact reads before editing.',
74
+ contextSchema: hazeToolContextSchema,
73
75
  inputSchema: z.object({
74
76
  path: z.string().describe('File path relative to the current workspace'),
75
77
  offset: z.number().int().positive().optional().describe('1-based line number to start reading from'),
@@ -80,11 +82,13 @@ export const hazeTools = {
80
82
  execute: async ({ path: filePath, offset, limit, mode, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, mode, allowIgnored }, context, async () => {
81
83
  try {
82
84
  const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored);
83
- const content = await fs.readFile(absolutePath, 'utf8');
84
- const lines = content.split(/\r?\n/);
85
85
  const start = offset == null ? 0 : offset - 1;
86
- const requestedEnd = Math.min(lines.length, start + (limit ?? DEFAULT_READ_LINES));
87
- 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;
88
92
  const outlineEntries = mode === 'outline' ? sourceOutlineEntries(selectedLines, start + 1) : undefined;
89
93
  const displayLines = outlineEntries?.map(entry => ({ lineNumber: entry.lineNumber, text: entry.text }))
90
94
  ?? selectedLines.map((line, index) => ({ lineNumber: start + index + 1, text: line }));
@@ -115,15 +119,15 @@ export const hazeTools = {
115
119
  ? displayLines[Math.max(0, includedLines - 1)]?.lineNumber ?? start + 1
116
120
  : start + includedLines;
117
121
  const hasMore = mode === 'outline'
118
- ? requestedEnd < lines.length
119
- : endLine < lines.length;
122
+ ? requestedEnd < totalLines
123
+ : endLine < totalLines;
120
124
  const scopedContext = await discoverScopedContext(filePath, context);
121
125
  return withScopedContext({
122
126
  path: filePath,
123
127
  mode,
124
128
  startLine: start + 1,
125
129
  endLine,
126
- totalLines: lines.length,
130
+ totalLines,
127
131
  content: numberedLines.join('\n'),
128
132
  nextOffset: hasMore ? requestedEnd + 1 : undefined,
129
133
  truncated: hasMore || lineTruncated,
@@ -138,6 +142,7 @@ export const hazeTools = {
138
142
  }),
139
143
  grep: tool({
140
144
  description: 'Regex search workspace files with structured, globally capped results. Prefer this to reading files one by one.',
145
+ contextSchema: hazeToolContextSchema,
141
146
  inputSchema: z.object({
142
147
  pattern: z.string().min(1).describe('Regex pattern'),
143
148
  path: z.string().default('.').describe('Workspace-relative file or directory'),
@@ -145,10 +150,11 @@ export const hazeTools = {
145
150
  contextLines: z.number().int().nonnegative().max(5).default(2).describe('Context lines before/after each match'),
146
151
  maxMatches: z.number().int().positive().max(200).default(50).describe('Global match limit'),
147
152
  caseInsensitive: z.boolean().default(false).describe('Ignore case'),
153
+ includeIgnored: z.boolean().default(false).describe('Search ignored paths only when explicitly needed'),
148
154
  }),
149
- 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 () => {
150
156
  try {
151
- const absolutePath = await prepareWorkspaceExisting(searchPath);
157
+ const absolutePath = await prepareWorkspaceRead(searchPath, includeIgnored);
152
158
  const args = [
153
159
  '--json', '--color=never',
154
160
  '--max-count', String(maxMatches),
@@ -159,20 +165,14 @@ export const hazeTools = {
159
165
  if (glob)
160
166
  args.push('--glob', glob);
161
167
  args.push('--', pattern, absolutePath);
162
- let stdout = '';
163
- try {
164
- const result = await execFile(rgPath, args, { cwd: workspaceRoot(), timeout: 30_000 });
165
- stdout = result.stdout;
166
- }
167
- catch (error) {
168
- const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
169
- if (code === 1) {
170
- stdout = '';
171
- }
172
- else {
173
- throw error;
174
- }
175
- }
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}`);
176
176
  const scopedContext = await discoverScopedContext(searchPath, context);
177
177
  if (!stdout) {
178
178
  return withScopedContext({ pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches: [], totalMatches: 0, truncated: false }, scopedContext);
@@ -199,14 +199,15 @@ export const hazeTools = {
199
199
  omittedMatches,
200
200
  omittedResultLines: compacted.omittedResultLines,
201
201
  lineTruncated: compacted.lineTruncated,
202
- truncated: omittedMatches > 0 || outputTruncated,
202
+ truncated: result.capped || omittedMatches > 0 || outputTruncated,
203
+ matchCountIsLowerBound: result.capped,
203
204
  reducerName: 'grep-structured',
204
205
  contentKind: 'search',
205
- lossy: omittedMatches > 0 || outputTruncated,
206
+ lossy: result.capped || omittedMatches > 0 || outputTruncated,
206
207
  parseTier: 'full',
207
208
  ...grepMetrics,
208
209
  ...(fullOutputHandle ? { handle: fullOutputHandle, rawHandle: fullOutputHandle, omittedChars: Math.max(0, rawRenderedMatches.length - returnedRenderedMatches.length) } : { omittedChars: 0 }),
209
- 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,
210
211
  }, scopedContext);
211
212
  }
212
213
  catch (error) {
@@ -216,6 +217,7 @@ export const hazeTools = {
216
217
  }),
217
218
  replaceLines: tool({
218
219
  description: 'Replace a 1-based inclusive line range. Use after readFile when exact editFile text is ambiguous or stale.',
220
+ contextSchema: hazeToolContextSchema,
219
221
  inputSchema: z.object({
220
222
  path: z.string().describe('File path relative to the current workspace'),
221
223
  startLine: z.number().int().positive().describe('First 1-based line number to replace'),
@@ -228,7 +230,10 @@ export const hazeTools = {
228
230
  const { absolutePath, scopedStop } = await prepareWorkspaceMutation('replaceLines', filePath, allowIgnored, context);
229
231
  if (scopedStop)
230
232
  return scopedStop;
231
- 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;
232
237
  const hasTrailingNewline = original.endsWith('\n');
233
238
  const lines = original.split(/\r?\n/);
234
239
  if (hasTrailingNewline)
@@ -264,6 +269,7 @@ export const hazeTools = {
264
269
  }),
265
270
  writeFile: tool({
266
271
  description: 'Create a UTF-8 file. Existing files require explicit full-rewrite approval.',
272
+ contextSchema: hazeToolContextSchema,
267
273
  inputSchema: z.object({
268
274
  path: z.string().describe('File path relative to the current workspace'),
269
275
  content: z.string().describe('Complete file contents to write'),
@@ -299,6 +305,7 @@ export const hazeTools = {
299
305
  }),
300
306
  editFile: tool({
301
307
  description: 'Apply unique text replacements. Batch same-file edits; reread and use replaceLines if matching fails.',
308
+ contextSchema: hazeToolContextSchema,
302
309
  inputSchema: z.object({
303
310
  path: z.string().describe('File path relative to the current workspace'),
304
311
  edits: z.array(z.object({
@@ -312,7 +319,10 @@ export const hazeTools = {
312
319
  const { absolutePath, scopedStop } = await prepareWorkspaceMutation('editFile', filePath, allowIgnored, context);
313
320
  if (scopedStop)
314
321
  return scopedStop;
315
- 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;
316
326
  const ranges = edits.map((edit, index) => {
317
327
  const match = findEditRange(original, edit.oldText);
318
328
  if (match.kind === 'missing')
@@ -1,6 +1,6 @@
1
1
  import { MAX_CONTEXT_FILE_CHARS } from '../config/contextFiles.js';
2
2
  export function buildInitPrompt() {
3
- return `Initialize this repository for Haze by creating a best-practice AGENTS.md file.
3
+ return `Initialize this repository for haze by creating a best-practice AGENTS.md file.
4
4
 
5
5
  Explore the codebase first, respecting .gitignore, but keep this quick and minimal:
6
6
  1. Start with exactly one listFiles call from the workspace root. Do not announce that you are starting before the tool call.
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 = [];
@@ -92,7 +119,16 @@ export class StdioLspClient {
92
119
  constructor(server, child) {
93
120
  this.server = server;
94
121
  this.child = child;
95
- child.stdout.on('data', chunk => this.onData(chunk));
122
+ child.stdout.on('data', chunk => {
123
+ try {
124
+ this.onData(chunk);
125
+ }
126
+ catch (error) {
127
+ const lspError = error instanceof Error ? error : new LspError(String(error));
128
+ this.rejectAll(lspError);
129
+ this.child.kill('SIGTERM');
130
+ }
131
+ });
96
132
  child.stderr.on('data', () => undefined);
97
133
  child.on('error', error => this.rejectAll(error instanceof Error ? error : new Error(String(error))));
98
134
  child.on('exit', code => this.rejectAll(new LspError(`LSP server exited${code == null ? '' : ` with code ${code}`}`)));
@@ -111,16 +147,25 @@ export class StdioLspClient {
111
147
  this.pending.clear();
112
148
  }
113
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.`);
114
152
  this.buffer = Buffer.concat([this.buffer, chunk]);
115
153
  while (true) {
116
154
  const headerEnd = this.buffer.indexOf('\r\n\r\n');
117
- 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.`);
118
158
  return;
159
+ }
160
+ if (headerEnd > LSP_HEADER_BYTES)
161
+ throw new LspError(`LSP header exceeds ${LSP_HEADER_BYTES} bytes.`);
119
162
  const header = this.buffer.slice(0, headerEnd).toString('utf8');
120
163
  const match = /Content-Length: (\d+)/i.exec(header);
121
164
  if (!match)
122
165
  throw new LspError('Malformed LSP response: missing Content-Length.');
123
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.`);
124
169
  const bodyStart = headerEnd + 4;
125
170
  if (this.buffer.length < bodyStart + length)
126
171
  return;
@@ -174,7 +219,10 @@ export class StdioLspClient {
174
219
  this.notify('initialized', {});
175
220
  }
176
221
  async openDocument(absolutePath) {
177
- 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;
178
226
  this.notify('textDocument/didOpen', {
179
227
  textDocument: { uri: toUri(absolutePath), languageId: languageId(absolutePath), version: 1, text },
180
228
  });
@@ -190,7 +238,7 @@ export class StdioLspClient {
190
238
  }
191
239
  }
192
240
  async function withLsp(server, filePath, fn) {
193
- const absolutePath = resolveWorkspacePath(filePath);
241
+ const absolutePath = await prepareWorkspaceRead(filePath, false);
194
242
  const client = StdioLspClient.start(server);
195
243
  try {
196
244
  await client.initialize();
@@ -212,14 +260,14 @@ export async function lspDefinition(server, filePath, line, character, limit) {
212
260
  return await withLsp(server, filePath, async (client, absolutePath) => {
213
261
  const result = await client.request('textDocument/definition', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 } });
214
262
  const values = Array.isArray(result) ? result : result ? [result] : [];
215
- 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);
216
264
  });
217
265
  }
218
266
  export async function lspReferences(server, filePath, line, character, limit) {
219
267
  return await withLsp(server, filePath, async (client, absolutePath) => {
220
268
  const result = await client.request('textDocument/references', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 }, context: { includeDeclaration: true } });
221
269
  const values = Array.isArray(result) ? result : [];
222
- 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);
223
271
  });
224
272
  }
225
273
  export async function lspWorkspaceSymbols(server, query, limit) {
@@ -228,12 +276,15 @@ export async function lspWorkspaceSymbols(server, query, limit) {
228
276
  await client.initialize();
229
277
  const result = await client.request('workspace/symbol', { query });
230
278
  const values = Array.isArray(result) ? result : [];
231
- return values.flatMap(value => {
279
+ const locations = await Promise.all(values.map(async (value) => {
232
280
  if (!isObject(value) || typeof value.name !== 'string')
233
281
  return [];
234
- const location = locationToResult(value.location);
282
+ const location = await locationToWorkspaceResult(value.location);
283
+ if (!location)
284
+ return [];
235
285
  return [{ name: value.name, kind: typeof value.kind === 'number' ? value.kind : undefined, ...location }];
236
- }).slice(0, limit);
286
+ }));
287
+ return locations.flat().slice(0, limit);
237
288
  }
238
289
  finally {
239
290
  await client.close();