@denizokcu/haze 1.1.1 → 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 (133) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +26 -15
  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 +25 -2
  11. package/dist/cli/chat/sessionRecorder.d.ts +7 -0
  12. package/dist/cli/chat/sessionRecorder.js +6 -0
  13. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  14. package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
  15. package/dist/cli/commands/chat.js +63 -36
  16. package/dist/cli/commands/commandHelp.js +2 -0
  17. package/dist/cli/commands/commands.js +2 -0
  18. package/dist/cli/commands/formatters.js +5 -1
  19. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  20. package/dist/cli/commands/ndjsonSink.js +29 -0
  21. package/dist/cli/commands/reasoningCommand.d.ts +35 -0
  22. package/dist/cli/commands/reasoningCommand.js +46 -0
  23. package/dist/cli/commands/runCommand.d.ts +14 -0
  24. package/dist/cli/commands/runCommand.js +43 -11
  25. package/dist/cli/commands/settingsSummary.js +2 -0
  26. package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
  27. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  28. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  29. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  30. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  31. package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
  32. package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
  33. package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
  34. package/dist/cli/commands/streaming/attemptSetup.js +40 -15
  35. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
  36. package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
  37. package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
  38. package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
  39. package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
  40. package/dist/cli/commands/streaming/prepareStep.js +43 -22
  41. package/dist/cli/commands/streaming/stallRecovery.js +2 -2
  42. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  43. package/dist/cli/commands/streaming/streamLoop.js +280 -44
  44. package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
  45. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  46. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  47. package/dist/cli/commands/streaming.d.ts +15 -2
  48. package/dist/cli/commands/streaming.js +37 -8
  49. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  50. package/dist/cli/commands/wizardFlow.js +22 -0
  51. package/dist/cli/index.js +8 -3
  52. package/dist/config/modelCatalog.d.ts +32 -0
  53. package/dist/config/modelCatalog.js +84 -0
  54. package/dist/config/modelDiscovery.js +68 -5
  55. package/dist/config/settings.d.ts +18 -6
  56. package/dist/config/settings.js +11 -1
  57. package/dist/core/agent/budgets.d.ts +10 -2
  58. package/dist/core/agent/budgets.js +10 -2
  59. package/dist/core/agent/compaction.d.ts +42 -3
  60. package/dist/core/agent/compaction.js +53 -5
  61. package/dist/core/agent/completionController.d.ts +11 -1
  62. package/dist/core/agent/completionController.js +33 -0
  63. package/dist/core/agent/contextBudget.d.ts +56 -0
  64. package/dist/core/agent/contextBudget.js +53 -0
  65. package/dist/core/agent/errors.js +2 -2
  66. package/dist/core/agent/events.d.ts +26 -2
  67. package/dist/core/agent/goalPolicy.d.ts +7 -0
  68. package/dist/core/agent/goalPolicy.js +9 -0
  69. package/dist/core/agent/overflow.d.ts +45 -0
  70. package/dist/core/agent/overflow.js +91 -0
  71. package/dist/core/agent/reasoningPolicy.d.ts +45 -9
  72. package/dist/core/agent/reasoningPolicy.js +49 -9
  73. package/dist/core/agent/requestAssembly.d.ts +7 -0
  74. package/dist/core/agent/requestAssembly.js +15 -7
  75. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  76. package/dist/core/agent/toolCapabilities.js +31 -7
  77. package/dist/core/agent/workState.d.ts +6 -4
  78. package/dist/core/agent/workState.js +53 -29
  79. package/dist/core/deadline.js +22 -24
  80. package/dist/core/safety/secretPaths.js +10 -7
  81. package/dist/core/safety/shellClassifier.d.ts +18 -0
  82. package/dist/core/safety/shellClassifier.js +39 -0
  83. package/dist/core/session/sessionSlimming.d.ts +2 -0
  84. package/dist/core/session/sessionSlimming.js +50 -1
  85. package/dist/core/session/sessionStore.d.ts +14 -8
  86. package/dist/core/session/sessionStore.js +59 -32
  87. package/dist/core/shellOutput/reducers/git.js +7 -2
  88. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  89. package/dist/core/shellOutput/reducers/validation.js +14 -1
  90. package/dist/core/shellOutput/registry.js +3 -2
  91. package/dist/core/subagent/contracts.d.ts +8 -1
  92. package/dist/core/subagent/subagentRunner.d.ts +4 -0
  93. package/dist/core/subagent/subagentRunner.js +33 -25
  94. package/dist/core/tasks/taskStorage.js +8 -1
  95. package/dist/core/validation/outputParser.d.ts +1 -1
  96. package/dist/core/validation/outputParser.js +30 -1
  97. package/dist/llm/client.d.ts +4 -3
  98. package/dist/llm/client.js +34 -16
  99. package/dist/llm/hazeTools.d.ts +2039 -16
  100. package/dist/llm/hazeTools.js +43 -2
  101. package/dist/llm/lsp/client.d.ts +7 -1
  102. package/dist/llm/lsp/client.js +58 -9
  103. package/dist/llm/lsp/pool.d.ts +11 -0
  104. package/dist/llm/lsp/pool.js +61 -4
  105. package/dist/llm/lsp/protocol.d.ts +6 -23
  106. package/dist/llm/lsp/requests.d.ts +54 -60
  107. package/dist/llm/lsp/requests.js +152 -28
  108. package/dist/llm/lsp/symbols.d.ts +16 -0
  109. package/dist/llm/lsp/symbols.js +70 -0
  110. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  111. package/dist/llm/lsp/workspaceEdit.js +117 -0
  112. package/dist/llm/lspTools.d.ts +7518 -2859
  113. package/dist/llm/lspTools.js +195 -110
  114. package/dist/llm/requestContext.d.ts +3 -2
  115. package/dist/llm/requestContext.js +8 -4
  116. package/dist/llm/systemPrompt.js +2 -2
  117. package/dist/llm/tools/fetchTool.d.ts +4 -0
  118. package/dist/llm/tools/processTool.d.ts +4 -0
  119. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  120. package/dist/llm/tools/replaceInFiles.js +131 -0
  121. package/dist/llm/tools/shellTool.d.ts +4 -0
  122. package/dist/llm/tools/shellTool.js +27 -8
  123. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  124. package/dist/llm/tools/taskTool.d.ts +4 -0
  125. package/dist/llm/tools/toolContext.d.ts +3 -0
  126. package/dist/llm/tools/toolContext.js +26 -4
  127. package/dist/skills/SkillLoader.js +27 -1
  128. package/dist/ui/components/TextInput.d.ts +18 -1
  129. package/dist/ui/components/TextInput.js +44 -6
  130. package/dist/ui/components/useInputSuggestions.js +18 -6
  131. package/dist/utils/buildInfo.js +29 -8
  132. package/dist/utils/fs.js +5 -1
  133. package/package.json +20 -19
