@denizokcu/haze 0.10.0 → 1.0.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 (294) hide show
  1. package/CHANGELOG.md +100 -1
  2. package/README.md +77 -27
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/chatMetrics.d.ts +2 -2
  9. package/dist/cli/chat/chatMetrics.js +1 -1
  10. package/dist/cli/chat/contextReport.js +2 -0
  11. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  12. package/dist/cli/chat/inputSuggestions.d.ts +8 -16
  13. package/dist/cli/chat/inputSuggestions.js +9 -41
  14. package/dist/cli/chat/liveRegion.d.ts +25 -0
  15. package/dist/cli/chat/liveRegion.js +48 -0
  16. package/dist/cli/chat/messages.d.ts +33 -4
  17. package/dist/cli/chat/messages.js +218 -35
  18. package/dist/cli/chat/sessionLifecycle.d.ts +11 -1
  19. package/dist/cli/chat/sessionLifecycle.js +64 -14
  20. package/dist/cli/chat/sessionRecorder.js +75 -7
  21. package/dist/cli/chat/startupInfo.d.ts +0 -1
  22. package/dist/cli/chat/startupInfo.js +11 -15
  23. package/dist/cli/chat/turnState.d.ts +1 -1
  24. package/dist/cli/chat/wizardDispatch.d.ts +90 -28
  25. package/dist/cli/chat/wizardDispatch.js +349 -133
  26. package/dist/cli/commands/chat.d.ts +5 -0
  27. package/dist/cli/commands/chat.js +216 -172
  28. package/dist/cli/commands/chatModes.d.ts +8 -1
  29. package/dist/cli/commands/chatModes.js +9 -44
  30. package/dist/cli/commands/commands.d.ts +2 -0
  31. package/dist/cli/commands/commands.js +10 -5
  32. package/dist/cli/commands/doctor.d.ts +19 -0
  33. package/dist/cli/commands/doctor.js +76 -0
  34. package/dist/cli/commands/formatters.d.ts +3 -3
  35. package/dist/cli/commands/formatters.js +8 -25
  36. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  37. package/dist/cli/commands/ndjsonSink.js +38 -0
  38. package/dist/cli/commands/providerWizard.d.ts +9 -2
  39. package/dist/cli/commands/providerWizard.js +39 -7
  40. package/dist/cli/commands/runCommand.d.ts +3 -0
  41. package/dist/cli/commands/runCommand.js +117 -11
  42. package/dist/cli/commands/serverWizard.d.ts +34 -0
  43. package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
  44. package/dist/cli/commands/skillsWizard.d.ts +41 -0
  45. package/dist/cli/commands/{skillWizard.js → skillsWizard.js} +33 -11
  46. package/dist/cli/commands/streaming/abortCause.d.ts +25 -0
  47. package/dist/cli/commands/streaming/abortCause.js +16 -0
  48. package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
  49. package/dist/cli/commands/streaming/agentAttempt.js +79 -0
  50. package/dist/cli/commands/streaming/assistantText.js +9 -2
  51. package/dist/cli/commands/streaming/attemptLifecycle.d.ts +56 -0
  52. package/dist/cli/commands/streaming/attemptLifecycle.js +110 -0
  53. package/dist/cli/commands/streaming/attemptOutcome.d.ts +96 -0
  54. package/dist/cli/commands/streaming/attemptOutcome.js +206 -0
  55. package/dist/cli/commands/streaming/attemptSetup.d.ts +78 -0
  56. package/dist/cli/commands/streaming/attemptSetup.js +167 -0
  57. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  58. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  59. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.js +130 -0
  61. package/dist/cli/commands/streaming/stallRecovery.d.ts +94 -0
  62. package/dist/cli/commands/streaming/stallRecovery.js +105 -0
  63. package/dist/cli/commands/streaming/streamLoop.d.ts +72 -0
  64. package/dist/cli/commands/streaming/streamLoop.js +448 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +16 -0
  66. package/dist/cli/commands/streaming/toolCallRecovery.js +80 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -1
  68. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  69. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  70. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  71. package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -0
  73. package/dist/cli/commands/streaming.d.ts +65 -9
  74. package/dist/cli/commands/streaming.js +133 -430
  75. package/dist/cli/commands/wizardFlow.d.ts +334 -0
  76. package/dist/cli/commands/wizardFlow.js +377 -0
  77. package/dist/cli/contextReport.js +3 -0
  78. package/dist/cli/index.js +68 -22
  79. package/dist/cli/terminalTitle.js +1 -1
  80. package/dist/config/contextFiles.js +9 -3
  81. package/dist/config/inputHistory.d.ts +0 -1
  82. package/dist/config/inputHistory.js +1 -1
  83. package/dist/config/modelDiscovery.d.ts +36 -0
  84. package/dist/config/modelDiscovery.js +164 -1
  85. package/dist/config/privateStorage.js +28 -2
  86. package/dist/config/providerAuth.d.ts +14 -0
  87. package/dist/config/providerAuth.js +49 -0
  88. package/dist/config/providerPresets.d.ts +39 -7
  89. package/dist/config/providerPresets.js +371 -100
  90. package/dist/config/providers.js +2 -0
  91. package/dist/config/settings.d.ts +43 -0
  92. package/dist/config/settings.js +12 -0
  93. package/dist/config/skillSettings.js +4 -4
  94. package/dist/config/updateCheck.d.ts +0 -1
  95. package/dist/config/updateCheck.js +1 -1
  96. package/dist/core/agent/budgets.d.ts +73 -1
  97. package/dist/core/agent/budgets.js +94 -1
  98. package/dist/core/agent/compaction.d.ts +38 -0
  99. package/dist/core/agent/compaction.js +92 -17
  100. package/dist/core/agent/completionController.d.ts +224 -0
  101. package/dist/core/agent/completionController.js +296 -0
  102. package/dist/core/agent/contextBudget.d.ts +36 -2
  103. package/dist/core/agent/contextBudget.js +62 -9
  104. package/dist/core/agent/errors.d.ts +0 -1
  105. package/dist/core/agent/errors.js +1 -1
  106. package/dist/core/agent/events.d.ts +78 -0
  107. package/dist/core/agent/goalPolicy.d.ts +47 -0
  108. package/dist/core/agent/goalPolicy.js +106 -0
  109. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  110. package/dist/core/agent/reasoningPolicy.js +27 -0
  111. package/dist/core/agent/requestAssembly.d.ts +2 -2
  112. package/dist/core/agent/requestAssembly.js +16 -4
  113. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  114. package/dist/core/agent/toolCapabilities.js +58 -0
  115. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  116. package/dist/core/agent/toolOutputStore.js +11 -11
  117. package/dist/core/agent/toolResults.d.ts +12 -0
  118. package/dist/core/agent/toolResults.js +38 -0
  119. package/dist/core/agent/turnPolicy.d.ts +11 -0
  120. package/dist/core/agent/turnPolicy.js +19 -0
  121. package/dist/core/agent/workState.d.ts +81 -3
  122. package/dist/core/agent/workState.js +176 -10
  123. package/dist/core/attachments/imageAttachments.js +90 -42
  124. package/dist/core/deadline.d.ts +27 -0
  125. package/dist/core/deadline.js +74 -0
  126. package/dist/core/io/boundedRead.js +1 -1
  127. package/dist/core/limits.d.ts +51 -0
  128. package/dist/core/limits.js +51 -0
  129. package/dist/core/log/llmLog.js +8 -1
  130. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  131. package/dist/core/persistence/orderedFileWriter.js +16 -2
  132. package/dist/core/process/backgroundRegistry.d.ts +2 -3
  133. package/dist/core/process/backgroundRegistry.js +15 -10
  134. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  135. package/dist/core/process/runBoundedProcess.js +15 -6
  136. package/dist/core/process/userShell.d.ts +16 -0
  137. package/dist/core/process/userShell.js +59 -0
  138. package/dist/core/safety/missingExecutable.d.ts +42 -0
  139. package/dist/core/safety/missingExecutable.js +77 -0
  140. package/dist/core/safety/shellClassifier.d.ts +11 -0
  141. package/dist/core/safety/{bashClassifier.js → shellClassifier.js} +5 -3
  142. package/dist/core/safety/urlGuard.d.ts +1 -1
  143. package/dist/core/session/sessionSlimming.d.ts +0 -3
  144. package/dist/core/session/sessionSlimming.js +2 -3
  145. package/dist/core/session/sessionStore.d.ts +38 -0
  146. package/dist/core/session/sessionStore.js +242 -59
  147. package/dist/core/{bashOutput → shellOutput}/lineFilter.js +8 -2
  148. package/dist/core/{bashOutput → shellOutput}/reducers/search.d.ts +0 -1
  149. package/dist/core/{bashOutput → shellOutput}/reducers/search.js +1 -1
  150. package/dist/core/shellOutput/registry.d.ts +2 -0
  151. package/dist/core/{bashOutput → shellOutput}/registry.js +3 -3
  152. package/dist/core/{bashOutput → shellOutput}/types.d.ts +6 -5
  153. package/dist/core/subagent/contracts.d.ts +6 -14
  154. package/dist/core/subagent/contracts.js +4 -3
  155. package/dist/core/subagent/executionProfiles.js +2 -2
  156. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  157. package/dist/core/subagent/subagentCoordinator.js +32 -2
  158. package/dist/core/subagent/subagentRunner.js +19 -40
  159. package/dist/core/toolOutput/reduction.d.ts +0 -12
  160. package/dist/core/toolOutput/reduction.js +1 -1
  161. package/dist/core/validation/outputParser.d.ts +2 -2
  162. package/dist/llm/client.d.ts +17 -1
  163. package/dist/llm/client.js +86 -14
  164. package/dist/llm/hazeTools.d.ts +693 -204
  165. package/dist/llm/hazeTools.js +110 -28
  166. package/dist/llm/initPrompt.js +1 -1
  167. package/dist/llm/lsp/client.d.ts +45 -0
  168. package/dist/llm/lsp/client.js +195 -0
  169. package/dist/llm/lsp/pool.d.ts +23 -0
  170. package/dist/llm/lsp/pool.js +86 -0
  171. package/dist/llm/lsp/protocol.d.ts +64 -0
  172. package/dist/llm/lsp/protocol.js +128 -0
  173. package/dist/llm/lsp/requests.d.ts +94 -0
  174. package/dist/llm/lsp/requests.js +119 -0
  175. package/dist/llm/lspTools.d.ts +5653 -33
  176. package/dist/llm/lspTools.js +152 -80
  177. package/dist/llm/openaiCodex.d.ts +1 -0
  178. package/dist/llm/openaiCodex.js +43 -0
  179. package/dist/llm/openaiCodexOAuth.d.ts +51 -0
  180. package/dist/llm/openaiCodexOAuth.js +217 -0
  181. package/dist/llm/requestContext.d.ts +7 -0
  182. package/dist/llm/requestContext.js +30 -4
  183. package/dist/llm/systemPrompt.d.ts +12 -0
  184. package/dist/llm/systemPrompt.js +24 -11
  185. package/dist/llm/toolResultTypes.d.ts +7 -14
  186. package/dist/llm/toolResultTypes.js +1 -4
  187. package/dist/llm/tools/editMatch.d.ts +14 -9
  188. package/dist/llm/tools/editMatch.js +73 -1
  189. package/dist/llm/tools/failures.d.ts +2 -0
  190. package/dist/llm/tools/failures.js +1 -0
  191. package/dist/llm/tools/fetchTool.d.ts +16 -0
  192. package/dist/llm/tools/fetchTool.js +1 -1
  193. package/dist/llm/tools/fileToolShared.d.ts +8 -5
  194. package/dist/llm/tools/fileToolShared.js +22 -23
  195. package/dist/llm/tools/gitIgnore.d.ts +42 -0
  196. package/dist/llm/tools/gitIgnore.js +247 -0
  197. package/dist/llm/tools/grepParse.d.ts +2 -1
  198. package/dist/llm/tools/grepRunner.d.ts +1 -1
  199. package/dist/llm/tools/grepRunner.js +2 -2
  200. package/dist/llm/tools/outputCap.d.ts +2 -7
  201. package/dist/llm/tools/outputCap.js +3 -3
  202. package/dist/llm/tools/processTool.d.ts +16 -16
  203. package/dist/llm/tools/processTool.js +1 -1
  204. package/dist/llm/tools/readRecovery.d.ts +8 -0
  205. package/dist/llm/tools/readRecovery.js +135 -0
  206. package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +171 -123
  207. package/dist/llm/tools/{bashTool.js → shellTool.js} +20 -14
  208. package/dist/llm/tools/toolContext.d.ts +1 -1
  209. package/dist/llm/tools/toolContext.js +66 -37
  210. package/dist/llm/tools/workspaceFile.d.ts +0 -1
  211. package/dist/llm/tools/workspaceFile.js +1 -6
  212. package/dist/llm/webFetch.d.ts +18 -1
  213. package/dist/llm/webFetch.js +64 -97
  214. package/dist/skills/SkillLoader.d.ts +1 -11
  215. package/dist/skills/SkillLoader.js +1 -2
  216. package/dist/skills/types.d.ts +2 -1
  217. package/dist/ui/codeHighlight.d.ts +4 -0
  218. package/dist/ui/codeHighlight.js +31 -0
  219. package/dist/ui/components/Header.d.ts +1 -1
  220. package/dist/ui/components/MarkdownText.d.ts +16 -2
  221. package/dist/ui/components/MarkdownText.js +244 -34
  222. package/dist/ui/components/TextInput.d.ts +8 -1
  223. package/dist/ui/components/TextInput.js +6 -2
  224. package/dist/ui/theme.d.ts +4 -3
  225. package/dist/ui/theme.js +5 -4
  226. package/dist/utils/buildInfo.d.ts +97 -0
  227. package/dist/utils/buildInfo.js +244 -0
  228. package/dist/utils/fs.d.ts +11 -0
  229. package/dist/utils/fs.js +91 -26
  230. package/dist/utils/openPath.d.ts +2 -2
  231. package/dist/utils/openPath.js +19 -6
  232. package/dist/utils/path.d.ts +2 -1
  233. package/dist/utils/path.js +6 -2
  234. package/dist/utils/utf8.d.ts +22 -0
  235. package/dist/utils/utf8.js +54 -0
  236. package/dist/utils/version.d.ts +9 -3
  237. package/dist/utils/version.js +28 -2
  238. package/package.json +28 -21
  239. package/dist/cli/commands/lspWizard.d.ts +0 -14
  240. package/dist/cli/commands/lspWizard.js +0 -44
  241. package/dist/cli/commands/mcpWizard.d.ts +0 -15
  242. package/dist/cli/commands/skillConfirmRemove.d.ts +0 -11
  243. package/dist/cli/commands/skillConfirmRemove.js +0 -20
  244. package/dist/cli/commands/skillCreation.d.ts +0 -12
  245. package/dist/cli/commands/skillCreation.js +0 -14
  246. package/dist/cli/commands/skillWizard.d.ts +0 -17
  247. package/dist/cli/commands/streaming/idleTimer.d.ts +0 -26
  248. package/dist/cli/commands/streaming/idleTimer.js +0 -24
  249. package/dist/cli/commands/streaming/turnOutcome.d.ts +0 -10
  250. package/dist/cli/commands/streaming/turnOutcome.js +0 -13
  251. package/dist/cli/commands/wizardActions.d.ts +0 -46
  252. package/dist/cli/commands/wizardActions.js +0 -46
  253. package/dist/cli/commands/wizardInput.d.ts +0 -4
  254. package/dist/cli/commands/wizardInput.js +0 -19
  255. package/dist/cli/commands/wizardPrompts.d.ts +0 -22
  256. package/dist/cli/commands/wizardPrompts.js +0 -52
  257. package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
  258. package/dist/cli/commands/wizardSuggestions.js +0 -188
  259. package/dist/cli/commands/wizardTransition.d.ts +0 -37
  260. package/dist/cli/commands/wizardTransition.js +0 -43
  261. package/dist/core/bashOutput/ansi.d.ts +0 -1
  262. package/dist/core/bashOutput/ansi.js +0 -7
  263. package/dist/core/bashOutput/registry.d.ts +0 -4
  264. package/dist/core/goal/completionPolicy.d.ts +0 -2
  265. package/dist/core/goal/completionPolicy.js +0 -7
  266. package/dist/core/goal/requestClassifier.d.ts +0 -3
  267. package/dist/core/goal/requestClassifier.js +0 -18
  268. package/dist/core/goal/sessionGoal.d.ts +0 -8
  269. package/dist/core/goal/sessionGoal.js +0 -30
  270. package/dist/core/limits/byteBudgets.d.ts +0 -18
  271. package/dist/core/limits/byteBudgets.js +0 -18
  272. package/dist/core/limits/textBudgets.d.ts +0 -23
  273. package/dist/core/limits/textBudgets.js +0 -23
  274. package/dist/core/safety/bashClassifier.d.ts +0 -10
  275. package/dist/llm/lsp.d.ts +0 -129
  276. package/dist/llm/lsp.js +0 -307
  277. package/dist/ui/components/ErrorView.d.ts +0 -4
  278. package/dist/ui/components/ErrorView.js +0 -7
  279. package/dist/utils/yaml.d.ts +0 -2
  280. package/dist/utils/yaml.js +0 -8
  281. package/examples/skills/files/SKILL.md +0 -16
  282. package/examples/skills/files/examples/file-editing.md +0 -3
  283. /package/dist/core/{bashOutput → shellOutput}/command.d.ts +0 -0
  284. /package/dist/core/{bashOutput → shellOutput}/command.js +0 -0
  285. /package/dist/core/{bashOutput → shellOutput}/lineFilter.d.ts +0 -0
  286. /package/dist/core/{bashOutput → shellOutput}/reducers/content.d.ts +0 -0
  287. /package/dist/core/{bashOutput → shellOutput}/reducers/content.js +0 -0
  288. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.d.ts +0 -0
  289. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.js +0 -0
  290. /package/dist/core/{bashOutput → shellOutput}/reducers/git.d.ts +0 -0
  291. /package/dist/core/{bashOutput → shellOutput}/reducers/git.js +0 -0
  292. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.d.ts +0 -0
  293. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.js +0 -0
  294. /package/dist/core/{bashOutput → shellOutput}/types.js +0 -0
