@oh-my-pi/pi-coding-agent 3.21.0 → 3.24.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 (66) hide show
  1. package/CHANGELOG.md +40 -1
  2. package/docs/sdk.md +47 -50
  3. package/examples/custom-tools/README.md +0 -15
  4. package/examples/hooks/custom-compaction.ts +1 -3
  5. package/examples/sdk/README.md +6 -10
  6. package/package.json +5 -5
  7. package/src/cli/args.ts +9 -6
  8. package/src/core/agent-session.ts +3 -3
  9. package/src/core/custom-tools/wrapper.ts +0 -1
  10. package/src/core/extensions/index.ts +1 -6
  11. package/src/core/extensions/wrapper.ts +0 -7
  12. package/src/core/file-mentions.ts +5 -8
  13. package/src/core/sdk.ts +41 -111
  14. package/src/core/session-manager.ts +7 -0
  15. package/src/core/system-prompt.ts +22 -33
  16. package/src/core/tools/ask.ts +14 -7
  17. package/src/core/tools/bash-interceptor.ts +4 -4
  18. package/src/core/tools/bash.ts +19 -9
  19. package/src/core/tools/context.ts +7 -0
  20. package/src/core/tools/edit.ts +8 -15
  21. package/src/core/tools/exa/render.ts +4 -16
  22. package/src/core/tools/find.ts +7 -18
  23. package/src/core/tools/git.ts +13 -3
  24. package/src/core/tools/grep.ts +7 -18
  25. package/src/core/tools/index.test.ts +180 -0
  26. package/src/core/tools/index.ts +94 -237
  27. package/src/core/tools/ls.ts +4 -9
  28. package/src/core/tools/lsp/index.ts +32 -29
  29. package/src/core/tools/lsp/render.ts +7 -28
  30. package/src/core/tools/notebook.ts +3 -5
  31. package/src/core/tools/output.ts +5 -17
  32. package/src/core/tools/read.ts +8 -19
  33. package/src/core/tools/review.ts +0 -18
  34. package/src/core/tools/rulebook.ts +8 -2
  35. package/src/core/tools/task/agents.ts +28 -7
  36. package/src/core/tools/task/discovery.ts +0 -6
  37. package/src/core/tools/task/executor.ts +264 -254
  38. package/src/core/tools/task/index.ts +45 -220
  39. package/src/core/tools/task/render.ts +21 -11
  40. package/src/core/tools/task/types.ts +6 -11
  41. package/src/core/tools/task/worker-protocol.ts +17 -0
  42. package/src/core/tools/task/worker.ts +238 -0
  43. package/src/core/tools/web-fetch.ts +4 -36
  44. package/src/core/tools/web-search/index.ts +2 -1
  45. package/src/core/tools/web-search/render.ts +1 -4
  46. package/src/core/tools/write.ts +7 -15
  47. package/src/discovery/helpers.test.ts +1 -1
  48. package/src/index.ts +5 -16
  49. package/src/main.ts +4 -4
  50. package/src/modes/interactive/theme/theme.ts +4 -4
  51. package/src/prompts/task.md +0 -7
  52. package/src/prompts/tools/output.md +2 -2
  53. package/src/prompts/tools/task.md +68 -0
  54. package/examples/custom-tools/question/index.ts +0 -84
  55. package/examples/custom-tools/subagent/README.md +0 -172
  56. package/examples/custom-tools/subagent/agents/planner.md +0 -37
  57. package/examples/custom-tools/subagent/agents/scout.md +0 -50
  58. package/examples/custom-tools/subagent/agents/worker.md +0 -24
  59. package/examples/custom-tools/subagent/agents.ts +0 -156
  60. package/examples/custom-tools/subagent/commands/implement-and-review.md +0 -10
  61. package/examples/custom-tools/subagent/commands/implement.md +0 -10
  62. package/examples/custom-tools/subagent/commands/scout-and-plan.md +0 -9
  63. package/examples/custom-tools/subagent/index.ts +0 -1002
  64. package/examples/sdk/05-tools.ts +0 -94
  65. package/examples/sdk/12-full-control.ts +0 -95
  66. package/src/prompts/browser.md +0 -71
@@ -1,14 +1,14 @@
1
1
  export { type AskToolDetails, askTool, createAskTool } from "./ask";
2
- export { type BashToolDetails, bashTool, createBashTool } from "./bash";
3
- export { createEditTool, type EditToolOptions, editTool } from "./edit";
2
+ export { type BashToolDetails, createBashTool } from "./bash";
3
+ export { createEditTool } from "./edit";
4
4
  // Exa MCP tools (22 tools)
