@denizokcu/haze 1.2.0 → 1.4.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 (109) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +18 -10
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +27 -7
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/inputSuggestions.js +3 -0
  7. package/dist/cli/chat/liveMessages.d.ts +36 -0
  8. package/dist/cli/chat/liveMessages.js +64 -0
  9. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  10. package/dist/cli/chat/sessionLifecycle.js +23 -2
  11. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  12. package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
  13. package/dist/cli/commands/chat.js +39 -34
  14. package/dist/cli/commands/commandHelp.js +2 -0
  15. package/dist/cli/commands/commands.js +2 -0
  16. package/dist/cli/commands/formatters.js +5 -1
  17. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  18. package/dist/cli/commands/ndjsonSink.js +29 -0
  19. package/dist/cli/commands/reasoningCommand.d.ts +35 -0
  20. package/dist/cli/commands/reasoningCommand.js +46 -0
  21. package/dist/cli/commands/runCommand.d.ts +14 -0
  22. package/dist/cli/commands/runCommand.js +37 -11
  23. package/dist/cli/commands/settingsSummary.js +2 -0
  24. package/dist/cli/commands/streaming/agentAttempt.d.ts +3 -0
  25. package/dist/cli/commands/streaming/agentAttempt.js +2 -2
  26. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  27. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  28. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  29. package/dist/cli/commands/streaming/attemptOutcome.js +13 -3
  30. package/dist/cli/commands/streaming/attemptSetup.d.ts +3 -0
  31. package/dist/cli/commands/streaming/attemptSetup.js +11 -3
  32. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
  33. package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
  34. package/dist/cli/commands/streaming/goalSupervisor.d.ts +5 -0
  35. package/dist/cli/commands/streaming/goalSupervisor.js +9 -4
  36. package/dist/cli/commands/streaming/prepareStep.d.ts +0 -3
  37. package/dist/cli/commands/streaming/prepareStep.js +8 -3
  38. package/dist/cli/commands/streaming.d.ts +7 -2
  39. package/dist/cli/commands/streaming.js +24 -5
  40. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  41. package/dist/cli/commands/wizardFlow.js +22 -0
  42. package/dist/cli/index.js +5 -1
  43. package/dist/config/modelDiscovery.js +68 -5
  44. package/dist/config/settings.d.ts +8 -4
  45. package/dist/config/settings.js +8 -1
  46. package/dist/core/agent/budgets.d.ts +0 -2
  47. package/dist/core/agent/budgets.js +0 -2
  48. package/dist/core/agent/completionController.d.ts +8 -0
  49. package/dist/core/agent/completionController.js +32 -0
  50. package/dist/core/agent/events.d.ts +2 -1
  51. package/dist/core/agent/goalPolicy.d.ts +7 -0
  52. package/dist/core/agent/goalPolicy.js +9 -0
  53. package/dist/core/agent/reasoningPolicy.d.ts +45 -9
  54. package/dist/core/agent/reasoningPolicy.js +49 -9
  55. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  56. package/dist/core/agent/toolCapabilities.js +31 -7
  57. package/dist/core/agent/workState.d.ts +6 -4
  58. package/dist/core/agent/workState.js +40 -28
  59. package/dist/core/deadline.js +22 -24
  60. package/dist/core/safety/secretPaths.js +10 -7
  61. package/dist/core/safety/shellClassifier.d.ts +2 -0
  62. package/dist/core/safety/shellClassifier.js +9 -1
  63. package/dist/core/session/sessionSlimming.d.ts +2 -0
  64. package/dist/core/session/sessionSlimming.js +50 -1
  65. package/dist/core/session/sessionStore.d.ts +4 -8
  66. package/dist/core/session/sessionStore.js +53 -32
  67. package/dist/core/shellOutput/reducers/git.js +7 -2
  68. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  69. package/dist/core/shellOutput/reducers/validation.js +14 -1
  70. package/dist/core/shellOutput/registry.js +3 -2
  71. package/dist/core/subagent/contracts.d.ts +8 -1
  72. package/dist/core/subagent/subagentRunner.d.ts +4 -0
  73. package/dist/core/subagent/subagentRunner.js +33 -25
  74. package/dist/core/tasks/taskStorage.js +8 -1
  75. package/dist/core/validation/outputParser.js +24 -0
  76. package/dist/llm/client.d.ts +2 -1
  77. package/dist/llm/client.js +20 -10
  78. package/dist/llm/hazeTools.d.ts +2039 -16
  79. package/dist/llm/hazeTools.js +43 -2
  80. package/dist/llm/lsp/client.d.ts +7 -1
  81. package/dist/llm/lsp/client.js +58 -9
  82. package/dist/llm/lsp/pool.d.ts +11 -0
  83. package/dist/llm/lsp/pool.js +61 -4
  84. package/dist/llm/lsp/protocol.d.ts +6 -23
  85. package/dist/llm/lsp/requests.d.ts +54 -60
  86. package/dist/llm/lsp/requests.js +152 -28
  87. package/dist/llm/lsp/symbols.d.ts +16 -0
  88. package/dist/llm/lsp/symbols.js +70 -0
  89. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  90. package/dist/llm/lsp/workspaceEdit.js +117 -0
  91. package/dist/llm/lspTools.d.ts +7518 -2859
  92. package/dist/llm/lspTools.js +195 -110
  93. package/dist/llm/requestContext.d.ts +3 -2
  94. package/dist/llm/requestContext.js +8 -4
  95. package/dist/llm/systemPrompt.js +2 -2
  96. package/dist/llm/tools/fetchTool.d.ts +4 -0
  97. package/dist/llm/tools/processTool.d.ts +4 -0
  98. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  99. package/dist/llm/tools/replaceInFiles.js +131 -0
  100. package/dist/llm/tools/shellTool.d.ts +4 -0
  101. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  102. package/dist/llm/tools/taskTool.d.ts +4 -0
  103. package/dist/llm/tools/toolContext.d.ts +3 -0
  104. package/dist/llm/tools/toolContext.js +26 -4
  105. package/dist/skills/SkillLoader.js +27 -1
  106. package/dist/ui/components/useInputSuggestions.js +18 -6
  107. package/dist/utils/buildInfo.js +29 -8
  108. package/dist/utils/fs.js +5 -1
  109. package/package.json +19 -19
