@denizokcu/haze 0.8.0 → 0.10.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 (182) hide show
  1. package/CHANGELOG.md +67 -17
  2. package/README.md +121 -64
  3. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  4. package/dist/cli/chat/chatMetrics.js +22 -5
  5. package/dist/cli/chat/contextReport.d.ts +11 -0
  6. package/dist/cli/chat/contextReport.js +44 -0
  7. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  8. package/dist/cli/chat/fileMentionSuggestions.js +91 -0
  9. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  10. package/dist/cli/chat/inputSuggestions.js +17 -3
  11. package/dist/cli/chat/sessionLifecycle.d.ts +58 -0
  12. package/dist/cli/chat/sessionLifecycle.js +155 -0
  13. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  14. package/dist/cli/chat/sessionRecorder.js +21 -8
  15. package/dist/cli/chat/startupInfo.d.ts +1 -0
  16. package/dist/cli/chat/startupInfo.js +11 -0
  17. package/dist/cli/chat/tips.d.ts +21 -0
  18. package/dist/cli/chat/tips.js +43 -0
  19. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  20. package/dist/cli/chat/wizardDispatch.js +645 -0
  21. package/dist/cli/commands/chat.d.ts +1 -0
  22. package/dist/cli/commands/chat.js +246 -779
  23. package/dist/cli/commands/chatModes.d.ts +1 -1
  24. package/dist/cli/commands/chatModes.js +7 -2
  25. package/dist/cli/commands/commandHelp.js +5 -3
  26. package/dist/cli/commands/commands.d.ts +4 -3
  27. package/dist/cli/commands/commands.js +12 -13
  28. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  29. package/dist/cli/commands/fleetCommand.js +46 -0
  30. package/dist/cli/commands/formatters.d.ts +5 -0
  31. package/dist/cli/commands/formatters.js +36 -9
  32. package/dist/cli/commands/logsCommand.js +8 -28
  33. package/dist/cli/commands/mcpWizard.js +24 -2
  34. package/dist/cli/commands/modelCommand.js +1 -1
  35. package/dist/cli/commands/providerWizard.d.ts +1 -0
  36. package/dist/cli/commands/providerWizard.js +31 -5
  37. package/dist/cli/commands/runCommand.d.ts +1 -0
  38. package/dist/cli/commands/runCommand.js +32 -20
  39. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  40. package/dist/cli/commands/sessionPicker.js +29 -0
  41. package/dist/cli/commands/settingsSummary.js +8 -4
  42. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  43. package/dist/cli/commands/skillWizard.d.ts +2 -0
  44. package/dist/cli/commands/skillWizard.js +16 -6
  45. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  46. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  47. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -0
  48. package/dist/cli/commands/streaming/toolGroupRenderer.js +4 -2
  49. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  50. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  51. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  52. package/dist/cli/commands/streaming.d.ts +13 -1
  53. package/dist/cli/commands/streaming.js +104 -44
  54. package/dist/cli/commands/wizardActions.d.ts +6 -0
  55. package/dist/cli/commands/wizardActions.js +6 -0
  56. package/dist/cli/commands/wizardPrompts.js +1 -1
  57. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  58. package/dist/cli/commands/wizardSuggestions.js +62 -13
  59. package/dist/cli/commands/wizardTransition.d.ts +37 -0
  60. package/dist/cli/commands/wizardTransition.js +43 -0
  61. package/dist/cli/index.js +17 -3
  62. package/dist/cli/terminalTitle.d.ts +6 -0
  63. package/dist/cli/terminalTitle.js +36 -0
  64. package/dist/config/contextFiles.js +6 -3
  65. package/dist/config/endpointSecurity.d.ts +2 -0
  66. package/dist/config/endpointSecurity.js +28 -0
  67. package/dist/config/inputHistory.d.ts +3 -3
  68. package/dist/config/inputHistory.js +13 -17
  69. package/dist/config/modelDiscovery.d.ts +20 -0
  70. package/dist/config/modelDiscovery.js +51 -0
  71. package/dist/config/privateStorage.d.ts +6 -0
  72. package/dist/config/privateStorage.js +61 -0
  73. package/dist/config/providerPresets.d.ts +16 -4
  74. package/dist/config/providerPresets.js +263 -34
  75. package/dist/config/providers.d.ts +2 -0
  76. package/dist/config/providers.js +7 -0
  77. package/dist/config/settings.d.ts +22 -0
  78. package/dist/config/settings.js +33 -5
  79. package/dist/config/skillSettings.d.ts +6 -13
  80. package/dist/config/skillSettings.js +20 -19
  81. package/dist/config/updateCheck.js +4 -2
  82. package/dist/core/agent/budgets.d.ts +26 -0
  83. package/dist/core/agent/budgets.js +34 -0
  84. package/dist/core/agent/compaction.js +17 -3
  85. package/dist/core/agent/contextBudget.d.ts +8 -0
  86. package/dist/core/agent/contextBudget.js +29 -0
  87. package/dist/core/agent/errors.js +6 -2
  88. package/dist/core/agent/events.d.ts +12 -0
  89. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  90. package/dist/core/agent/toolOutputStore.js +49 -11
  91. package/dist/core/agent/workState.d.ts +1 -1
  92. package/dist/core/agent/workState.js +0 -4
  93. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  94. package/dist/core/attachments/imageAttachments.js +245 -0
  95. package/dist/core/attachments/readBlessings.d.ts +37 -0
  96. package/dist/core/attachments/readBlessings.js +79 -0
  97. package/dist/core/goal/completionPolicy.d.ts +0 -28
  98. package/dist/core/goal/completionPolicy.js +0 -88
  99. package/dist/core/goal/requestClassifier.d.ts +0 -3
  100. package/dist/core/goal/requestClassifier.js +0 -13
  101. package/dist/core/io/boundedRead.d.ts +15 -0
  102. package/dist/core/io/boundedRead.js +144 -0
  103. package/dist/core/limits/byteBudgets.d.ts +18 -0
  104. package/dist/core/limits/byteBudgets.js +18 -0
  105. package/dist/core/limits/textBudgets.d.ts +23 -0
  106. package/dist/core/limits/textBudgets.js +23 -0
  107. package/dist/core/log/llmLog.d.ts +10 -0
  108. package/dist/core/log/llmLog.js +59 -13
  109. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  110. package/dist/core/persistence/orderedFileWriter.js +29 -0
  111. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  112. package/dist/core/process/backgroundRegistry.js +194 -0
  113. package/dist/core/process/runBoundedProcess.d.ts +30 -0
  114. package/dist/core/process/runBoundedProcess.js +116 -0
  115. package/dist/core/safety/urlGuard.d.ts +2 -1
  116. package/dist/core/safety/urlGuard.js +3 -2
  117. package/dist/core/session/sessionSlimming.js +47 -4
  118. package/dist/core/session/sessionStore.d.ts +37 -0
  119. package/dist/core/session/sessionStore.js +136 -27
  120. package/dist/core/subagent/contracts.d.ts +116 -0
  121. package/dist/core/subagent/contracts.js +54 -0
  122. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  123. package/dist/core/subagent/executionProfiles.js +45 -0
  124. package/dist/core/subagent/subagentCoordinator.d.ts +74 -0
  125. package/dist/core/subagent/subagentCoordinator.js +134 -0
  126. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  127. package/dist/core/subagent/subagentRunner.js +228 -98
  128. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  129. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  130. package/dist/core/tasks/taskStorage.js +12 -1
  131. package/dist/llm/client.d.ts +20 -29
  132. package/dist/llm/client.js +33 -29
  133. package/dist/llm/hazeTools.d.ts +2396 -67
  134. package/dist/llm/hazeTools.js +50 -37
  135. package/dist/llm/lsp.d.ts +23 -3
  136. package/dist/llm/lsp.js +73 -16
  137. package/dist/llm/lspTools.d.ts +96 -48
  138. package/dist/llm/mcp.d.ts +1 -1
  139. package/dist/llm/mcp.js +65 -16
  140. package/dist/llm/requestContext.d.ts +23 -1
  141. package/dist/llm/requestContext.js +50 -7
  142. package/dist/llm/systemPrompt.d.ts +4 -1
  143. package/dist/llm/systemPrompt.js +14 -4
  144. package/dist/llm/toolResultTypes.d.ts +1 -1
  145. package/dist/llm/tools/bashTool.d.ts +1210 -16
  146. package/dist/llm/tools/bashTool.js +43 -60
  147. package/dist/llm/tools/fetchTool.d.ts +26 -26
  148. package/dist/llm/tools/fetchTool.js +1 -1
  149. package/dist/llm/tools/fileToolShared.d.ts +2 -1
  150. package/dist/llm/tools/fileToolShared.js +5 -5
  151. package/dist/llm/tools/grepRunner.d.ts +20 -0
  152. package/dist/llm/tools/grepRunner.js +66 -0
  153. package/dist/llm/tools/outputCap.d.ts +2 -6
  154. package/dist/llm/tools/outputCap.js +2 -6
  155. package/dist/llm/tools/processTool.d.ts +1077 -0
  156. package/dist/llm/tools/processTool.js +41 -0
  157. package/dist/llm/tools/toolContext.d.ts +8 -0
  158. package/dist/llm/tools/toolContext.js +22 -11
  159. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  160. package/dist/llm/tools/workspaceFile.js +33 -4
  161. package/dist/llm/webFetch.js +24 -11
  162. package/dist/llm/workerContext.d.ts +18 -0
  163. package/dist/llm/workerContext.js +55 -0
  164. package/dist/skills/SkillLoader.d.ts +2 -2
  165. package/dist/skills/SkillLoader.js +17 -5
  166. package/dist/skills/SkillRegistry.d.ts +3 -2
  167. package/dist/skills/SkillRegistry.js +53 -10
  168. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  169. package/dist/skills/builder/SkillBuilder.js +23 -5
  170. package/dist/skills/skillTools.js +11 -4
  171. package/dist/skills/types.d.ts +11 -1
  172. package/dist/ui/components/TextInput.d.ts +5 -2
  173. package/dist/ui/components/TextInput.js +76 -8
  174. package/dist/utils/format.d.ts +2 -0
  175. package/dist/utils/format.js +8 -0
  176. package/dist/utils/fs.d.ts +0 -1
  177. package/dist/utils/fs.js +0 -4
  178. package/dist/utils/openPath.d.ts +2 -0
  179. package/dist/utils/openPath.js +9 -0
  180. package/dist/utils/path.d.ts +2 -0
  181. package/dist/utils/path.js +9 -4
  182. 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,14 @@ 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';