@@ -12,19 +12,33 @@ import { reductionMetrics } from '../core/toolOutput/reduction.js';
12
12
  import { HazeToolError, structuredToolFailure } from './tools/failures.js';
13
13
  import { compactGrepMatches, renderGrepMatches } from './tools/outputCap.js';
14
14
  import { parseRipgrepJsonStream } from './tools/grepParse.js';
15
- import { findEditRange, splitDiffLines, lineNumberAtOffset, replacementDiff } from './tools/editMatch.js';
15
+ import { boundedDiff, fileDiff, findEditRange, splitDiffLines, lineNumberAtOffset, renderToolDiff, replacementDiff } from './tools/editMatch.js';
16
16
  import { runDedupedTool, discoverScopedContext, withScopedContext, hazeToolContextSchema } from './tools/toolContext.js';
17
17
  import { prepareWorkspaceMutation, prepareWorkspaceRead, prepareWorkspaceWritePath } from './tools/workspaceFile.js';
18
18
  import { fetchTool } from './tools/fetchTool.js';
19
- import { bashTool } from './tools/bashTool.js';
19
+ import { shellTool } from './tools/shellTool.js';
20
20
  import { processTool } from './tools/processTool.js';
21
- import { DEFAULT_READ_LINES, INLINE_DIFF_LINE_LIMIT, isGitIgnored, MAX_OUTPUT_CHARS, sourceOutlineEntries } from './tools/fileToolShared.js';
21
+ import { DEFAULT_READ_LINES, INLINE_DIFF_LINE_LIMIT, MAX_OUTPUT_CHARS, sourceOutlineEntries } from './tools/fileToolShared.js';
22
+ import { createIgnoreClassifier } from './tools/gitIgnore.js';
22
23
  import { runRipgrepBounded } from './tools/grepRunner.js';