@@ -26,6 +26,7 @@ import { EXACT_MUTATION_BYTES } from '../core/limits.js';
26
26
  import { WRITE_FILE_CHUNK_BYTES } from '../core/agent/budgets.js';
27
27
  import { readUtf8LinesPage, readUtf8Prefix } from '../core/io/boundedRead.js';
28
28
  import { assertReadableTextFile, readFailureRecovery } from './tools/readRecovery.js';
29
+ import { replaceInFiles } from './tools/replaceInFiles.js';
29
30
  function mutationDiffFields(filePath, fullDiff) {
30
31
  const preview = boundedDiff(fullDiff, INLINE_DIFF_LINE_LIMIT);
31
32
  const diffHandle = preview.truncated ? storeToolOutput(renderToolDiff(filePath, fullDiff)) : undefined;
@@ -51,7 +52,21 @@ export const hazeTools = {
51
52
  }),
52
53
  execute: async ({ path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context) => runDedupedTool('listFiles', { path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context, async () => {
53
54
  try {
54
- const absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored, context);
55
+ let absolutePath;
56
+ try {
57
+ absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored, context);
58
+ }
59
+ catch (error) {
60
+ // RT-06: an out-of-workspace path must refuse honestly instead of
61
+ // returning a success-shaped empty listing, which the model reads as
62
+ // "directory is empty" and can report as a false fact. Reuse the
63
+ // shared structured failure shape (readFile/grep already do).
64
+ const message = error instanceof Error ? error.message : String(error);
65
+ if (message.includes('outside the workspace')) {
66
+ return { ok: false, toolName: 'listFiles', path: dirPath, error: message, reasonCode: 'outside_workspace', recoverable: true, suggestedNextStep: 'Use a workspace-relative path, or ask the user to mention the outside path explicitly so it can be read directly.' };
67
+ }
68
+ throw error;
69
+ }
55
70
  const entries = [];
56
71
  let ignoredSkipped = 0;
57
72
  // One persistent classifier owns the whole listing so rule files are
@@ -192,13 +207,16 @@ export const hazeTools = {
192
207
  ];
193
208
  if (caseInsensitive)
194
209
  args.push('--ignore-case');
210
+ if (includeIgnored)
211
+ args.push('--no-ignore', '--hidden');
195
212
  if (glob)
196
213
  args.push('--glob', glob);
197
214
  // Secret-file exclusions come after any model-supplied glob: later
198
215
  // ripgrep globs take precedence, and an explicit glob (which also
199
216
  // re-enables hidden-file search) must never re-include secrets.
200
217
  for (const secretGlob of secretSearchExcludeGlobs())
201
- args.push('--glob', secretGlob);
218
+ args.push('--iglob', secretGlob);
219
+ args.push('--glob', '!**/.git/**', '--glob', '!**/node_modules/**');
202
220
  args.push('--', pattern, absolutePath);
203
221
  const result = await runRipgrepBounded({ executable: rgPath, args, cwd: workspaceRoot(), maxMatches, signal: context.abortSignal });
204
222
  const stdout = result.stdout;
@@ -250,6 +268,29 @@ export const hazeTools = {
250
268
  }
251
269
  }),
252
270
  }),
