@denizokcu/haze 0.5.0 → 0.6.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 (36) hide show
  1. package/CHANGELOG.md +18 -2
  2. package/README.md +51 -21
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +686 -61
  5. package/dist/cli/commands/commands.d.ts +2 -1
  6. package/dist/cli/commands/commands.js +62 -101
  7. package/dist/cli/commands/formatters.d.ts +27 -0
  8. package/dist/cli/commands/formatters.js +137 -0
  9. package/dist/cli/commands/streaming.d.ts +10 -13
  10. package/dist/cli/commands/streaming.js +319 -716
  11. package/dist/config/lspSettings.d.ts +16 -0
  12. package/dist/config/lspSettings.js +98 -0
  13. package/dist/config/mcpSettings.d.ts +24 -0
  14. package/dist/config/mcpSettings.js +100 -0
  15. package/dist/config/settings.d.ts +34 -0
  16. package/dist/config/skillSettings.d.ts +15 -0
  17. package/dist/config/skillSettings.js +31 -0
  18. package/dist/config/updateCheck.d.ts +44 -0
  19. package/dist/config/updateCheck.js +83 -0
  20. package/dist/llm/lsp.d.ts +64 -0
  21. package/dist/llm/lsp.js +241 -0
  22. package/dist/llm/lspTools.d.ts +122 -0
  23. package/dist/llm/lspTools.js +115 -0
  24. package/dist/llm/mcp.d.ts +19 -0
  25. package/dist/llm/mcp.js +64 -0
  26. package/dist/llm/requestContext.d.ts +28 -0
  27. package/dist/llm/requestContext.js +56 -0
  28. package/dist/llm/systemPrompt.d.ts +4 -1
  29. package/dist/llm/systemPrompt.js +8 -2
  30. package/dist/skills/builder/SkillBuilder.js +23 -44
  31. package/dist/ui/components/TextInput.d.ts +1 -1
  32. package/dist/utils/version.d.ts +20 -0
  33. package/dist/utils/version.js +72 -0
  34. package/package.json +2 -1
  35. package/dist/cli/commands/skills.d.ts +0 -4
  36. package/dist/cli/commands/skills.js +0 -38