23
- import { EXACT_MUTATION_BYTES } from '../core/limits/byteBudgets.js';
24
+ import { EXACT_MUTATION_BYTES } from '../core/limits.js';
25
+ import { WRITE_FILE_CHUNK_BYTES } from '../core/agent/budgets.js';
24
26
  import { readUtf8LinesPage, readUtf8Prefix } from '../core/io/boundedRead.js';
27
+ import { assertReadableTextFile, readFailureRecovery } from './tools/readRecovery.js';
28
+ function mutationDiffFields(filePath, fullDiff) {
29
+ const preview = boundedDiff(fullDiff, INLINE_DIFF_LINE_LIMIT);
30
+ const diffHandle = preview.truncated ? storeToolOutput(renderToolDiff(filePath, fullDiff)) : undefined;
31
+ return {
32
+ diffLineCount: fullDiff.length,
33
+ diff: preview.diff,
34
+ diffTruncated: preview.truncated,
35
+ diffOmittedLines: preview.omittedLines,
36
+ ...(diffHandle ? { diffHandle } : {}),
37
+ };
38
+ }
25
39
  export const hazeTools = {
26
40
  listFiles: tool({
27
- description: 'List workspace files/directories with pagination. Prefer this to bash for discovery.',
41
+ description: 'List workspace files/directories with pagination. Prefer this to shell for discovery.',
28
42
  contextSchema: hazeToolContextSchema,
29
43
  inputSchema: z.object({
30
44
  path: z.string().default('.').describe('Directory path relative to the current workspace'),
@@ -39,13 +53,15 @@ export const hazeTools = {
39
53
  const absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored, context);
40
54
  const entries = [];
41
55
  let ignoredSkipped = 0;
42
- const walked = await walkDir(absolutePath, { recursive, maxEntries: maxEntries + 1, cursor, filter: async (entry) => {
43
- if (!includeIgnored && await isGitIgnored(entry.absolutePath)) {
44
- ignoredSkipped++;
45
- return false;
46
- }
47
- return true;
48
- } });
56
+ // One persistent classifier owns the whole listing so rule files are
57
+ // cached across directory frontiers. Walk entries include absolute paths,
58
+ // allowing subtree listings to classify workspace-relative identities.
59
+ const ignoreClassifier = includeIgnored ? undefined : createIgnoreClassifier(workspaceRoot());
60
+ const ignoreBatch = ignoreClassifier ? (entries) => ignoreClassifier.classify(entries).then(ignored => {
61
+ ignoredSkipped += ignored.size;
62
+ return ignored;
63
+ }) : undefined;
64
+ const walked = await walkDir(absolutePath, { recursive, maxEntries: maxEntries + 1, cursor, ignoreBatch });
49
65
  const page = walked.slice(0, maxEntries);
50
66
  const hasMore = walked.length > maxEntries;
51
67
  for (const entry of page) {
@@ -83,9 +99,13 @@ export const hazeTools = {
83
99
  execute: async ({ path: filePath, offset, limit, mode, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, mode, allowIgnored }, context, async () => {
84
100
  try {
85
101
  const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored, context);
102
+ await assertReadableTextFile(absolutePath, filePath);
86
103
  const start = offset == null ? 0 : offset - 1;
87
104
  const pageLimit = limit ?? DEFAULT_READ_LINES;
88
105
  const page = await readUtf8LinesPage(absolutePath, start + 1, pageLimit);
106
+ if (offset != null && offset > page.totalLines) {
107
+ throw new HazeToolError(`offset ${offset} is beyond end of file (${page.totalLines} lines)`, 'invalid_line_range', { recoveryTool: 'readFile', recoveryInput: { path: filePath, offset: Math.max(1, page.totalLines) } });
108
+ }
89
109
  const lines = page.lines;
90
110
  const totalLines = page.totalLines;
91
111
  const requestedEnd = Math.min(totalLines, start + pageLimit);
@@ -144,7 +164,8 @@ export const hazeTools = {
144
164
  }, scopedContext);
145
165
  }
146
166
  catch (error) {
147
- return structuredToolFailure('readFile', error, 'Check the path with listFiles, or set allowIgnored=true only if the user explicitly asked to inspect an ignored file.', filePath);
167
+ const recovery = await readFailureRecovery(filePath, error);
168
+ return structuredToolFailure('readFile', error, recovery.suggestedNextStep, filePath, { reasonCode: recovery.reasonCode, suggestedPaths: recovery.suggestedPaths });
148
169
  }
149
170
  }),
150
171
  }),
@@ -265,10 +286,23 @@ export const hazeTools = {
265
286
  lines.splice(startLine - 1, effectiveEndLine - startLine + 1, ...replacementLines);
266
287
  }
267
288
  const updated = lines.join('\n') + (hasTrailingNewline ? '\n' : '');
268
- const { diff, addedLines, removedLines } = replacementDiff(removedText, content, startLine, startLine, { before: beforeContext, after: afterContext });
269
- const diffLineCount = diff.length;
289
+ const replacement = replacementDiff(removedText, content, startLine, startLine, { before: beforeContext, after: afterContext });
290
+ const changed = updated !== original;
270
291
  await fs.writeFile(absolutePath, updated, 'utf8');
271
- return { ok: true, path: filePath, startLine, endLine: effectiveEndLine, requestedEndLine: endLine, endLineClamped: effectiveEndLine !== endLine, replacementLines: replacementLines.length, appended: isAppend, addedLines, removedLines, diffLineCount, diff: diffLineCount <= INLINE_DIFF_LINE_LIMIT ? diff : undefined };
292
+ return {
293
+ ok: true,
294
+ path: filePath,
295
+ startLine,
296
+ endLine: effectiveEndLine,
297
+ requestedEndLine: endLine,
298
+ endLineClamped: effectiveEndLine !== endLine,
299
+ replacementLines: replacementLines.length,
300
+ appended: isAppend,
301
+ noChange: !changed,
302
+ addedLines: changed ? replacement.addedLines : 0,
303
+ removedLines: changed ? replacement.removedLines : 0,
304
+ ...mutationDiffFields(filePath, changed ? replacement.diff : []),
305
+ };
272
306
  }
273
307
  catch (error) {
274
308
  return structuredToolFailure('replaceLines', error, 'Read the file again for current line numbers, then retry replaceLines with a valid range.', filePath);
@@ -276,38 +310,77 @@ export const hazeTools = {
276
310
  }),
277
311
  }),
