@denizokcu/haze 0.9.0 → 0.11.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 (241) hide show
  1. package/CHANGELOG.md +133 -17
  2. package/README.md +164 -68
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  9. package/dist/cli/chat/chatMetrics.js +22 -5
  10. package/dist/cli/chat/contextReport.d.ts +11 -0
  11. package/dist/cli/chat/contextReport.js +46 -0
  12. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  13. package/dist/cli/chat/fileMentionSuggestions.js +92 -0
  14. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  15. package/dist/cli/chat/inputSuggestions.js +17 -3
  16. package/dist/cli/chat/liveRegion.d.ts +25 -0
  17. package/dist/cli/chat/liveRegion.js +48 -0
  18. package/dist/cli/chat/messages.d.ts +33 -2
  19. package/dist/cli/chat/messages.js +216 -33
  20. package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
  21. package/dist/cli/chat/sessionLifecycle.js +205 -0
  22. package/dist/cli/chat/sessionRecorder.js +80 -14
  23. package/dist/cli/chat/startupInfo.js +11 -4
  24. package/dist/cli/chat/tips.d.ts +21 -0
  25. package/dist/cli/chat/tips.js +43 -0
  26. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  27. package/dist/cli/chat/wizardDispatch.js +744 -0
  28. package/dist/cli/commands/chat.d.ts +6 -0
  29. package/dist/cli/commands/chat.js +373 -790
  30. package/dist/cli/commands/chatModes.d.ts +1 -1
  31. package/dist/cli/commands/chatModes.js +7 -2
  32. package/dist/cli/commands/commandHelp.js +5 -3
  33. package/dist/cli/commands/commands.d.ts +5 -2
  34. package/dist/cli/commands/commands.js +22 -18
  35. package/dist/cli/commands/doctor.d.ts +19 -0
  36. package/dist/cli/commands/doctor.js +76 -0
  37. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  38. package/dist/cli/commands/fleetCommand.js +46 -0
  39. package/dist/cli/commands/formatters.d.ts +5 -0
  40. package/dist/cli/commands/formatters.js +35 -6
  41. package/dist/cli/commands/logsCommand.js +1 -7
  42. package/dist/cli/commands/modelCommand.js +1 -1
  43. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  44. package/dist/cli/commands/ndjsonSink.js +38 -0
  45. package/dist/cli/commands/providerWizard.d.ts +10 -2
  46. package/dist/cli/commands/providerWizard.js +50 -4
  47. package/dist/cli/commands/runCommand.d.ts +4 -0
  48. package/dist/cli/commands/runCommand.js +142 -16
  49. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  50. package/dist/cli/commands/sessionPicker.js +29 -0
  51. package/dist/cli/commands/settingsSummary.js +6 -4
  52. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  53. package/dist/cli/commands/skillWizard.d.ts +2 -0
  54. package/dist/cli/commands/skillWizard.js +16 -6
  55. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  56. package/dist/cli/commands/streaming/abortCause.js +16 -0
  57. package/dist/cli/commands/streaming/assistantText.js +9 -2
  58. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  59. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  61. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  62. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  63. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  64. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  66. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
  68. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  69. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  70. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  71. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  73. package/dist/cli/commands/streaming.d.ts +82 -3
  74. package/dist/cli/commands/streaming.js +528 -91
  75. package/dist/cli/commands/wizardActions.d.ts +7 -0
  76. package/dist/cli/commands/wizardActions.js +7 -0
  77. package/dist/cli/commands/wizardPrompts.js +7 -1
  78. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  79. package/dist/cli/commands/wizardSuggestions.js +64 -14
  80. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  81. package/dist/cli/commands/wizardTransition.js +1 -2
  82. package/dist/cli/index.js +82 -22
  83. package/dist/cli/terminalTitle.d.ts +6 -0
  84. package/dist/cli/terminalTitle.js +36 -0
  85. package/dist/config/inputHistory.d.ts +3 -3
  86. package/dist/config/inputHistory.js +12 -18
  87. package/dist/config/modelDiscovery.d.ts +71 -0
  88. package/dist/config/modelDiscovery.js +214 -0
  89. package/dist/config/privateStorage.js +28 -2
  90. package/dist/config/providerAuth.d.ts +14 -0
  91. package/dist/config/providerAuth.js +49 -0
  92. package/dist/config/providerPresets.d.ts +49 -5
  93. package/dist/config/providerPresets.js +573 -73
  94. package/dist/config/providers.d.ts +2 -0
  95. package/dist/config/providers.js +9 -0
  96. package/dist/config/settings.d.ts +58 -0
  97. package/dist/config/settings.js +38 -1
  98. package/dist/config/skillSettings.d.ts +6 -13
  99. package/dist/config/skillSettings.js +20 -19
  100. package/dist/core/agent/budgets.d.ts +36 -0
  101. package/dist/core/agent/budgets.js +44 -0
  102. package/dist/core/agent/compaction.d.ts +38 -0
  103. package/dist/core/agent/compaction.js +108 -19
  104. package/dist/core/agent/completionController.d.ts +230 -0
  105. package/dist/core/agent/completionController.js +287 -0
  106. package/dist/core/agent/contextBudget.d.ts +46 -0
  107. package/dist/core/agent/contextBudget.js +89 -7
  108. package/dist/core/agent/errors.js +6 -2
  109. package/dist/core/agent/events.d.ts +86 -0
  110. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  111. package/dist/core/agent/reasoningPolicy.js +27 -0
  112. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  113. package/dist/core/agent/toolCapabilities.js +58 -0
  114. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  115. package/dist/core/agent/toolExecutionBudget.js +49 -0
  116. package/dist/core/agent/toolOutputStore.d.ts +13 -0
  117. package/dist/core/agent/toolOutputStore.js +27 -10
  118. package/dist/core/agent/toolResults.d.ts +12 -0
  119. package/dist/core/agent/toolResults.js +38 -0
  120. package/dist/core/agent/turnBudget.d.ts +35 -0
  121. package/dist/core/agent/turnBudget.js +27 -0
  122. package/dist/core/agent/turnPolicy.d.ts +11 -0
  123. package/dist/core/agent/turnPolicy.js +19 -0
  124. package/dist/core/agent/workState.d.ts +76 -1
  125. package/dist/core/agent/workState.js +120 -13
  126. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  127. package/dist/core/attachments/imageAttachments.js +245 -0
  128. package/dist/core/attachments/readBlessings.d.ts +37 -0
  129. package/dist/core/attachments/readBlessings.js +79 -0
  130. package/dist/core/deadline.d.ts +33 -0
  131. package/dist/core/deadline.js +74 -0
  132. package/dist/core/goal/completionPolicy.d.ts +27 -0
  133. package/dist/core/goal/completionPolicy.js +37 -1
  134. package/dist/core/goal/requestClassifier.d.ts +0 -3
  135. package/dist/core/goal/requestClassifier.js +0 -13
  136. package/dist/core/io/boundedRead.js +76 -29
  137. package/dist/core/limits/byteBudgets.d.ts +7 -0
  138. package/dist/core/limits/byteBudgets.js +7 -0
  139. package/dist/core/limits/textBudgets.d.ts +25 -0
  140. package/dist/core/limits/textBudgets.js +25 -0
  141. package/dist/core/log/llmLog.js +7 -0
  142. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  143. package/dist/core/persistence/orderedFileWriter.js +16 -2
  144. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  145. package/dist/core/process/backgroundRegistry.js +195 -0
  146. package/dist/core/process/runBoundedProcess.d.ts +9 -0
  147. package/dist/core/process/runBoundedProcess.js +74 -29
  148. package/dist/core/safety/missingExecutable.d.ts +42 -0
  149. package/dist/core/safety/missingExecutable.js +77 -0
  150. package/dist/core/safety/urlGuard.d.ts +2 -1
  151. package/dist/core/safety/urlGuard.js +3 -2
  152. package/dist/core/session/sessionSlimming.js +47 -4
  153. package/dist/core/session/sessionStore.d.ts +74 -0
  154. package/dist/core/session/sessionStore.js +268 -18
  155. package/dist/core/subagent/contracts.d.ts +120 -0
  156. package/dist/core/subagent/contracts.js +55 -0
  157. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  158. package/dist/core/subagent/executionProfiles.js +45 -0
  159. package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
  160. package/dist/core/subagent/subagentCoordinator.js +164 -0
  161. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  162. package/dist/core/subagent/subagentRunner.js +208 -98
  163. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  164. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  165. package/dist/core/tasks/taskStorage.js +12 -1
  166. package/dist/llm/client.d.ts +36 -29
  167. package/dist/llm/client.js +102 -33
  168. package/dist/llm/hazeTools.d.ts +2559 -150
  169. package/dist/llm/hazeTools.js +119 -31
  170. package/dist/llm/lsp.d.ts +26 -4
  171. package/dist/llm/lsp.js +90 -14
  172. package/dist/llm/lspTools.d.ts +2366 -0
  173. package/dist/llm/lspTools.js +87 -79
  174. package/dist/llm/openaiCodex.d.ts +3 -0
  175. package/dist/llm/openaiCodex.js +47 -0
  176. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  177. package/dist/llm/openaiCodexOAuth.js +214 -0
  178. package/dist/llm/requestContext.d.ts +25 -1
  179. package/dist/llm/requestContext.js +51 -8
  180. package/dist/llm/systemPrompt.d.ts +15 -1
  181. package/dist/llm/systemPrompt.js +24 -8
  182. package/dist/llm/toolResultTypes.d.ts +8 -1
  183. package/dist/llm/tools/bashTool.d.ts +906 -32
  184. package/dist/llm/tools/bashTool.js +30 -4
  185. package/dist/llm/tools/editMatch.d.ts +14 -0
  186. package/dist/llm/tools/editMatch.js +72 -0
  187. package/dist/llm/tools/failures.d.ts +2 -0
  188. package/dist/llm/tools/failures.js +1 -0
  189. package/dist/llm/tools/fetchTool.d.ts +42 -26
  190. package/dist/llm/tools/fetchTool.js +1 -1
  191. package/dist/llm/tools/fileToolShared.d.ts +6 -4
  192. package/dist/llm/tools/fileToolShared.js +18 -23
  193. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  194. package/dist/llm/tools/gitIgnore.js +129 -0
  195. package/dist/llm/tools/grepRunner.d.ts +5 -0
  196. package/dist/llm/tools/grepRunner.js +52 -71
  197. package/dist/llm/tools/outputCap.d.ts +2 -6
  198. package/dist/llm/tools/outputCap.js +2 -6
  199. package/dist/llm/tools/processTool.d.ts +1077 -0
  200. package/dist/llm/tools/processTool.js +41 -0
  201. package/dist/llm/tools/readRecovery.d.ts +10 -0
  202. package/dist/llm/tools/readRecovery.js +135 -0
  203. package/dist/llm/tools/toolContext.d.ts +9 -1
  204. package/dist/llm/tools/toolContext.js +83 -43
  205. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  206. package/dist/llm/tools/workspaceFile.js +33 -4
  207. package/dist/llm/webFetch.d.ts +17 -0
  208. package/dist/llm/webFetch.js +66 -86
  209. package/dist/llm/workerContext.d.ts +18 -0
  210. package/dist/llm/workerContext.js +55 -0
  211. package/dist/skills/SkillLoader.d.ts +2 -2
  212. package/dist/skills/SkillRegistry.d.ts +3 -2
  213. package/dist/skills/SkillRegistry.js +43 -13
  214. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  215. package/dist/skills/builder/SkillBuilder.js +23 -5
  216. package/dist/skills/skillTools.js +11 -4
  217. package/dist/skills/types.d.ts +6 -1
  218. package/dist/ui/codeHighlight.d.ts +4 -0
  219. package/dist/ui/codeHighlight.js +31 -0
  220. package/dist/ui/components/Header.d.ts +1 -1
  221. package/dist/ui/components/MarkdownText.d.ts +16 -2
  222. package/dist/ui/components/MarkdownText.js +244 -34
  223. package/dist/ui/components/TextInput.d.ts +12 -2
  224. package/dist/ui/components/TextInput.js +80 -8
  225. package/dist/ui/theme.d.ts +4 -3
  226. package/dist/ui/theme.js +5 -4
  227. package/dist/utils/buildInfo.d.ts +104 -0
  228. package/dist/utils/buildInfo.js +253 -0
  229. package/dist/utils/format.d.ts +2 -0
  230. package/dist/utils/format.js +8 -0
  231. package/dist/utils/fs.d.ts +9 -1
  232. package/dist/utils/fs.js +87 -29
  233. package/dist/utils/openPath.d.ts +2 -0
  234. package/dist/utils/openPath.js +22 -0
  235. package/dist/utils/path.d.ts +2 -0
  236. package/dist/utils/path.js +5 -1
  237. package/dist/utils/utf8.d.ts +22 -0
  238. package/dist/utils/utf8.js +54 -0
  239. package/dist/utils/version.d.ts +9 -3
  240. package/dist/utils/version.js +28 -2
  241. package/package.json +24 -19