@@ -2,57 +2,110 @@ import path from 'node:path';
2
2
  import { tool } from 'ai';
3
3
  import { z } from 'zod';
4
4
  import { readSettings } from '../config/settings.js';
5
- import { configuredLspServers } from '../config/lspSettings.js';
5
+ import { configuredLspServers, installedLspServers } from '../config/lspSettings.js';
6
6
  import { pickLspServer } from './lsp/pool.js';
7
- import { lspDefinition, lspDiagnostics, lspDocumentSymbols, lspImplementation, lspReferences, lspTypeDefinition, lspWorkspaceSymbols } from './lsp/requests.js';
8
- async function serverFor(filePath) {
9
- const servers = configuredLspServers(await readSettings()).filter(server => server.enabled !== false);
10
- return pickLspServer(servers, filePath);
11
- }
7
+ import { lspDefinition, lspDiagnostics, lspDiagnosticsForSymbol, lspDocumentSymbols, lspFindSymbols, lspImplementation, lspReferenceLocations, lspReferences, lspRename, lspTypeDefinition, lspWorkspaceSymbols } from './lsp/requests.js';
8
+ import { applyWorkspaceEdit } from './lsp/workspaceEdit.js';
9
+ import { hazeToolContextSchema, runDedupedTool } from './tools/toolContext.js';
10
+ import { prepareWorkspaceRead } from './tools/workspaceFile.js';
11
+ import { toUri } from './lsp/protocol.js';
12
12
  function noServer(filePath) {
13
- return { ok: false, error: `No enabled LSP server configured for ${path.extname(filePath) || 'this file type'}. Use /lsp presets and /lsp add <preset> to configure one.` };
13
+ return `No enabled LSP server configured for ${path.extname(filePath) || 'this file type'}. Use /lsp presets and /lsp add <preset> to configure one.`;
14
+ }
15
+ function notInstalled(server, filePath) {
16
+ const scope = filePath ? ` for ${path.extname(filePath) || 'this file type'}` : '';
17
+ return `LSP server ${server.name} is enabled${scope} but its command "${server.command}" is not installed (not found on PATH). Install it or reconfigure via /lsp; fall back to grep/readFile meanwhile.`;
18
+ }
19
+ /** Resolve the server for a file: enabled for the extension and actually installed. */
20
+ async function serverFor(filePath) {
21
+ const settings = await readSettings();
22
+ const candidate = pickLspServer(configuredLspServers(settings).filter(server => server.enabled !== false), filePath);
23
+ if (!candidate)
24
+ return { ok: false, error: noServer(filePath) };
25
+ const installed = await installedLspServers(settings);
26
+ return installed.some(server => server.name === candidate.name) ? { ok: true, server: candidate } : { ok: false, error: notInstalled(candidate, filePath) };
14
27
  }
28
+ /** Resolve a named server, or the first installed one when unnamed. */
15
29
  async function namedOrFirstServer(name) {
16
- const servers = configuredLspServers(await readSettings()).filter(server => server.enabled !== false);
17
- if (name)
18
- return servers.find(server => server.name === name);
19
- return servers[0];
30
+ const settings = await readSettings();
31
+ const enabled = configuredLspServers(settings).filter(server => server.enabled !== false);
32
+ if (name) {
33
+ const candidate = enabled.find(server => server.name === name);
34
+ if (!candidate)
35
+ return { ok: false, error: `No enabled LSP server named ${name}.` };
36
+ const installed = await installedLspServers(settings);
37
+ return installed.some(server => server.name === candidate.name) ? { ok: true, server: candidate } : { ok: false, error: notInstalled(candidate) };
38
+ }
39
+ const firstInstalled = (await installedLspServers(settings))[0];
40
+ if (firstInstalled)
41
+ return { ok: true, server: firstInstalled };
42
+ return { ok: false, error: enabled.length > 0 ? 'No enabled LSP server is installed (command not found on PATH). Install one or adjust /lsp.' : 'No enabled LSP server configured. Use /lsp add <preset>.' };
20
43
  }
21
44
  function cleanLspError(message) {
22
45
  if (/No Project/i.test(message))
23
46
  return 'LSP server reported no project for workspace-symbol search. Use grep/listFiles to find likely files, then try file-scoped lspSymbols on those files; fall back to readFile when needed.';
24
- return message
25
- .split('\n')
26
- .filter(line => line.trim() && !/^\s*at\s/.test(line))
27
- .slice(0, 2)
28
- .join('\n');
47
+ return message.split('\n').filter(line => line.trim() && !/^\s*at\s/.test(line)).slice(0, 2).join('\n');
29
48
  }