278
312
  writeFile: tool({
279
- description: 'Create a UTF-8 file. Existing files require explicit full-rewrite approval.',
313
+ description: `Create, rewrite, or append a UTF-8 file in chunks of at most ${WRITE_FILE_CHUNK_BYTES} bytes. Existing files require explicit rewrite or append approval.`,
280
314
  contextSchema: hazeToolContextSchema,
281
315
  inputSchema: z.object({
282
316
  path: z.string().describe('File path relative to the current workspace'),
283
- content: z.string().describe('Complete file contents to write'),
284
- overwriteExisting: z.boolean().default(false).describe('Approve intentional full rewrite of an existing file'),
317
+ // Size policy lives in execute (write_chunk_too_large with chunking
318
+ // guidance), not in the schema: a Zod .max() would shadow that error
319
+ // with a cryptic AI_TypeValidationError before execute can run.
320
+ content: z.string().describe(`File content chunk, at most ${WRITE_FILE_CHUNK_BYTES} UTF-8 bytes`),
321
+ overwriteExisting: z.boolean().default(false).describe('Approve replacing an existing file with the first chunk of an intentional full rewrite'),
322
+ append: z.boolean().default(false).describe('Append this chunk to an existing file; use after creating or replacing the file with the first chunk'),
285
323
  allowIgnored: z.boolean().default(false).describe('Write a .gitignored file only when needed'),
286
324
  }),
287
- execute: async ({ path: filePath, content, overwriteExisting, allowIgnored }, context) => runDedupedTool('writeFile', { path: filePath, content, overwriteExisting, allowIgnored }, context, async () => {
325
+ execute: async ({ path: filePath, content, overwriteExisting, append, allowIgnored }, context) => runDedupedTool('writeFile', { path: filePath, content, overwriteExisting, append, allowIgnored }, context, async () => {
288
326
  try {
327
+ const contentBytes = Buffer.byteLength(content, 'utf8');
328
+ if (contentBytes > WRITE_FILE_CHUNK_BYTES) {
329
+ throw new HazeToolError(`Content is ${contentBytes} UTF-8 bytes; writeFile accepts at most ${WRITE_FILE_CHUNK_BYTES} bytes per call. Write the first chunk normally, then use append=true for later chunks.`, 'write_chunk_too_large');
330
+ }
331
+ if (append && overwriteExisting) {
332
+ throw new HazeToolError('append=true and overwriteExisting=true are mutually exclusive', 'conflicting_write_modes');
333
+ }
289
334
  const { absolutePath, scopedStop, assertExistingInsideWorkspace, assertWritableInsideWorkspace } = await prepareWorkspaceWritePath('writeFile', filePath, allowIgnored, context);
290
335
  if (scopedStop)
291
336
  return scopedStop;
337
+ let targetExisted = false;
338
+ let previousContent = '';
339
+ let previousContentTruncated = false;
340
+ let previousContentOmittedBytes = 0;
292
341
  try {
293
342
  await fs.access(absolutePath);
343
+ targetExisted = true;
294
344
  await assertExistingInsideWorkspace();
295
- if (!overwriteExisting) {
296
- throw new HazeToolError(`Refusing to overwrite existing file: ${filePath}. Use editFile/replaceLines for targeted edits, or set overwriteExisting=true for an intentional complete rewrite.`, 'existing_file_requires_overwrite', { recoveryTool: 'readFile', recoveryInput: { path: filePath } });
345
+ if (!overwriteExisting && !append) {
346
+ throw new HazeToolError(`Refusing to overwrite existing file: ${filePath}. Use editFile/replaceLines for targeted edits, set append=true for a later chunk, or set overwriteExisting=true for an intentional rewrite.`, 'existing_file_requires_overwrite', { recoveryTool: 'readFile', recoveryInput: { path: filePath } });
297
347
  }
348
+ const previous = await readUtf8Prefix(absolutePath, EXACT_MUTATION_BYTES);
349
+ previousContent = previous.content;
350
+ previousContentTruncated = previous.truncated;
351
+ previousContentOmittedBytes = Math.max(0, previous.totalBytes - Buffer.byteLength(previous.content, 'utf8'));
298
352
  }
299
353
  catch (error) {
300
354
  const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
301
355
  if (code !== 'ENOENT')
302
356
  throw error;
357
+ if (append)
358
+ throw new HazeToolError(`Cannot append to missing file: ${filePath}. Create its first chunk with append=false.`, 'append_target_missing');
303
359
  await assertWritableInsideWorkspace();
304
360
  }
305
361
  await fs.mkdir(path.dirname(absolutePath), { recursive: true });
306
- await fs.writeFile(absolutePath, content, 'utf8');
307
- return { ok: true, path: filePath, bytes: Buffer.byteLength(content, 'utf8'), overwritten: overwriteExisting };
362
+ const updated = append ? `${previousContent}${content}` : content;
363
+ const writeDiff = fileDiff(previousContent, updated);
364
+ if (append)
365
+ await fs.appendFile(absolutePath, content, 'utf8');
366
+ else
367
+ await fs.writeFile(absolutePath, content, 'utf8');
368
+ return {
369
+ ok: true,
370
+ path: filePath,
371
+ bytes: contentBytes,
372
+ overwritten: overwriteExisting,
373
+ appended: append,
374
+ noChange: targetExisted && !previousContentTruncated && previousContent === updated,
375
+ addedLines: writeDiff.addedLines,
376
+ removedLines: writeDiff.removedLines,
377
+ diffComplete: !previousContentTruncated,
378
+ ...(previousContentTruncated ? { previousContentOmittedBytes } : {}),
379
+ ...mutationDiffFields(filePath, writeDiff.diff),
380
+ };
308
381
  }
309
382
  catch (error) {
310
- return structuredToolFailure('writeFile', error, 'Use editFile/replaceLines for existing files, set overwriteExisting=true only for an intentional rewrite, or check the path/ignored-file setting.', filePath);
383
+ return structuredToolFailure('writeFile', error, `Keep each content chunk at or below ${WRITE_FILE_CHUNK_BYTES} UTF-8 bytes. Create or replace the first chunk, then continue with append=true.`, filePath);
311
384
  }
312
385
  }),
313
386
  }),
@@ -369,9 +442,18 @@ export const hazeTools = {
369
442
  removedLines += rangeDiff.removedLines;
370
443
  lineDelta += rangeDiff.addedLines - rangeDiff.removedLines;
371
444
  }
372
- const diffLineCount = diff.length;
445
+ const changed = updated !== original;
373
446
  await fs.writeFile(absolutePath, updated, 'utf8');
374
- return { ok: true, path: filePath, edits: edits.length, approximateMatches: ranges.filter(range => range.approximate).length, addedLines, removedLines, diffLineCount, diff: diffLineCount <= INLINE_DIFF_LINE_LIMIT ? diff : undefined };
447
+ return {
448
+ ok: true,
449
+ path: filePath,
450
+ edits: edits.length,
451
+ approximateMatches: ranges.filter(range => range.approximate).length,
452
+ noChange: !changed,
453
+ addedLines: changed ? addedLines : 0,
454
+ removedLines: changed ? removedLines : 0,
455
+ ...mutationDiffFields(filePath, changed ? diff : []),
456
+ };
375
457
  }
376
458
  catch (error) {
377
459
  return structuredToolFailure('editFile', error, 'Read the file again, then retry with exact current text or use replaceLines with the latest line numbers.', filePath);
@@ -381,6 +463,6 @@ export const hazeTools = {
381
463
  writeTasks: writeTasksTool,
382
464
  readToolOutput: readToolOutputTool,
383
465
  fetch: fetchTool,
384
- bash: bashTool,
466
+ shell: shellTool,
385
467
  process: processTool,
386
468
  };
@@ -4,7 +4,7 @@ export function buildInitPrompt() {
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.
7
- 2. Do not use bash for discovery unless package metadata is missing. Do not grep/find the tree for this command.
7
+ 2. Do not use shell for discovery unless package metadata is missing. Do not grep/find the tree for this command.
8
8
  3. After listFiles returns, read only the small set needed to understand conventions: package/config files, README, existing AGENTS.md if present, and at most three key source entrypoints/directories.
9
9
  4. Do not call listFiles with the same input twice. Do not read the same path repeatedly. Do not read speculative files; list the parent first if unsure.
10
10
  5. Aim to finish in 12 tool calls or fewer. Do not read ignored files unless truly necessary.
@@ -0,0 +1,45 @@
1
+ import { type ChildProcessWithoutNullStreams } from 'node:child_process';
2
+ import type { HazeLspServer } from '../../config/lspSettings.js';
3
+ /**
4
+ * Stdio JSON-RPC LSP client: framing, request/response correlation, push
5
+ * notifications, and bounded teardown. One client wraps one spawned server
6
+ * process; reuse across requests is owned by `pool.ts`.
7
+ */
8
+ type Json = null | boolean | number | string | Json[] | {
9
+ [key: string]: Json;
10
+ };
11
+ export declare class LspError extends Error {
12
+ constructor(message: string);
13
+ }
14
+ export declare class StdioLspClient {
15
+ private server;
16
+ private child;
17
+ private id;
18
+ private buffer;
19
+ private pending;
20
+ private terminating;
21
+ private initializeResult;
22
+ private readonly published;
23
+ constructor(server: HazeLspServer, child: ChildProcessWithoutNullStreams);
24
+ static start(server: HazeLspServer): StdioLspClient;
25
+ private rejectAll;
26
+ private terminate;
27
+ /** Whether this client has begun (or completed) teardown and must not be reused. */
28
+ get terminated(): boolean;
29
+ private onData;
30
+ private handleNotification;
31
+ private send;
32
+ request(method: string, params?: Json, timeoutMs?: number): Promise<unknown>;
33
+ notify(method: string, params?: Json): void;
34
+ initialize(): Promise<void>;
35
+ /** Server capabilities from the initialize handshake; undefined until it completes. */
36
+ get capabilities(): unknown;
37
+ /** Whether the server advertised pull diagnostics (`textDocument/documentDiagnostic`). */
38
+ diagnosticPullSupported(): boolean;
39
+ /** Latest push-published diagnostics for a document URI, if any arrived. */
40
+ publishedDiagnostics(uri: string): unknown[] | undefined;
41
+ openDocument(absolutePath: string): Promise<void>;
42
+ closeDocument(absolutePath: string): void;
43
+ close(): Promise<void>;
44
+ }
45
+ export {};
@@ -0,0 +1,195 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { workspaceRoot } from '../../utils/path.js';
3
+ import { LSP_BUFFER_BYTES, LSP_DOCUMENT_BYTES, LSP_FRAME_BYTES, LSP_HEADER_BYTES } from '../../core/limits.js';
4
+ import { readUtf8Prefix } from '../../core/io/boundedRead.js';
5
+ import { signalProcessTree } from '../../core/process/runBoundedProcess.js';
6
+ import { isObject, languageId, toUri } from './protocol.js';
7
+ export class LspError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = 'LspError';
11
+ }
12
+ }
13
+ export class StdioLspClient {
14
+ server;
15
+ child;
16
+ id = 0;
17
+ buffer = Buffer.alloc(0);
18
+ pending = new Map();
19
+ terminating = false;
20
+ initializeResult;
21
+ published = new Map();
22
+ constructor(server, child) {
23
+ this.server = server;
24
+ this.child = child;
25
+ child.stdout.on('data', chunk => {
26
+ try {
27
+ this.onData(chunk);
28
+ }
29
+ catch (error) {
30
+ const lspError = error instanceof Error ? error : new LspError(String(error));
31
+ this.rejectAll(lspError);
32
+ this.terminate();
33
+ }
34
+ });
35
+ child.stderr.on('data', () => undefined);
36
+ child.on('error', error => this.rejectAll(error instanceof Error ? error : new Error(String(error))));
37
+ child.on('exit', code => this.rejectAll(new LspError(`LSP server exited${code == null ? '' : ` with code ${code}`}`)));
38
+ }
39
+ static start(server) {
40
+ if (!server.command)
41
+ throw new LspError(`LSP server ${server.name} has no command.`);
42
+ const child = spawn(server.command, server.args ?? [], { cwd: workspaceRoot(), detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
43
+ return new StdioLspClient(server, child);
44
+ }
45
+ rejectAll(error) {
46
+ for (const pending of this.pending.values()) {
47
+ clearTimeout(pending.timer);
48
+ pending.reject(error);
49
+ }
50
+ this.pending.clear();
51
+ }
52
+ terminate() {
53
+ if (this.terminating)
54
+ return;
55
+ this.terminating = true;
56
+ signalProcessTree(this.child, 'SIGTERM');
57
+ const forceTimer = setTimeout(() => signalProcessTree(this.child, 'SIGKILL'), 500);
58
+ forceTimer.unref?.();
59
+ this.child.stdin.destroy?.();
60
+ this.child.stdout.destroy?.();
61
+ this.child.stderr.destroy?.();
62
+ }
63
+ /** Whether this client has begun (or completed) teardown and must not be reused. */
64
+ get terminated() {
65
+ return this.terminating;
66
+ }
67
+ onData(chunk) {
68
+ if (this.buffer.length + chunk.length > LSP_BUFFER_BYTES)
69
+ throw new LspError(`LSP receive buffer exceeds ${LSP_BUFFER_BYTES} bytes.`);
70
+ this.buffer = Buffer.concat([this.buffer, chunk]);
71
+ while (true) {
72
+ const headerEnd = this.buffer.indexOf('\r\n\r\n');
73
+ if (headerEnd === -1) {
74
+ if (this.buffer.length > LSP_HEADER_BYTES)
75
+ throw new LspError(`LSP header exceeds ${LSP_HEADER_BYTES} bytes.`);
76
+ return;
77
+ }
78
+ if (headerEnd > LSP_HEADER_BYTES)
79
+ throw new LspError(`LSP header exceeds ${LSP_HEADER_BYTES} bytes.`);
80
+ const header = this.buffer.slice(0, headerEnd).toString('utf8');
81
+ const match = /Content-Length: (\d+)/i.exec(header);
82
+ if (!match)
83
+ throw new LspError('Malformed LSP response: missing Content-Length.');
84
+ const length = Number(match[1]);
85
+ if (!Number.isSafeInteger(length) || length < 0 || length > LSP_FRAME_BYTES)
86
+ throw new LspError(`LSP frame exceeds ${LSP_FRAME_BYTES} bytes.`);
87
+ const bodyStart = headerEnd + 4;
88
+ if (this.buffer.length < bodyStart + length)
89
+ return;
90
+ const raw = this.buffer.slice(bodyStart, bodyStart + length).toString('utf8');
91
+ this.buffer = this.buffer.slice(bodyStart + length);
92
+ const message = JSON.parse(raw);
93
+ if (typeof message.id !== 'number') {
94
+ // Server-initiated notification; only diagnostics are consumed, others are dropped.
95
+ if (typeof message.method === 'string')
96
+ this.handleNotification(message.method, message.params);
97
+ continue;
98
+ }
99
+ const pending = this.pending.get(message.id);
100
+ if (!pending)
101
+ continue;
102
+ this.pending.delete(message.id);
103
+ clearTimeout(pending.timer);
104
+ if (message.error)
105
+ pending.reject(new LspError(message.error.message ?? 'LSP request failed.'));
106
+ else
107
+ pending.resolve(message.result);
108
+ }
109
+ }
110
+ handleNotification(method, params) {
111
+ if (method !== 'textDocument/publishDiagnostics')
112
+ return;
113
+ if (!isObject(params) || typeof params.uri !== 'string')
114
+ return;
115
+ const diagnostics = Array.isArray(params.diagnostics) ? params.diagnostics : [];
116
+ this.published.set(params.uri, { diagnostics, version: typeof params.version === 'number' ? params.version : undefined });
117
+ }
118
+ send(message) {
119
+ const body = JSON.stringify({ ...message, jsonrpc: '2.0' });
120
+ this.child.stdin.write(`Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`);
121
+ }
122
+ request(method, params, timeoutMs = 8000) {
123
+ const id = ++this.id;
124
+ this.send({ id, method, params });
125
+ return new Promise((resolve, reject) => {
126
+ const timer = setTimeout(() => {
127
+ this.pending.delete(id);
128
+ reject(new LspError(`LSP request timed out: ${method}`));
129
+ }, timeoutMs);
130
+ this.pending.set(id, { resolve, reject, timer });
131
+ });
132
+ }
133
+ notify(method, params) {
134
+ this.send({ method, params });
135
+ }
136
+ async initialize() {
137
+ this.initializeResult = await this.request('initialize', {
138
+ processId: process.pid,
139
+ rootUri: toUri(workspaceRoot()),
140
+ capabilities: {
141
+ textDocument: {
142
+ documentSymbol: { hierarchicalDocumentSymbolSupport: true },
143
+ definition: { linkSupport: true },
144
+ typeDefinition: { linkSupport: true },
145
+ implementation: { linkSupport: true },
146
+ references: {},
147
+ diagnostic: {},
148
+ },
149
+ workspace: { symbol: {} },
150
+ },
151
+ });
152
+ this.notify('initialized', {});
153
+ }
154
+ /** Server capabilities from the initialize handshake; undefined until it completes. */
155
+ get capabilities() {
156
+ return this.initializeResult;
157
+ }
158
+ /** Whether the server advertised pull diagnostics (`textDocument/documentDiagnostic`). */
159
+ diagnosticPullSupported() {
160
+ const result = this.initializeResult;
161
+ if (!isObject(result) || !isObject(result.capabilities))
162
+ return false;
163
+ return isObject(result.capabilities.textDocumentDiagnostic);
164
+ }
165
+ /** Latest push-published diagnostics for a document URI, if any arrived. */
166
+ publishedDiagnostics(uri) {
167
+ return this.published.get(uri)?.diagnostics;
168
+ }
169
+ async openDocument(absolutePath) {
170
+ const document = await readUtf8Prefix(absolutePath, LSP_DOCUMENT_BYTES);
171
+ if (document.truncated)
172
+ throw new LspError(`LSP document exceeds ${LSP_DOCUMENT_BYTES} byte limit.`);
173
+ const text = document.content;
174
+ this.notify('textDocument/didOpen', {
175
+ textDocument: { uri: toUri(absolutePath), languageId: languageId(absolutePath), version: 1, text },
176
+ });
177
+ }
178
+ closeDocument(absolutePath) {
179
+ const uri = toUri(absolutePath);
180
+ this.notify('textDocument/didClose', { textDocument: { uri } });
181
+ // Servers may publish an empty set on close; drop the stale snapshot either way.
182
+ this.published.delete(uri);
183
+ }
184
+ async close() {
185
+ if (this.terminating)
186
+ return;
187
+ try {
188
+ await this.request('shutdown', null, 2000).catch(() => undefined);
189
+ this.notify('exit');
190
+ }
191
+ finally {
192
+ this.terminate();
193
+ }
194
+ }
195
+ }
@@ -0,0 +1,23 @@
1
+ import type { HazeLspServer } from '../../config/lspSettings.js';
2
+ import { StdioLspClient } from './client.js';
3
+ /** Server selection and turn-scoped client reuse. */
4
+ export declare function pickLspServer(servers: HazeLspServer[], filePath: string): HazeLspServer | undefined;
5
+ /**
6
+ * Turn-scoped pool of reused LSP clients (RH-009). Autonomous code navigation
7
+ * issues many symbols/definition/references calls per turn; reusing one
8
+ * initialized server and its opened documents avoids repeating expensive
9
+ * startup and indexing on every call. Clients are keyed by server name; a
10
+ * crashed/terminated client is evicted so the next call restarts it.
11
+ */
12
+ export declare class LspPool {
13
+ private readonly clients;
14
+ private readonly openedDocuments;
15
+ private readonly openSnapshots;
16
+ private closed;
17
+ /** Get (or lazily start + initialize) the reusable client for a server. */
18
+ getClient(server: HazeLspServer, filePath?: string): Promise<StdioLspClient>;
19
+ /** Open a document once per client; subsequent calls for the same URI are no-ops. */
20
+ ensureOpen(server: HazeLspServer, client: StdioLspClient, absolutePath: string): Promise<void>;
21
+ /** Bounded teardown of every pooled client. Safe to call once. */
22
+ close(): Promise<void>;
23
+ }
@@ -0,0 +1,86 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { workspaceRelativePath, workspaceRoot } from '../../utils/path.js';
4
+ import { toUri } from './protocol.js';
5
+ import { LspError, StdioLspClient } from './client.js';
6
+ /** Server selection and turn-scoped client reuse. */
7
+ export function pickLspServer(servers, filePath) {
8
+ const ext = path.extname(filePath).toLowerCase();
9
+ return servers.find(server => server.enabled !== false && (server.extensions ?? []).map(e => e.toLowerCase()).includes(ext));
10
+ }
11
+ /** Cheap file fingerprint (mtime + size) used to detect on-disk modification. */
12
+ async function fileFingerprint(absolutePath) {
13
+ try {
14
+ const stats = await fs.stat(absolutePath);
15
+ return `${stats.mtimeMs}:${stats.size}`;
16
+ }
17
+ catch {
18
+ return '';
19
+ }
20
+ }
21
+ /**
22
+ * Turn-scoped pool of reused LSP clients (RH-009). Autonomous code navigation
23
+ * issues many symbols/definition/references calls per turn; reusing one
24
+ * initialized server and its opened documents avoids repeating expensive
25
+ * startup and indexing on every call. Clients are keyed by server name; a
26
+ * crashed/terminated client is evicted so the next call restarts it.
27
+ */
28
+ export class LspPool {
29
+ clients = new Map();
30
+ openedDocuments = new Map();
31
+ openSnapshots = new Map();
32
+ closed = false;
33
+ /** Get (or lazily start + initialize) the reusable client for a server. */
34
+ async getClient(server, filePath) {
35
+ const existing = this.clients.get(server.name);
36
+ if (existing && !existing.terminated) {
37
+ // Read-only navigation must not serve stale positions: when a document was
38
+ // modified on disk since it was opened, close/reopen it so the server sees
39
+ // the current text before answering position-based requests.
40
+ if (filePath) {
41
+ const snapshot = this.openSnapshots.get(filePath);
42
+ if (snapshot !== undefined && snapshot !== await fileFingerprint(filePath)) {
43
+ const absolutePath = path.resolve(workspaceRoot(), filePath);
44
+ const uri = toUri(absolutePath);
45
+ existing.closeDocument(absolutePath);
46
+ this.openedDocuments.get(server.name)?.delete(uri);
47
+ await existing.openDocument(absolutePath);
48
+ this.openedDocuments.get(server.name)?.add(uri);
49
+ this.openSnapshots.set(filePath, await fileFingerprint(filePath));
50
+ }
51
+ }
52
+ return existing;
53
+ }
54
+ const client = StdioLspClient.start(server);
55
+ await client.initialize();
56
+ if (this.closed) {
57
+ await client.close();
58
+ throw new LspError('LSP pool closed during initialization.');
59
+ }
60
+ this.clients.set(server.name, client);
61
+ this.openedDocuments.set(server.name, new Set());
62
+ return client;
63
+ }
64
+ /** Open a document once per client; subsequent calls for the same URI are no-ops. */
65
+ async ensureOpen(server, client, absolutePath) {
66
+ const uri = toUri(absolutePath);
67
+ const opened = this.openedDocuments.get(server.name);
68
+ if (opened && opened.has(uri))
69
+ return;
70
+ await client.openDocument(absolutePath);
71
+ opened?.add(uri);
72
+ const relative = workspaceRelativePath(absolutePath);
73
+ this.openSnapshots.set(relative, await fileFingerprint(absolutePath));
74
+ }
75
+ /** Bounded teardown of every pooled client. Safe to call once. */
76
+ async close() {
77
+ if (this.closed)
78
+ return;
79
+ this.closed = true;
80
+ const clients = [...this.clients.values()];
81
+ this.clients.clear();
82
+ this.openedDocuments.clear();
83
+ this.openSnapshots.clear();
84
+ await Promise.all(clients.map(client => client.close().catch(() => undefined)));
85
+ }
86
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Pure LSP protocol helpers: language/URI mapping, 1-indexed range conversion,
3
+ * location/symbol/diagnostic shaping. No client, process, or filesystem state
4
+ * beyond workspace-relative path resolution.
5
+ */
6
+ export declare function languageId(filePath: string): string;
7
+ export declare function toUri(absolutePath: string): string;
8
+ export declare function fromUri(uri: string): string;
9
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
10
+ export declare function asRange(value: unknown): {
11
+ start: {
12
+ line: number;
13
+ character: number;
14
+ };
15
+ end: {
16
+ line: number;
17
+ character: number;
18
+ };
19
+ } | undefined;
20
+ export declare function locationToResult(value: unknown): {
21
+ external?: boolean | undefined;
22
+ path: string;
23
+ range: {
24
+ start: {
25
+ line: number;
26
+ character: number;
27
+ };
28
+ end: {
29
+ line: number;
30
+ character: number;
31
+ };
32
+ };
33
+ } | undefined;
34
+ export declare function locationToWorkspaceResult(value: unknown): Promise<{
35
+ external?: boolean | undefined;
36
+ path: string;
37
+ range: {
38
+ start: {
39
+ line: number;
40
+ character: number;
41
+ };
42
+ end: {
43
+ line: number;
44
+ character: number;
45
+ };
46
+ };
47
+ } | undefined>;
48
+ export declare function flattenSymbols(symbols: unknown[], filePath: string, limit: number): {
49
+ name: string;
50
+ kind?: number;
51
+ path: string;
52
+ range?: ReturnType<typeof asRange>;
53
+ selectionRange?: ReturnType<typeof asRange>;
54
+ }[];
55
+ /** Structured, workspace-safe summary of one LSP diagnostic. */
56
+ export interface LspDiagnostic {
57
+ severity: 'error' | 'warning' | 'information' | 'hint';
58
+ range: ReturnType<typeof asRange>;
59
+ message: string;
60
+ code?: string;
61
+ source?: string;
62
+ }
63
+ export declare function toDiagnostic(value: unknown): LspDiagnostic | undefined;
64
+ export declare function diagnosticsFrom(values: unknown[], limit: number): LspDiagnostic[];