@denizokcu/haze 0.11.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 (230) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +23 -14
  3. package/SECURITY.md +3 -3
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/chatMetrics.d.ts +2 -2
  6. package/dist/cli/chat/chatMetrics.js +1 -1
  7. package/dist/cli/chat/fileMentionSuggestions.js +1 -1
  8. package/dist/cli/chat/inputSuggestions.d.ts +8 -16
  9. package/dist/cli/chat/inputSuggestions.js +9 -41
  10. package/dist/cli/chat/messages.d.ts +0 -2
  11. package/dist/cli/chat/messages.js +2 -2
  12. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  13. package/dist/cli/chat/turnState.d.ts +1 -1
  14. package/dist/cli/chat/wizardDispatch.d.ts +90 -28
  15. package/dist/cli/chat/wizardDispatch.js +250 -133
  16. package/dist/cli/commands/chat.js +14 -72
  17. package/dist/cli/commands/chatModes.d.ts +8 -1
  18. package/dist/cli/commands/chatModes.js +9 -44
  19. package/dist/cli/commands/doctor.js +1 -1
  20. package/dist/cli/commands/formatters.d.ts +3 -3
  21. package/dist/cli/commands/formatters.js +6 -25
  22. package/dist/cli/commands/providerWizard.js +2 -3
  23. package/dist/cli/commands/runCommand.js +1 -1
  24. package/dist/cli/commands/serverWizard.d.ts +34 -0
  25. package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
  26. package/dist/cli/commands/skillsWizard.d.ts +41 -0
  27. package/dist/cli/commands/{skillWizard.js → skillsWizard.js} +33 -11
  28. package/dist/cli/commands/streaming/abortCause.d.ts +2 -1
  29. package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
  30. package/dist/cli/commands/streaming/agentAttempt.js +79 -0
  31. package/dist/cli/commands/streaming/attemptLifecycle.d.ts +56 -0
  32. package/dist/cli/commands/streaming/attemptLifecycle.js +110 -0
  33. package/dist/cli/commands/streaming/attemptOutcome.d.ts +96 -0
  34. package/dist/cli/commands/streaming/attemptOutcome.js +206 -0
  35. package/dist/cli/commands/streaming/attemptSetup.d.ts +78 -0
  36. package/dist/cli/commands/streaming/attemptSetup.js +167 -0
  37. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
  38. package/dist/cli/commands/streaming/goalCheckpoint.js +2 -2
  39. package/dist/cli/commands/streaming/goalSupervisor.js +9 -6
  40. package/dist/cli/commands/streaming/stallRecovery.d.ts +94 -0
  41. package/dist/cli/commands/streaming/stallRecovery.js +105 -0
  42. package/dist/cli/commands/streaming/streamLoop.d.ts +72 -0
  43. package/dist/cli/commands/streaming/streamLoop.js +448 -0
  44. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +14 -0
  45. package/dist/cli/commands/streaming/toolCallRecovery.js +56 -0
  46. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -1
  47. package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
  48. package/dist/cli/commands/streaming/turnRuntime.js +6 -0
  49. package/dist/cli/commands/streaming.d.ts +14 -25
  50. package/dist/cli/commands/streaming.js +43 -754
  51. package/dist/cli/commands/wizardFlow.d.ts +334 -0
  52. package/dist/cli/commands/wizardFlow.js +377 -0
  53. package/dist/cli/contextReport.js +3 -0
  54. package/dist/cli/index.js +1 -1
  55. package/dist/config/contextFiles.js +9 -3
  56. package/dist/config/inputHistory.d.ts +0 -1
  57. package/dist/config/inputHistory.js +1 -1
  58. package/dist/config/modelDiscovery.d.ts +0 -15
  59. package/dist/config/modelDiscovery.js +1 -1
  60. package/dist/config/settings.d.ts +7 -0
  61. package/dist/config/settings.js +3 -0
  62. package/dist/config/skillSettings.js +4 -4
  63. package/dist/config/updateCheck.d.ts +0 -1
  64. package/dist/config/updateCheck.js +1 -1
  65. package/dist/core/agent/budgets.d.ts +63 -1
  66. package/dist/core/agent/budgets.js +84 -1
  67. package/dist/core/agent/compaction.js +1 -1
  68. package/dist/core/agent/completionController.d.ts +7 -13
  69. package/dist/core/agent/completionController.js +17 -8
  70. package/dist/core/agent/contextBudget.d.ts +0 -4
  71. package/dist/core/agent/contextBudget.js +3 -3
  72. package/dist/core/agent/errors.d.ts +0 -1
  73. package/dist/core/agent/errors.js +1 -1
  74. package/dist/core/agent/events.d.ts +5 -1
  75. package/dist/core/{goal/completionPolicy.d.ts → agent/goalPolicy.d.ts} +18 -0
  76. package/dist/core/agent/goalPolicy.js +106 -0
  77. package/dist/core/agent/requestAssembly.d.ts +2 -2
  78. package/dist/core/agent/requestAssembly.js +16 -4
  79. package/dist/core/agent/toolCapabilities.d.ts +2 -2
  80. package/dist/core/agent/toolCapabilities.js +5 -5
  81. package/dist/core/agent/toolOutputStore.js +1 -1
  82. package/dist/core/agent/toolResults.js +1 -1
  83. package/dist/core/agent/workState.d.ts +6 -3
  84. package/dist/core/agent/workState.js +62 -7
  85. package/dist/core/attachments/imageAttachments.js +90 -42
  86. package/dist/core/deadline.d.ts +0 -6
  87. package/dist/core/deadline.js +1 -1
  88. package/dist/core/io/boundedRead.js +1 -1
  89. package/dist/core/limits.d.ts +51 -0
  90. package/dist/core/limits.js +51 -0
  91. package/dist/core/log/llmLog.js +1 -1
  92. package/dist/core/process/backgroundRegistry.d.ts +2 -3
  93. package/dist/core/process/backgroundRegistry.js +10 -6
  94. package/dist/core/process/userShell.d.ts +16 -0
  95. package/dist/core/process/userShell.js +59 -0
  96. package/dist/core/safety/shellClassifier.d.ts +11 -0
  97. package/dist/core/safety/{bashClassifier.js → shellClassifier.js} +5 -3
  98. package/dist/core/safety/urlGuard.d.ts +1 -1
  99. package/dist/core/session/sessionSlimming.d.ts +0 -3
  100. package/dist/core/session/sessionSlimming.js +2 -3
  101. package/dist/core/session/sessionStore.d.ts +1 -0
  102. package/dist/core/session/sessionStore.js +39 -20
  103. package/dist/core/{bashOutput → shellOutput}/lineFilter.js +8 -2
  104. package/dist/core/{bashOutput → shellOutput}/reducers/search.d.ts +0 -1
  105. package/dist/core/{bashOutput → shellOutput}/reducers/search.js +1 -1
  106. package/dist/core/shellOutput/registry.d.ts +2 -0
  107. package/dist/core/{bashOutput → shellOutput}/registry.js +3 -3
  108. package/dist/core/{bashOutput → shellOutput}/types.d.ts +6 -5
  109. package/dist/core/subagent/contracts.d.ts +2 -14
  110. package/dist/core/subagent/contracts.js +3 -3
  111. package/dist/core/subagent/executionProfiles.js +2 -2
  112. package/dist/core/subagent/subagentRunner.js +3 -4
  113. package/dist/core/toolOutput/reduction.d.ts +0 -12
  114. package/dist/core/toolOutput/reduction.js +1 -1
  115. package/dist/core/validation/outputParser.d.ts +2 -2
  116. package/dist/llm/client.js +5 -1
  117. package/dist/llm/hazeTools.d.ts +139 -124
  118. package/dist/llm/hazeTools.js +14 -11
  119. package/dist/llm/initPrompt.js +1 -1
  120. package/dist/llm/lsp/client.d.ts +45 -0
  121. package/dist/llm/lsp/client.js +195 -0
  122. package/dist/llm/lsp/pool.d.ts +23 -0
  123. package/dist/llm/lsp/pool.js +86 -0
  124. package/dist/llm/lsp/protocol.d.ts +64 -0
  125. package/dist/llm/lsp/protocol.js +128 -0
  126. package/dist/llm/lsp/requests.d.ts +94 -0
  127. package/dist/llm/lsp/requests.js +119 -0
  128. package/dist/llm/lspTools.d.ts +3824 -570
  129. package/dist/llm/lspTools.js +65 -1
  130. package/dist/llm/openaiCodex.d.ts +0 -2
  131. package/dist/llm/openaiCodex.js +0 -4
  132. package/dist/llm/openaiCodexOAuth.d.ts +0 -3
  133. package/dist/llm/openaiCodexOAuth.js +6 -3
  134. package/dist/llm/requestContext.d.ts +5 -1
  135. package/dist/llm/requestContext.js +25 -2
  136. package/dist/llm/systemPrompt.d.ts +1 -0
  137. package/dist/llm/systemPrompt.js +13 -6
  138. package/dist/llm/toolResultTypes.d.ts +0 -14
  139. package/dist/llm/toolResultTypes.js +1 -4
  140. package/dist/llm/tools/editMatch.d.ts +0 -9
  141. package/dist/llm/tools/editMatch.js +1 -1
  142. package/dist/llm/tools/fetchTool.js +1 -1
  143. package/dist/llm/tools/fileToolShared.d.ts +4 -2
  144. package/dist/llm/tools/fileToolShared.js +9 -5
  145. package/dist/llm/tools/gitIgnore.d.ts +25 -32
  146. package/dist/llm/tools/gitIgnore.js +216 -98
  147. package/dist/llm/tools/grepParse.d.ts +2 -1
  148. package/dist/llm/tools/grepRunner.d.ts +1 -1
  149. package/dist/llm/tools/grepRunner.js +2 -2
  150. package/dist/llm/tools/outputCap.d.ts +2 -7
  151. package/dist/llm/tools/outputCap.js +3 -3
  152. package/dist/llm/tools/processTool.d.ts +16 -16
  153. package/dist/llm/tools/processTool.js +1 -1
  154. package/dist/llm/tools/readRecovery.d.ts +0 -2
  155. package/dist/llm/tools/readRecovery.js +2 -2
  156. package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +123 -107
  157. package/dist/llm/tools/{bashTool.js → shellTool.js} +15 -14
  158. package/dist/llm/tools/toolContext.js +5 -5
  159. package/dist/llm/tools/workspaceFile.d.ts +0 -1
  160. package/dist/llm/tools/workspaceFile.js +1 -6
  161. package/dist/llm/webFetch.d.ts +1 -1
  162. package/dist/skills/SkillLoader.d.ts +1 -11
  163. package/dist/skills/SkillLoader.js +1 -2
  164. package/dist/skills/types.d.ts +2 -1
  165. package/dist/utils/buildInfo.d.ts +6 -13
  166. package/dist/utils/buildInfo.js +6 -15
  167. package/dist/utils/fs.d.ts +7 -5
  168. package/dist/utils/fs.js +5 -2
  169. package/dist/utils/path.d.ts +0 -1
  170. package/dist/utils/path.js +1 -1
  171. package/package.json +6 -4
  172. package/dist/cli/commands/lspWizard.d.ts +0 -14
  173. package/dist/cli/commands/lspWizard.js +0 -44
  174. package/dist/cli/commands/mcpWizard.d.ts +0 -15
  175. package/dist/cli/commands/skillConfirmRemove.d.ts +0 -11
  176. package/dist/cli/commands/skillConfirmRemove.js +0 -20
  177. package/dist/cli/commands/skillCreation.d.ts +0 -12
  178. package/dist/cli/commands/skillCreation.js +0 -14
  179. package/dist/cli/commands/skillWizard.d.ts +0 -17
  180. package/dist/cli/commands/streaming/idleTimer.d.ts +0 -26
  181. package/dist/cli/commands/streaming/idleTimer.js +0 -24
  182. package/dist/cli/commands/streaming/turnOutcome.d.ts +0 -27
  183. package/dist/cli/commands/streaming/turnOutcome.js +0 -29
  184. package/dist/cli/commands/wizardActions.d.ts +0 -47
  185. package/dist/cli/commands/wizardActions.js +0 -47
  186. package/dist/cli/commands/wizardInput.d.ts +0 -4
  187. package/dist/cli/commands/wizardInput.js +0 -19
  188. package/dist/cli/commands/wizardPrompts.d.ts +0 -22
  189. package/dist/cli/commands/wizardPrompts.js +0 -58
  190. package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
  191. package/dist/cli/commands/wizardSuggestions.js +0 -190
  192. package/dist/cli/commands/wizardTransition.d.ts +0 -37
  193. package/dist/cli/commands/wizardTransition.js +0 -43
  194. package/dist/core/agent/toolExecutionBudget.d.ts +0 -35
  195. package/dist/core/agent/toolExecutionBudget.js +0 -49
  196. package/dist/core/agent/turnBudget.d.ts +0 -35
  197. package/dist/core/agent/turnBudget.js +0 -27
  198. package/dist/core/bashOutput/ansi.d.ts +0 -1
  199. package/dist/core/bashOutput/ansi.js +0 -7
  200. package/dist/core/bashOutput/registry.d.ts +0 -4
  201. package/dist/core/goal/completionPolicy.js +0 -43
  202. package/dist/core/goal/requestClassifier.d.ts +0 -3
  203. package/dist/core/goal/requestClassifier.js +0 -18
  204. package/dist/core/goal/sessionGoal.d.ts +0 -8
  205. package/dist/core/goal/sessionGoal.js +0 -30
  206. package/dist/core/limits/byteBudgets.d.ts +0 -20
  207. package/dist/core/limits/byteBudgets.js +0 -20
  208. package/dist/core/limits/textBudgets.d.ts +0 -25
  209. package/dist/core/limits/textBudgets.js +0 -25
  210. package/dist/core/safety/bashClassifier.d.ts +0 -10
  211. package/dist/llm/lsp.d.ts +0 -149
  212. package/dist/llm/lsp.js +0 -368
  213. package/dist/ui/components/ErrorView.d.ts +0 -4
  214. package/dist/ui/components/ErrorView.js +0 -7
  215. package/dist/utils/yaml.d.ts +0 -2
  216. package/dist/utils/yaml.js +0 -8
  217. package/examples/skills/files/SKILL.md +0 -16
  218. package/examples/skills/files/examples/file-editing.md +0 -3
  219. /package/dist/core/{bashOutput → shellOutput}/command.d.ts +0 -0
  220. /package/dist/core/{bashOutput → shellOutput}/command.js +0 -0
  221. /package/dist/core/{bashOutput → shellOutput}/lineFilter.d.ts +0 -0
  222. /package/dist/core/{bashOutput → shellOutput}/reducers/content.d.ts +0 -0
  223. /package/dist/core/{bashOutput → shellOutput}/reducers/content.js +0 -0
  224. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.d.ts +0 -0
  225. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.js +0 -0
  226. /package/dist/core/{bashOutput → shellOutput}/reducers/git.d.ts +0 -0
  227. /package/dist/core/{bashOutput → shellOutput}/reducers/git.js +0 -0
  228. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.d.ts +0 -0
  229. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.js +0 -0
  230. /package/dist/core/{bashOutput → shellOutput}/types.js +0 -0