@@ -30,86 +30,94 @@ function lspFailure(error) {
30
30
  const message = error instanceof Error ? error.message : String(error);
31
31
  return { ok: false, error: cleanLspError(message) };
32
32
  }
33
- export const lspTools = {
34
- lspWorkspaceSymbols: tool({
35
- 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.',
36
- inputSchema: z.object({
37
- query: z.string().min(1).describe('Symbol name or prefix to search for'),
38
- server: z.string().optional().describe('Optional configured LSP server name. If omitted, the first enabled server is used.'),
39
- maxSymbols: z.number().int().positive().max(100).default(50).describe('Maximum symbols to return'),
33
+ export const lspTools = buildLspTools();
34
+ /**
35
+ * Build the LSP tool set bound to a shared turn-scoped client pool so repeated
36
+ * symbols/definition/references calls reuse one initialized server and its
37
+ * opened documents instead of paying startup + indexing per call (RH-009).
38
+ */
39
+ export function buildLspTools(pool) {
40
+ return {
41
+ lspWorkspaceSymbols: tool({
42
+ 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.',
43
+ inputSchema: z.object({
44
+ query: z.string().min(1).describe('Symbol name or prefix to search for'),
45
+ server: z.string().optional().describe('Optional configured LSP server name. If omitted, the first enabled server is used.'),
46
+ maxSymbols: z.number().int().positive().max(100).default(50).describe('Maximum symbols to return'),
47
+ }),
48
+ execute: async ({ query, server: serverName, maxSymbols }) => {
49
+ const server = await namedOrFirstServer(serverName);
50
+ if (!server)
51
+ return { ok: false, error: serverName ? `No enabled LSP server named ${serverName}.` : 'No enabled LSP server configured. Use /lsp add <preset>.' };
52
+ try {
53
+ const symbols = await lspWorkspaceSymbols(server, query, maxSymbols, pool);
54
+ return { ok: true, server: server.name, query, symbols, truncated: symbols.length >= maxSymbols };
55
+ }
56
+ catch (error) {
57
+ return lspFailure(error);
58
+ }
59
+ },
40
60
  }),
41
- execute: async ({ query, server: serverName, maxSymbols }) => {
42
- const server = await namedOrFirstServer(serverName);
43
- if (!server)
44
- return { ok: false, error: serverName ? `No enabled LSP server named ${serverName}.` : 'No enabled LSP server configured. Use /lsp add <preset>.' };
45
- try {
46
- const symbols = await lspWorkspaceSymbols(server, query, maxSymbols);
47
- return { ok: true, server: server.name, query, symbols, truncated: symbols.length >= maxSymbols };
48
- }
49
- catch (error) {
50
- return lspFailure(error);
51
- }
52
- },
53
- }),
54
- lspSymbols: tool({
55
- 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.',
56
- inputSchema: z.object({
57
- path: z.string().min(1).describe('Workspace-relative source file path'),
58
- maxSymbols: z.number().int().positive().max(200).default(80).describe('Maximum symbols to return'),
61
+ lspSymbols: tool({
62
+ 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.',
63
+ inputSchema: z.object({
64
+ path: z.string().min(1).describe('Workspace-relative source file path'),
65
+ maxSymbols: z.number().int().positive().max(200).default(80).describe('Maximum symbols to return'),
66
+ }),
67
+ execute: async ({ path: filePath, maxSymbols }) => {
68
+ const server = await serverFor(filePath);
69
+ if (!server)
70
+ return noServer(filePath);
71
+ try {
72
+ const symbols = await lspDocumentSymbols(server, filePath, maxSymbols, pool);
73
+ return { ok: true, server: server.name, path: filePath, symbols, truncated: symbols.length >= maxSymbols };
74
+ }
75
+ catch (error) {
76
+ return lspFailure(error);
77
+ }
78
+ },
59
79
  }),
60
- execute: async ({ path: filePath, maxSymbols }) => {
61
- const server = await serverFor(filePath);
62
- if (!server)
63
- return noServer(filePath);
64
- try {
65
- const symbols = await lspDocumentSymbols(server, filePath, maxSymbols);
66
- return { ok: true, server: server.name, path: filePath, symbols, truncated: symbols.length >= maxSymbols };
67
- }
68
- catch (error) {
69
- return lspFailure(error);
70
- }
71
- },
72
- }),
73
- lspDefinition: tool({
74
- description: 'Use a configured language server to find the definition at a 1-based line/column in a source file. Read-only.',
75
- inputSchema: z.object({
76
- path: z.string().min(1).describe('Workspace-relative source file path'),
77
- line: z.number().int().positive().describe('1-based line number'),
78
- column: z.number().int().positive().describe('1-based column/character number'),
79
- maxResults: z.number().int().positive().max(50).default(20).describe('Maximum locations to return'),
80
+ lspDefinition: tool({
81
+ description: 'Use a configured language server to find the definition at a 1-based line/column in a source file. Read-only.',
82
+ inputSchema: z.object({
83
+ path: z.string().min(1).describe('Workspace-relative source file path'),
84
+ line: z.number().int().positive().describe('1-based line number'),
85
+ column: z.number().int().positive().describe('1-based column/character number'),
86
+ maxResults: z.number().int().positive().max(50).default(20).describe('Maximum locations to return'),
87
+ }),
88
+ execute: async ({ path: filePath, line, column, maxResults }) => {
89
+ const server = await serverFor(filePath);
90
+ if (!server)
91
+ return noServer(filePath);
92
+ try {
93
+ const locations = await lspDefinition(server, filePath, line, column, maxResults, pool);
94
+ return { ok: true, server: server.name, path: filePath, locations, truncated: locations.length >= maxResults };
95
+ }
96
+ catch (error) {
97
+ return lspFailure(error);
98
+ }
99
+ },
80
100
  }),
81
- execute: async ({ path: filePath, line, column, maxResults }) => {
82
- const server = await serverFor(filePath);
83
- if (!server)
84
- return noServer(filePath);
85
- try {
86
- const locations = await lspDefinition(server, filePath, line, column, maxResults);
87
- return { ok: true, server: server.name, path: filePath, locations, truncated: locations.length >= maxResults };
88
- }
89
- catch (error) {
90
- return lspFailure(error);
91
- }
92
- },
93
- }),
94
- lspReferences: tool({
95
- description: 'Use a configured language server to find references at a 1-based line/column in a source file. Read-only.',
96
- inputSchema: z.object({
97
- path: z.string().min(1).describe('Workspace-relative source file path'),
98
- line: z.number().int().positive().describe('1-based line number'),
99
- column: z.number().int().positive().describe('1-based column/character number'),
100
- maxResults: z.number().int().positive().max(100).default(50).describe('Maximum locations to return'),
101
+ lspReferences: tool({
102
+ description: 'Use a configured language server to find references at a 1-based line/column in a source file. Read-only.',
103
+ inputSchema: z.object({
104
+ path: z.string().min(1).describe('Workspace-relative source file path'),
105
+ line: z.number().int().positive().describe('1-based line number'),
106
+ column: z.number().int().positive().describe('1-based column/character number'),
107
+ maxResults: z.number().int().positive().max(100).default(50).describe('Maximum locations to return'),
108
+ }),
109
+ execute: async ({ path: filePath, line, column, maxResults }) => {
110
+ const server = await serverFor(filePath);
111
+ if (!server)
112
+ return noServer(filePath);
113
+ try {
114
+ const locations = await lspReferences(server, filePath, line, column, maxResults, pool);
115
+ return { ok: true, server: server.name, path: filePath, locations, truncated: locations.length >= maxResults };
116
+ }
117
+ catch (error) {
118
+ return lspFailure(error);
119
+ }
120
+ },
101
121
  }),
102
- execute: async ({ path: filePath, line, column, maxResults }) => {
103
- const server = await serverFor(filePath);
104
- if (!server)
105
- return noServer(filePath);
106
- try {
107
- const locations = await lspReferences(server, filePath, line, column, maxResults);
108
- return { ok: true, server: server.name, path: filePath, locations, truncated: locations.length >= maxResults };
109
- }
110
- catch (error) {
111
- return lspFailure(error);
112
- }
113
- },
114
- }),
115
- };
122
+ };
123
+ }
@@ -0,0 +1,3 @@
1
+ export declare function createChatGptCodexFetch(providerName: string, fetchImpl?: typeof fetch): typeof fetch;
2
+ /** Test-only reset for process-global refresh deduplication. */
3
+ export declare function clearChatGptRefreshes(): void;
@@ -0,0 +1,47 @@
1
+ import { getProviderAuth, setProviderAuth } from '../config/providerAuth.js';
2
+ import { CHATGPT_CODEX_RESPONSES_URL, refreshChatGptAuth } from './openaiCodexOAuth.js';
3
+ const REFRESH_MARGIN_MS = 60_000;
4
+ const refreshes = new Map();
5
+ async function currentAuth(providerName) {
6
+ const stored = await getProviderAuth(providerName);
7
+ if (!stored || stored.type !== 'oauth')
8
+ throw new Error(`ChatGPT is not connected for provider ${providerName}. Run /provider and choose "sign in with ChatGPT".`);
9
+ if (stored.expires > Date.now() + REFRESH_MARGIN_MS)
10
+ return stored;
11
+ let pending = refreshes.get(providerName);
12
+ if (!pending) {
13
+ pending = refreshChatGptAuth(stored)
14
+ .then(async (auth) => {
15
+ // Re-read the store before writing back so a concurrent sign-out on
16
+ // another haze instance (or this one) wins. Without this, an in-flight
17
+ // refresh would resurrect credentials the user just removed.
18
+ const current = await getProviderAuth(providerName);
19
+ if (!current || current.type !== 'oauth')
20
+ return auth;
21
+ await setProviderAuth(providerName, auth);
22
+ return auth;
23
+ })
24
+ .finally(() => refreshes.delete(providerName));
25
+ refreshes.set(providerName, pending);
26
+ }
27
+ return pending;
28
+ }
29
+ function authenticatedHeaders(init, auth) {
30
+ const headers = new Headers(init?.headers);
31
+ headers.delete('authorization');
32
+ headers.set('authorization', `Bearer ${auth.access}`);
33
+ if (auth.accountId)
34
+ headers.set('ChatGPT-Account-Id', auth.accountId);
35
+ headers.set('originator', 'haze');
36
+ return headers;
37
+ }
38
+ export function createChatGptCodexFetch(providerName, fetchImpl = fetch) {
39
+ return async (_input, init) => {
40
+ const auth = await currentAuth(providerName);
41
+ return fetchImpl(CHATGPT_CODEX_RESPONSES_URL, { ...init, headers: authenticatedHeaders(init, auth) });
42
+ };
43
+ }
44
+ /** Test-only reset for process-global refresh deduplication. */
45
+ export function clearChatGptRefreshes() {
46
+ refreshes.clear();
47
+ }
@@ -0,0 +1,54 @@
1
+ import type { OAuthProviderAuth } from '../config/providerAuth.js';
2
+ export declare const CHATGPT_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
3
+ export declare const CHATGPT_OAUTH_ISSUER = "https://auth.openai.com";
4
+ export declare const CHATGPT_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex";
5
+ export declare const CHATGPT_CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
6
+ export declare const CHATGPT_OAUTH_CALLBACK_PORT = 1455;
7
+ interface PkceCodes {
8
+ verifier: string;
9
+ challenge: string;
10
+ }
11
+ interface TokenResponse {
12
+ id_token?: string;
13
+ access_token?: string;
14
+ refresh_token?: string;
15
+ expires_in?: number;
16
+ }
17
+ export interface ChatGptBrowserLogin {
18
+ url: string;
19
+ complete: () => Promise<OAuthProviderAuth>;
20
+ close: () => Promise<void>;
21
+ }
22
+ export interface StartChatGptBrowserLoginOptions {
23
+ issuer?: string;
24
+ port?: number;
25
+ timeoutMs?: number;
26
+ fetchImpl?: typeof fetch;
27
+ signal?: AbortSignal;
28
+ }
29
+ export interface IdTokenClaims {
30
+ chatgpt_account_id?: string;
31
+ organizations?: Array<{
32
+ id: string;
33
+ }>;
34
+ 'https://api.openai.com/auth'?: {
35
+ chatgpt_account_id?: string;
36
+ };
37
+ }
38
+ export declare function generatePkce(): Promise<PkceCodes>;
39
+ export declare function buildChatGptAuthorizeUrl(input: {
40
+ issuer?: string;
41
+ redirectUri: string;
42
+ pkce: PkceCodes;
43
+ state: string;
44
+ }): string;
45
+ export declare function parseJwtClaims(token: string): IdTokenClaims | undefined;
46
+ export declare function extractChatGptAccountId(tokens: Pick<TokenResponse, 'id_token' | 'access_token'>): string | undefined;
47
+ export declare function refreshChatGptAuth(auth: OAuthProviderAuth, options?: {
48
+ issuer?: string;
49
+ fetchImpl?: typeof fetch;
50
+ signal?: AbortSignal;
51
+ }): Promise<OAuthProviderAuth>;
52
+ export declare function startChatGptBrowserLogin(options?: StartChatGptBrowserLoginOptions): Promise<ChatGptBrowserLogin>;
53
+ export declare function openBrowser(url: string): Promise<boolean>;
54
+ export {};
@@ -0,0 +1,214 @@
1
+ import crypto from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { openPath } from '../utils/openPath.js';
4
+ export const CHATGPT_OAUTH_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
5
+ export const CHATGPT_OAUTH_ISSUER = 'https://auth.openai.com';
6
+ export const CHATGPT_CODEX_BASE_URL = 'https://chatgpt.com/backend-api/codex';
7
+ export const CHATGPT_CODEX_RESPONSES_URL = `${CHATGPT_CODEX_BASE_URL}/responses`;
8
+ // Fixed by the registered ChatGPT OAuth client: the redirect_uri must match
9
+ // exactly. Do not switch to an ephemeral port — the auth server would reject
10
+ // the callback.
11
+ export const CHATGPT_OAUTH_CALLBACK_PORT = 1455;
12
+ const CALLBACK_PATH = '/auth/callback';
13
+ const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;
14
+ function base64UrlEncode(value) {
15
+ return Buffer.from(value instanceof Uint8Array ? value : new Uint8Array(value)).toString('base64url');
16
+ }
17
+ export async function generatePkce() {
18
+ const verifier = base64UrlEncode(crypto.randomBytes(32));
19
+ const challenge = base64UrlEncode(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));
20
+ return { verifier, challenge };
21
+ }
22
+ export function buildChatGptAuthorizeUrl(input) {
23
+ const params = new URLSearchParams({
24
+ response_type: 'code',
25
+ client_id: CHATGPT_OAUTH_CLIENT_ID,
26
+ redirect_uri: input.redirectUri,
27
+ scope: 'openid profile email offline_access',
28
+ code_challenge: input.pkce.challenge,
29
+ code_challenge_method: 'S256',
30
+ id_token_add_organizations: 'true',
31
+ codex_cli_simplified_flow: 'true',
32
+ state: input.state,
33
+ originator: 'haze',
34
+ });
35
+ return `${input.issuer ?? CHATGPT_OAUTH_ISSUER}/oauth/authorize?${params.toString()}`;
36
+ }
37
+ export function parseJwtClaims(token) {
38
+ const parts = token.split('.');
39
+ if (parts.length !== 3)
40
+ return undefined;
41
+ try {
42
+ return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ }
48
+ export function extractChatGptAccountId(tokens) {
49
+ for (const token of [tokens.id_token, tokens.access_token]) {
50
+ if (!token)
51
+ continue;
52
+ const claims = parseJwtClaims(token);
53
+ const accountId = claims?.chatgpt_account_id
54
+ ?? claims?.['https://api.openai.com/auth']?.chatgpt_account_id
55
+ ?? claims?.organizations?.[0]?.id;
56
+ if (accountId)
57
+ return accountId;
58
+ }
59
+ return undefined;
60
+ }
61
+ async function tokenRequest(issuer, body, fetchImpl, signal) {
62
+ const response = await fetchImpl(`${issuer}/oauth/token`, {
63
+ method: 'POST',
64
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
65
+ body: body.toString(),
66
+ signal,
67
+ });
68
+ if (!response.ok)
69
+ throw new Error(`ChatGPT token request failed with HTTP ${response.status}.`);
70
+ return response.json();
71
+ }
72
+ function credentialsFromTokens(tokens, previous) {
73
+ const access = tokens.access_token;
74
+ const refresh = tokens.refresh_token ?? previous?.refresh;
75
+ if (!access || !refresh)
76
+ throw new Error('ChatGPT authorization returned incomplete credentials. Sign in again.');
77
+ const extracted = extractChatGptAccountId(tokens);
78
+ // When the new tokens carry no account claim (e.g., an opaque access token
79
+ // without JWT claims), fall back to the previous accountId so refresh keeps
80
+ // the same account context. Theoretically stale if the user switched account
81
+ // since the original login; requires a fresh sign-in to correct.
82
+ const accountId = extracted ?? previous?.accountId;
83
+ return {
84
+ type: 'oauth',
85
+ access,
86
+ refresh,
87
+ expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
88
+ ...(accountId ? { accountId } : {}),
89
+ };
90
+ }
91
+ export async function refreshChatGptAuth(auth, options = {}) {
92
+ const tokens = await tokenRequest(options.issuer ?? CHATGPT_OAUTH_ISSUER, new URLSearchParams({
93
+ grant_type: 'refresh_token',
94
+ refresh_token: auth.refresh,
95
+ client_id: CHATGPT_OAUTH_CLIENT_ID,
96
+ }), options.fetchImpl ?? fetch, options.signal);
97
+ return credentialsFromTokens(tokens, auth);
98
+ }
99
+ function callbackHtml(success) {
100
+ const title = success ? 'ChatGPT connected' : 'ChatGPT sign-in failed';
101
+ const detail = success ? 'You can close this window and return to haze.' : 'Return to haze for details and try again.';
102
+ return `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body><main><h1>${title}</h1><p>${detail}</p></main></body></html>`;
103
+ }
104
+ async function closeServer(server) {
105
+ if (!server.listening)
106
+ return;
107
+ // Force-close idle keep-alive connections so the event loop can settle
108
+ // promptly (server.close alone only stops listening).
109
+ server.closeAllConnections?.();
110
+ await new Promise(resolve => server.close(() => resolve()));
111
+ }
112
+ export async function startChatGptBrowserLogin(options = {}) {
113
+ const issuer = options.issuer ?? CHATGPT_OAUTH_ISSUER;
114
+ const port = options.port ?? CHATGPT_OAUTH_CALLBACK_PORT;
115
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
116
+ const fetchImpl = options.fetchImpl ?? fetch;
117
+ const redirectUri = `http://localhost:${port}${CALLBACK_PATH}`;
118
+ const pkce = await generatePkce();
119
+ const state = base64UrlEncode(crypto.randomBytes(32));
120
+ const controller = new AbortController();
121
+ const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
122
+ let settled = false;
123
+ let resolveLogin;
124
+ let rejectLogin;
125
+ const completion = new Promise((resolve, reject) => {
126
+ resolveLogin = resolve;
127
+ rejectLogin = reject;
128
+ });
129
+ // The browser may redirect before the UI starts awaiting complete(). Keep the
130
+ // rejection observed while preserving it for the eventual caller.
131
+ void completion.catch(() => undefined);
132
+ const settleError = (error) => {
133
+ if (settled)
134
+ return;
135
+ settled = true;
136
+ rejectLogin(error);
137
+ };
138
+ const settleSuccess = (auth) => {
139
+ if (settled)
140
+ return;
141
+ settled = true;
142
+ resolveLogin(auth);
143
+ };
144
+ const server = createServer((request, response) => {
145
+ void (async () => {
146
+ const url = new URL(request.url ?? '/', `http://localhost:${port}`);
147
+ if (url.pathname !== CALLBACK_PATH) {
148
+ response.writeHead(404).end('Not found');
149
+ return;
150
+ }
151
+ const oauthError = url.searchParams.get('error_description') ?? url.searchParams.get('error');
152
+ const code = url.searchParams.get('code');
153
+ if (oauthError || !code || url.searchParams.get('state') !== state) {
154
+ const message = oauthError ?? (!code ? 'ChatGPT callback did not include an authorization code.' : 'ChatGPT callback state did not match.');
155
+ settleError(new Error(message));
156
+ response.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' }).end(callbackHtml(false));
157
+ return;
158
+ }
159
+ try {
160
+ const tokens = await tokenRequest(issuer, new URLSearchParams({
161
+ grant_type: 'authorization_code',
162
+ code,
163
+ redirect_uri: redirectUri,
164
+ client_id: CHATGPT_OAUTH_CLIENT_ID,
165
+ code_verifier: pkce.verifier,
166
+ }), fetchImpl, signal);
167
+ const auth = credentialsFromTokens(tokens);
168
+ settleSuccess(auth);
169
+ response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(callbackHtml(true));
170
+ }
171
+ catch (error) {
172
+ const failure = error instanceof Error ? error : new Error(String(error));
173
+ settleError(failure);
174
+ response.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' }).end(callbackHtml(false));
175
+ }
176
+ })();
177
+ });
178
+ await new Promise((resolve, reject) => {
179
+ server.once('error', reject);
180
+ server.listen(port, 'localhost', resolve);
181
+ }).catch(error => {
182
+ controller.abort();
183
+ throw new Error(`Could not start the ChatGPT sign-in callback on localhost:${port}: ${error instanceof Error ? error.message : String(error)}`);
184
+ });
185
+ const timeout = setTimeout(() => {
186
+ controller.abort();
187
+ settleError(new Error('ChatGPT sign-in timed out. Run /provider and try again.'));
188
+ }, timeoutMs);
189
+ const onAbort = () => settleError(new Error('ChatGPT sign-in was cancelled.'));
190
+ options.signal?.addEventListener('abort', onAbort, { once: true });
191
+ const close = async () => {
192
+ if (!settled)
193
+ settleError(new Error('ChatGPT sign-in was cancelled.'));
194
+ clearTimeout(timeout);
195
+ options.signal?.removeEventListener('abort', onAbort);
196
+ controller.abort();
197
+ await closeServer(server);
198
+ };
199
+ return {
200
+ url: buildChatGptAuthorizeUrl({ issuer, redirectUri, pkce, state }),
201
+ complete: async () => {
202
+ try {
203
+ return await completion;
204
+ }
205
+ finally {
206
+ await close();
207
+ }
208
+ },
209
+ close,
210
+ };
211
+ }
212
+ export async function openBrowser(url) {
213
+ return openPath(url);
214
+ }
@@ -1,17 +1,35 @@
1
1
  import type { ToolSet } from 'ai';
2
+ import { LspPool } from './lsp.js';
2
3
  import { type PromptSession } from './systemPrompt.js';
4
+ import { readSettings } from '../config/settings.js';
5
+ import { type ModelRuntimeSelection } from './client.js';
6
+ import { SubagentCoordinator, type CoordinatorEvent } from '../core/subagent/subagentCoordinator.js';
7
+ import { WorkspaceMutationPolicy } from '../core/subagent/workspaceMutationPolicy.js';
3
8
  import { type LoadedMcpTools } from './mcp.js';
4
9
  import { createSubagentTool } from '../core/subagent/subagentRunner.js';
5
10
  import type { ContextFile } from '../config/contextFiles.js';
6
11
  export type ToolCategory = 'builtin' | 'lsp' | 'skill' | 'subagent' | 'mcp';
7
12
  /** Model type accepted by the subagent tool; derived so this module stays decoupled. */
8
- export type RequestModel = Parameters<typeof createSubagentTool>[0]['model'];
13
+ export type RequestModel = NonNullable<Parameters<typeof createSubagentTool>[0]['model']>;
14
+ export interface SubagentOverrides {
15
+ profile?: string;
16
+ workerModel?: string;
17
+ maxConcurrency?: number;
18
+ forceMode?: 'inspect';
19
+ }
20
+ export interface TurnExecutionScope {
21
+ coordinator: SubagentCoordinator;
22
+ mutationPolicy: WorkspaceMutationPolicy;
23
+ }
9
24
  export interface AssembledRequestContext {
10
25
  systemPrompt: string;
11
26
  availableTools: ToolSet;
12
27
  /** Tool name -> coarse origin bucket, used by /context to group token estimates. */
13
28
  toolCategories: Map<string, ToolCategory>;
14
29
  loadedMcp?: LoadedMcpTools;
30
+ /** Turn-scoped LSP client pool; callers close it once the turn/context is done. */
31
+ lspPool?: LspPool;
32
+ executionScope: TurnExecutionScope;
15
33
  }
16
34
  /**
17
35
  * Assemble the system prompt and full tool set (built-in + LSP + subagent +
@@ -25,5 +43,11 @@ export declare function assembleRequestContext(input: {
25
43
  contextFiles: ContextFile[];
26
44
  session?: PromptSession;
27
45
  model: RequestModel;
46
+ modelRuntime?: ModelRuntimeSelection;
47
+ subagentOverrides?: SubagentOverrides;
48
+ onSubagentEvent?: (event: CoordinatorEvent) => void;
28
49
  abortSignal?: AbortSignal;
50
+ executionScope?: TurnExecutionScope;
51
+ /** Pre-read settings so a turn performs a single settings read (CR-024). */
52
+ settings?: Awaited<ReturnType<typeof readSettings>>;
29
53
  }): Promise<AssembledRequestContext>;
@@ -1,7 +1,13 @@
1
1
  import { hazeTools } from './hazeTools.js';
2
- import { lspTools } from './lspTools.js';
2
+ import { buildLspTools } from './lspTools.js';
3
+ import { LspPool } from './lsp.js';
3
4
  import { buildSystemPrompt } from './systemPrompt.js';
4
5
  import { readSettings } from '../config/settings.js';
6
+ import { resolveWorkerRuntime } from './client.js';
7
+ import { resolveExecutionProfile } from '../core/subagent/executionProfiles.js';
8
+ import { SubagentCoordinator } from '../core/subagent/subagentCoordinator.js';
9
+ import { WorkspaceMutationPolicy } from '../core/subagent/workspaceMutationPolicy.js';
10
+ import { fallbackProviderCapabilities, fallbackWorkerRuntime } from '../core/subagent/contracts.js';
5
11
  import { installedLspServers } from '../config/lspSettings.js';
6
12
  import { configuredMcpServers } from '../config/mcpSettings.js';
7
13
  import { loadMcpTools } from './mcp.js';
@@ -19,16 +25,52 @@ import { addCapabilityTools } from './capabilities.js';
19
25
  * close (`.close()`) once it is done with the assembled context.
20
26
  */
21
27
  export async function assembleRequestContext(input) {
22
- const settings = await readSettings();
28
+ const settings = input.settings ?? await readSettings();
23
29
  const skillRegistry = await loadSkillRegistry();
24
- const enabledSkills = new Map([...skillRegistry.skills.entries()].filter(([name]) => isSkillEnabled(settings, name)));
30
+ const enabledSkills = new Map(skillRegistry.skills);
31
+ if (skillRegistry.candidates) {
32
+ enabledSkills.clear();
33
+ for (const skill of skillRegistry.candidates) {
34
+ if (isSkillEnabled(settings, skill.name, skill.source) && !enabledSkills.has(skill.name))
35
+ enabledSkills.set(skill.name, skill);
36
+ }
37
+ }
38
+ else {
39
+ for (const [name, skill] of enabledSkills)
40
+ if (!isSkillEnabled(settings, name, skill.source))
41
+ enabledSkills.delete(name);
42
+ }
25
43
  const hasInstalledLsp = (await installedLspServers(settings)).length > 0;
44
+ const profileName = input.subagentOverrides?.profile ?? settings.subagents?.defaultProfile;
45
+ const profile = resolveExecutionProfile(profileName, settings.subagents?.profiles, input.subagentOverrides?.maxConcurrency);
46
+ const executionScope = input.executionScope ?? {
47
+ mutationPolicy: new WorkspaceMutationPolicy(),
48
+ coordinator: new SubagentCoordinator(profile ?? resolveExecutionProfile(undefined, undefined), input.onSubagentEvent),
49
+ };
50
+ const { coordinator, mutationPolicy } = executionScope;
51
+ let blockedReason = profile ? undefined : `Unknown subagent profile ${profileName}. Configure subagents.profiles or select a built-in profile.`;
52
+ let workerRuntime;
53
+ if (input.modelRuntime) {
54
+ const resolution = await resolveWorkerRuntime({ active: input.modelRuntime, settings, selector: input.subagentOverrides?.workerModel ?? settings.subagents?.workerModel, cwd: input.session?.cwd });
55
+ if (resolution.status === 'found')
56
+ workerRuntime = resolution.runtime;
57
+ else
58
+ blockedReason = resolution.message;
59
+ }
60
+ else if (settings.subagents?.workerModel || input.subagentOverrides?.workerModel) {
61
+ blockedReason = 'An explicit worker model could not be resolved for this request. Configure it via /provider and retry.';
62
+ }
63
+ workerRuntime ??= {
64
+ ...fallbackWorkerRuntime(input.model, input.modelRuntime?.selector, input.modelRuntime?.config.providerName),
65
+ capabilities: input.modelRuntime?.config.capabilities ?? fallbackProviderCapabilities(),
66
+ };
26
67
  const toolCategories = new Map();
27
68
  const availableTools = {};
69
+ const lspPool = hasInstalledLsp ? new LspPool() : undefined;
28
70
  addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'builtin', tools: hazeTools } });
29
71
  if (hasInstalledLsp)
30
- addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'lsp', tools: lspTools } });
31
- addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'subagent', tools: { subagent: createSubagentTool({ model: input.model, contextFiles: input.contextFiles, session: input.session }) } } });
72
+ addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'lsp', tools: buildLspTools(lspPool) } });
73
+ addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'subagent', tools: { subagent: createSubagentTool({ runtime: workerRuntime, profile: profile ?? undefined, coordinator, mutationPolicy, blockedReason, forceMode: input.subagentOverrides?.forceMode, session: input.session }) } } });
32
74
  addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'skill', tools: buildSkillTools({ skills: enabledSkills, errors: skillRegistry.errors ?? [] }) } });