@@ -0,0 +1,241 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { resolveWorkspacePath, workspaceRelativePath, workspaceRoot } from '../utils/path.js';
6
+ export class LspError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = 'LspError';
10
+ }
11
+ }
12
+ function languageId(filePath) {
13
+ const ext = path.extname(filePath).toLowerCase();
14
+ if (ext === '.ts')
15
+ return 'typescript';
16
+ if (ext === '.tsx')
17
+ return 'typescriptreact';
18
+ if (ext === '.js')
19
+ return 'javascript';
20
+ if (ext === '.jsx')
21
+ return 'javascriptreact';
22
+ if (ext === '.rs')
23
+ return 'rust';
24
+ if (ext === '.py')
25
+ return 'python';
26
+ if (ext === '.go')
27
+ return 'go';
28
+ return ext.replace(/^\./, '') || 'plaintext';
29
+ }
30
+ function toUri(absolutePath) {
31
+ return pathToFileURL(absolutePath).toString();
32
+ }
33
+ function fromUri(uri) {
34
+ if (!uri.startsWith('file://'))
35
+ return uri;
36
+ return workspaceRelativePath(new URL(uri).pathname);
37
+ }
38
+ function isObject(value) {
39
+ return typeof value === 'object' && value != null && !Array.isArray(value);
40
+ }
41
+ function asRange(value) {
42
+ if (!isObject(value) || !isObject(value.start) || !isObject(value.end))
43
+ return undefined;
44
+ const start = value.start;
45
+ const end = value.end;
46
+ return {
47
+ start: { line: typeof start.line === 'number' ? start.line + 1 : 1, character: typeof start.character === 'number' ? start.character + 1 : 1 },
48
+ end: { line: typeof end.line === 'number' ? end.line + 1 : 1, character: typeof end.character === 'number' ? end.character + 1 : 1 },
49
+ };
50
+ }
51
+ function locationToResult(value) {
52
+ if (!isObject(value))
53
+ return undefined;
54
+ const uri = typeof value.uri === 'string' ? value.uri : (isObject(value.targetUri) && typeof value.targetUri === 'string' ? value.targetUri : undefined);
55
+ const range = asRange(value.range ?? value.targetSelectionRange ?? value.targetRange);
56
+ if (!uri || !range)
57
+ return undefined;
58
+ return { path: fromUri(uri), range };
59
+ }
60
+ function flattenSymbols(symbols, filePath, limit) {
61
+ const out = [];
62
+ const visit = (items) => {
63
+ for (const item of items) {
64
+ if (out.length >= limit || !isObject(item))
65
+ return;
66
+ if (typeof item.name === 'string') {
67
+ out.push({
68
+ name: item.name,
69
+ kind: typeof item.kind === 'number' ? item.kind : undefined,
70
+ path: filePath,
71
+ range: asRange(item.range),
72
+ selectionRange: asRange(item.selectionRange),
73
+ });
74
+ }
75
+ if (Array.isArray(item.children))
76
+ visit(item.children);
77
+ }
78
+ };
79
+ visit(symbols);
80
+ return out;
81
+ }
82
+ export function pickLspServer(servers, filePath) {
83
+ const ext = path.extname(filePath).toLowerCase();
84
+ return servers.find(server => server.enabled !== false && (server.extensions ?? []).map(e => e.toLowerCase()).includes(ext));
85
+ }
86
+ class StdioLspClient {
87
+ server;
88
+ child;
89
+ id = 0;
90
+ buffer = Buffer.alloc(0);
91
+ pending = new Map();
92
+ constructor(server, child) {
93
+ this.server = server;
94
+ this.child = child;
95
+ child.stdout.on('data', chunk => this.onData(chunk));
96
+ child.stderr.on('data', () => undefined);
97
+ child.on('error', error => this.rejectAll(error instanceof Error ? error : new Error(String(error))));
98
+ child.on('exit', code => this.rejectAll(new LspError(`LSP server exited${code == null ? '' : ` with code ${code}`}`)));
99
+ }
100
+ static start(server) {
101
+ if (!server.command)
102
+ throw new LspError(`LSP server ${server.name} has no command.`);
103
+ const child = spawn(server.command, server.args ?? [], { cwd: workspaceRoot(), stdio: ['pipe', 'pipe', 'pipe'] });
104
+ return new StdioLspClient(server, child);
105
+ }
106
+ rejectAll(error) {
107
+ for (const pending of this.pending.values()) {
108
+ clearTimeout(pending.timer);
109
+ pending.reject(error);
110
+ }
111
+ this.pending.clear();
112
+ }
113
+ onData(chunk) {
114
+ this.buffer = Buffer.concat([this.buffer, chunk]);
115
+ while (true) {
116
+ const headerEnd = this.buffer.indexOf('\r\n\r\n');
117
+ if (headerEnd === -1)
118
+ return;
119
+ const header = this.buffer.slice(0, headerEnd).toString('utf8');
120
+ const match = /Content-Length: (\d+)/i.exec(header);
121
+ if (!match)
122
+ throw new LspError('Malformed LSP response: missing Content-Length.');
123
+ const length = Number(match[1]);
124
+ const bodyStart = headerEnd + 4;
125
+ if (this.buffer.length < bodyStart + length)
126
+ return;
127
+ const raw = this.buffer.slice(bodyStart, bodyStart + length).toString('utf8');
128
+ this.buffer = this.buffer.slice(bodyStart + length);
129
+ const message = JSON.parse(raw);
130
+ if (typeof message.id !== 'number')
131
+ continue;
132
+ const pending = this.pending.get(message.id);
133
+ if (!pending)
134
+ continue;
135
+ this.pending.delete(message.id);
136
+ clearTimeout(pending.timer);
137
+ if (message.error)
138
+ pending.reject(new LspError(message.error.message ?? 'LSP request failed.'));
139
+ else
140
+ pending.resolve(message.result);
141
+ }
142
+ }
143
+ send(message) {
144
+ const body = JSON.stringify({ ...message, jsonrpc: '2.0' });
145
+ this.child.stdin.write(`Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`);
146
+ }
147
+ request(method, params, timeoutMs = 8000) {
148
+ const id = ++this.id;
149
+ this.send({ id, method, params });
150
+ return new Promise((resolve, reject) => {
151
+ const timer = setTimeout(() => {
152
+ this.pending.delete(id);
153
+ reject(new LspError(`LSP request timed out: ${method}`));
154
+ }, timeoutMs);
155
+ this.pending.set(id, { resolve, reject, timer });
156
+ });
157
+ }
158
+ notify(method, params) {
159
+ this.send({ method, params });
160
+ }
161
+ async initialize() {
162
+ await this.request('initialize', {
163
+ processId: process.pid,
164
+ rootUri: toUri(workspaceRoot()),
165
+ capabilities: {
166
+ textDocument: {
167
+ documentSymbol: { hierarchicalDocumentSymbolSupport: true },
168
+ definition: { linkSupport: true },
169
+ references: {},
170
+ },
171
+ workspace: { symbol: {} },
172
+ },
173
+ });
174
+ this.notify('initialized', {});
175
+ }
176
+ async openDocument(absolutePath) {
177
+ const text = await fs.readFile(absolutePath, 'utf8');
178
+ this.notify('textDocument/didOpen', {
179
+ textDocument: { uri: toUri(absolutePath), languageId: languageId(absolutePath), version: 1, text },
180
+ });
181
+ }
182
+ async close() {
183
+ try {
184
+ await this.request('shutdown', null, 2000).catch(() => undefined);
185
+ this.notify('exit');
186
+ }
187
+ finally {
188
+ this.child.kill('SIGTERM');
189
+ }
190
+ }
191
+ }
192
+ async function withLsp(server, filePath, fn) {
193
+ const absolutePath = resolveWorkspacePath(filePath);
194
+ const client = StdioLspClient.start(server);
195
+ try {
196
+ await client.initialize();
197
+ await client.openDocument(absolutePath);
198
+ return await fn(client, absolutePath);
199
+ }
200
+ finally {
201
+ await client.close();
202
+ }
203
+ }
204
+ export async function lspDocumentSymbols(server, filePath, limit) {
205
+ return await withLsp(server, filePath, async (client, absolutePath) => {
206
+ const result = await client.request('textDocument/documentSymbol', { textDocument: { uri: toUri(absolutePath) } });
207
+ const symbols = Array.isArray(result) ? result : [];
208
+ return flattenSymbols(symbols, workspaceRelativePath(absolutePath), limit);
209
+ });
210
+ }
211
+ export async function lspDefinition(server, filePath, line, character, limit) {
212
+ return await withLsp(server, filePath, async (client, absolutePath) => {
213
+ const result = await client.request('textDocument/definition', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 } });
214
+ const values = Array.isArray(result) ? result : result ? [result] : [];
215
+ return values.map(locationToResult).filter(result => result != null).slice(0, limit);
216
+ });
217
+ }
218
+ export async function lspReferences(server, filePath, line, character, limit) {
219
+ return await withLsp(server, filePath, async (client, absolutePath) => {
220
+ const result = await client.request('textDocument/references', { textDocument: { uri: toUri(absolutePath) }, position: { line: line - 1, character: character - 1 }, context: { includeDeclaration: true } });
221
+ const values = Array.isArray(result) ? result : [];
222
+ return values.map(locationToResult).filter(result => result != null).slice(0, limit);
223
+ });
224
+ }
225
+ export async function lspWorkspaceSymbols(server, query, limit) {
226
+ const client = StdioLspClient.start(server);
227
+ try {
228
+ await client.initialize();
229
+ const result = await client.request('workspace/symbol', { query });
230
+ const values = Array.isArray(result) ? result : [];
231
+ return values.flatMap(value => {
232
+ if (!isObject(value) || typeof value.name !== 'string')
233
+ return [];
234
+ const location = locationToResult(value.location);
235
+ return [{ name: value.name, kind: typeof value.kind === 'number' ? value.kind : undefined, ...location }];
236
+ }).slice(0, limit);
237
+ }
238
+ finally {
239
+ await client.close();
240
+ }
241
+ }
@@ -0,0 +1,122 @@
1
+ export declare const lspTools: {
2
+ lspWorkspaceSymbols: import("ai").Tool<{
3
+ query: string;
4
+ maxSymbols: number;
5
+ server?: string | undefined;
6
+ }, {
7
+ ok: boolean;
8
+ error: string;
9
+ } | {
10
+ ok: boolean;
11
+ server: string;
12
+ query: string;
13
+ symbols: {
14
+ path?: string | undefined;
15
+ range?: {
16
+ start: {
17
+ line: number;
18
+ character: number;
19
+ };
20
+ end: {
21
+ line: number;
22
+ character: number;
23
+ };
24
+ } | undefined;
25
+ name: string;
26
+ kind: number | undefined;
27
+ }[];
28
+ truncated: boolean;
29
+ }>;
30
+ lspSymbols: import("ai").Tool<{
31
+ path: string;
32
+ maxSymbols: number;
33
+ }, {
34
+ ok: boolean;
35
+ error: string;
36
+ } | {
37
+ ok: boolean;
38
+ server: string;
39
+ path: string;
40
+ symbols: {
41
+ name: string;
42
+ kind?: number;
43
+ path: string;
44
+ range?: ReturnType<(value: unknown) => {
45
+ start: {
46
+ line: number;
47
+ character: number;
48
+ };
49
+ end: {
50
+ line: number;
51
+ character: number;
52
+ };
53
+ } | undefined>;
54
+ selectionRange?: ReturnType<(value: unknown) => {
55
+ start: {
56
+ line: number;
57
+ character: number;
58
+ };
59
+ end: {
60
+ line: number;
61
+ character: number;
62
+ };
63
+ } | undefined>;
64
+ }[];
65
+ truncated: boolean;
66
+ }>;
67
+ lspDefinition: import("ai").Tool<{
68
+ path: string;
69
+ line: number;
70
+ column: number;
71
+ maxResults: number;
72
+ }, {
73
+ ok: boolean;
74
+ error: string;
75
+ } | {
76
+ ok: boolean;
77
+ server: string;
78
+ path: string;
79
+ locations: {
80
+ path: string;
81
+ range: {
82
+ start: {
83
+ line: number;
84
+ character: number;
85
+ };
86
+ end: {
87
+ line: number;
88
+ character: number;
89
+ };
90
+ };
91
+ }[];
92
+ truncated: boolean;
93
+ }>;
94
+ lspReferences: import("ai").Tool<{
95
+ path: string;
96
+ line: number;
97
+ column: number;
98
+ maxResults: number;
99
+ }, {
100
+ ok: boolean;
101
+ error: string;
102
+ } | {
103
+ ok: boolean;
104
+ server: string;
105
+ path: string;
106
+ locations: {
107
+ path: string;
108
+ range: {
109
+ start: {
110
+ line: number;
111
+ character: number;
112
+ };
113
+ end: {
114
+ line: number;
115
+ character: number;
116
+ };
117
+ };
118
+ }[];
119
+ truncated: boolean;
120
+ }>;
121
+ };
122
+ export type LspTools = typeof lspTools;
@@ -0,0 +1,115 @@
1
+ import path from 'node:path';
2
+ import { tool } from 'ai';
3
+ import { z } from 'zod';
4
+ import { readSettings } from '../config/settings.js';
5
+ import { configuredLspServers } from '../config/lspSettings.js';
6
+ import { lspDefinition, lspDocumentSymbols, lspReferences, lspWorkspaceSymbols, pickLspServer } from './lsp.js';
7
+ async function serverFor(filePath) {
8
+ const servers = configuredLspServers(await readSettings()).filter(server => server.enabled !== false);
9
+ return pickLspServer(servers, filePath);
10
+ }
11
+ function noServer(filePath) {
12
+ 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
+ }
14
+ async function namedOrFirstServer(name) {
15
+ const servers = configuredLspServers(await readSettings()).filter(server => server.enabled !== false);
16
+ if (name)
17
+ return servers.find(server => server.name === name);
18
+ return servers[0];
19
+ }
20
+ function cleanLspError(message) {
21
+ if (/No Project/i.test(message))
22
+ 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.';
23
+ return message
24
+ .split('\n')
25
+ .filter(line => line.trim() && !/^\s*at\s/.test(line))
26
+ .slice(0, 2)
27
+ .join('\n');
28
+ }
29
+ function lspFailure(error) {
30
+ const message = error instanceof Error ? error.message : String(error);
31
+ return { ok: false, error: cleanLspError(message) };
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'),
40
+ }),
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'),
59
+ }),
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
+ }),
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
+ }),
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
+ };
@@ -0,0 +1,19 @@
1
+ import { type MCPClient } from '@ai-sdk/mcp';
2
+ import type { ToolSet } from 'ai';
3
+ import type { HazeMcpServer } from '../config/settings.js';
4
+ export interface LoadedMcpTools {
5
+ tools: ToolSet;
6
+ clients: MCPClient[];
7
+ errors: string[];
8
+ }
9
+ /**
10
+ * Connect to each enabled MCP server, discover its tools, and merge them into a
11
+ * single toolset. Tool names that collide with `reserved` or with an earlier
12
+ * server's tools are skipped (reported in `errors`) so MCP servers can never
13
+ * shadow built-in tools. A failing server is isolated: its error is collected
14
+ * and the remaining servers still load. Returns the tools, the live clients
15
+ * (for `.close()` after the turn), and any per-server error messages.
16
+ */
17
+ export declare function loadMcpTools(servers: HazeMcpServer[], reserved?: ReadonlySet<string>): Promise<LoadedMcpTools>;
18
+ /** Close all MCP clients opened during a turn. Never throws. */
19
+ export declare function closeMcpClients(clients: MCPClient[]): Promise<void>;
@@ -0,0 +1,64 @@
1
+ import { createMCPClient } from '@ai-sdk/mcp';
2
+ function headersToRecord(server) {
3
+ if (!server.headers || server.headers.length === 0)
4
+ return undefined;
5
+ const record = {};
6
+ for (const header of server.headers)
7
+ record[header.name] = header.value;
8
+ return record;
9
+ }
10
+ /**
11
+ * Connect to each enabled MCP server, discover its tools, and merge them into a
12
+ * single toolset. Tool names that collide with `reserved` or with an earlier
13
+ * server's tools are skipped (reported in `errors`) so MCP servers can never
14
+ * shadow built-in tools. A failing server is isolated: its error is collected
15
+ * and the remaining servers still load. Returns the tools, the live clients
16
+ * (for `.close()` after the turn), and any per-server error messages.
17
+ */
18
+ export async function loadMcpTools(servers, reserved = new Set()) {
19
+ const enabled = servers.filter(server => server.enabled !== false);
20
+ const tools = {};
21
+ const clients = [];
22
+ const errors = [];
23
+ const taken = new Set(reserved);
24
+ for (const server of enabled) {
25
+ try {
26
+ const client = await createMcpClient(server);
27
+ clients.push(client);
28
+ const serverTools = await client.tools();
29
+ for (const [name, toolDef] of Object.entries(serverTools)) {
30
+ if (taken.has(name)) {
31
+ errors.push(`${server.name}: skipped tool "${name}" (name already in use)`);
32
+ continue;
33
+ }
34
+ taken.add(name);
35
+ tools[name] = toolDef;
36
+ }
37
+ }
38
+ catch (error) {
39
+ const message = error instanceof Error ? error.message : String(error);
40
+ errors.push(`${server.name}: ${message}`);
41
+ }
42
+ }
43
+ return { tools, clients, errors };
44
+ }
45
+ async function createMcpClient(server) {
46
+ if (server.transport === 'stdio') {
47
+ if (!server.command)
48
+ throw new Error('missing command for stdio transport');
49
+ const { Experimental_StdioMCPTransport } = await import('@ai-sdk/mcp/mcp-stdio');
50
+ return createMCPClient({
51
+ transport: new Experimental_StdioMCPTransport({ command: server.command, args: server.args ?? [] }),
52
+ });
53
+ }
54
+ if (!server.url)
55
+ throw new Error(`missing url for ${server.transport} transport`);
56
+ const headers = headersToRecord(server);
57
+ return createMCPClient({
58
+ transport: { type: server.transport, url: server.url, ...(headers ? { headers } : {}) },
59
+ });
60
+ }
61
+ /** Close all MCP clients opened during a turn. Never throws. */
62
+ export async function closeMcpClients(clients) {
63
+ await Promise.allSettled(clients.map(client => client.close()));
64
+ }
@@ -0,0 +1,28 @@
1
+ import type { ToolSet } from 'ai';
2
+ import { type PromptSession } from './systemPrompt.js';
3
+ import { type LoadedMcpTools } from './mcp.js';
4
+ import { createSubagentTool } from '../core/subagent/subagentRunner.js';
5
+ import type { ContextFile } from '../config/contextFiles.js';
6
+ export type ToolCategory = 'builtin' | 'lsp' | 'skill' | 'subagent' | 'mcp';
7
+ /** Model type accepted by the subagent tool; derived so this module stays decoupled. */
8
+ export type RequestModel = Parameters<typeof createSubagentTool>[0]['model'];
9
+ export interface AssembledRequestContext {
10
+ systemPrompt: string;
11
+ availableTools: ToolSet;
12
+ /** Tool name -> coarse origin bucket, used by /context to group token estimates. */
13
+ toolCategories: Map<string, ToolCategory>;
14
+ loadedMcp?: LoadedMcpTools;
15
+ }
16
+ /**
17
+ * Assemble the system prompt and full tool set (built-in + LSP + subagent +
18
+ * skills + MCP) for a model request. This is the single source of truth shared
19
+ * by the agent turn (streaming.ts) and the /context command, so both observe
20
+ * identical token breakdowns. Reads fresh settings from disk so MCP/LSP changes
21
+ * since the last turn are reflected. MCP clients are returned for the caller to
22
+ * close (`.close()`) once it is done with the assembled context.
23
+ */
24
+ export declare function assembleRequestContext(input: {
25
+ contextFiles: ContextFile[];
26
+ session?: PromptSession;
27
+ model: RequestModel;
28
+ }): Promise<AssembledRequestContext>;
@@ -0,0 +1,56 @@
1
+ import { hazeTools } from './hazeTools.js';
2
+ import { lspTools } from './lspTools.js';
3
+ import { buildSystemPrompt } from './systemPrompt.js';
4
+ import { readSettings } from '../config/settings.js';
5
+ import { installedLspServers } from '../config/lspSettings.js';
6
+ import { configuredMcpServers } from '../config/mcpSettings.js';
7
+ import { loadMcpTools } from './mcp.js';
8
+ import { loadSkillRegistry } from '../skills/SkillRegistry.js';
9
+ import { buildSkillTools } from '../skills/skillTools.js';
10
+ import { isSkillEnabled } from '../config/skillSettings.js';
11
+ import { createSubagentTool } from '../core/subagent/subagentRunner.js';
12
+ /**
13
+ * Assemble the system prompt and full tool set (built-in + LSP + subagent +
14
+ * skills + MCP) for a model request. This is the single source of truth shared
15
+ * by the agent turn (streaming.ts) and the /context command, so both observe
16
+ * identical token breakdowns. Reads fresh settings from disk so MCP/LSP changes
17
+ * since the last turn are reflected. MCP clients are returned for the caller to
18
+ * close (`.close()`) once it is done with the assembled context.
19
+ */
20
+ export async function assembleRequestContext(input) {
21
+ const settings = await readSettings();
22
+ const skillRegistry = await loadSkillRegistry();
23
+ const enabledSkills = new Map([...skillRegistry.skills.entries()].filter(([name]) => isSkillEnabled(settings, name)));
24
+ const hasInstalledLsp = (await installedLspServers(settings)).length > 0;
25
+ const toolCategories = new Map();
26
+ const availableTools = {};
27
+ for (const [name, value] of Object.entries(hazeTools)) {
28
+ toolCategories.set(name, 'builtin');
29
+ availableTools[name] = value;
30
+ }
31
+ if (hasInstalledLsp) {
32
+ for (const [name, value] of Object.entries(lspTools)) {
33
+ toolCategories.set(name, 'lsp');
34
+ availableTools[name] = value;
35
+ }
36
+ }
37
+ const subagentTool = createSubagentTool({ model: input.model, contextFiles: input.contextFiles, session: input.session });
38
+ toolCategories.set('subagent', 'subagent');
39
+ availableTools.subagent = subagentTool;
40
+ const skillTools = buildSkillTools({ skills: enabledSkills });
41
+ for (const [name, value] of Object.entries(skillTools)) {
42
+ toolCategories.set(name, 'skill');
43
+ availableTools[name] = value;
44
+ }
45
+ const mcpServers = configuredMcpServers(settings).filter(server => server.enabled !== false);
46
+ const loadedMcp = mcpServers.length > 0 ? await loadMcpTools(mcpServers, new Set(Object.keys(availableTools))) : undefined;
47
+ if (loadedMcp && Object.keys(loadedMcp.tools).length > 0) {
48
+ for (const [name, value] of Object.entries(loadedMcp.tools)) {
49
+ toolCategories.set(name, 'mcp');
50
+ availableTools[name] = value;
51
+ }
52
+ }
53
+ const mcpAvailable = Boolean(loadedMcp && Object.keys(loadedMcp.tools).length > 0);
54
+ const systemPrompt = buildSystemPrompt(input.contextFiles, input.session, { lspAvailable: hasInstalledLsp, mcpAvailable });
55
+ return { systemPrompt, availableTools, toolCategories, loadedMcp };
56
+ }
@@ -3,5 +3,8 @@ export interface PromptSession {
3
3
  start?: Date;
4
4
  cwd?: string;
5
5
  }
6
- export declare function buildSystemPrompt(contextFiles?: ContextFile[], session?: PromptSession): string;
6
+ export declare function buildSystemPrompt(contextFiles?: ContextFile[], session?: PromptSession, options?: {
7
+ lspAvailable?: boolean;
8
+ mcpAvailable?: boolean;
9
+ }): string;
7
10
  export declare function buildSubagentPrompt(contextFiles?: ContextFile[], session?: PromptSession): string;