@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
@@ -1,22 +1,26 @@
1
+ import fs from 'node:fs/promises';
1
2
  import { workspaceRelativePath } from '../../utils/path.js';
2
3
  import { prepareWorkspaceRead } from '../tools/workspaceFile.js';
3
- import { diagnosticsFrom, flattenSymbols, isObject, locationToWorkspaceResult, toUri } from './protocol.js';
4
+ import { diagnosticsFrom, isObject, locationToWorkspaceResult, toUri } from './protocol.js';
4
5
  import { LspError, StdioLspClient } from './client.js';
5
- /**
6
- * Workspace-safe LSP request facades: document symbols, definitions,
7
- * implementations, references, diagnostics, and workspace symbols. Each facade
8
- * resolves the path through workspace-read confinement, then runs on a pooled
9
- * client (or a single-call fallback lifecycle). This module is the seam the
10
- * AI-SDK tools (`lspTools.ts`) and their tests program against.
11
- */
6
+ import { flattenSemanticSymbols, matchesNamePath, readRange, readSnippet, semanticSymbols, smallestContainingSymbol } from './symbols.js';
7
+ /** Workspace-safe LSP request facades used by the AI-SDK tool layer. */
12
8
  async function withLspClient(server, filePath, pool, fn) {
13
9
  const absolutePath = await prepareWorkspaceRead(filePath, false);
14
10
  if (pool) {
15
- const client = await pool.getClient(server, absolutePath);
11
+ let client = await pool.getClient(server, absolutePath);
16
12
  await pool.ensureOpen(server, client, absolutePath);
17
- return fn(client, absolutePath);
13
+ try {
14
+ return await fn(client, absolutePath);
15
+ }
16
+ catch (error) {
17
+ if (!client.terminated && !/\b(exited|terminated|broken pipe|EPIPE)\b/i.test(error instanceof Error ? error.message : String(error)))
18
+ throw error;
19
+ client = await pool.restart(server);
20
+ await pool.ensureOpen(server, client, absolutePath);
21
+ return await fn(client, absolutePath);
22
+ }
18
23
  }
19
- // Single-call fallback (no pool): full server lifecycle per invocation.
20
24
  const client = StdioLspClient.start(server);
21
25
  try {
22
26
  await client.initialize();
@@ -27,11 +31,67 @@ async function withLspClient(server, filePath, pool, fn) {
27
31
  await client.close();
28
32
  }
29
33
  }
34
+ async function prepareCrossFile(server, pool) {
35
+ return pool ? await pool.prepareCrossFileQuery(server) : { changedFiles: 0, indexingComplete: true };
36
+ }
37
+ async function rawDocumentSymbols(client, absolutePath) {
38
+ const result = await client.request('textDocument/documentSymbol', { textDocument: { uri: toUri(absolutePath) } });
39
+ return Array.isArray(result) ? result : [];
40
+ }
30
41
  export async function lspDocumentSymbols(server, filePath, limit, pool) {
31
42
  return await withLspClient(server, filePath, pool, async (client, absolutePath) => {
32
- const result = await client.request('textDocument/documentSymbol', { textDocument: { uri: toUri(absolutePath) } });
33
- const symbols = Array.isArray(result) ? result : [];
34
- return flattenSymbols(symbols, workspaceRelativePath(absolutePath), limit);
43
+ return flattenSemanticSymbols(semanticSymbols(await rawDocumentSymbols(client, absolutePath))).slice(0, limit)
44
+ .map(symbol => ({ ...symbol, path: workspaceRelativePath(absolutePath) }));
45
+ });
46
+ }
47
+ function limitedChildren(symbol, depth) {
48
+ if (depth <= 0 || !symbol.children)
49
+ return { ...symbol, children: undefined };
50
+ return { ...symbol, children: symbol.children.map(child => limitedChildren(child, depth - 1)) };
51
+ }
52
+ function kindAllowed(symbol, options) {
53
+ if (options.includeKinds.length > 0 && (symbol.kind == null || !options.includeKinds.includes(symbol.kind)))
54
+ return false;
55
+ return symbol.kind == null || !options.excludeKinds.includes(symbol.kind);
56
+ }
57
+ export async function lspFindSymbols(server, namePath, options, pool) {
58
+ const scopedPath = options.path?.trim();
59
+ if (!scopedPath) {
60
+ const indexing = await prepareCrossFile(server, pool);
61
+ const symbols = (await lspWorkspaceSymbols(server, namePath.split('/').at(-1) ?? namePath, options.maxResults * 2, pool))
62
+ .filter(symbol => options.substringMatching ? symbol.name.includes(namePath.split('/').at(-1) ?? namePath) : symbol.name === (namePath.split('/').at(-1) ?? namePath))
63
+ .slice(0, options.maxResults)
64
+ .map(symbol => ({ ...symbol, namePath: symbol.name, range: symbol.range }));
65
+ return { symbols, indexingComplete: indexing.indexingComplete };
66
+ }
67
+ const absolute = await prepareWorkspaceRead(scopedPath, false);
68
+ const stat = await fs.stat(absolute);
69
+ if (stat.isDirectory()) {
70
+ const indexing = await prepareCrossFile(server, pool);
71
+ const prefix = `${workspaceRelativePath(absolute).replace(/\\/g, '/')}/`;
72
+ const symbols = (await lspWorkspaceSymbols(server, namePath.split('/').at(-1) ?? namePath, options.maxResults * 4, pool))
73
+ .filter(symbol => symbol.path.replace(/\\/g, '/').startsWith(prefix))
74
+ .slice(0, options.maxResults)
75
+ .map(symbol => ({ ...symbol, namePath: symbol.name, range: symbol.range }));
76
+ return { symbols, indexingComplete: indexing.indexingComplete };
77
+ }
78
+ return await withLspClient(server, scopedPath, pool, async (client, absolutePath) => {
79
+ const all = semanticSymbols(await rawDocumentSymbols(client, absolutePath));
80
+ const matches = flattenSemanticSymbols(all)
81
+ .filter(symbol => matchesNamePath(symbol, namePath, options.substringMatching) && kindAllowed(symbol, options))
82
+ .slice(0, options.maxResults);
83
+ const found = [];
84
+ for (const match of matches) {
85
+ const symbol = { ...limitedChildren(match, options.depth), path: workspaceRelativePath(absolutePath) };
86
+ if (options.includeBody)
87
+ symbol.body = await readRange(absolutePath, match.range);
88
+ if (options.includeInfo) {
89
+ const position = match.selectionRange?.start ?? match.range.start;
90
+ symbol.info = await client.request('textDocument/hover', { textDocument: { uri: toUri(absolutePath) }, position: { line: position.line - 1, character: position.character - 1 } }).catch(() => undefined);
91
+ }
92
+ found.push(symbol);
93
+ }
94
+ return { symbols: found, indexingComplete: true };
35
95
  });
36
96
  }
37
97
  async function requestLocations(client, absolutePath, method, line, character, limit) {
@@ -46,21 +106,50 @@ export async function lspTypeDefinition(server, filePath, line, character, limit
46
106
  return await withLspClient(server, filePath, pool, (client, absolutePath) => requestLocations(client, absolutePath, 'textDocument/typeDefinition', line, character, limit));
47
107
  }
48
108
  export async function lspImplementation(server, filePath, line, character, limit, pool) {
109
+ await prepareCrossFile(server, pool);
49
110
  return await withLspClient(server, filePath, pool, (client, absolutePath) => requestLocations(client, absolutePath, 'textDocument/implementation', line, character, limit));
50
111
  }
51
- export async function lspReferences(server, filePath, line, character, limit, pool) {
112
+ async function rawReferences(server, filePath, line, character, includeDeclaration, limit, pool) {
113
+ await prepareCrossFile(server, pool);
52
114
  return await withLspClient(server, filePath, pool, async (client, absolutePath) => {
53
- const result = await client.request('textDocument/references', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 }, context: { includeDeclaration: true } });
115
+ const result = await client.request('textDocument/references', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 }, context: { includeDeclaration } });
54
116
  const values = Array.isArray(result) ? result : [];
55
117
  return (await Promise.all(values.map(locationToWorkspaceResult))).filter(result => result != null).slice(0, limit);
56
118
  });