33
75
  const mcpServers = configuredMcpServers(settings).filter(server => server.enabled !== false);
34
76
  const loadedMcp = mcpServers.length > 0
@@ -38,7 +80,8 @@ export async function assembleRequestContext(input) {
38
80
  addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'mcp', tools: loadedMcp.tools }, skipCollisions: true });
39
81
  }
40
82
  const mcpAvailable = Boolean(loadedMcp && Object.keys(loadedMcp.tools).length > 0);
41
- const skillErrors = (skillRegistry.errors ?? []).map(error => `${error.directory}: ${error.message}`);
42
- const systemPrompt = `${buildSystemPrompt(input.contextFiles, input.session, { lspAvailable: hasInstalledLsp, mcpAvailable })}${skillErrors.length ? `\n\n<skill-load-errors>\nInvalid skills were isolated:\n${skillErrors.map(error => `- ${error}`).join('\n')}\n</skill-load-errors>` : ''}`;
43
- return { systemPrompt, availableTools, toolCategories, loadedMcp };
83
+ const skillErrors = (skillRegistry.errors ?? []).map(error => `${error.source ? `${error.source}/` : ''}${error.directory}: ${error.message}`);
84
+ const model = input.modelRuntime?.config ? { provider: input.modelRuntime.config.providerName, name: input.modelRuntime.config.modelName } : undefined;
85
+ const systemPrompt = `${buildSystemPrompt(input.contextFiles, input.session, { lspAvailable: hasInstalledLsp, mcpAvailable, model })}${skillErrors.length ? `\n\n<skill-load-errors>\nInvalid skills were isolated:\n${skillErrors.map(error => `- ${error}`).join('\n')}\n</skill-load-errors>` : ''}`;
86
+ return { systemPrompt, availableTools, toolCategories, loadedMcp, lspPool, executionScope };
44
87
  }