5
5
  export { exaTools } from "./exa/index";
6
6
  export type { ExaRenderDetails, ExaSearchResponse, ExaSearchResult } from "./exa/types";
7
- export { createFindTool, type FindToolDetails, findTool } from "./find";
7
+ export { createFindTool, type FindToolDetails } from "./find";
8
8
  export { setPreferredImageProvider } from "./gemini-image";
9
9
  export { createGitTool, type GitToolDetails, gitTool } from "./git";
10
- export { createGrepTool, type GrepToolDetails, grepTool } from "./grep";
11
- export { createLsTool, type LsToolDetails, lsTool } from "./ls";
10
+ export { createGrepTool, type GrepToolDetails } from "./grep";
11
+ export { createLsTool, type LsToolDetails } from "./ls";
12
12
  export {
13
13
  createLspTool,
14
14
  type FileDiagnosticsResult,
@@ -20,14 +20,14 @@ export {
20
20
  lspTool,
21
21
  warmupLspServers,
22
22
  } from "./lsp/index";
23
- export { createNotebookTool, type NotebookToolDetails, notebookTool } from "./notebook";
24
- export { createOutputTool, type OutputToolDetails, outputTool } from "./output";
25
- export { createReadTool, type ReadToolDetails, type ReadToolOptions, readTool } from "./read";
26
- export { createReportFindingTool, createSubmitReviewTool, reportFindingTool, submitReviewTool } from "./review";
27
- export { createRulebookTool, filterRulebookRules, formatRulesForPrompt, type RulebookToolDetails } from "./rulebook";
23
+ export { createNotebookTool, type NotebookToolDetails } from "./notebook";
24
+ export { createOutputTool, type OutputToolDetails } from "./output";
25
+ export { createReadTool, type ReadToolDetails } from "./read";
26
+ export { reportFindingTool, submitReviewTool } from "./review";
27
+ export { filterRulebookRules, formatRulesForPrompt, type RulebookToolDetails } from "./rulebook";
28
28
  export { BUNDLED_AGENTS, createTaskTool, taskTool } from "./task/index";
29
29
  export type { TruncationResult } from "./truncate";
30
- export { createWebFetchTool, type WebFetchToolDetails, webFetchCustomTool, webFetchTool } from "./web-fetch";
30
+ export { createWebFetchTool, type WebFetchToolDetails } from "./web-fetch";
31
31
  export {
32
32
  companyWebSearchTools,
33
33
  createWebSearchTool,
@@ -47,247 +47,104 @@ export {
47
47
  webSearchLinkedinTool,
48
48
  webSearchTool,
49
49
  } from "./web-search/index";
50
- export { createWriteTool, type WriteToolDetails, type WriteToolOptions, writeTool } from "./write";
50
+ export { createWriteTool, type WriteToolDetails } from "./write";
51
51
 
52
52
  import type { AgentTool } from "@oh-my-pi/pi-agent-core";
53
- import { askTool, createAskTool } from "./ask";
54
- import { bashTool, createBashTool } from "./bash";
55
- import { checkBashInterception, checkSimpleLsInterception } from "./bash-interceptor";
56
- import { createEditTool, editTool } from "./edit";
57
- import { createFindTool, findTool } from "./find";
58
- import { createGitTool, gitTool } from "./git";
59
- import { createGrepTool, grepTool } from "./grep";
60
- import { createLsTool, lsTool } from "./ls";
61
- import { createLspTool, createLspWritethrough, lspTool } from "./lsp/index";
62
- import { createNotebookTool, notebookTool } from "./notebook";
63
- import { createOutputTool, outputTool } from "./output";
64
- import { createReadTool, readTool } from "./read";
65
- import { createReportFindingTool, createSubmitReviewTool, reportFindingTool, submitReviewTool } from "./review";
66
- import { createTaskTool, taskTool } from "./task/index";
67
- import { createWebFetchTool, webFetchTool } from "./web-fetch";
68
- import { createWebSearchTool, webSearchTool } from "./web-search/index";
69
- import { createWriteTool, writeTool } from "./write";
53
+ import type { Rule } from "../../capability/rule";
54
+ import type { EventBus } from "../event-bus";
55
+ import { createAskTool } from "./ask";
56
+ import { createBashTool } from "./bash";
57
+ import { createEditTool } from "./edit";
58
+ import { createFindTool } from "./find";
59
+ import { createGitTool } from "./git";
60
+ import { createGrepTool } from "./grep";
61
+ import { createLsTool } from "./ls";
62
+ import { createLspTool } from "./lsp/index";
63
+ import { createNotebookTool } from "./notebook";
64
+ import { createOutputTool } from "./output";
65
+ import { createReadTool } from "./read";
66
+ import { reportFindingTool, submitReviewTool } from "./review";
67
+ import { createRulebookTool } from "./rulebook";
68
+ import { createTaskTool } from "./task/index";
69
+ import { createWebFetchTool } from "./web-fetch";
70
+ import { createWebSearchTool } from "./web-search/index";
71
+ import { createWriteTool } from "./write";
70
72
 
71
73
  /** Tool type (AgentTool from pi-ai) */
72
74
  export type Tool = AgentTool<any, any, any>;
73
75
 
74
- /** Context for tools that need session information */
75
- export interface SessionContext {
76
+ /** Session context for tool factories */
77
+ export interface ToolSession {
78
+ /** Current working directory */
79
+ cwd: string;
80
+ /** Whether UI is available */
81
+ hasUI: boolean;
82
+ /** Rulebook rules */
83
+ rulebookRules: Rule[];
84
+ /** Event bus for tool/extension communication */
85
+ eventBus?: EventBus;
86
+ /** Get session file */
76
87
  getSessionFile: () => string | null;
88
+ /** Get session spawns */
89
+ getSessionSpawns: () => string | null;
90
+ /** Settings manager (optional) */
91
+ settings?: {
92
+ getImageAutoResize(): boolean;
93
+ getLspFormatOnWrite(): boolean;
94
+ getLspDiagnosticsOnWrite(): boolean;
95
+ getLspDiagnosticsOnEdit(): boolean;
96
+ getEditFuzzyMatch(): boolean;
97
+ getGitToolEnabled(): boolean;
98
+ getBashInterceptorEnabled(): boolean;
99
+ };
77
100
  }
78
101
 
79
- /** Options for creating coding tools */
80
- export interface CodingToolsOptions {
81
- /** Whether to fetch LSP diagnostics after write tool writes files (default: true) */
82
- lspDiagnosticsOnWrite?: boolean;
83
- /** Whether to fetch LSP diagnostics after edit tool edits files (default: false) */
84
- lspDiagnosticsOnEdit?: boolean;
85
- /** Whether to format files using LSP after write tool writes (default: true) */
86
- lspFormatOnWrite?: boolean;
87
- /** Whether to accept high-confidence fuzzy matches in edit tool (default: true) */
88
- editFuzzyMatch?: boolean;
89
- /** Whether to auto-resize images to 2000x2000 max in read tool (default: true) */
90
- readAutoResizeImages?: boolean;
91
- /** Set of tool names available to the agent (for cross-tool awareness) */
92
- availableTools?: Set<string>;
93
- }
94
-
95
- // Factory function type
96
- type ToolFactory = (cwd: string, sessionContext?: SessionContext, options?: CodingToolsOptions) => Tool | Promise<Tool>;
97
-
98
- // Tool definitions: static tools and their factory functions
99
- const toolDefs: Record<string, { tool: Tool; create: ToolFactory }> = {
100
- ask: { tool: askTool, create: createAskTool },
101
- read: {
102
- tool: readTool,
103
- create: (cwd, _ctx, options) => createReadTool(cwd, { autoResizeImages: options?.readAutoResizeImages ?? true }),
104
- },
105
- bash: { tool: bashTool, create: createBashTool },
106
- edit: {
107
- tool: editTool,
108
- create: (cwd, _ctx, options) => {
109
- const enableDiagnostics = options?.lspDiagnosticsOnEdit ?? false;
110
- const enableFormat = options?.lspFormatOnWrite ?? true;
111
- const writethrough = createLspWritethrough(cwd, {
112
- enableFormat,
113
- enableDiagnostics,
114
- });
115
- return createEditTool(cwd, { fuzzyMatch: options?.editFuzzyMatch ?? true, writethrough });
116
- },
117
- },
118
- write: {
119
- tool: writeTool,
120
- create: (cwd, _ctx, options) => {
121
- const enableFormat = options?.lspFormatOnWrite ?? true;
122
- const enableDiagnostics = options?.lspDiagnosticsOnWrite ?? true;
123
- const writethrough = createLspWritethrough(cwd, {
124
- enableFormat,
125
- enableDiagnostics,
126
- });
127
- return createWriteTool(cwd, { writethrough });
128
- },
129
- },
130
- grep: { tool: grepTool, create: createGrepTool },
131
- find: { tool: findTool, create: createFindTool },
132
- git: { tool: gitTool, create: createGitTool },
133
- ls: { tool: lsTool, create: createLsTool },
134
- lsp: { tool: lspTool, create: createLspTool },
135
- notebook: { tool: notebookTool, create: createNotebookTool },
136
- output: { tool: outputTool, create: (cwd, ctx) => createOutputTool(cwd, ctx) },
137
- task: { tool: taskTool, create: (cwd, ctx, opts) => createTaskTool(cwd, ctx, opts) },
138
- web_fetch: { tool: webFetchTool, create: createWebFetchTool },
139
- web_search: { tool: webSearchTool, create: createWebSearchTool },
140
- report_finding: { tool: reportFindingTool, create: createReportFindingTool },
141
- submit_review: { tool: submitReviewTool, create: createSubmitReviewTool },
102
+ type ToolFactory = (session: ToolSession) => Tool | null | Promise<Tool | null>;
103
+
104
+ export const BUILTIN_TOOLS: Record<string, ToolFactory> = {
105
+ ask: createAskTool,
106
+ bash: createBashTool,
107
+ edit: createEditTool,
108
+ find: createFindTool,
109
+ git: createGitTool,
110
+ grep: createGrepTool,
111
+ ls: createLsTool,
112
+ lsp: createLspTool,
113
+ notebook: createNotebookTool,
114
+ output: createOutputTool,
115
+ read: createReadTool,
116
+ rulebook: createRulebookTool,
117
+ task: createTaskTool,
118
+ web_fetch: createWebFetchTool,
119
+ web_search: createWebSearchTool,
120
+ write: createWriteTool,
142
121
  };
143
122
 
144
- export type ToolName = keyof typeof toolDefs;
145
-
146
- // Tools that require UI (excluded when hasUI is false)
147
- const uiToolNames: ToolName[] = ["ask"];
148
-
149
- // Tool sets defined by name (base sets, without UI-only tools)
150
- export const baseCodingToolNames: ToolName[] = [
151
- "read",
152
- "bash",
153
- "edit",
154
- "write",
155
- "grep",
156
- "find",
157
- "git",
158
- "ls",
159
- "lsp",
160
- "notebook",
161
- "output",
162
- "task",
163
- "web_fetch",
164
- "web_search",
165
- ];
166
- const baseReadOnlyToolNames: ToolName[] = ["read", "grep", "find", "ls"];
167
-
168
- // Default tools for full access mode (using process.cwd(), no UI)
169
- export const codingTools: Tool[] = baseCodingToolNames.map((name) => toolDefs[name].tool);
170
-
171
- // Read-only tools for exploration without modification (using process.cwd(), no UI)
172
- export const readOnlyTools: Tool[] = baseReadOnlyToolNames.map((name) => toolDefs[name].tool);
173
-
174
- // All available tools (using process.cwd(), no UI)
175
- export const allTools = Object.fromEntries(Object.entries(toolDefs).map(([name, def]) => [name, def.tool])) as Record<
176
- ToolName,
177
- Tool
178
- >;
179
-
180
- /**
181
- * Create coding tools configured for a specific working directory.
182
- * @param cwd - Working directory for tools
183
- * @param hasUI - Whether UI is available (includes ask tool if true)
184
- * @param sessionContext - Optional session context for tools that need it
185
- * @param options - Options for tool configuration
186
- */
187
- export async function createCodingTools(
188
- cwd: string,
189
- hasUI = false,
190
- sessionContext?: SessionContext,
191
- options?: CodingToolsOptions,
192
- ): Promise<Tool[]> {
193
- const names = hasUI ? [...baseCodingToolNames, ...uiToolNames] : baseCodingToolNames;
194
- const optionsWithTools = { ...options, availableTools: new Set(names) };
195
- return Promise.all(names.map((name) => toolDefs[name].create(cwd, sessionContext, optionsWithTools)));
196
- }
197
-
198
- /**
199
- * Create read-only tools configured for a specific working directory.
200
- * @param cwd - Working directory for tools
201
- * @param hasUI - Whether UI is available (includes ask tool if true)
202
- * @param sessionContext - Optional session context for tools that need it
203
- * @param options - Options for tool configuration
204
- */
205
- export async function createReadOnlyTools(
206
- cwd: string,
207
- hasUI = false,
208
- sessionContext?: SessionContext,
209
- options?: CodingToolsOptions,
210
- ): Promise<Tool[]> {
211
- const names = hasUI ? [...baseReadOnlyToolNames, ...uiToolNames] : baseReadOnlyToolNames;
212
- const optionsWithTools = { ...options, availableTools: new Set(names) };
213
- return Promise.all(names.map((name) => toolDefs[name].create(cwd, sessionContext, optionsWithTools)));
214
- }
215
-
216
- /**
217
- * Create all tools configured for a specific working directory.
218
- * @param cwd - Working directory for tools
219
- * @param sessionContext - Optional session context for tools that need it
220
- * @param options - Options for tool configuration
221
- */
222
- export async function createAllTools(
223
- cwd: string,
224
- sessionContext?: SessionContext,
225
- options?: CodingToolsOptions,
226
- ): Promise<Record<ToolName, Tool>> {
227
- const names = Object.keys(toolDefs);
228
- const optionsWithTools = { ...options, availableTools: new Set(names) };
229
- const entries = await Promise.all(
230
- Object.entries(toolDefs).map(async ([name, def]) => [
231
- name,
232
- await def.create(cwd, sessionContext, optionsWithTools),
233
- ]),
234
- );
235
- return Object.fromEntries(entries) as Record<ToolName, Tool>;
236
- }
237
-
238
- /**
239
- * Wrap a bash tool with interception that redirects common patterns to specialized tools.
240
- * This helps prevent LLMs from falling back to shell commands when better tools exist.
241
- *
242
- * @param bashTool - The bash tool to wrap
243
- * @param availableTools - Set of tool names that are available (for context-aware blocking)
244
- * @returns Wrapped bash tool with interception
245
- */
246
- export function wrapBashWithInterception(bashTool: Tool, availableTools: Set<string>): Tool {
247
- const originalExecute = bashTool.execute;
248
-
249
- return {
250
- ...bashTool,
251
- execute: async (toolCallId, params, signal, onUpdate, context) => {
252
- const command = (params as { command: string }).command;
253
-
254
- // Check for forbidden patterns
255
- const interception = checkBashInterception(command, availableTools);
256
- if (interception.block) {
257
- throw new Error(interception.message);
258
- }
123
+ export const HIDDEN_TOOLS: Record<string, ToolFactory> = {
124
+ report_finding: () => reportFindingTool,
125
+ submit_review: () => submitReviewTool,
126
+ };
259
127
 
260
- // Check for simple ls that should use ls tool
261
- const lsInterception = checkSimpleLsInterception(command, availableTools);
262
- if (lsInterception.block) {
263
- throw new Error(lsInterception.message);
264
- }
265
-
266
- // Pass through to original bash tool
267
- return originalExecute(toolCallId, params, signal, onUpdate, context);
268
- },
269
- };
270
- }
128
+ export type ToolName = keyof typeof BUILTIN_TOOLS;
271
129
 
272
130
  /**
273
- * Apply bash interception to a set of tools.
274
- * Finds the bash tool and wraps it with interception based on other available tools.
275
- *
276
- * @param tools - Array of tools to process
277
- * @returns Tools with bash interception applied
131
+ * Create tools from BUILTIN_TOOLS registry.
278
132
  */
279
- export function applyBashInterception(tools: Tool[]): Tool[] {
280
- const toolNames = new Set(tools.map((t) => t.name));
281
-
282
- // If bash isn't in the tools, nothing to do
283
- if (!toolNames.has("bash")) {
284
- return tools;
133
+ export async function createTools(session: ToolSession, toolNames?: string[]): Promise<Tool[]> {
134
+ const requestedTools = toolNames && toolNames.length > 0 ? toolNames : undefined;
135
+ const allTools: Record<string, ToolFactory> = { ...BUILTIN_TOOLS, ...HIDDEN_TOOLS };
136
+ const entries = requestedTools
137
+ ? requestedTools
138
+ .filter((name, index) => requestedTools.indexOf(name) === index && name in allTools)
139
+ .map((name) => [name, allTools[name]] as const)
140
+ : Object.entries(BUILTIN_TOOLS);
141
+ const results = await Promise.all(entries.map(([, factory]) => factory(session)));
142
+ const tools = results.filter((t): t is Tool => t !== null);
143
+
144
+ if (requestedTools) {
145
+ const allowed = new Set(requestedTools);
146
+ return tools.filter((tool) => allowed.has(tool.name));
285
147
  }
286
148
 
287
- return tools.map((tool) => {
288
- if (tool.name === "bash") {
289
- return wrapBashWithInterception(tool, toolNames);
290
- }
291
- return tool;
292
- });
149
+ return tools;
293
150
  }
@@ -7,6 +7,7 @@ import { Type } from "@sinclair/typebox";
7
7
  import { getLanguageFromPath, type Theme } from "../../modes/interactive/theme/theme";
8
8
  import type { RenderResultOptions } from "../custom-tools/types";
9
9
  import { untilAborted } from "../utils";
10
+ import type { ToolSession } from "./index";
10
11
  import { resolveToCwd } from "./path-utils";
11
12
  import {
12
13
  formatAge,
@@ -37,7 +38,7 @@ export interface LsToolDetails {
37
38
  entryLimitReached?: number;
38
39
  }
39
40
 
40
- export function createLsTool(cwd: string): AgentTool<typeof lsSchema> {
41
+ export function createLsTool(session: ToolSession): AgentTool<typeof lsSchema> {
41
42
  return {
42
43
  name: "ls",
43
44
  label: "Ls",
@@ -49,7 +50,7 @@ export function createLsTool(cwd: string): AgentTool<typeof lsSchema> {
49
50
  signal?: AbortSignal,
50
51
  ) => {
51
52
  return untilAborted(signal, async () => {
52
- const dirPath = resolveToCwd(path || ".", cwd);
53
+ const dirPath = resolveToCwd(path || ".", session.cwd);
53
54
  const effectiveLimit = limit ?? DEFAULT_LIMIT;
54
55
 
55
56
  // Check if path exists
@@ -159,9 +160,6 @@ export function createLsTool(cwd: string): AgentTool<typeof lsSchema> {
159
160
  };
160
161
  }
161
162
 
162
- /** Default ls tool using process.cwd() - for backwards compatibility */
163
- export const lsTool = createLsTool(process.cwd());
164
-
165
163
  // =============================================================================
166
164
  // TUI Renderer
167
165
  // =============================================================================
@@ -271,10 +269,7 @@ export const lsToolRenderer = {
271
269
  }
272
270
 
273
271
  if (hasTruncation) {
274
- text += `\n ${uiTheme.fg("dim", uiTheme.tree.last)} ${uiTheme.fg(
275
- "warning",
276
- `truncated: ${truncationReasons.join(", ")}`,
277
- )}`;
272
+ text += `\n ${uiTheme.fg("dim", uiTheme.tree.last)} ${uiTheme.fg("warning", `truncated: ${truncationReasons.join(", ")}`)}`;
278
273
  }
279
274
 
280
275
  return new Text(text, 0, 0);
@@ -7,6 +7,7 @@ import { type Theme, theme } from "../../../modes/interactive/theme/theme";
7
7
  import lspDescription from "../../../prompts/tools/lsp.md" with { type: "text" };
8
8
  import { logger } from "../../logger";
9
9
  import { once, untilAborted } from "../../utils";
10
+ import type { ToolSession } from "../index";
10
11
  import { resolveToCwd } from "../path-utils";
11
12
  import {
12
13
  ensureFileOpen,
@@ -687,7 +688,7 @@ export function createLspWritethrough(cwd: string, options?: WritethroughOptions
687
688
  }
688
689
 
689
690
  /** Create an LSP tool */
690
- export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolDetails, Theme> {
691
+ export function createLspTool(session: ToolSession): AgentTool<typeof lspSchema, LspToolDetails, Theme> {
691
692
  return {
692
693
  name: "lsp",
693
694
  label: "LSP",
@@ -713,7 +714,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
713
714
  include_declaration,
714
715
  } = params;
715
716
 
716
- const config = await getConfig(cwd);
717
+ const config = await getConfig(session.cwd);
717
718
 
718
719
  // Status action doesn't need a file
719
720
  if (action === "status") {
@@ -730,7 +731,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
730
731
 
731
732
  // Workspace diagnostics - check entire project
732
733
  if (action === "workspace_diagnostics") {
733
- const result = await runWorkspaceDiagnostics(cwd, config);
734
+ const result = await runWorkspaceDiagnostics(session.cwd, config);
734
735
  return {
735
736
  content: [
736
737
  {
@@ -757,7 +758,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
757
758
  const allServerNames = new Set<string>();
758
759
 
759
760
  for (const target of targets) {
760
- const resolved = resolveToCwd(target, cwd);
761
+ const resolved = resolveToCwd(target, session.cwd);
761
762
  const servers = getServersForFile(config, resolved);
762
763
  if (servers.length === 0) {
763
764
  results.push(`${theme.status.error} ${target}: No language server found`);
@@ -765,7 +766,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
765
766
  }
766
767
 
767
768
  const uri = fileToUri(resolved);
768
- const relPath = path.relative(cwd, resolved);
769
+ const relPath = path.relative(session.cwd, resolved);
769
770
  const allDiagnostics: Diagnostic[] = [];
770
771
 
771
772
  // Query all applicable servers for this file
@@ -773,12 +774,12 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
773
774
  allServerNames.add(serverName);
774
775
  try {
775
776
  if (serverConfig.createClient) {
776
- const linterClient = getLinterClient(serverName, serverConfig, cwd);
777
+ const linterClient = getLinterClient(serverName, serverConfig, session.cwd);
777
778
  const diagnostics = await linterClient.lint(resolved);
778
779
  allDiagnostics.push(...diagnostics);
779
780
  continue;
780
781
  }
781
- const client = await getOrCreateClient(serverConfig, cwd);
782
+ const client = await getOrCreateClient(serverConfig, session.cwd);
782
783
  await refreshFile(client, resolved);
783
784
  const diagnostics = await waitForDiagnostics(client, uri);
784
785
  allDiagnostics.push(...diagnostics);
@@ -847,7 +848,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
847
848
  };
848
849
  }
849
850
 
850
- const resolvedFile = file ? resolveToCwd(file, cwd) : null;
851
+ const resolvedFile = file ? resolveToCwd(file, session.cwd) : null;
851
852
  const serverInfo = resolvedFile
852
853
  ? getLspServerForFile(config, resolvedFile)
853
854
  : getServerForWorkspaceAction(config, action);
@@ -862,10 +863,10 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
862
863
  const [serverName, serverConfig] = serverInfo;
863
864
 
864
865
  try {
865
- const client = await getOrCreateClient(serverConfig, cwd);
866
+ const client = await getOrCreateClient(serverConfig, session.cwd);
866
867
  let targetFile = resolvedFile;
867
868
  if (action === "runnables" && !targetFile) {
868
- targetFile = findFileForServer(cwd, serverConfig);
869
+ targetFile = findFileForServer(session.cwd, serverConfig);
869
870
  if (!targetFile) {
870
871
  return {
871
872
  content: [{ type: "text", text: "Error: no matching files found for runnables" }],
@@ -914,7 +915,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
914
915
  output = "No definition found";
915
916
  } else {
916
917
  output = `Found ${locations.length} definition(s):\n${locations
917
- .map((loc) => ` ${formatLocation(loc, cwd)}`)
918
+ .map((loc) => ` ${formatLocation(loc, session.cwd)}`)
918
919
  .join("\n")}`;
919
920
  }
920
921
  }
@@ -931,7 +932,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
931
932
  if (!result || result.length === 0) {
932
933
  output = "No references found";
933
934
  } else {
934
- const lines = result.map((loc) => ` ${formatLocation(loc, cwd)}`);
935
+ const lines = result.map((loc) => ` ${formatLocation(loc, session.cwd)}`);
935
936
  output = `Found ${result.length} reference(s):\n${lines.join("\n")}`;
936
937
  }
937
938
  break;
@@ -964,7 +965,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
964
965
  details: { action, serverName, success: false },
965
966
  };
966
967
  } else {
967
- const relPath = path.relative(cwd, targetFile);
968
+ const relPath = path.relative(session.cwd, targetFile);
968
969
  // Check if hierarchical (DocumentSymbol) or flat (SymbolInformation)
969
970
  if ("selectionRange" in result[0]) {
970
971
  // Hierarchical
@@ -998,10 +999,8 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
998
999
  if (!result || result.length === 0) {
999
1000
  output = `No symbols matching "${query}"`;
1000
1001
  } else {
1001
- const lines = result.map((s) => formatSymbolInformation(s, cwd));
1002
- output = `Found ${result.length} symbol(s) matching "${query}":\n${lines
1003
- .map((l) => ` ${l}`)
1004
- .join("\n")}`;
1002
+ const lines = result.map((s) => formatSymbolInformation(s, session.cwd));
1003
+ output = `Found ${result.length} symbol(s) matching "${query}":\n${lines.map((l) => ` ${l}`).join("\n")}`;
1005
1004
  }
1006
1005
  break;
1007
1006
  }
@@ -1025,10 +1024,10 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1025
1024
  } else {
1026
1025
  const shouldApply = apply !== false;
1027
1026
  if (shouldApply) {
1028
- const applied = await applyWorkspaceEdit(result, cwd);
1027
+ const applied = await applyWorkspaceEdit(result, session.cwd);
1029
1028
  output = `Applied rename:\n${applied.map((a) => ` ${a}`).join("\n")}`;
1030
1029
  } else {
1031
- const preview = formatWorkspaceEdit(result, cwd);
1030
+ const preview = formatWorkspaceEdit(result, session.cwd);
1032
1031
  output = `Rename preview:\n${preview.map((p) => ` ${p}`).join("\n")}`;
1033
1032
  }
1034
1033
  }
@@ -1114,7 +1113,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1114
1113
  }
1115
1114
 
1116
1115
  if (isCodeAction(resolvedAction) && resolvedAction.edit) {
1117
- const applied = await applyWorkspaceEdit(resolvedAction.edit, cwd);
1116
+ const applied = await applyWorkspaceEdit(resolvedAction.edit, session.cwd);
1118
1117
  output = `Applied "${codeAction.title}":\n${applied.map((a) => ` ${a}`).join("\n")}`;
1119
1118
  } else {
1120
1119
  const commandPayload = getCommandPayload(resolvedAction);
@@ -1136,9 +1135,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1136
1135
  }
1137
1136
  return ` [${i}] ${actionItem.title}`;
1138
1137
  });
1139
- output = `Available code actions:\n${lines.join(
1140
- "\n",
1141
- )}\n\nUse action_index parameter to apply a specific action.`;
1138
+ output = `Available code actions:\n${lines.join("\n")}\n\nUse action_index parameter to apply a specific action.`;
1142
1139
  }
1143
1140
  break;
1144
1141
  }
@@ -1169,7 +1166,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1169
1166
  const lines = calls.map((call) => {
1170
1167
  const loc = { uri: call.from.uri, range: call.from.selectionRange };
1171
1168
  const detail = call.from.detail ? ` (${call.from.detail})` : "";
1172
- return ` ${call.from.name}${detail} @ ${formatLocation(loc, cwd)}`;
1169
+ return ` ${call.from.name}${detail} @ ${formatLocation(loc, session.cwd)}`;
1173
1170
  });
1174
1171
  output = `Found ${calls.length} caller(s) of "${item.name}":\n${lines.join("\n")}`;
1175
1172
  }
@@ -1184,7 +1181,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1184
1181
  const lines = calls.map((call) => {
1185
1182
  const loc = { uri: call.to.uri, range: call.to.selectionRange };
1186
1183
  const detail = call.to.detail ? ` (${call.to.detail})` : "";
1187
- return ` ${call.to.name}${detail} @ ${formatLocation(loc, cwd)}`;
1184
+ return ` ${call.to.name}${detail} @ ${formatLocation(loc, session.cwd)}`;
1188
1185
  });
1189
1186
  output = `"${item.name}" calls ${calls.length} function(s):\n${lines.join("\n")}`;
1190
1187
  }
@@ -1207,7 +1204,7 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1207
1204
  await rustAnalyzer.flycheck(client, resolvedFile ?? undefined);
1208
1205
  const collected: Array<{ filePath: string; diagnostic: Diagnostic }> = [];
1209
1206
  for (const [diagUri, diags] of client.diagnostics.entries()) {
1210
- const relPath = path.relative(cwd, uriToFile(diagUri));
1207
+ const relPath = path.relative(session.cwd, uriToFile(diagUri));
1211
1208
  for (const diag of diags) {
1212
1209
  collected.push({ filePath: relPath, diagnostic: diag });
1213
1210
  }
@@ -1274,13 +1271,13 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1274
1271
  const result = await rustAnalyzer.ssr(client, query, replacement, !shouldApply);
1275
1272
 
1276
1273
  if (shouldApply) {
1277
- const applied = await applyWorkspaceEdit(result, cwd);
1274
+ const applied = await applyWorkspaceEdit(result, session.cwd);
1278
1275
  output =
1279
1276
  applied.length > 0
1280
1277
  ? `Applied SSR:\n${applied.map((a) => ` ${a}`).join("\n")}`
1281
1278
  : "SSR: no matches found";
1282
1279
  } else {
1283
- const preview = formatWorkspaceEdit(result, cwd);
1280
+ const preview = formatWorkspaceEdit(result, session.cwd);
1284
1281
  output =
1285
1282
  preview.length > 0
1286
1283
  ? `SSR preview:\n${preview.map((p) => ` ${p}`).join("\n")}`
@@ -1366,4 +1363,10 @@ export function createLspTool(cwd: string): AgentTool<typeof lspSchema, LspToolD
1366
1363
  };
1367
1364
  }
1368
1365
 
1369
- export const lspTool = createLspTool(process.cwd());
1366
+ export const lspTool = createLspTool({
1367
+ cwd: process.cwd(),
1368
+ hasUI: false,
1369
+ rulebookRules: [],
1370
+ getSessionFile: () => null,
1371
+ getSessionSpawns: () => null,
1372
+ });