271
+ replaceInFiles: tool({
272
+ description: 'Preview or apply guarded literal/regex replacements across files. Use dryRun and occurrence IDs when unintended matches are possible.',
273
+ contextSchema: hazeToolContextSchema,
274
+ inputSchema: z.object({
275
+ path: z.string().default('.').describe('Workspace-relative file or directory scope'),
276
+ needle: z.string().min(1).describe('Literal text or JavaScript regular expression'),
277
+ replacement: z.string().describe('Replacement text; regex mode supports $1-style capture substitutions'),
278
+ mode: z.enum(['literal', 'regex']).default('literal'),
279
+ includeGlob: z.string().optional().describe('Optional workspace-relative include glob'),
280
+ excludeGlob: z.string().optional().describe('Optional workspace-relative exclude glob'),
281
+ dryRun: z.boolean().default(true).describe('Preview changes without writing'),
282
+ occurrenceIds: z.array(z.string()).optional().describe('Apply only stable IDs returned by a dry run; stale IDs abort all changes'),
283
+ expectedCount: z.number().int().nonnegative().optional().describe('Abort all changes unless this many occurrences are currently found'),
284
+ }),
285
+ execute: async (input, context) => runDedupedTool('replaceInFiles', input, context, async () => {
286
+ try {
287
+ return await replaceInFiles(input, context);
288
+ }
289
+ catch (error) {
290
+ return structuredToolFailure('replaceInFiles', error, 'Run a dry run with a narrower path/glob or corrected pattern, then apply current occurrence IDs.', input.path);
291
+ }
292
+ }),
293
+ }),
253
294
  replaceLines: tool({
254
295
  description: 'Replace a 1-based inclusive line range. Use after readFile when exact editFile text is ambiguous or stale.',
255
296
  contextSchema: hazeToolContextSchema,
@@ -18,11 +18,15 @@ export declare class StdioLspClient {
18
18
  private buffer;
19
19
  private pending;
20
20
  private terminating;
21
+ private failed;
21
22
  private initializeResult;
22
23
  private readonly published;
24
+ private readonly activeProgress;
25
+ private lastProgressAt;
23
26
  constructor(server: HazeLspServer, child: ChildProcessWithoutNullStreams);
24
27
  static start(server: HazeLspServer): StdioLspClient;
25
28
  private rejectAll;
29
+ private fail;
26
30
  private terminate;
27
31
  /** Whether this client has begun (or completed) teardown and must not be reused. */
28
32
  get terminated(): boolean;
@@ -34,8 +38,10 @@ export declare class StdioLspClient {
34
38
  initialize(): Promise<void>;
35
39
  /** Server capabilities from the initialize handshake; undefined until it completes. */
36
40
  get capabilities(): unknown;
37
- /** Whether the server advertised pull diagnostics (`textDocument/documentDiagnostic`). */
41
+ /** Whether the server advertised pull diagnostics (`textDocument/diagnostic`). */
38
42
  diagnosticPullSupported(): boolean;
43
+ /** Wait until server-reported indexing settles, bounded to avoid blocking unsupported servers. */
44
+ waitForIndexing(timeoutMs?: number, quietMs?: number): Promise<boolean>;
39
45
  /** Latest push-published diagnostics for a document URI, if any arrived. */
40
46
  publishedDiagnostics(uri: string): unknown[] | undefined;
41
47
  openDocument(absolutePath: string): Promise<void>;
@@ -1,4 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import path from 'node:path';
2
3
  import { workspaceRoot } from '../../utils/path.js';
3
4
  import { LSP_BUFFER_BYTES, LSP_DOCUMENT_BYTES, LSP_FRAME_BYTES, LSP_HEADER_BYTES } from '../../core/limits.js';
4
5
  import { readUtf8Prefix } from '../../core/io/boundedRead.js';
@@ -17,8 +18,11 @@ export class StdioLspClient {
17
18
  buffer = Buffer.alloc(0);
18
19
  pending = new Map();
19
20
  terminating = false;
21
+ failed = false;
20
22
  initializeResult;
21
23
  published = new Map();
24
+ activeProgress = new Set();
25
+ lastProgressAt = 0;
22
26
  constructor(server, child) {
23
27
  this.server = server;
24
28
  this.child = child;
@@ -33,8 +37,8 @@ export class StdioLspClient {
33
37
  }
34
38
  });
35
39
  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}`}`)));