30
49
  function lspFailure(error) {
31
- const message = error instanceof Error ? error.message : String(error);
32
- return { ok: false, error: cleanLspError(message) };
50
+ return { ok: false, error: cleanLspError(error instanceof Error ? error.message : String(error)) };
33
51
  }
52
+ const locationSchema = {
53
+ path: z.string().min(1).describe('Workspace-relative source file path'),
54
+ line: z.number().int().positive().describe('1-based line number'),
55
+ column: z.number().int().positive().describe('1-based column/character number'),
56
+ };
57
+ const symbolNameSchema = {
58
+ path: z.string().min(1).describe('Workspace-relative source file path'),
59
+ namePath: z.string().min(1).describe('Symbol name or hierarchical name path, such as Class/method'),
60
+ };
34
61
  export const lspTools = buildLspTools();
35
- /**
36
- * Build the LSP tool set bound to a shared turn-scoped client pool so repeated
37
- * symbols/definition/references calls reuse one initialized server and its
38
- * opened documents instead of paying startup + indexing per call (RH-009).
39
- */
62
+ const AUTOMATIC_DIAGNOSTIC_FILE_LIMIT = 20;
63
+ const AUTOMATIC_DIAGNOSTIC_RESULT_LIMIT = 20;
64
+ /** Build the bounded diagnostics hook attached to successful file-mutation results. */
65
+ export function createPostMutationDiagnostics(servers, pool) {
66
+ return async (paths) => {
67
+ const uniquePaths = [...new Set(paths)];
68
+ const supported = uniquePaths.flatMap(filePath => {
69
+ const server = pickLspServer(servers, filePath);
70
+ return server ? [{ filePath, server }] : [];
71
+ });
72
+ if (supported.length === 0)
73
+ return undefined;
74
+ const files = [];
75
+ let remainingResults = AUTOMATIC_DIAGNOSTIC_RESULT_LIMIT;
76
+ for (const { filePath, server } of supported.slice(0, AUTOMATIC_DIAGNOSTIC_FILE_LIMIT)) {
77
+ if (remainingResults === 0)
78
+ break;
79
+ try {
80
+ const result = await lspDiagnostics(server, filePath, remainingResults, pool);
81
+ if (!result.ok) {
82
+ files.push({ ok: false, path: filePath, server: server.name, error: result.error });
83
+ continue;
84
+ }
85
+ files.push({ ok: true, path: filePath, server: server.name, diagnostics: result.diagnostics });
86
+ remainingResults -= result.diagnostics.length;
87
+ }
88
+ catch (error) {
89
+ files.push({ ok: false, path: filePath, server: server.name, error: cleanLspError(error instanceof Error ? error.message : String(error)) });
90
+ }
91
+ }
92
+ const truncated = supported.length > files.length || remainingResults === 0;
93
+ return { ok: files.every(file => file.ok === true), files, truncated };
94
+ };
95
+ }
96
+ /** Build the optional LSP tool set bound to one turn-scoped client pool. */
40
97
  export function buildLspTools(pool) {
41
98
  return {
42
99
  lspWorkspaceSymbols: tool({
43
- description: 'Use a configured language server to search workspace symbols by name. Read-only. Best first LSP tool when the user names a function/class but you do not yet have a precise reference position. If this fails with no project or returns empty, use grep/listFiles to find candidate files, then lspSymbols on those files.',
44
- inputSchema: z.object({
45
- query: z.string().min(1).describe('Symbol name or prefix to search for'),
46
- server: z.string().optional().describe('Optional configured LSP server name. If omitted, the first enabled server is used.'),
47
- maxSymbols: z.number().int().positive().max(100).default(50).describe('Maximum symbols to return'),
48
- }),
100
+ description: 'Use a configured language server to search workspace symbols by name. Read-only. Best first LSP tool when you do not know the defining file.',
101
+ inputSchema: z.object({ query: z.string().min(1), server: z.string().optional(), maxSymbols: z.number().int().positive().max(100).default(50) }),
49
102
  execute: async ({ query, server: serverName, maxSymbols }) => {
50
- const server = await namedOrFirstServer(serverName);
51
- if (!server)
52
- return { ok: false, error: serverName ? `No enabled LSP server named ${serverName}.` : 'No enabled LSP server configured. Use /lsp add <preset>.' };
103
+ const resolved = await namedOrFirstServer(serverName);
104
+ if (!resolved.ok)
105
+ return resolved;
53
106
  try {
54
- const symbols = await lspWorkspaceSymbols(server, query, maxSymbols, pool);
55
- return { ok: true, server: server.name, query, symbols, truncated: symbols.length >= maxSymbols };
107
+ const symbols = await lspWorkspaceSymbols(resolved.server, query, maxSymbols, pool);
108
+ return { ok: true, server: resolved.server.name, query, symbols, truncated: symbols.length >= maxSymbols };
56
109
  }
57
110
  catch (error) {
58
111
  return lspFailure(error);
@@ -60,123 +113,137 @@ export function buildLspTools(pool) {
60
113
  },
61
114
  }),
62
115
  lspSymbols: tool({
63
- description: 'Use a configured language server to list semantic symbols in a source file. Read-only. Use this after grep/listFiles identifies a likely file, especially when workspace symbol search fails or is not indexed.',
64
- inputSchema: z.object({
65
- path: z.string().min(1).describe('Workspace-relative source file path'),
66
- maxSymbols: z.number().int().positive().max(200).default(80).describe('Maximum symbols to return'),
67
- }),
116
+ description: 'List semantic symbols in a source file, including hierarchical name paths. Use lspFindSymbol for targeted body/signature retrieval.',
117
+ inputSchema: z.object({ path: z.string().min(1), maxSymbols: z.number().int().positive().max(200).default(80) }),
68
118
  execute: async ({ path: filePath, maxSymbols }) => {
69
- const server = await serverFor(filePath);
70
- if (!server)
71
- return noServer(filePath);
119
+ const resolved = await serverFor(filePath);
120
+ if (!resolved.ok)
121
+ return resolved;
72
122
  try {
73
- const symbols = await lspDocumentSymbols(server, filePath, maxSymbols, pool);
74
- return { ok: true, server: server.name, path: filePath, symbols, truncated: symbols.length >= maxSymbols };
123
+ const symbols = await lspDocumentSymbols(resolved.server, filePath, maxSymbols, pool);
124
+ return { ok: true, server: resolved.server.name, path: filePath, symbols, truncated: symbols.length >= maxSymbols };
75
125
  }
76
126
  catch (error) {
77
127
  return lspFailure(error);
78
128
  }
79
129
  },
80
130
  }),
81
- lspDefinition: tool({
82
- description: 'Use a configured language server to find the definition at a 1-based line/column in a source file. Read-only.',
131
+ lspFindSymbol: tool({
132
+ description: 'Find a symbol by hierarchical name path. Can scope to a file/directory, retrieve children, exact body text, and hover/signature info.',
83
133
  inputSchema: z.object({
84
- path: z.string().min(1).describe('Workspace-relative source file path'),
85
- line: z.number().int().positive().describe('1-based line number'),
86
- column: z.number().int().positive().describe('1-based column/character number'),
87
- maxResults: z.number().int().positive().max(50).default(20).describe('Maximum locations to return'),
134
+ namePath: z.string().min(1),
135
+ path: z.string().optional().describe('Optional workspace-relative file or directory scope'),
136
+ depth: z.number().int().min(0).max(4).default(0),
137
+ includeBody: z.boolean().default(false),
138
+ includeInfo: z.boolean().default(false),
139
+ includeKinds: z.array(z.number().int().positive()).default([]),
140
+ excludeKinds: z.array(z.number().int().positive()).default([]),
141
+ substringMatching: z.boolean().default(false),
142
+ maxResults: z.number().int().positive().max(100).default(20),
88
143
  }),
89
- execute: async ({ path: filePath, line, column, maxResults }) => {
90
- const server = await serverFor(filePath);
91
- if (!server)
92
- return noServer(filePath);
144
+ execute: async (input) => {
145
+ const resolved = input.path && path.extname(input.path) ? await serverFor(input.path) : await namedOrFirstServer();
146
+ if (!resolved.ok)
147
+ return resolved;
93
148
  try {
94
- const locations = await lspDefinition(server, filePath, line, column, maxResults, pool);
95
- return { ok: true, server: server.name, path: filePath, locations, truncated: locations.length >= maxResults };
149
+ const result = await lspFindSymbols(resolved.server, input.namePath, input, pool);
150
+ return { ok: true, server: resolved.server.name, ...result, truncated: result.symbols.length >= input.maxResults };
96
151
  }
97
152
  catch (error) {
98
153
  return lspFailure(error);
99
154
  }
100
155
  },
101
156
  }),
157
+ lspDefinition: locationTool('Find the definition at a 1-based source position.', 'definition', lspDefinition, pool),
158
+ lspTypeDefinition: locationTool('Find the type definition at a 1-based source position.', 'type definition', lspTypeDefinition, pool),
159
+ lspImplementation: locationTool('Find implementations at a 1-based source position.', 'implementations', lspImplementation, pool, 100),
102
160
  lspReferences: tool({
103
- description: 'Use a configured language server to find references at a 1-based line/column in a source file. Read-only.',
104
- inputSchema: z.object({
105
- path: z.string().min(1).describe('Workspace-relative source file path'),
106
- line: z.number().int().positive().describe('1-based line number'),
107
- column: z.number().int().positive().describe('1-based column/character number'),
108
- maxResults: z.number().int().positive().max(100).default(50).describe('Maximum locations to return'),
109
- }),
161
+ description: 'Find references and return each location with its enclosing symbol and a compact source snippet.',
162
+ inputSchema: z.object({ ...locationSchema, maxResults: z.number().int().positive().max(100).default(50) }),
110
163
  execute: async ({ path: filePath, line, column, maxResults }) => {
111
- const server = await serverFor(filePath);
112
- if (!server)
113
- return noServer(filePath);
164
+ const resolved = await serverFor(filePath);
165
+ if (!resolved.ok)
166
+ return resolved;
114
167
  try {
115
- const locations = await lspReferences(server, filePath, line, column, maxResults, pool);
116
- return { ok: true, server: server.name, path: filePath, locations, truncated: locations.length >= maxResults };
168
+ const references = await lspReferences(resolved.server, filePath, line, column, maxResults, pool);
169
+ return { ok: true, server: resolved.server.name, path: filePath, references, locations: references, truncated: references.length >= maxResults };
117
170
  }
118
171
  catch (error) {
119
172
  return lspFailure(error);
120
173
  }
121
174
  },
122
175
  }),
123
- lspTypeDefinition: tool({
124
- description: 'Use a configured language server to find the type definition (e.g. interface, type alias, class) for the symbol at a 1-based line/column. Read-only. Useful for generics and annotated values where lspDefinition lands on the annotated name instead of its type.',
125
- inputSchema: z.object({
126
- path: z.string().min(1).describe('Workspace-relative source file path'),
127
- line: z.number().int().positive().describe('1-based line number'),
128
- column: z.number().int().positive().describe('1-based column/character number'),
129
- maxResults: z.number().int().positive().max(50).default(20).describe('Maximum locations to return'),
130
- }),
131
- execute: async ({ path: filePath, line, column, maxResults }) => {
132
- const server = await serverFor(filePath);
133
- if (!server)
134
- return noServer(filePath);
176
+ lspRenameSymbol: tool({
177
+ description: 'Rename one symbol across the workspace using the language server. Resolves the symbol by name path immediately before applying the workspace edit.',
178
+ contextSchema: hazeToolContextSchema,
179
+ inputSchema: z.object({ ...symbolNameSchema, newName: z.string().min(1) }),
180
+ execute: async (input, context) => await runDedupedTool('lspRenameSymbol', input, context, async () => {
181
+ const resolved = await serverFor(input.path);
182
+ if (!resolved.ok)
183
+ return resolved;
135
184
  try {
136
- const locations = await lspTypeDefinition(server, filePath, line, column, maxResults, pool);
137
- return { ok: true, server: server.name, path: filePath, locations, truncated: locations.length >= maxResults };
185
+ const found = await lspFindSymbols(resolved.server, input.namePath, { path: input.path, depth: 0, includeBody: false, includeInfo: false, includeKinds: [], excludeKinds: [], substringMatching: false, maxResults: 2 }, pool);
186
+ if (found.symbols.length !== 1)
187
+ return { ok: false, error: `Expected one symbol named ${input.namePath}, found ${found.symbols.length}.` };
188
+ const position = found.symbols[0].selectionRange?.start ?? found.symbols[0].range.start;
189
+ return await applyWorkspaceEdit('lspRenameSymbol', await lspRename(resolved.server, input.path, position.line, position.character, input.newName, pool), context);
138
190
  }
139
191
  catch (error) {
140
192
  return lspFailure(error);
141
193
  }
142
- },
143
- }),
144
- lspImplementation: tool({
145
- description: 'Use a configured language server to find implementations of an interface, abstract member, or generic signature at a 1-based line/column. Read-only.',
146
- inputSchema: z.object({
147
- path: z.string().min(1).describe('Workspace-relative source file path'),
148
- line: z.number().int().positive().describe('1-based line number'),
149
- column: z.number().int().positive().describe('1-based column/character number'),
150
- maxResults: z.number().int().positive().max(100).default(50).describe('Maximum locations to return'),
151
194
  }),
152
- execute: async ({ path: filePath, line, column, maxResults }) => {
153
- const server = await serverFor(filePath);
154
- if (!server)
155
- return noServer(filePath);
195
+ }),
196
+ lspSafeDeleteSymbol: tool({
197
+ description: 'Delete a symbol only when the language server reports no references. Otherwise returns the blocking reference locations without editing.',
198
+ contextSchema: hazeToolContextSchema,
199
+ inputSchema: z.object(symbolNameSchema),
200
+ execute: async (input, context) => await runDedupedTool('lspSafeDeleteSymbol', input, context, async () => {
201
+ const resolved = await serverFor(input.path);
202
+ if (!resolved.ok)
203
+ return resolved;
156
204
  try {
157
- const locations = await lspImplementation(server, filePath, line, column, maxResults, pool);
158
- return { ok: true, server: server.name, path: filePath, locations, truncated: locations.length >= maxResults };
205
+ const found = await lspFindSymbols(resolved.server, input.namePath, { path: input.path, depth: 0, includeBody: false, includeInfo: false, includeKinds: [], excludeKinds: [], substringMatching: false, maxResults: 2 }, pool);
206
+ if (found.symbols.length !== 1)
207
+ return { ok: false, error: `Expected one symbol named ${input.namePath}, found ${found.symbols.length}.` };
208
+ const symbol = found.symbols[0];
209
+ const position = symbol.selectionRange?.start ?? symbol.range.start;
210
+ const references = await lspReferenceLocations(resolved.server, input.path, position.line, position.character, false, 100, pool);
211
+ if (references.length > 0)
212
+ return { ok: false, error: `Cannot delete ${symbol.namePath}: ${references.length} reference(s) remain.`, references, recoverable: true, suggestedNextStep: 'Remove or migrate the references, then retry safe delete.' };
213
+ const absolutePath = await prepareWorkspaceRead(input.path, false, context);
214
+ const range = { start: { line: symbol.range.start.line - 1, character: symbol.range.start.character - 1 }, end: { line: symbol.range.end.line - 1, character: symbol.range.end.character - 1 } };
215
+ return await applyWorkspaceEdit('lspSafeDeleteSymbol', { changes: { [toUri(absolutePath)]: [{ range, newText: '' }] } }, context);
159
216
  }
160
217
  catch (error) {
161
218
  return lspFailure(error);
162
219
  }
163
- },
220
+ }),
164
221
  }),
165
222
  lspDiagnostics: tool({
166
- description: 'Use a configured language server to get diagnostics (errors/warnings) for one source file. Read-only. Best for a quick post-edit check of a single touched file; prefer the relevant build/test command for authoritative whole-project validation.',
167
- inputSchema: z.object({
168
- path: z.string().min(1).describe('Workspace-relative source file path'),
169
- maxResults: z.number().int().positive().max(100).default(50).describe('Maximum diagnostics to return'),
170
- }),
223
+ description: 'Get diagnostics for one source file. Successful file-mutation results already include automatic diagnostics for supported files; call this only when a fresh standalone check is needed. Prefer the relevant build/test command for authoritative validation.',
224
+ inputSchema: z.object({ path: z.string().min(1), maxResults: z.number().int().positive().max(100).default(50) }),
171
225
  execute: async ({ path: filePath, maxResults }) => {
172
- const server = await serverFor(filePath);
173
- if (!server)
174
- return noServer(filePath);
226
+ const resolved = await serverFor(filePath);
227
+ if (!resolved.ok)
228
+ return resolved;
175
229
  try {
176
- const result = await lspDiagnostics(server, filePath, maxResults, pool);
177
- if (!result.ok)
178
- return { ok: false, error: result.error };
179
- return { ok: true, server: server.name, path: filePath, diagnostics: result.diagnostics, truncated: result.diagnostics.length >= maxResults };
230
+ const result = await lspDiagnostics(resolved.server, filePath, maxResults, pool);
231
+ return result.ok ? { ok: true, server: resolved.server.name, path: filePath, diagnostics: result.diagnostics, truncated: result.diagnostics.length >= maxResults } : result;
232
+ }
233
+ catch (error) {
234
+ return lspFailure(error);
235
+ }
236
+ },
237
+ }),
238
+ lspDiagnosticsForSymbol: tool({
239
+ description: 'Get diagnostics owned by a symbol and optionally by symbols that reference it. This is a focused intermediate check, not a replacement for tests/typecheck.',
240
+ inputSchema: z.object({ ...symbolNameSchema, checkReferences: z.boolean().default(false), maxResults: z.number().int().positive().max(100).default(50) }),
241
+ execute: async ({ path: filePath, namePath, checkReferences, maxResults }) => {
242
+ const resolved = await serverFor(filePath);
243
+ if (!resolved.ok)
244
+ return resolved;
245
+ try {
246
+ return { ok: true, server: resolved.server.name, path: filePath, groups: await lspDiagnosticsForSymbol(resolved.server, filePath, namePath, checkReferences, maxResults, pool) };
180
247
  }
181
248
  catch (error) {
182
249
  return lspFailure(error);
@@ -185,3 +252,21 @@ export function buildLspTools(pool) {
185
252
  }),
186
253
  };
187
254
  }
255
+ function locationTool(description, label, request, pool, max = 50) {
256
+ return tool({
257
+ description,
258
+ inputSchema: z.object({ ...locationSchema, maxResults: z.number().int().positive().max(max).default(Math.min(20, max)) }),
259
+ execute: async ({ path: filePath, line, column, maxResults }) => {
260
+ const resolved = await serverFor(filePath);
261
+ if (!resolved.ok)
262
+ return resolved;
263
+ try {
264
+ const locations = await request(resolved.server, filePath, line, column, maxResults, pool);
265
+ return { ok: true, server: resolved.server.name, path: filePath, locations, truncated: locations.length >= maxResults, query: label };
266
+ }
267
+ catch (error) {
268
+ return lspFailure(error);
269
+ }
270
+ },
271
+ });
272
+ }
@@ -8,6 +8,7 @@ import { WorkspaceMutationPolicy } from '../core/subagent/workspaceMutationPolic
8
8
  import { type LoadedMcpTools } from './mcp.js';
9
9
  import { createSubagentTool } from '../core/subagent/subagentRunner.js';
10
10
  import type { ContextFile } from '../config/contextFiles.js';
11
+ import type { PostMutationDiagnostics } from './tools/toolContext.js';
11
12
  export type ToolCategory = 'builtin' | 'lsp' | 'skill' | 'subagent' | 'mcp';
12
13
  /** Model type accepted by the subagent tool; derived so this module stays decoupled. */
13
14
  export type RequestModel = NonNullable<Parameters<typeof createSubagentTool>[0]['model']>;
@@ -21,8 +22,6 @@ export interface TurnExecutionScope {
21
22
  coordinator: SubagentCoordinator;
22
23
  mutationPolicy: WorkspaceMutationPolicy;
23
24
  }
24
- /** Keep the common coding path lean while preserving explicitly relevant capabilities. */
25
- export declare function selectToolsForRequest(tools: ToolSet, request?: string): ToolSet;
26
25
  export interface AssembledRequestContext {
27
26
  systemPrompt: string;
28
27
  availableTools: ToolSet;
@@ -31,6 +30,8 @@ export interface AssembledRequestContext {
31
30
  loadedMcp?: LoadedMcpTools;
32
31
  /** Turn-scoped LSP client pool; callers close it once the turn/context is done. */
33
32
  lspPool?: LspPool;
33
+ /** Bounded automatic diagnostics attached to successful file-mutation results. */
34
+ postMutationDiagnostics?: PostMutationDiagnostics;
34
35
  executionScope: TurnExecutionScope;
35
36
  }
36
37
  /**
@@ -1,5 +1,5 @@
1
1
  import { hazeTools } from './hazeTools.js';
2
- import { buildLspTools } from './lspTools.js';
2
+ import { buildLspTools, createPostMutationDiagnostics } from './lspTools.js';
3
3
  import { LspPool } from './lsp/pool.js';
4
4
  import { buildSystemPrompt } from './systemPrompt.js';
5
5
  import { readSettings } from '../config/settings.js';
@@ -18,7 +18,7 @@ import { createSubagentTool } from '../core/subagent/subagentRunner.js';
18
18
  import { addCapabilityTools } from './capabilities.js';
19
19
  const ALWAYS_AVAILABLE_TOOLS = new Set(['listFiles', 'readFile', 'grep', 'replaceLines', 'writeFile', 'editFile', 'shell', 'writeTasks', 'readToolOutput', 'skill']);
20
20
  /** Keep the common coding path lean while preserving explicitly relevant capabilities. */
21
- export function selectToolsForRequest(tools, request) {
21
+ function selectToolsForRequest(tools, request) {
22
22
  if (request === undefined)
23
23
  return tools;
24
24
  const lower = request.toLowerCase();
@@ -56,7 +56,8 @@ export async function assembleRequestContext(input) {
56
56
  if (!isSkillEnabled(settings, name, skill.source))
57
57
  enabledSkills.delete(name);
58
58
  }
59
- const hasInstalledLsp = (await installedLspServers(settings)).length > 0;
59
+ const installedLsp = await installedLspServers(settings);
60
+ const hasInstalledLsp = installedLsp.length > 0;
60
61
  const profileName = input.subagentOverrides?.profile ?? settings.subagents?.defaultProfile;
61
62
  const profile = resolveExecutionProfile(profileName, settings.subagents?.profiles, input.subagentOverrides?.maxConcurrency);
62
63
  const executionScope = input.executionScope ?? {
@@ -106,5 +107,8 @@ export async function assembleRequestContext(input) {
106
107
  const skillErrors = (skillRegistry.errors ?? []).map(error => `${error.source ? `${error.source}/` : ''}${error.directory}: ${error.message}`);
107
108
  const model = input.modelRuntime?.config ? { provider: input.modelRuntime.config.providerName, name: input.modelRuntime.config.modelName } : undefined;
108
109
  const systemPrompt = `${buildSystemPrompt(input.contextFiles, input.session, { lspAvailable: hasInstalledLsp, mcpAvailable, model, availableTools: new Set(Object.keys(availableTools)) })}${skillErrors.length ? `\n\n<skill-load-errors>\nInvalid skills were isolated:\n${skillErrors.map(error => `- ${error}`).join('\n')}\n</skill-load-errors>` : ''}`;
109
- return { systemPrompt, availableTools, toolCategories, loadedMcp, lspPool, executionScope };
110
+ return {
111
+ systemPrompt, availableTools, toolCategories, loadedMcp, lspPool, executionScope,
112
+ ...(lspPool ? { postMutationDiagnostics: createPostMutationDiagnostics(installedLsp, lspPool) } : {}),
113
+ };
110
114
  }
@@ -15,7 +15,7 @@ export function buildSystemPrompt(contextFiles = [], session, options = {}) {
15
15
  const date = (session?.start ?? new Date()).toISOString().slice(0, 10);
16
16
  const cwd = (session?.cwd ?? process.cwd()).replace(/\\/g, '/');
17
17
  const lspToolRule = options.lspAvailable
18
- ? '- When LSP tools are available for a file type, prefer them for semantic code navigation. For a named symbol, try lspWorkspaceSymbols first; if it reports no project, returns no useful result, or the workspace may not be indexed, do not inspect config repeatedly — use grep/listFiles to find likely files, then lspSymbols on those files. Treat lspSymbols results as definitions when they contain the named symbol. Use lspDefinition/lspTypeDefinition/lspImplementation/lspReferences only when you have an exact line/column at a real symbol occurrence. lspDiagnostics is a quick read-only check of one touched file; the relevant build/test command remains the authoritative validation. Fall back to grep/readFile when LSP is unavailable or text search is the better fit.\n'
18
+ ? '- When LSP tools are available for a file type, prefer them for semantic code navigation. Use lspWorkspaceSymbols to discover an unknown defining file, then lspFindSymbol with a file-scoped hierarchical name path for targeted children, body, or signature retrieval. Use position-based definition/type/implementation queries only at real symbol occurrences. Prefer lspReferences for impact context, lspRenameSymbol for semantic renames, and lspSafeDeleteSymbol for checked removals. Successful file-mutation results already include automatic LSP diagnostics for supported changed files; do not immediately repeat them with lspDiagnostics. lspDiagnosticsForSymbol is a focused intermediate check; relevant tests/typechecks remain authoritative. Fall back to grep/readFile and textual edits when LSP is unavailable or unsuitable.\n'
19
19
  : '';
20
20
  const mcpToolRule = options.mcpAvailable
21
21
  ? '- MCP server tools (e.g. Context7 docs lookup) are available when configured via /mcp. They extend the toolset with external capabilities; use them when the user asks for up-to-date docs or library info those tools expose, instead of guessing from memory.\n'
@@ -44,7 +44,7 @@ export function buildSystemPrompt(contextFiles = [], session, options = {}) {
44
44
  ## Tool use
45
45
  ${lspToolRule}${mcpToolRule}- ${UNTRUSTED_TOOL_OUTPUT_RULE}
46
46
  - grep locates text patterns and non-semantic matches. listFiles discovers structure. readFile returns bounded numbered lines with nextOffset for pagination.
47
- - editFile performs unique replacements. If an edit fails, read that exact file again before retrying; use replaceLines when current line numbers are safer.
47
+ - editFile performs unique replacements. If an edit fails, read that exact file again before retrying; use replaceLines when current line numbers are safer. For repeated cross-file text changes, use replaceInFiles with a dry run and current occurrence IDs or an expected-count guard.
48
48
  - writeFile creates files and only overwrites when explicitly requested. Before a complete rewrite of a requested path that may already exist, read it, then use overwriteExisting=true. Keep each content payload within the tool's byte limit; for larger files, write the first chunk normally and continue the same file with append=true. Never split one logical file into imported part files merely to bypass the limit. shell runs inspection, scripts, and validation; set purpose=validation for custom assertion/check commands so their real exit result counts as completion evidence. Use background=true only when managed process tools are available${processRule}. readToolOutput retrieves omitted oversized command output.
49
49
  ${fetchRule}${subagentRule}${coordinationRule ? `- ${coordinationRule}\n` : ''}
50
50
  - Prefer targeted reads and checks. Do not repeat unchanged reads or failing validation without a relevant change. When several independent files are already known, read them together instead of discovering them one model step at a time.
@@ -1,4 +1,5 @@
1
1
  export declare const fetchTool: ({
2
+ deferLoading?: boolean;
2
3
  title?: string;
3
4
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
4
5
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -307,6 +308,7 @@ export declare const fetchTool: ({
307
308
  parseTier: string;
308
309
  }, NoInfer<import("./toolContext.js").HazeToolContext>>;
309
310
  }) | ({
311
+ deferLoading?: boolean;
310
312
  title?: string;
311
313
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
312
314
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -615,6 +617,7 @@ export declare const fetchTool: ({
615
617
  parseTier: string;
616
618
  }, NoInfer<import("./toolContext.js").HazeToolContext>>;
617
619
  }) | ({
620
+ deferLoading?: boolean;
618
621
  title?: string;
619
622
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
620
623
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -915,6 +918,7 @@ export declare const fetchTool: ({
915
918
  parseTier: string;
916
919
  }, NoInfer<import("./toolContext.js").HazeToolContext>>;
917
920
  }) | ({
921
+ deferLoading?: boolean;
918
922
  title?: string;
919
923
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
920
924
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -1,4 +1,5 @@
1
1
  export declare const processTool: ({
2
+ deferLoading?: boolean;
2
3
  title?: string;
3
4
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
4
5
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -273,6 +274,7 @@ export declare const processTool: ({
273
274
  processes?: undefined;
274
275
  }, NoInfer<import("./toolContext.js").HazeToolContext>>;
275
276
  }) | ({
277
+ deferLoading?: boolean;
276
278
  title?: string;
277
279
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
278
280
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -547,6 +549,7 @@ export declare const processTool: ({
547
549
  processes?: undefined;
548
550
  }, NoInfer<import("./toolContext.js").HazeToolContext>>;
549
551
  }) | ({
552
+ deferLoading?: boolean;
550
553
  title?: string;
551
554
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
552
555
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -811,6 +814,7 @@ export declare const processTool: ({
811
814
  processes?: undefined;
812
815
  }, NoInfer<import("./toolContext.js").HazeToolContext>>;
813
816
  }) | ({
817
+ deferLoading?: boolean;
814
818
  title?: string;
815
819
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
816
820
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -0,0 +1,105 @@
1
+ import type { ToolExecutionContext } from './toolContext.js';
2
+ export interface ReplaceInFilesInput {
3
+ path: string;
4
+ needle: string;
5
+ replacement: string;
6
+ mode: 'literal' | 'regex';
7
+ includeGlob?: string;
8
+ excludeGlob?: string;
9
+ dryRun: boolean;
10
+ occurrenceIds?: string[];
11
+ expectedCount?: number;
12
+ }
13
+ export declare function replaceInFiles(input: ReplaceInFilesInput, context: ToolExecutionContext): Promise<{
14
+ ok: boolean;
15
+ toolName: string;
16
+ path: string;
17
+ error: string;
18
+ reasonCode: "scoped_instructions_discovered";
19
+ recoverable: boolean;
20
+ suggestedNextStep: string;
21
+ applicableProjectInstructions: import("../../config/contextFiles.js").ContextFile[];
22
+ } | {
23
+ occurrenceHandle?: string | undefined;
24
+ skippedFiles: number;
25
+ occurrences: {
26
+ before: string;
27
+ after: string;
28
+ id: string;
29
+ path: string;
30
+ line: number;
31
+ }[];
32
+ occurrencesTruncated: boolean;
33
+ ok: boolean;
34
+ dryRun: boolean;
35
+ occurrenceCount: number;
36
+ fileCount: number;
37
+ error?: undefined;
38
+ staleOccurrenceIds?: undefined;
39
+ recoverable?: undefined;
40
+ suggestedNextStep?: undefined;
41
+ changedPaths?: undefined;
42
+ uncertainPaths?: undefined;
43
+ } | {
44
+ recoverable: boolean;
45
+ occurrenceHandle?: string | undefined;
46
+ skippedFiles: number;
47
+ occurrences: {
48
+ before: string;
49
+ after: string;
50
+ id: string;
51
+ path: string;
52
+ line: number;
53
+ }[];
54
+ occurrencesTruncated: boolean;
55
+ ok: boolean;
56
+ error: string;
57
+ staleOccurrenceIds?: undefined;
58
+ suggestedNextStep?: undefined;
59
+ changedPaths?: undefined;
60
+ uncertainPaths?: undefined;
61
+ } | {
62
+ ok: boolean;
63
+ error: string;
64
+ staleOccurrenceIds: string[];
65
+ recoverable: boolean;
66
+ suggestedNextStep: string;
67
+ changedPaths?: undefined;
68
+ uncertainPaths?: undefined;
69
+ } | {
70
+ ok: boolean;
71
+ error: string;
72
+ recoverable: boolean;
73
+ staleOccurrenceIds?: undefined;
74
+ suggestedNextStep?: undefined;
75
+ changedPaths?: undefined;
76
+ uncertainPaths?: undefined;
77
+ } | {
78
+ ok: boolean;
79
+ changedPaths: string[];
80
+ uncertainPaths: string[];
81
+ error: string;
82
+ recoverable: boolean;
83
+ suggestedNextStep: string;
84
+ staleOccurrenceIds?: undefined;
85
+ } | {
86
+ diffHandle?: string | undefined;
87
+ ok: boolean;
88
+ dryRun: boolean;
89
+ changedPaths: string[];
90
+ noChange: boolean;
91
+ occurrenceCount: number;
92
+ fileCount: number;
93
+ diffLineCount: number;
94
+ files: {
95
+ diff: import("../toolResultTypes.js").ToolDiffLine[];
96
+ addedLines: number;
97
+ removedLines: number;
98
+ path: string;
99
+ }[];
100
+ error?: undefined;
101
+ staleOccurrenceIds?: undefined;
102
+ recoverable?: undefined;
103
+ suggestedNextStep?: undefined;
104
+ uncertainPaths?: undefined;
105
+ }>;