57
119
  }
120
+ export async function lspReferenceLocations(server, filePath, line, character, includeDeclaration, limit, pool) {
121
+ return await rawReferences(server, filePath, line, character, includeDeclaration, limit, pool);
122
+ }
123
+ export async function lspRename(server, filePath, line, character, newName, pool) {
124
+ await prepareCrossFile(server, pool);
125
+ return await withLspClient(server, filePath, pool, async (client, absolutePath) => await client.request('textDocument/rename', {
126
+ textDocument: { uri: toUri(absolutePath) },
127
+ position: { line: line - 1, character: character - 1 },
128
+ newName,
129
+ }, 15_000));
130
+ }
131
+ export async function lspReferences(server, filePath, line, character, limit, pool) {
132
+ const locations = await rawReferences(server, filePath, line, character, true, limit, pool);
133
+ return await Promise.all(locations.map(async (location) => {
134
+ if (location.external)
135
+ return location;
136
+ try {
137
+ const absolutePath = await prepareWorkspaceRead(location.path, false);
138
+ const owner = await withLspClient(server, location.path, pool, async (client, openedPath) => smallestContainingSymbol(semanticSymbols(await rawDocumentSymbols(client, openedPath)), location.range.start.line, location.range.start.character));
139
+ return { ...location, ...(owner ? { owner: { namePath: owner.namePath, kind: owner.kind, range: owner.range } } : {}), snippet: await readSnippet(absolutePath, location.range.start.line) };
140
+ }
141
+ catch {
142
+ return location;
143
+ }
144
+ }));
145
+ }
146
+ const PULL_DIAGNOSTIC_METHOD = 'textDocument/diagnostic';
58
147
  async function pullDiagnostics(client, absolutePath, limit) {
59
- const result = await client.request('textDocument/documentDiagnostic', { textDocument: { uri: toUri(absolutePath) } }, 15000);
60
- const items = isObject(result) && Array.isArray(result.items) ? result.items : [];
61
- return diagnosticsFrom(items, limit);
148
+ const result = await client.request(PULL_DIAGNOSTIC_METHOD, { textDocument: { uri: toUri(absolutePath) } }, 15000);
149
+ if (!isObject(result) || !Array.isArray(result.items))
150
+ return { kind: 'unavailable' };
151
+ return { kind: 'report', diagnostics: diagnosticsFrom(result.items, limit) };
62
152
  }