40
+ child.on('error', error => this.fail(error instanceof Error ? error : new Error(String(error))));
41
+ child.on('exit', code => this.fail(new LspError(`LSP server exited${code == null ? '' : ` with code ${code}`}`)));
38
42
  }
39
43
  static start(server) {
40
44
  if (!server.command)
@@ -49,6 +53,10 @@ export class StdioLspClient {
49
53
  }
50
54
  this.pending.clear();
51
55
  }
56
+ fail(error) {
57
+ this.failed = true;
58
+ this.rejectAll(error);
59
+ }
52
60
  terminate() {
53
61
  if (this.terminating)
54
62
  return;
@@ -62,7 +70,7 @@ export class StdioLspClient {
62
70
  }
63
71
  /** Whether this client has begun (or completed) teardown and must not be reused. */
64
72
  get terminated() {
65
- return this.terminating;
73
+ return this.terminating || this.failed;
66
74
  }
67
75
  onData(chunk) {
68
76
  if (this.buffer.length + chunk.length > LSP_BUFFER_BYTES)
@@ -91,11 +99,17 @@ export class StdioLspClient {
91
99
  this.buffer = this.buffer.slice(bodyStart + length);
92
100
  const message = JSON.parse(raw);
93
101
  if (typeof message.id !== 'number') {
94
- // Server-initiated notification; only diagnostics are consumed, others are dropped.
102
+ // Server-initiated notifications are consumed selectively; unknown ones are dropped.
95
103
  if (typeof message.method === 'string')
96
104
  this.handleNotification(message.method, message.params);
97
105
  continue;
98
106
  }
107
+ if (typeof message.method === 'string') {
108
+ // A few common server requests must be acknowledged or indexing can stall.
109
+ const result = message.method === 'workspace/configuration' ? [] : null;
110
+ this.send({ id: message.id, result });
111
+ continue;
112
+ }
99
113
  const pending = this.pending.get(message.id);
100
114
  if (!pending)
101
115
  continue;
@@ -108,6 +122,16 @@ export class StdioLspClient {
108
122
  }
109
123
  }
110
124
  handleNotification(method, params) {
125
+ if (method === '$/progress' && isObject(params) && (typeof params.token === 'string' || typeof params.token === 'number') && isObject(params.value)) {
126
+ const token = String(params.token);
127
+ const kind = params.value.kind;
128
+ if (kind === 'begin' || kind === 'report')
129
+ this.activeProgress.add(token);
130
+ if (kind === 'end')
131
+ this.activeProgress.delete(token);
132
+ this.lastProgressAt = Date.now();
133
+ return;
134
+ }
111
135
  if (method !== 'textDocument/publishDiagnostics')
112
136
  return;
113
137
  if (!isObject(params) || typeof params.uri !== 'string')
@@ -120,23 +144,36 @@ export class StdioLspClient {
120
144
  this.child.stdin.write(`Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`);
121
145
  }
122
146
  request(method, params, timeoutMs = 8000) {
147
+ if (this.terminated)
148
+ return Promise.reject(new LspError(`LSP client is terminated; cannot request ${method}.`));
123
149
  const id = ++this.id;
124
- this.send({ id, method, params });
125
150
  return new Promise((resolve, reject) => {
126
151
  const timer = setTimeout(() => {
127
152
  this.pending.delete(id);
128
153
  reject(new LspError(`LSP request timed out: ${method}`));
129
154
  }, timeoutMs);
130
155
  this.pending.set(id, { resolve, reject, timer });
156
+ try {
157
+ this.send({ id, method, params });
158
+ }
159
+ catch (error) {
160
+ clearTimeout(timer);
161
+ this.pending.delete(id);
162
+ reject(error instanceof Error ? error : new LspError(String(error)));
163
+ }
131
164
  });
132
165
  }
133
166
  notify(method, params) {
134
167
  this.send({ method, params });
135
168
  }
136
169
  async initialize() {
170
+ const root = workspaceRoot();
171
+ const rootUri = toUri(root);
137
172
  this.initializeResult = await this.request('initialize', {
138
173
  processId: process.pid,
139
- rootUri: toUri(workspaceRoot()),
174
+ rootPath: root,
175
+ rootUri,
176
+ workspaceFolders: [{ uri: rootUri, name: path.basename(root) }],
140
177
  capabilities: {
141
178
  textDocument: {
142
179
  documentSymbol: { hierarchicalDocumentSymbolSupport: true },
@@ -145,8 +182,10 @@ export class StdioLspClient {
145
182
  implementation: { linkSupport: true },
146
183
  references: {},
147
184
  diagnostic: {},
185
+ rename: { prepareSupport: true },
148
186
  },
149
- workspace: { symbol: {} },
187
+ window: { workDoneProgress: true },
188
+ workspace: { symbol: {}, didChangeWatchedFiles: { dynamicRegistration: false }, workspaceEdit: { documentChanges: true } },
150
189
  },
151
190
  });
152
191
  this.notify('initialized', {});
@@ -155,12 +194,22 @@ export class StdioLspClient {
155
194
  get capabilities() {
156
195
  return this.initializeResult;
157
196
  }
158
- /** Whether the server advertised pull diagnostics (`textDocument/documentDiagnostic`). */
197
+ /** Whether the server advertised pull diagnostics (`textDocument/diagnostic`). */
159
198
  diagnosticPullSupported() {
160
199
  const result = this.initializeResult;
161
200
  if (!isObject(result) || !isObject(result.capabilities))
162
201
  return false;
163
- return isObject(result.capabilities.textDocumentDiagnostic);
202
+ return isObject(result.capabilities.diagnosticProvider);
203
+ }
204
+ /** Wait until server-reported indexing settles, bounded to avoid blocking unsupported servers. */
205
+ async waitForIndexing(timeoutMs = 3000, quietMs = 100) {
206
+ const deadline = Date.now() + timeoutMs;
207
+ while (this.activeProgress.size > 0 || (this.lastProgressAt > 0 && Date.now() - this.lastProgressAt < quietMs)) {
208
+ if (Date.now() >= deadline)
209
+ return false;
210
+ await new Promise(resolve => setTimeout(resolve, Math.min(50, deadline - Date.now())));
211
+ }
212
+ return true;
164
213
  }
165
214
  /** Latest push-published diagnostics for a document URI, if any arrived. */
166
215
  publishedDiagnostics(uri) {
@@ -13,9 +13,20 @@ export declare class LspPool {
13
13
  private readonly clients;
14
14
  private readonly openedDocuments;
15
15
  private readonly openSnapshots;
16
+ private readonly workspaceSnapshots;
16
17
  private closed;
17
18
  /** Get (or lazily start + initialize) the reusable client for a server. */
18
19
  getClient(server: HazeLspServer, filePath?: string): Promise<StdioLspClient>;
20
+ /** Evict and close a failed client so a retry gets a clean process. */
21
+ restart(server: HazeLspServer): Promise<StdioLspClient>;
22
+ /**
23
+ * Refresh a warm server's cross-file index after shell/editor/agent changes.
24
+ * The scan is bounded and restricted to the server's configured source extensions.
25
+ */
26
+ prepareCrossFileQuery(server: HazeLspServer): Promise<{
27
+ changedFiles: number;
28
+ indexingComplete: boolean;
29
+ }>;
19
30
  /** Open a document once per client; subsequent calls for the same URI are no-ops. */
20
31
  ensureOpen(server: HazeLspServer, client: StdioLspClient, absolutePath: string): Promise<void>;
21
32
  /** Bounded teardown of every pooled client. Safe to call once. */
@@ -1,6 +1,8 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { workspaceRelativePath, workspaceRoot } from '../../utils/path.js';
4
+ import { walkDir } from '../../utils/fs.js';
5
+ import { createIgnoreClassifier } from '../tools/gitIgnore.js';
4
6
  import { toUri } from './protocol.js';
5
7
  import { LspError, StdioLspClient } from './client.js';
6
8
  /** Server selection and turn-scoped client reuse. */
@@ -29,6 +31,7 @@ export class LspPool {
29
31
  clients = new Map();
30
32
  openedDocuments = new Map();
31
33
  openSnapshots = new Map();
34
+ workspaceSnapshots = new Map();
32
35
  closed = false;
33
36
  /** Get (or lazily start + initialize) the reusable client for a server. */
34
37
  async getClient(server, filePath) {
@@ -38,15 +41,16 @@ export class LspPool {
38
41
  // modified on disk since it was opened, close/reopen it so the server sees
39
42
  // the current text before answering position-based requests.
40
43
  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 absolutePath = path.resolve(workspaceRoot(), filePath);
45
+ const snapshotKey = workspaceRelativePath(absolutePath);
46
+ const snapshot = this.openSnapshots.get(snapshotKey);
47
+ if (snapshot !== undefined && snapshot !== await fileFingerprint(absolutePath)) {
44
48
  const uri = toUri(absolutePath);
45
49
  existing.closeDocument(absolutePath);
46
50
  this.openedDocuments.get(server.name)?.delete(uri);
47
51
  await existing.openDocument(absolutePath);
48
52
  this.openedDocuments.get(server.name)?.add(uri);
49
- this.openSnapshots.set(filePath, await fileFingerprint(filePath));
53
+ this.openSnapshots.set(snapshotKey, await fileFingerprint(absolutePath));
50
54
  }
51
55
  }
52
56
  return existing;
@@ -61,6 +65,58 @@ export class LspPool {
61
65
  this.openedDocuments.set(server.name, new Set());
62
66
  return client;
63
67
  }
68
+ /** Evict and close a failed client so a retry gets a clean process. */
69
+ async restart(server) {
70
+ const existing = this.clients.get(server.name);
71
+ this.clients.delete(server.name);
72
+ this.openedDocuments.delete(server.name);
73
+ this.workspaceSnapshots.delete(server.name);
74
+ await existing?.close().catch(() => undefined);
75
+ return await this.getClient(server);
76
+ }
77
+ /**
78
+ * Refresh a warm server's cross-file index after shell/editor/agent changes.
79
+ * The scan is bounded and restricted to the server's configured source extensions.
80
+ */
81
+ async prepareCrossFileQuery(server) {
82
+ const client = await this.getClient(server);
83
+ const extensions = new Set((server.extensions ?? []).map(extension => extension.toLowerCase()));
84
+ const ignore = createIgnoreClassifier(workspaceRoot());
85
+ const entries = await walkDir(workspaceRoot(), {
86
+ recursive: true,
87
+ maxEntries: 10_000,
88
+ filter: entry => entry.isDirectory || (entry.isFile && extensions.has(path.extname(entry.path).toLowerCase())),
89
+ ignoreBatch: async (entriesToClassify) => await ignore.classify(entriesToClassify.map(entry => ({ path: entry.path, isDirectory: entry.isDirectory }))),
90
+ });
91
+ const sourceEntries = entries.filter(entry => entry.isFile);
92
+ const current = new Map();
93
+ for (const entry of sourceEntries)
94
+ current.set(entry.path, await fileFingerprint(entry.absolutePath));
95
+ // TypeScript and some other servers do not instantiate a project from the
96
+ // initialize root alone. Open one source document before the first
97
+ // workspace/symbol request so project-wide navigation has a project to query.
98
+ const bootstrap = sourceEntries[0];
99
+ if (bootstrap)
100
+ await this.ensureOpen(server, client, bootstrap.absolutePath);
101
+ const previous = this.workspaceSnapshots.get(server.name);
102
+ this.workspaceSnapshots.set(server.name, current);
103
+ let changedFiles = 0;
104
+ if (previous) {
105
+ const changes = [];
106
+ for (const [relative, fingerprint] of current) {
107
+ const old = previous.get(relative);
108
+ if (old !== fingerprint)
109
+ changes.push({ uri: toUri(path.resolve(workspaceRoot(), relative)), type: old === undefined ? 1 : 2 });
110
+ }
111
+ for (const relative of previous.keys())
112
+ if (!current.has(relative))
113
+ changes.push({ uri: toUri(path.resolve(workspaceRoot(), relative)), type: 3 });
114
+ changedFiles = changes.length;
115
+ if (changes.length > 0)
116
+ client.notify('workspace/didChangeWatchedFiles', { changes });
117
+ }
118
+ return { changedFiles, indexingComplete: await client.waitForIndexing() };
119
+ }
64
120
  /** Open a document once per client; subsequent calls for the same URI are no-ops. */
65
121
  async ensureOpen(server, client, absolutePath) {
66
122
  const uri = toUri(absolutePath);
@@ -81,6 +137,7 @@ export class LspPool {
81
137
  this.clients.clear();
82
138
  this.openedDocuments.clear();
83
139
  this.openSnapshots.clear();
140
+ this.workspaceSnapshots.clear();
84
141
  await Promise.all(clients.map(client => client.close().catch(() => undefined)));
85
142
  }
86
143
  }
@@ -7,7 +7,7 @@ export declare function languageId(filePath: string): string;
7
7
  export declare function toUri(absolutePath: string): string;
8
8
  export declare function fromUri(uri: string): string;
9
9
  export declare function isObject(value: unknown): value is Record<string, unknown>;
10
- export declare function asRange(value: unknown): {
10
+ export interface LspRange {
11
11
  start: {
12
12
  line: number;
13
13
  character: number;
@@ -16,34 +16,17 @@ export declare function asRange(value: unknown): {
16
16
  line: number;
17
17
  character: number;
18
18
  };
19
- } | undefined;
19
+ }
20
+ export declare function asRange(value: unknown): LspRange | undefined;
20
21
  export declare function locationToResult(value: unknown): {
21
22
  external?: boolean | undefined;
22
23
  path: string;
23
- range: {
24
- start: {
25
- line: number;
26
- character: number;
27
- };
28
- end: {
29
- line: number;
30
- character: number;
31
- };
32
- };
24
+ range: LspRange;
33
25
  } | undefined;
34
26
  export declare function locationToWorkspaceResult(value: unknown): Promise<{
35
27
  external?: boolean | undefined;
36
28
  path: string;
37
- range: {
38
- start: {
39
- line: number;
40
- character: number;
41
- };
42
- end: {
43
- line: number;
44
- character: number;
45
- };
46
- };
29
+ range: LspRange;
47
30
  } | undefined>;
48
31
  export declare function flattenSymbols(symbols: unknown[], filePath: string, limit: number): {
49
32
  name: string;
@@ -55,7 +38,7 @@ export declare function flattenSymbols(symbols: unknown[], filePath: string, lim
55
38
  /** Structured, workspace-safe summary of one LSP diagnostic. */
56
39
  export interface LspDiagnostic {
57
40
  severity: 'error' | 'warning' | 'information' | 'hint';
58
- range: ReturnType<typeof asRange>;
41
+ range: LspRange;
59
42
  message: string;
60
43
  code?: string;
61
44
  source?: string;
@@ -1,74 +1,71 @@
1
1
  import type { HazeLspServer } from '../../config/lspSettings.js';
2
- import { type LspDiagnostic } from './protocol.js';
2
+ import { type LspDiagnostic, type LspRange } from './protocol.js';
3
3
  import type { LspPool } from './pool.js';
4
+ import { type SemanticSymbol } from './symbols.js';
4
5
  export declare function lspDocumentSymbols(server: HazeLspServer, filePath: string, limit: number, pool?: LspPool): Promise<{
6
+ path: string;
5
7
  name: string;
8
+ namePath: string;
6
9
  kind?: number;
7
- path: string;
8
- range?: ReturnType<typeof import("./protocol.js").asRange>;
9
- selectionRange?: ReturnType<typeof import("./protocol.js").asRange>;
10
+ range: LspRange;
11
+ selectionRange?: LspRange;
12
+ children?: SemanticSymbol[];
10
13
  }[]>;
14
+ export interface FindSymbolOptions {
15
+ path?: string;
16
+ depth: number;
17
+ includeBody: boolean;
18
+ includeInfo: boolean;
19
+ includeKinds: number[];
20
+ excludeKinds: number[];
21
+ substringMatching: boolean;
22
+ maxResults: number;
23
+ }
24
+ type FoundSymbol = SemanticSymbol & {
25
+ path: string;
26
+ body?: string;
27
+ info?: unknown;
28
+ };
29
+ export declare function lspFindSymbols(server: HazeLspServer, namePath: string, options: FindSymbolOptions, pool?: LspPool): Promise<{
30
+ symbols: FoundSymbol[];
31
+ indexingComplete: boolean;
32
+ }>;
11
33
  export declare function lspDefinition(server: HazeLspServer, filePath: string, line: number, character: number, limit: number, pool?: LspPool): Promise<{
12
34
  external?: boolean | undefined;
13
35
  path: string;
14
- range: {
15
- start: {
16
- line: number;
17
- character: number;
18
- };
19
- end: {
20
- line: number;
21
- character: number;
22
- };
23
- };
36
+ range: LspRange;
24
37
  }[]>;
25
38
  export declare function lspTypeDefinition(server: HazeLspServer, filePath: string, line: number, character: number, limit: number, pool?: LspPool): Promise<{
26
39
  external?: boolean | undefined;
27
40
  path: string;
28
- range: {
29
- start: {
30
- line: number;
31
- character: number;
32
- };
33
- end: {
34
- line: number;
35
- character: number;
36
- };
37
- };
41
+ range: LspRange;
38
42
  }[]>;
39
43
  export declare function lspImplementation(server: HazeLspServer, filePath: string, line: number, character: number, limit: number, pool?: LspPool): Promise<{
40
44
  external?: boolean | undefined;
41
45
  path: string;
42
- range: {
43
- start: {
44
- line: number;
45
- character: number;
46
- };
47
- end: {
48
- line: number;
49
- character: number;
50
- };
51
- };
46
+ range: LspRange;
52
47
  }[]>;
53
- export declare function lspReferences(server: HazeLspServer, filePath: string, line: number, character: number, limit: number, pool?: LspPool): Promise<{
48
+ export declare function lspReferenceLocations(server: HazeLspServer, filePath: string, line: number, character: number, includeDeclaration: boolean, limit: number, pool?: LspPool): Promise<{
54
49
  external?: boolean | undefined;
55
50
  path: string;
56
- range: {
57
- start: {
58
- line: number;
59
- character: number;
60
- };
61
- end: {
62
- line: number;
63
- character: number;
64
- };
65
- };
51
+ range: LspRange;
66
52
  }[]>;
67
- /**
68
- * Diagnostics for one document: pull (`textDocument/documentDiagnostic`) when the
69
- * server advertises it, otherwise the latest push-published set after didOpen.
70
- * A timed-out pull falls back to push instead of failing the whole request.
71
- */
53
+ export declare function lspRename(server: HazeLspServer, filePath: string, line: number, character: number, newName: string, pool?: LspPool): Promise<unknown>;
54
+ export declare function lspReferences(server: HazeLspServer, filePath: string, line: number, character: number, limit: number, pool?: LspPool): Promise<({
55
+ external?: boolean | undefined;
56
+ path: string;
57
+ range: LspRange;
58
+ } | {
59
+ snippet: string;
60
+ owner?: {
61
+ namePath: string;
62
+ kind: number | undefined;
63
+ range: LspRange;
64
+ } | undefined;
65
+ external?: boolean | undefined;
66
+ path: string;
67
+ range: LspRange;
68
+ })[]>;
72
69
  export declare function lspDiagnostics(server: HazeLspServer, filePath: string, limit: number, pool?: LspPool): Promise<{
73
70
  ok: true;
74
71
  diagnostics: LspDiagnostic[];
@@ -76,19 +73,16 @@ export declare function lspDiagnostics(server: HazeLspServer, filePath: string,
76
73
  ok: false;
77
74
  error: string;
78
75
  }>;
76
+ export declare function lspDiagnosticsForSymbol(server: HazeLspServer, filePath: string, namePath: string, checkReferences: boolean, limit: number, pool?: LspPool): Promise<{
77
+ path: string;
78
+ namePath: string;
79
+ diagnostics: LspDiagnostic[];
80
+ }[]>;
79
81
  export declare function lspWorkspaceSymbols(server: HazeLspServer, query: string, limit: number, pool?: LspPool): Promise<{
80
82
  external?: boolean | undefined;
81
83
  path: string;
82
- range: {
83
- start: {
84
- line: number;
85
- character: number;
86
- };
87
- end: {
88
- line: number;
89
- character: number;
90
- };
91
- };
84
+ range: LspRange;
92
85
  name: string;
93
86
  kind: number | undefined;
94
87
  }[]>;
88
+ export {};