@@ -16,12 +16,12 @@ import { boundedDiff, fileDiff, findEditRange, splitDiffLines, lineNumberAtOffse
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
21
  import { DEFAULT_READ_LINES, INLINE_DIFF_LINE_LIMIT, MAX_OUTPUT_CHARS, sourceOutlineEntries } from './tools/fileToolShared.js';
22
22
  import { createIgnoreClassifier } from './tools/gitIgnore.js';
23
23
  import { runRipgrepBounded } from './tools/grepRunner.js';
24
- import { EXACT_MUTATION_BYTES } from '../core/limits/byteBudgets.js';
24
+ import { EXACT_MUTATION_BYTES } from '../core/limits.js';
25
25
  import { WRITE_FILE_CHUNK_BYTES } from '../core/agent/budgets.js';
26
26
  import { readUtf8LinesPage, readUtf8Prefix } from '../core/io/boundedRead.js';
27
27
  import { assertReadableTextFile, readFailureRecovery } from './tools/readRecovery.js';
@@ -38,7 +38,7 @@ function mutationDiffFields(filePath, fullDiff) {
38
38
  }
39
39
  export const hazeTools = {
40
40
  listFiles: tool({
41
- 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.',
42
42
  contextSchema: hazeToolContextSchema,
43
43
  inputSchema: z.object({
44
44
  path: z.string().default('.').describe('Directory path relative to the current workspace'),
@@ -53,14 +53,14 @@ export const hazeTools = {
53
53
  const absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored, context);
54
54
  const entries = [];
55
55
  let ignoredSkipped = 0;
56
- // One persistent classifier owns the whole listing so a frontier of
57
- // candidates collapses to O(visited directories) Git subprocesses
58
- // instead of one process per walked entry (RH-001). Page-2 cursor
59
- // resumes do not re-check entries preceding the cursor.
60
- const ignoreBatch = includeIgnored ? undefined : (relativePaths) => createIgnoreClassifier(workspaceRoot()).classify(relativePaths).then(ignored => {
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
61
  ignoredSkipped += ignored.size;
62
62
  return ignored;
63
- });
63
+ }) : undefined;
64
64
  const walked = await walkDir(absolutePath, { recursive, maxEntries: maxEntries + 1, cursor, ignoreBatch });
65
65
  const page = walked.slice(0, maxEntries);
66
66
  const hasMore = walked.length > maxEntries;
@@ -314,7 +314,10 @@ export const hazeTools = {
314
314
  contextSchema: hazeToolContextSchema,
315
315
  inputSchema: z.object({
316
316
  path: z.string().describe('File path relative to the current workspace'),
317
- content: z.string().max(WRITE_FILE_CHUNK_BYTES).describe(`File content chunk, at most ${WRITE_FILE_CHUNK_BYTES} UTF-8 bytes`),
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`),
318
321
  overwriteExisting: z.boolean().default(false).describe('Approve replacing an existing file with the first chunk of an intentional full rewrite'),
319
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'),
320
323
  allowIgnored: z.boolean().default(false).describe('Write a .gitignored file only when needed'),
@@ -460,6 +463,6 @@ export const hazeTools = {
460
463
  writeTasks: writeTasksTool,
461
464
  readToolOutput: readToolOutputTool,
462
465
  fetch: fetchTool,
463
- bash: bashTool,
466
+ shell: shellTool,
464
467
  process: processTool,
465
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[];
@@ -0,0 +1,128 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath, pathToFileURL } from 'node:url';
3
+ import { assertRealPathInsideWorkspace, workspaceRelativePath } from '../../utils/path.js';
4
+ /**
5
+ * Pure LSP protocol helpers: language/URI mapping, 1-indexed range conversion,
6
+ * location/symbol/diagnostic shaping. No client, process, or filesystem state
7
+ * beyond workspace-relative path resolution.
8
+ */
9
+ export function languageId(filePath) {
10
+ const ext = path.extname(filePath).toLowerCase();
11
+ if (ext === '.ts')
12
+ return 'typescript';
13
+ if (ext === '.tsx')
14
+ return 'typescriptreact';
15
+ if (ext === '.js')
16
+ return 'javascript';
17
+ if (ext === '.jsx')
18
+ return 'javascriptreact';
19
+ if (ext === '.rs')
20
+ return 'rust';
21
+ if (ext === '.py')
22
+ return 'python';
23
+ if (ext === '.go')
24
+ return 'go';
25
+ return ext.replace(/^\./, '') || 'plaintext';
26
+ }
27
+ export function toUri(absolutePath) {
28
+ return pathToFileURL(absolutePath).toString();
29
+ }
30
+ export function fromUri(uri) {
31
+ if (!uri.startsWith('file://'))
32
+ return uri;
33
+ try {
34
+ return workspaceRelativePath(fileURLToPath(uri));
35
+ }
36
+ catch {
37
+ return uri;
38
+ }
39
+ }
40
+ export function isObject(value) {
41
+ return typeof value === 'object' && value != null && !Array.isArray(value);
42
+ }
43
+ export function asRange(value) {
44
+ if (!isObject(value) || !isObject(value.start) || !isObject(value.end))
45
+ return undefined;
46
+ const start = value.start;
47
+ const end = value.end;
48
+ return {
49
+ start: { line: typeof start.line === 'number' ? start.line + 1 : 1, character: typeof start.character === 'number' ? start.character + 1 : 1 },
50
+ end: { line: typeof end.line === 'number' ? end.line + 1 : 1, character: typeof end.character === 'number' ? end.character + 1 : 1 },
51
+ };
52
+ }
53
+ export function locationToResult(value) {
54
+ if (!isObject(value))
55
+ return undefined;
56
+ const uri = typeof value.uri === 'string' ? value.uri : (typeof value.targetUri === 'string' ? value.targetUri : undefined);
57
+ const range = asRange(value.range ?? value.targetSelectionRange ?? value.targetRange);
58
+ if (!uri || !range)
59
+ return undefined;
60
+ const resultPath = fromUri(uri);
61
+ const external = !uri.startsWith('file://') || resultPath.startsWith('..') || path.isAbsolute(resultPath);
62
+ return { path: resultPath, range, ...(external ? { external: true } : {}) };
63
+ }
64
+ export async function locationToWorkspaceResult(value) {
65
+ const result = locationToResult(value);
66
+ if (!result || result.external)
67
+ return result;
68
+ if (!isObject(value))
69
+ return undefined;
70
+ const uri = typeof value.uri === 'string' ? value.uri : (typeof value.targetUri === 'string' ? value.targetUri : undefined);
71
+ if (!uri?.startsWith('file://'))
72
+ return result;
73
+ try {
74
+ const absolutePath = fileURLToPath(uri);
75
+ await assertRealPathInsideWorkspace(absolutePath, uri);
76
+ return result;
77
+ }
78
+ catch {
79
+ return { ...result, path: uri, external: true };
80
+ }
81
+ }
82
+ export function flattenSymbols(symbols, filePath, limit) {
83
+ const out = [];
84
+ const visit = (items) => {
85
+ for (const item of items) {
86
+ if (out.length >= limit || !isObject(item))
87
+ return;
88
+ if (typeof item.name === 'string') {
89
+ out.push({
90
+ name: item.name,
91
+ kind: typeof item.kind === 'number' ? item.kind : undefined,
92
+ path: filePath,
93
+ range: asRange(item.range),
94
+ selectionRange: asRange(item.selectionRange),
95
+ });
96
+ }
97
+ if (Array.isArray(item.children))
98
+ visit(item.children);
99
+ }
100
+ };
101
+ visit(symbols);
102
+ return out;
103
+ }
104
+ const DIAGNOSTIC_SEVERITIES = ['error', 'warning', 'information', 'hint'];
105
+ export function toDiagnostic(value) {
106
+ if (!isObject(value))
107
+ return undefined;
108
+ const range = asRange(value.range);
109
+ if (!range)
110
+ return undefined;
111
+ const severity = typeof value.severity === 'number' && value.severity >= 1 && value.severity <= 4
112
+ ? DIAGNOSTIC_SEVERITIES[value.severity - 1]
113
+ : 'information';
114
+ const code = typeof value.code === 'number' || typeof value.code === 'string' ? String(value.code) : undefined;
115
+ const source = typeof value.source === 'string' ? value.source : undefined;
116
+ return { severity, range, message: typeof value.message === 'string' ? value.message : '', ...(code ? { code } : {}), ...(source ? { source } : {}) };
117
+ }
118
+ export function diagnosticsFrom(values, limit) {
119
+ const out = [];
120
+ for (const value of values) {
121
+ if (out.length >= limit)
122
+ break;
123
+ const diagnostic = toDiagnostic(value);
124
+ if (diagnostic)
125
+ out.push(diagnostic);
126
+ }
127
+ return out;
128
+ }