63
- /** Wait briefly for `textDocument/publishDiagnostics` push diagnostics after didOpen. */
64
153
  async function awaitPushDiagnostics(client, absolutePath, limit, waitMs) {
65
154
  const uri = toUri(absolutePath);
66
155
  const deadline = Date.now() + waitMs;
@@ -73,18 +162,16 @@ async function awaitPushDiagnostics(client, absolutePath, limit, waitMs) {
73
162
  await new Promise(resolve => setTimeout(resolve, Math.min(100, deadline - Date.now())));
74
163
  }
75
164
  }
76
- /**
77
- * Diagnostics for one document: pull (`textDocument/documentDiagnostic`) when the
78
- * server advertises it, otherwise the latest push-published set after didOpen.
79
- * A timed-out pull falls back to push instead of failing the whole request.
80
- */
81
165
  export async function lspDiagnostics(server, filePath, limit, pool) {
82
166
  return await withLspClient(server, filePath, pool, async (client, absolutePath) => {
83
167
  if (client.diagnosticPullSupported()) {
84
168
  try {
85
- return { ok: true, diagnostics: await pullDiagnostics(client, absolutePath, limit) };
169
+ const pulled = await pullDiagnostics(client, absolutePath, limit);
170
+ if (pulled.kind === 'report')
171
+ return { ok: true, diagnostics: pulled.diagnostics };
86
172
  }
87
173
  catch (error) {
174
+ // A timeout is a transport symptom, not a clean report; fall back to push.
88
175
  if (!(error instanceof LspError) || !/timed out/.test(error.message))
89
176
  throw error;
90
177
  }
@@ -92,6 +179,32 @@ export async function lspDiagnostics(server, filePath, limit, pool) {
92
179
  return { ok: true, diagnostics: await awaitPushDiagnostics(client, absolutePath, limit, 500) };
93
180
  });
94
181
  }
182
+ function rangesOverlap(a, b) {
183
+ return a.start.line <= b.end.line && b.start.line <= a.end.line;
184
+ }
185
+ export async function lspDiagnosticsForSymbol(server, filePath, namePath, checkReferences, limit, pool) {
186
+ const found = await lspFindSymbols(server, namePath, { path: filePath, depth: 0, includeBody: false, includeInfo: false, includeKinds: [], excludeKinds: [], substringMatching: false, maxResults: 2 }, pool);
187
+ if (found.symbols.length !== 1)
188
+ throw new LspError(`Expected one symbol named ${namePath} in ${filePath}, found ${found.symbols.length}.`);
189
+ const target = found.symbols[0];
190
+ const diagnosticsBySymbol = [];
191
+ const own = await lspDiagnostics(server, filePath, limit, pool);
192
+ if (own.ok)
193
+ diagnosticsBySymbol.push({ path: filePath, namePath: target.namePath, diagnostics: own.diagnostics.filter(diagnostic => rangesOverlap(diagnostic.range, target.range)) });
194
+ if (checkReferences) {
195
+ const position = target.selectionRange?.start ?? target.range.start;
196
+ const references = await lspReferences(server, filePath, position.line, position.character, limit, pool);
197
+ for (const reference of references) {
198
+ if (reference.external || !('owner' in reference) || !reference.owner)
199
+ continue;
200
+ const owner = reference.owner;
201
+ const result = await lspDiagnostics(server, reference.path, limit, pool);
202
+ if (result.ok)
203
+ diagnosticsBySymbol.push({ path: reference.path, namePath: owner.namePath, diagnostics: result.diagnostics.filter(diagnostic => rangesOverlap(diagnostic.range, owner.range)) });
204
+ }
205
+ }
206
+ return diagnosticsBySymbol.filter(group => group.diagnostics.length > 0).slice(0, limit);
207
+ }
95
208
  export async function lspWorkspaceSymbols(server, query, limit, pool) {
96
209
  const run = async (client) => {
97
210
  const result = await client.request('workspace/symbol', { query });
@@ -106,8 +219,19 @@ export async function lspWorkspaceSymbols(server, query, limit, pool) {
106
219
  }));
107
220
  return locations.flat().slice(0, limit);
108
221
  };
109
- if (pool)
110
- return run(await pool.getClient(server));
222
+ if (pool) {
223
+ await pool.prepareCrossFileQuery(server);
224
+ let client = await pool.getClient(server);
225
+ try {
226
+ return await run(client);
227
+ }
228
+ catch (error) {
229
+ if (!client.terminated && !/\b(exited|terminated|broken pipe|EPIPE)\b/i.test(error instanceof Error ? error.message : String(error)))
230
+ throw error;
231
+ client = await pool.restart(server);
232
+ return await run(client);
233
+ }
234
+ }
111
235
  const client = StdioLspClient.start(server);
112
236
  try {
113
237
  await client.initialize();
@@ -0,0 +1,16 @@
1
+ import { type LspRange } from './protocol.js';
2
+ /** A document symbol with a stable hierarchical name path. */
3
+ export interface SemanticSymbol {
4
+ name: string;
5
+ namePath: string;
6
+ kind?: number;
7
+ range: LspRange;
8
+ selectionRange?: LspRange;
9
+ children?: SemanticSymbol[];
10
+ }
11
+ export declare function semanticSymbols(values: unknown[], depth?: number): SemanticSymbol[];
12
+ export declare function flattenSemanticSymbols(symbols: readonly SemanticSymbol[]): SemanticSymbol[];
13
+ export declare function matchesNamePath(symbol: SemanticSymbol, pattern: string, substring: boolean): boolean;
14
+ export declare function smallestContainingSymbol(symbols: readonly SemanticSymbol[], line: number, character?: number): SemanticSymbol;
15
+ export declare function readRange(absolutePath: string, range: LspRange): Promise<string>;
16
+ export declare function readSnippet(absolutePath: string, line: number, contextLines?: number): Promise<string>;
@@ -0,0 +1,70 @@
1
+ import fs from 'node:fs/promises';
2
+ import { asRange, isObject } from './protocol.js';
3
+ function symbolFrom(value, parents, depth) {
4
+ if (!isObject(value) || typeof value.name !== 'string')
5
+ return undefined;
6
+ const locationRange = isObject(value.location) ? value.location.range : undefined;
7
+ const range = asRange(value.range ?? locationRange);
8
+ if (!range)
9
+ return undefined;
10
+ const namePath = [...parents, value.name];
11
+ const children = depth !== 0 && Array.isArray(value.children)
12
+ ? value.children.map(child => symbolFrom(child, namePath, depth - 1)).filter((child) => child != null)
13
+ : undefined;
14
+ return {
15
+ name: value.name,
16
+ namePath: namePath.join('/'),
17
+ kind: typeof value.kind === 'number' ? value.kind : undefined,
18
+ range,
19
+ selectionRange: asRange(value.selectionRange),
20
+ ...(children?.length ? { children } : {}),
21
+ };
22
+ }
23
+ export function semanticSymbols(values, depth = Number.POSITIVE_INFINITY) {
24
+ return values.map(value => symbolFrom(value, [], depth)).filter((symbol) => symbol != null);
25
+ }
26
+ export function flattenSemanticSymbols(symbols) {
27
+ const result = [];
28
+ const visit = (items) => {
29
+ for (const item of items) {
30
+ result.push(item);
31
+ if (item.children)
32
+ visit(item.children);
33
+ }
34
+ };
35
+ visit(symbols);
36
+ return result;
37
+ }
38
+ function lastSegment(namePath) {
39
+ return namePath.replace(/^\//, '').split('/').at(-1) ?? namePath;
40
+ }
41
+ export function matchesNamePath(symbol, pattern, substring) {
42
+ const normalized = pattern.replace(/^\//, '');
43
+ if (pattern.startsWith('/'))
44
+ return symbol.namePath === normalized;
45
+ if (normalized.includes('/'))
46
+ return symbol.namePath === normalized || symbol.namePath.endsWith(`/${normalized}`);
47
+ return substring ? symbol.name.includes(normalized) : lastSegment(symbol.namePath) === normalized;
48
+ }
49
+ function rangeContains(outer, line, character = 1) {
50
+ const startsBefore = line > outer.start.line || (line === outer.start.line && character >= outer.start.character);
51
+ const endsAfter = line < outer.end.line || (line === outer.end.line && character <= outer.end.character);
52
+ return startsBefore && endsAfter;
53
+ }
54
+ export function smallestContainingSymbol(symbols, line, character = 1) {
55
+ return flattenSemanticSymbols(symbols)
56
+ .filter(symbol => rangeContains(symbol.range, line, character))
57
+ .sort((a, b) => (a.range.end.line - a.range.start.line) - (b.range.end.line - b.range.start.line))[0];
58
+ }
59
+ export async function readRange(absolutePath, range) {
60
+ const content = await fs.readFile(absolutePath, 'utf8');
61
+ const lines = content.split(/\r?\n/);
62
+ return lines.slice(Math.max(0, range.start.line - 1), range.end.line).join('\n');
63
+ }
64
+ export async function readSnippet(absolutePath, line, contextLines = 1) {
65
+ const content = await fs.readFile(absolutePath, 'utf8');
66
+ const lines = content.split(/\r?\n/);
67
+ const start = Math.max(0, line - contextLines - 1);
68
+ const end = Math.min(lines.length, line + contextLines);
69
+ return lines.slice(start, end).map((text, index) => `${start + index + 1} | ${text}`).join('\n');
70
+ }
@@ -0,0 +1,43 @@
1
+ import { type LspRange } from './protocol.js';
2
+ import type { ToolExecutionContext } from '../tools/toolContext.js';
3
+ interface TextEdit {
4
+ range: LspRange;
5
+ newText: string;
6
+ }
7
+ export declare function workspaceEditChanges(value: unknown): Map<string, TextEdit[]>;
8
+ export declare function applyTextEdits(content: string, edits: readonly TextEdit[]): string;
9
+ export declare function applyWorkspaceEdit(toolName: string, workspaceEdit: unknown, context: ToolExecutionContext): Promise<{
10
+ ok: boolean;
11
+ toolName: string;
12
+ path: string;
13
+ error: string;
14
+ reasonCode: "scoped_instructions_discovered";
15
+ recoverable: boolean;
16
+ suggestedNextStep: string;
17
+ applicableProjectInstructions: import("../../config/contextFiles.js").ContextFile[];
18
+ } | {
19
+ ok: boolean;
20
+ changedPaths: string[];
21
+ uncertainPaths: string[];
22
+ error: string;
23
+ recoverable: boolean;
24
+ suggestedNextStep: string;
25
+ } | {
26
+ diffHandle?: string | undefined;
27
+ ok: boolean;
28
+ changedPaths: string[];
29
+ noChange: boolean;
30
+ changedFiles: number;
31
+ diffLineCount: number;
32
+ files: {
33
+ diff: import("../toolResultTypes.js").ToolDiffLine[];
34
+ addedLines: number;
35
+ removedLines: number;
36
+ path: string;
37
+ }[];
38
+ uncertainPaths?: undefined;
39
+ error?: undefined;
40
+ recoverable?: undefined;
41
+ suggestedNextStep?: undefined;
42
+ }>;
43
+ export {};
@@ -0,0 +1,117 @@
1
+ import fs from 'node:fs/promises';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { workspaceRelativePath } from '../../utils/path.js';
4
+ import { prepareWorkspaceMutation } from '../tools/workspaceFile.js';
5
+ import { boundedDiff, fileDiff } from '../tools/editMatch.js';
6
+ import { storeToolOutput } from '../../core/agent/toolOutputStore.js';
7
+ import { isObject } from './protocol.js';
8
+ import { readUtf8Prefix } from '../../core/io/boundedRead.js';
9
+ import { EXACT_MUTATION_BYTES } from '../../core/limits.js';
10
+ function textEdits(value) {
11
+ if (!Array.isArray(value) || value.length > 10_000)
12
+ throw new Error('Invalid or oversized LSP edit list.');
13
+ return value.map(edit => {
14
+ if (!isObject(edit) || !isObject(edit.range) || typeof edit.newText !== 'string')
15
+ throw new Error('Invalid LSP text edit.');
16
+ const point = (value) => {
17
+ if (!isObject(value) || !Number.isSafeInteger(value.line) || !Number.isSafeInteger(value.character)
18
+ || value.line < 0 || value.character < 0)
19
+ throw new Error('Invalid LSP edit position.');
20
+ return { line: value.line + 1, character: value.character + 1 };
21
+ };
22
+ const range = { start: point(edit.range.start), end: point(edit.range.end) };
23
+ assertOrderedRange(range);
24
+ return { range, newText: edit.newText };
25
+ });
26
+ }
27
+ export function workspaceEditChanges(value) {
28
+ const result = new Map();
29
+ if (!isObject(value))
30
+ return result;
31
+ if (isObject(value.changes)) {
32
+ for (const [uri, edits] of Object.entries(value.changes))
33
+ result.set(uri, [...(result.get(uri) ?? []), ...textEdits(edits)]);
34
+ }
35
+ if (Array.isArray(value.documentChanges)) {
36
+ for (const change of value.documentChanges) {
37
+ if (!isObject(change) || !isObject(change.textDocument) || typeof change.textDocument.uri !== 'string')
38
+ continue;
39
+ const uri = change.textDocument.uri;
40
+ result.set(uri, [...(result.get(uri) ?? []), ...textEdits(change.edits)]);
41
+ }
42
+ }
43
+ return result;
44
+ }
45
+ function assertOrderedRange(range) {
46
+ if (range.start.line > range.end.line || (range.start.line === range.end.line && range.start.character > range.end.character))
47
+ throw new Error('Reversed LSP edit range.');
48
+ }
49
+ function offsetAt(text, line, character) {
50
+ const lines = text.split('\n');
51
+ if (!Number.isSafeInteger(line) || !Number.isSafeInteger(character) || line < 1 || line > lines.length || character < 1)
52
+ throw new Error('LSP edit position is outside the document.');
53
+ let offset = 0;
54
+ for (let index = 0; index < line - 1; index++)
55
+ offset += (lines[index]?.length ?? 0) + 1;
56
+ // LSP character positions are UTF-16 code units, as are JavaScript string offsets.
57
+ const lineLength = lines[line - 1].replace(/\r$/, '').length;
58
+ if (character - 1 > lineLength)
59
+ throw new Error('LSP edit position is outside the document.');
60
+ return offset + character - 1;
61
+ }
62
+ export function applyTextEdits(content, edits) {
63
+ for (const edit of edits)
64
+ assertOrderedRange(edit.range);
65
+ const located = edits.map(edit => ({ ...edit, start: offsetAt(content, edit.range.start.line, edit.range.start.character), end: offsetAt(content, edit.range.end.line, edit.range.end.character) }))
66
+ .sort((a, b) => b.start - a.start);
67
+ for (let index = 1; index < located.length; index++)
68
+ if (located[index - 1].start < located[index].end)
69
+ throw new Error('LSP workspace edit contains overlapping changes.');
70
+ let updated = content;
71
+ for (const edit of located)
72
+ updated = `${updated.slice(0, edit.start)}${edit.newText}${updated.slice(edit.end)}`;
73
+ return updated;
74
+ }
75
+ export async function applyWorkspaceEdit(toolName, workspaceEdit, context) {
76
+ const changes = workspaceEditChanges(workspaceEdit);
77
+ if (changes.size === 0)
78
+ throw new Error('Language server returned no workspace edits.');
79
+ if (changes.size > 100 || [...changes.values()].reduce((sum, edits) => sum + edits.length, 0) > 10_000
80
+ || [...changes.values()].flat().reduce((sum, edit) => sum + Buffer.byteLength(edit.newText), 0) > EXACT_MUTATION_BYTES)
81
+ throw new Error('LSP workspace edit exceeds the aggregate edit limit.');
82
+ let remainingBytes = EXACT_MUTATION_BYTES;
83
+ const pending = [];
84
+ for (const [uri, edits] of changes) {
85
+ if (!uri.startsWith('file://'))
86
+ throw new Error(`Refusing non-file workspace edit URI: ${uri}`);
87
+ const filePath = workspaceRelativePath(fileURLToPath(uri));
88
+ const prepared = await prepareWorkspaceMutation(toolName, filePath, false, context);
89
+ if (prepared.scopedStop)
90
+ return prepared.scopedStop;
91
+ const read = await readUtf8Prefix(prepared.absolutePath, remainingBytes);
92
+ if (read.truncated)
93
+ throw new Error('LSP workspace edit exceeds the aggregate document limit.');
94
+ const original = read.content;
95
+ remainingBytes -= Buffer.byteLength(original);
96
+ const updated = applyTextEdits(original, edits);
97
+ if (updated !== original)
98
+ pending.push({ path: filePath, absolutePath: prepared.absolutePath, original, updated });
99
+ }
100
+ const changedPaths = [];
101
+ for (const file of pending) {
102
+ try {
103
+ await fs.writeFile(file.absolutePath, file.updated, 'utf8');
104
+ changedPaths.push(file.path);
105
+ }
106
+ catch {
107
+ return { ok: false, changedPaths, uncertainPaths: [file.path], error: `Write failed for ${file.path}; earlier writes were not rolled back.`, recoverable: true, suggestedNextStep: 'Read the changed and uncertain paths before retrying; validate all completed changes.' };
108
+ }
109
+ }
110
+ const fullFiles = pending.map(file => ({ path: file.path, ...fileDiff(file.original, file.updated) }));
111
+ const diffLineCount = fullFiles.reduce((sum, file) => sum + file.diff.length, 0);
112
+ const files = fullFiles.map(file => ({ ...file, diff: boundedDiff(file.diff, 12).diff }));
113
+ const diffHandle = diffLineCount > files.reduce((sum, file) => sum + file.diff.length, 0)
114
+ ? storeToolOutput(JSON.stringify(fullFiles, null, 2))
115
+ : undefined;
116
+ return { ok: true, changedPaths, noChange: pending.length === 0, changedFiles: pending.length, diffLineCount, files, ...(diffHandle ? { diffHandle } : {}) };
117
+ }