20
+ import { processTool } from './tools/processTool.js';
22
21
  import { DEFAULT_READ_LINES, INLINE_DIFF_LINE_LIMIT, isGitIgnored, MAX_OUTPUT_CHARS, sourceOutlineEntries } from './tools/fileToolShared.js';
23
- const execFile = promisify(execFileCallback);
22
+ import { runRipgrepBounded } from './tools/grepRunner.js';
23
+ import { EXACT_MUTATION_BYTES } from '../core/limits/byteBudgets.js';
24
+ import { readUtf8LinesPage, readUtf8Prefix } from '../core/io/boundedRead.js';
24
25
  export const hazeTools = {
25
26
  listFiles: tool({
26
27
  description: 'List workspace files/directories with pagination. Prefer this to bash for discovery.',
@@ -35,7 +36,7 @@ export const hazeTools = {
35
36
  }),
36
37
  execute: async ({ path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context) => runDedupedTool('listFiles', { path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context, async () => {
37
38
  try {
38
- const absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored);
39
+ const absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored, context);
39
40
  const entries = [];
40
41
  let ignoredSkipped = 0;
41
42
  const walked = await walkDir(absolutePath, { recursive, maxEntries: maxEntries + 1, cursor, filter: async (entry) => {
@@ -81,12 +82,14 @@ export const hazeTools = {
81
82
  }),
82
83
  execute: async ({ path: filePath, offset, limit, mode, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, mode, allowIgnored }, context, async () => {
83
84
  try {
84
- const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored);
85
- const content = await fs.readFile(absolutePath, 'utf8');
86
- const lines = content.split(/\r?\n/);
85
+ const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored, context);
87
86
  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);
87
+ const pageLimit = limit ?? DEFAULT_READ_LINES;
88
+ const page = await readUtf8LinesPage(absolutePath, start + 1, pageLimit);
89
+ const lines = page.lines;
90
+ const totalLines = page.totalLines;
91
+ const requestedEnd = Math.min(totalLines, start + pageLimit);
92
+ const selectedLines = lines;
90
93
  const outlineEntries = mode === 'outline' ? sourceOutlineEntries(selectedLines, start + 1) : undefined;
91
94
  const displayLines = outlineEntries?.map(entry => ({ lineNumber: entry.lineNumber, text: entry.text }))
92
95
  ?? selectedLines.map((line, index) => ({ lineNumber: start + index + 1, text: line }));
@@ -116,21 +119,28 @@ export const hazeTools = {
116
119
  const endLine = mode === 'outline'
117
120
  ? displayLines[Math.max(0, includedLines - 1)]?.lineNumber ?? start + 1
118
121
  : start + includedLines;
122
+ const outlineDroppedEntries = mode === 'outline' ? displayLines.length - includedLines : 0;
119
123
  const hasMore = mode === 'outline'
120
- ? requestedEnd < lines.length
121
- : endLine < lines.length;
124
+ ? requestedEnd < totalLines || outlineDroppedEntries > 0
125
+ : endLine < totalLines;
126
+ // Outline pages resume after the last *included* entry: the output cap can
127
+ // stop a page before requestedEnd, and jumping to requestedEnd + 1 would
128
+ // silently skip the entries in between (CR-028).
129
+ const nextOffset = hasMore
130
+ ? (mode === 'outline' && includedLines > 0 ? endLine + 1 : requestedEnd + 1)
131
+ : undefined;
122
132
  const scopedContext = await discoverScopedContext(filePath, context);
123
133
  return withScopedContext({
124
134
  path: filePath,
125
135
  mode,
126
136
  startLine: start + 1,
127
137
  endLine,
128
- totalLines: lines.length,
138
+ totalLines,
129
139
  content: numberedLines.join('\n'),
130
- nextOffset: hasMore ? requestedEnd + 1 : undefined,
140
+ nextOffset,
131
141
  truncated: hasMore || lineTruncated,
132
142
  lineTruncated,
133
- ...(mode === 'outline' ? { outline: true, outlineEntries: includedLines, warning: 'Outline mode is lossy discovery output. Use exact readFile around relevant lines before editing.' } : {}),
143
+ ...(mode === 'outline' ? { outline: true, outlineEntries: includedLines, ...(outlineDroppedEntries > 0 ? { outlineDroppedEntries } : {}), warning: 'Outline mode is lossy discovery output. Use exact readFile around relevant lines before editing.' } : {}),
134
144
  }, scopedContext);
135
145
  }
136
146
  catch (error) {
@@ -146,12 +156,13 @@ export const hazeTools = {
146
156
  path: z.string().default('.').describe('Workspace-relative file or directory'),
147
157
  glob: z.string().optional().describe('Optional file glob, e.g. "*.ts"'),
148
158
  contextLines: z.number().int().nonnegative().max(5).default(2).describe('Context lines before/after each match'),
149
- maxMatches: z.number().int().positive().max(200).default(50).describe('Global match limit'),
159
+ maxMatches: z.number().int().positive().max(200).default(50).describe('Global match limit (enforced by the runner; ripgrep also applies it as a per-file cap)'),
150
160
  caseInsensitive: z.boolean().default(false).describe('Ignore case'),
161
+ includeIgnored: z.boolean().default(false).describe('Search ignored paths only when explicitly needed'),
151
162
  }),
152
- execute: async ({ pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context) => runDedupedTool('grep', { pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive }, context, async () => {
163
+ execute: async ({ pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive, includeIgnored }, context) => runDedupedTool('grep', { pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive, includeIgnored }, context, async () => {
153
164
  try {
154
- const absolutePath = await prepareWorkspaceExisting(searchPath);
165
+ const absolutePath = await prepareWorkspaceRead(searchPath, includeIgnored, context);
155
166
  const args = [
156
167
  '--json', '--color=never',
157
168
  '--max-count', String(maxMatches),
@@ -162,20 +173,14 @@ export const hazeTools = {
162
173
  if (glob)
163
174
  args.push('--glob', glob);
164
175
  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
- }
176
+ const result = await runRipgrepBounded({ executable: rgPath, args, cwd: workspaceRoot(), maxMatches, signal: context.abortSignal });
177
+ const stdout = result.stdout;
178
+ if (result.aborted)
179
+ throw new Error('ripgrep aborted');
180
+ if (result.timedOut)
181
+ throw new Error('ripgrep timed out');
182
+ if (result.code !== 0 && result.code !== 1 && !result.capped)
183
+ throw new Error(result.stderr || `ripgrep exited with code ${result.code}`);
179
184
  const scopedContext = await discoverScopedContext(searchPath, context);
180
185
  if (!stdout) {
181
186
  return withScopedContext({ pattern, path: searchPath, glob: glob ?? null, caseInsensitive, matches: [], totalMatches: 0, truncated: false }, scopedContext);
@@ -202,14 +207,15 @@ export const hazeTools = {
202
207
  omittedMatches,
203
208
  omittedResultLines: compacted.omittedResultLines,
204
209
  lineTruncated: compacted.lineTruncated,
205
- truncated: omittedMatches > 0 || outputTruncated,
210
+ truncated: result.capped || omittedMatches > 0 || outputTruncated,
211
+ matchCountIsLowerBound: result.capped,
206
212
  reducerName: 'grep-structured',
207
213
  contentKind: 'search',
208
- lossy: omittedMatches > 0 || outputTruncated,
214
+ lossy: result.capped || omittedMatches > 0 || outputTruncated,
209
215
  parseTier: 'full',
210
216
  ...grepMetrics,
211
217
  ...(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,
218
+ 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
219
  }, scopedContext);
214
220
  }
215
221
  catch (error) {
@@ -232,7 +238,10 @@ export const hazeTools = {
232
238
  const { absolutePath, scopedStop } = await prepareWorkspaceMutation('replaceLines', filePath, allowIgnored, context);
233
239
  if (scopedStop)
234
240
  return scopedStop;
235
- const original = await fs.readFile(absolutePath, 'utf8');
241
+ const file = await readUtf8Prefix(absolutePath, EXACT_MUTATION_BYTES);
242
+ if (file.truncated)
243
+ throw new HazeToolError(`File exceeds ${EXACT_MUTATION_BYTES} byte exact-mutation limit`, 'file_too_large');
244
+ const original = file.content;
236
245
  const hasTrailingNewline = original.endsWith('\n');
237
246
  const lines = original.split(/\r?\n/);
238
247
  if (hasTrailingNewline)
@@ -318,7 +327,10 @@ export const hazeTools = {
318
327
  const { absolutePath, scopedStop } = await prepareWorkspaceMutation('editFile', filePath, allowIgnored, context);
319
328
  if (scopedStop)
320
329
  return scopedStop;
321
- const original = await fs.readFile(absolutePath, 'utf8');
330
+ const file = await readUtf8Prefix(absolutePath, EXACT_MUTATION_BYTES);
331
+ if (file.truncated)
332
+ throw new HazeToolError(`File exceeds ${EXACT_MUTATION_BYTES} byte exact-mutation limit`, 'file_too_large');
333
+ const original = file.content;
322
334
  const ranges = edits.map((edit, index) => {
323
335
  const match = findEditRange(original, edit.oldText);
324
336
  if (match.kind === 'missing')
@@ -370,4 +382,5 @@ export const hazeTools = {
370
382
  readToolOutput: readToolOutputTool,
371
383
  fetch: fetchTool,
372
384
  bash: bashTool,
385
+ process: processTool,
373
386
  };
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;
@@ -47,9 +62,11 @@ export declare class StdioLspClient {
47
62
  private id;
48
63
  private buffer;
49
64
  private pending;
65
+ private terminating;
50
66
  constructor(server: HazeLspServer, child: ChildProcessWithoutNullStreams);
51
67
  static start(server: HazeLspServer): StdioLspClient;
52
68
  private rejectAll;
69
+ private terminate;
53
70
  private onData;
54
71
  private send;
55
72
  request(method: string, params?: Json, timeoutMs?: number): Promise<unknown>;
@@ -66,6 +83,7 @@ export declare function lspDocumentSymbols(server: HazeLspServer, filePath: stri
66
83
  selectionRange?: ReturnType<typeof asRange>;
67
84
  }[]>;
68
85
  export declare function lspDefinition(server: HazeLspServer, filePath: string, line: number, character: number, limit: number): Promise<{
86
+ external?: boolean | undefined;
69
87
  path: string;
70
88
  range: {
71
89
  start: {
@@ -79,6 +97,7 @@ export declare function lspDefinition(server: HazeLspServer, filePath: string, l
79
97
  };
80
98
  }[]>;
81
99
  export declare function lspReferences(server: HazeLspServer, filePath: string, line: number, character: number, limit: number): Promise<{
100
+ external?: boolean | undefined;
82
101
  path: string;
83
102
  range: {
84
103
  start: {
@@ -92,8 +111,9 @@ export declare function lspReferences(server: HazeLspServer, filePath: string, l
92
111
  };
93
112
  }[]>;
94
113
  export declare function lspWorkspaceSymbols(server: HazeLspServer, query: string, limit: number): Promise<{
95
- path?: string | undefined;
96
- range?: {
114
+ external?: boolean | undefined;
115
+ path: string;
116
+ range: {
97
117
  start: {
98
118
  line: number;
99
119
  character: number;
@@ -102,7 +122,7 @@ export declare function lspWorkspaceSymbols(server: HazeLspServer, query: string
102
122
  line: number;
103
123
  character: number;
104
124
  };
105
- } | undefined;
125
+ };
106
126
  name: string;
107
127
  kind: number | undefined;
108
128
  }[]>;
package/dist/llm/lsp.js CHANGED
@@ -1,8 +1,11 @@
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';
8
+ import { signalProcessTree } from '../core/process/runBoundedProcess.js';
6
9
  export class LspError extends Error {
7
10
  constructor(message) {
8
11
  super(message);
@@ -33,7 +36,12 @@ export function toUri(absolutePath) {
33
36
  export function fromUri(uri) {
34
37
  if (!uri.startsWith('file://'))
35
38
  return uri;
36
- return workspaceRelativePath(new URL(uri).pathname);
39
+ try {
40
+ return workspaceRelativePath(fileURLToPath(uri));
41
+ }
42
+ catch {
43
+ return uri;
44
+ }
37
45
  }
38
46
  export function isObject(value) {
39
47
  return typeof value === 'object' && value != null && !Array.isArray(value);
@@ -55,7 +63,27 @@ export function locationToResult(value) {
55
63
  const range = asRange(value.range ?? value.targetSelectionRange ?? value.targetRange);
56
64
  if (!uri || !range)
57
65
  return undefined;
58
- return { path: fromUri(uri), range };
66
+ const resultPath = fromUri(uri);
67
+ const external = !uri.startsWith('file://') || resultPath.startsWith('..') || path.isAbsolute(resultPath);
68
+ return { path: resultPath, range, ...(external ? { external: true } : {}) };
69
+ }
70
+ export async function locationToWorkspaceResult(value) {
71
+ const result = locationToResult(value);
72
+ if (!result || result.external)
73
+ return result;
74
+ if (!isObject(value))
75
+ return undefined;
76
+ const uri = typeof value.uri === 'string' ? value.uri : (typeof value.targetUri === 'string' ? value.targetUri : undefined);
77
+ if (!uri?.startsWith('file://'))
78
+ return result;
79
+ try {
80
+ const absolutePath = fileURLToPath(uri);
81
+ await assertRealPathInsideWorkspace(absolutePath, uri);
82
+ return result;
83
+ }
84
+ catch {
85
+ return { ...result, path: uri, external: true };
86
+ }
59
87
  }
60
88
  export function flattenSymbols(symbols, filePath, limit) {
61
89
  const out = [];
@@ -89,6 +117,7 @@ export class StdioLspClient {
89
117
  id = 0;
90
118
  buffer = Buffer.alloc(0);
91
119
  pending = new Map();
120
+ terminating = false;
92
121
  constructor(server, child) {
93
122
  this.server = server;
94
123
  this.child = child;
@@ -99,7 +128,7 @@ export class StdioLspClient {
99
128
  catch (error) {
100
129
  const lspError = error instanceof Error ? error : new LspError(String(error));
101
130
  this.rejectAll(lspError);
102
- this.child.kill('SIGTERM');
131
+ this.terminate();
103
132
  }
104
133
  });
105
134
  child.stderr.on('data', () => undefined);
@@ -109,7 +138,7 @@ export class StdioLspClient {
109
138
  static start(server) {
110
139
  if (!server.command)
111
140
  throw new LspError(`LSP server ${server.name} has no command.`);
112
- const child = spawn(server.command, server.args ?? [], { cwd: workspaceRoot(), stdio: ['pipe', 'pipe', 'pipe'] });
141
+ const child = spawn(server.command, server.args ?? [], { cwd: workspaceRoot(), detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
113
142
  return new StdioLspClient(server, child);
114
143
  }
115
144
  rejectAll(error) {
@@ -119,17 +148,37 @@ export class StdioLspClient {
119
148
  }
120
149
  this.pending.clear();
121
150
  }
151
+ terminate() {
152
+ if (this.terminating)
153
+ return;
154
+ this.terminating = true;
155
+ signalProcessTree(this.child, 'SIGTERM');
156
+ const forceTimer = setTimeout(() => signalProcessTree(this.child, 'SIGKILL'), 500);
157
+ forceTimer.unref?.();
158
+ this.child.stdin.destroy?.();
159
+ this.child.stdout.destroy?.();
160
+ this.child.stderr.destroy?.();
161
+ }
122
162
  onData(chunk) {
163
+ if (this.buffer.length + chunk.length > LSP_BUFFER_BYTES)
164
+ throw new LspError(`LSP receive buffer exceeds ${LSP_BUFFER_BYTES} bytes.`);
123
165
  this.buffer = Buffer.concat([this.buffer, chunk]);
124
166
  while (true) {
125
167
  const headerEnd = this.buffer.indexOf('\r\n\r\n');
126
- if (headerEnd === -1)
168
+ if (headerEnd === -1) {
169
+ if (this.buffer.length > LSP_HEADER_BYTES)
170
+ throw new LspError(`LSP header exceeds ${LSP_HEADER_BYTES} bytes.`);
127
171
  return;
172
+ }
173
+ if (headerEnd > LSP_HEADER_BYTES)
174
+ throw new LspError(`LSP header exceeds ${LSP_HEADER_BYTES} bytes.`);
128
175
  const header = this.buffer.slice(0, headerEnd).toString('utf8');
129
176
  const match = /Content-Length: (\d+)/i.exec(header);
130
177
  if (!match)
131
178
  throw new LspError('Malformed LSP response: missing Content-Length.');
132
179
  const length = Number(match[1]);
180
+ if (!Number.isSafeInteger(length) || length < 0 || length > LSP_FRAME_BYTES)
181
+ throw new LspError(`LSP frame exceeds ${LSP_FRAME_BYTES} bytes.`);
133
182
  const bodyStart = headerEnd + 4;
134
183
  if (this.buffer.length < bodyStart + length)
135
184
  return;
@@ -183,23 +232,28 @@ export class StdioLspClient {
183
232
  this.notify('initialized', {});
184
233
  }
185
234
  async openDocument(absolutePath) {
186
- const text = await fs.readFile(absolutePath, 'utf8');
235
+ const document = await readUtf8Prefix(absolutePath, LSP_DOCUMENT_BYTES);
236
+ if (document.truncated)
237
+ throw new LspError(`LSP document exceeds ${LSP_DOCUMENT_BYTES} byte limit.`);
238
+ const text = document.content;
187
239
  this.notify('textDocument/didOpen', {
188
240
  textDocument: { uri: toUri(absolutePath), languageId: languageId(absolutePath), version: 1, text },
189
241
  });
190
242
  }
191
243
  async close() {
244
+ if (this.terminating)
245
+ return;
192
246
  try {
193
247
  await this.request('shutdown', null, 2000).catch(() => undefined);
194
248
  this.notify('exit');
195
249
  }
196
250
  finally {
197
- this.child.kill('SIGTERM');
251
+ this.terminate();
198
252
  }
199
253
  }
200
254
  }
201
255
  async function withLsp(server, filePath, fn) {
202
- const absolutePath = resolveWorkspacePath(filePath);
256
+ const absolutePath = await prepareWorkspaceRead(filePath, false);
203
257
  const client = StdioLspClient.start(server);
204
258
  try {
205
259
  await client.initialize();
@@ -221,14 +275,14 @@ export async function lspDefinition(server, filePath, line, character, limit) {
221
275
  return await withLsp(server, filePath, async (client, absolutePath) => {
222
276
  const result = await client.request('textDocument/definition', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 } });
223
277
  const values = Array.isArray(result) ? result : result ? [result] : [];
224
- return values.map(locationToResult).filter(result => result != null).slice(0, limit);
278
+ return (await Promise.all(values.map(locationToWorkspaceResult))).filter(result => result != null).slice(0, limit);
225
279
  });
226
280
  }
227
281
  export async function lspReferences(server, filePath, line, character, limit) {
228
282
  return await withLsp(server, filePath, async (client, absolutePath) => {
229
283
  const result = await client.request('textDocument/references', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 }, context: { includeDeclaration: true } });
230
284
  const values = Array.isArray(result) ? result : [];
231
- return values.map(locationToResult).filter(result => result != null).slice(0, limit);
285
+ return (await Promise.all(values.map(locationToWorkspaceResult))).filter(result => result != null).slice(0, limit);
232
286
  });
233
287
  }
234
288
  export async function lspWorkspaceSymbols(server, query, limit) {
@@ -237,12 +291,15 @@ export async function lspWorkspaceSymbols(server, query, limit) {
237
291
  await client.initialize();
238
292
  const result = await client.request('workspace/symbol', { query });
239
293
  const values = Array.isArray(result) ? result : [];
240
- return values.flatMap(value => {
294
+ const locations = await Promise.all(values.map(async (value) => {
241
295
  if (!isObject(value) || typeof value.name !== 'string')
242
296
  return [];
243
- const location = locationToResult(value.location);
297
+ const location = await locationToWorkspaceResult(value.location);
298
+ if (!location)
299
+ return [];
244
300
  return [{ name: value.name, kind: typeof value.kind === 'number' ? value.kind : undefined, ...location }];
245
- }).slice(0, limit);
301
+ }));
302
+ return locations.flat().slice(0, limit);
246
303
  }
247
304
  finally {
248
305
  await client.close();