-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtool-registry.ts
More file actions
852 lines (743 loc) · 26 KB
/
tool-registry.ts
File metadata and controls
852 lines (743 loc) · 26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
import {
type CellData,
cellReferences$,
createCellBetween,
events,
tables,
} from "@runt/schema";
import type { Store } from "jsr:@runtimed/schema";
import { logger } from "@runtimed/agent-core";
import { getMCPClient } from "./mcp-client.ts";
export interface NotebookTool {
name: string;
description: string;
parameters: {
type: string;
properties: Record<string, ToolParameter>;
required: string[];
};
}
interface ToolParameter {
type: string;
enum?: string[];
description?: string;
default?: string;
items?: ToolParameter; // For array types
properties?: Record<string, ToolParameter>; // For object types
required?: string[]; // For object types
}
// Define basic notebook tools (always available)
const BASIC_NOTEBOOK_TOOLS: NotebookTool[] = [
{
name: "create_cell",
description: "Create a new cell in the notebook after a specific cell. " +
"The AI knows its own cell ID and can reference any previously created cell IDs.",
parameters: {
type: "object",
properties: {
cellType: {
type: "string",
enum: ["code", "markdown", "ai", "sql"],
description:
"The type of cell to create (defaults to 'code' if not specified)",
},
source: {
type: "string",
description: "The content/source code for the cell",
},
after_id: {
type: "string",
description: "The ID of the cell to place this new cell after. " +
"Use your own cell ID to place cells below yourself, " +
"or use a previously created cell's ID to build sequences.",
},
},
required: ["source", "after_id"],
},
},
{
name: "modify_cell",
description: "Modify the content of an existing cell in the notebook. " +
"Use this to fix bugs, improve code, or update content based on user feedback. " +
"Use the actual cell ID from the context (shown as 'ID: cell-xxx'), not position numbers.",
parameters: {
type: "object",
properties: {
cellId: {
type: "string",
description: "The actual cell ID from the context " +
"(e.g., 'cell-1234567890-abc'), not a position number",
},
source: {
type: "string",
description: "The new content/source code for the cell",
},
},
required: ["cellId", "source"],
},
},
{
name: "execute_cell",
description: "Execute a specific cell in the notebook. " +
"Use this to run code after creating or modifying it, or to re-run existing cells. " +
"Use the actual cell ID from the context (shown as 'ID: cell-xxx'), not position numbers.",
parameters: {
type: "object",
properties: {
cellId: {
type: "string",
description: "The actual cell ID from the context " +
"(e.g., 'cell-1234567890-abc'), not a position number",
},
},
required: ["cellId"],
},
},
];
// Define vector store tools (only available when indexing is enabled)
const VECTOR_STORE_TOOLS: NotebookTool[] = [
{
name: "query_documents",
description:
"Search and retrieve relevant content from mounted files based on natural language queries. " +
"Use this tool when the user asks questions about file contents, " +
"seeks specific information within files, or needs to understand what's in the mounted data. " +
"This tool searches through the actual file contents and returns relevant excerpts. " +
"IMPORTANT: Always try this tool first when the user asks about data, files, or analysis - " +
"don't ask the user to provide files manually when this tool is available. ",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description:
"Natural language search query to find relevant content within files " +
"(e.g., 'functions that handle authentication', 'sales data for Q3', 'error handling code')",
},
},
required: ["query"],
},
},
{
name: "list_indexed_files",
description:
"Lists all file paths that have been successfully indexed from mounted directories. " +
"Use this tool to see what files are available for analysis when you need an overview of the mounted data. " +
"This is helpful for understanding the scope of available data before diving into specific queries. ",
parameters: {
type: "object",
properties: {},
required: [],
},
},
];
// Combined notebook tools
const NOTEBOOK_TOOLS = [...VECTOR_STORE_TOOLS, ...BASIC_NOTEBOOK_TOOLS];
/**
* Convert MCP parameter schema to ToolParameter format
*/
function convertMcpParameterToToolParameter(
mcpParam: Record<string, unknown>,
): ToolParameter {
const baseParam: ToolParameter = {
type: (mcpParam.type as string) || "string",
description: mcpParam.description as string,
enum: mcpParam.enum as string[],
default: mcpParam.default as string,
};
// Handle array types with items
if (mcpParam.type === "array" && mcpParam.items) {
baseParam.items = convertMcpParameterToToolParameter(
mcpParam.items as Record<string, unknown>,
);
}
// Handle object types with properties
if (mcpParam.type === "object" && mcpParam.properties) {
baseParam.properties = Object.fromEntries(
Object.entries(mcpParam.properties as Record<string, unknown>).map(
([key, value]) => [
key,
convertMcpParameterToToolParameter(value as Record<string, unknown>),
],
),
);
baseParam.required = mcpParam.required as string[];
}
return baseParam;
}
/**
* Get all available tools including both notebook tools and MCP tools
*/
export async function getAllTools(): Promise<NotebookTool[]> {
const notebookTools = [...BASIC_NOTEBOOK_TOOLS];
try {
// Import vector store checking function to avoid circular dependencies
const { isVectorStoreIndexingEnabled } = await import("./vector-store.ts");
if (isVectorStoreIndexingEnabled()) {
notebookTools.push(...VECTOR_STORE_TOOLS);
}
} catch (_vectorstoreError) {
logger.error(`failed to import vector store or get its status`);
}
try {
const mcpClient = await getMCPClient();
const mcpTools = mcpClient.getTools();
// Convert MCP tools to notebook tool format
const convertedMcpTools: NotebookTool[] = mcpTools.map((mcpTool) => ({
name: mcpTool.name,
description: mcpTool.description,
parameters: {
type: mcpTool.parameters.type,
properties: Object.fromEntries(
Object.entries(mcpTool.parameters.properties || {}).map((
[key, value],
) => [
key,
convertMcpParameterToToolParameter(
value as Record<string, unknown>,
),
]),
),
required: mcpTool.parameters.required || [],
},
}));
notebookTools.push(...convertedMcpTools);
} catch (error) {
logger.error("Failed to get MCP tools, using only notebook tools", {
error: String(error),
});
}
return notebookTools;
}
/**
* Get only the notebook tools (for backward compatibility)
*/
export const NOTEBOOK_TOOLS_EXPORT = NOTEBOOK_TOOLS;
export function createCell(
store: Store,
sessionId: string,
_currentCell: CellData,
args: Record<string, unknown>,
) {
const cellType = String(args.cellType || "code");
const rawContent = String(args.source || args.content || ""); // Check source first, then content
const content = rawContent;
const afterId = String(args.after_id); // Now required
// Get ordered cells with fractional indices
const cellList = store.query(cellReferences$);
// Find the cell to insert after
const afterCellIndex = cellList.findIndex((c) => c.id === afterId);
if (afterCellIndex === -1) {
throw new Error(`Cell with ID ${afterId} not found`);
}
// Generate unique cell ID
const newCellId = `cell-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const cellBefore = cellList[afterCellIndex]!; // Safe because we checked afterCellIndex !== -1
const cellAfter = afterCellIndex < cellList.length - 1
? cellList[afterCellIndex + 1] || null
: null;
logger.info("Creating cell via AI tool call", {
cellType,
afterId,
contentLength: content.length,
cellBefore: cellBefore?.id,
cellAfter: cellAfter?.id,
});
// Create the new cell with fractional index
const createResult = createCellBetween(
{
id: newCellId,
cellType: cellType as "code" | "markdown" | "raw" | "sql" | "ai",
createdBy: `ai-assistant-${sessionId}`,
},
cellBefore,
cellAfter,
cellList,
);
// Commit all events (may include rebalancing)
createResult.events.forEach((event) => store.commit(event));
// Set the cell source if provided
if (content.length > 0) {
store.commit(
events.cellSourceChanged({
id: newCellId,
source: content,
modifiedBy: `ai-assistant-${sessionId}`,
}),
);
}
logger.info("Created cell successfully", {
cellId: newCellId,
contentPreview: content.slice(0, 100),
});
return `Created ${cellType} cell: ${newCellId}`;
}
/**
* Handle tool calls from AI with result return
*/
export async function handleToolCallWithResult(
store: Store,
sessionId: string,
currentCell: CellData,
toolCall: {
id: string;
name: string;
arguments: Record<string, unknown>;
},
sendWorkerMessage?: (type: string, data: unknown) => Promise<unknown>,
): Promise<string> {
const { name, arguments: args } = toolCall;
// Validate tool parameters against schema
try {
// Get all available tools to find the definition
const allTools = await getAllTools();
const toolDef = allTools.find((tool) => tool.name === name);
if (toolDef && toolDef.parameters?.required) {
const missingParams = toolDef.parameters.required.filter(
(param: string) => !(param in args),
);
if (missingParams.length > 0) {
const errorMessage = `Missing required parameters: ${
missingParams.join(", ")
}`;
logger.error("Tool call validation failed", {
toolName: name,
missingParams,
providedArgs: Object.keys(args),
});
throw new Error(errorMessage);
}
}
} catch (error) {
// If validation fails, log and re-throw
if (
error instanceof Error &&
error.message.includes("Missing required parameters")
) {
throw error;
}
logger.warn("Could not validate tool parameters", {
toolName: name,
error: error instanceof Error ? error.message : String(error),
});
}
// Check if tool requires approval - only external tools require approval
const isBuiltInTool = NOTEBOOK_TOOLS.some((tool) => tool.name === name);
const requiresApproval = !isBuiltInTool;
if (requiresApproval) {
// Check if we already have an approval for this specific tool call
let existingApproval = store.query(
tables.toolApprovals.select().where({ toolCallId: toolCall.id }),
)[0];
// If no specific approval, check for a blanket "always" approval for this tool
if (!existingApproval) {
const alwaysApprovals = store.query(
tables.toolApprovals.select().where({
toolName: name,
status: "approved_always",
}),
);
if (alwaysApprovals.length > 0) {
// Use the blanket approval
existingApproval = alwaysApprovals[0];
}
}
if (!existingApproval || existingApproval.status === "pending") {
// Request approval if we don't have one
if (!existingApproval) {
logger.info("Requesting tool approval", {
toolName: name,
toolCallId: toolCall.id,
});
store.commit(
events.toolApprovalRequested({
toolCallId: toolCall.id,
cellId: currentCell.id,
toolName: name,
arguments: args,
requestedAt: new Date(),
}),
);
}
// Wait for approval with polling
const approvalPromise = new Promise<string>((resolve, reject) => {
const cleanup = () => {
if (timeout) clearTimeout(timeout);
if (pollInterval) clearInterval(pollInterval);
};
const timeout = setTimeout(() => {
cleanup();
reject(
new Error(`Tool approval timeout after 60 seconds for ${name}`),
);
}, 60000); // 60 second timeout
// Poll for approval status
const pollInterval = setInterval(() => {
const approval = store.query(
tables.toolApprovals.select().where({ toolCallId: toolCall.id }),
)[0];
if (approval && approval.status !== "pending") {
cleanup();
if (approval.status === "denied") {
reject(new Error(`Tool call denied by user: ${name}`));
return;
}
if (
approval.status === "approved_once" ||
approval.status === "approved_always"
) {
resolve("approved");
return;
}
}
}, 500); // Poll every 500ms
});
try {
await approvalPromise;
} catch (error) {
logger.error("Tool approval failed", { toolName: name, error });
throw error;
}
} else if (existingApproval.status === "denied") {
logger.warn("Tool call denied by previous approval", { toolName: name });
throw new Error(`Tool call denied: ${name}`);
}
logger.info("Tool approved, proceeding with execution", { toolName: name });
}
// Handle MCP tools first (with mcp__ prefix)
if (name.startsWith("mcp__")) {
try {
// Transform name from mcp__<servername>__<toolname> to <servername>:<toolname>
const transformedName = name.slice(5).replace("__", ":"); // Remove 'mcp__' prefix and replace first '__' with ':'
logger.info("Calling MCP tool", {
toolName: name,
transformedName,
args,
});
const mcpClient = await getMCPClient();
const result = await mcpClient.callTool(transformedName, args);
logger.info("MCP tool executed successfully", {
toolName: name,
resultLength: result.length,
});
return result;
} catch (error) {
logger.error("MCP tool execution failed", { toolName: name, error });
throw new Error(
`MCP tool execution failed: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
// Handle built-in notebook tools
switch (name) {
case "create_cell": {
return createCell(store, sessionId, currentCell, args);
}
case "modify_cell": {
const cellId = String(args.cellId || "");
const rawContent = String(args.source || args.content || "");
const content = rawContent;
if (!cellId) {
logger.error("modify_cell: cellId is required");
throw new Error("modify_cell: cellId is required");
}
// Check if cell exists
const existingCell = store.query(
tables.cells.select().where({ id: cellId }),
)[0];
if (!existingCell) {
logger.error("modify_cell: Cell not found", { cellId });
throw new Error(`modify_cell: Cell not found: ${cellId}`);
}
logger.info("Modifying cell via AI tool call", {
cellId,
contentLength: content.length,
});
// Update the cell source
store.commit(
events.cellSourceChanged({
id: cellId,
source: content,
modifiedBy: `ai-assistant-${sessionId}`,
}),
);
logger.info("Modified cell successfully", {
cellId,
contentPreview: content.slice(0, 100),
});
return `Modified cell ${cellId} with ${content.length} characters`;
}
case "execute_cell": {
const cellId = String(args.cellId || "");
if (!cellId) {
logger.error("execute_cell: cellId is required");
throw new Error("execute_cell: cellId is required");
}
// Check if cell exists and is executable
const existingCell = store.query(
tables.cells.select().where({ id: cellId }),
)[0];
if (!existingCell) {
logger.error("execute_cell: Cell not found", { cellId });
throw new Error(`execute_cell: Cell not found: ${cellId}`);
}
if (existingCell.cellType !== "code") {
logger.error(
"execute_cell: Only code cells can be executed",
{
cellId,
cellType: existingCell.cellType,
},
);
throw new Error(
`execute_cell: Only code cells can be executed, got ${existingCell.cellType}`,
);
}
logger.info("Executing cell via AI tool call", { cellId });
const queueId = `exec-${Date.now()}-${
Math.random().toString(36).slice(2)
}`;
// Set up execution completion monitoring with polling
const executionCompletePromise = new Promise<string>(
(resolve, reject) => {
const cleanup = () => {
if (timeout) clearTimeout(timeout);
if (pollInterval) clearInterval(pollInterval);
};
const timeout = setTimeout(() => {
cleanup();
reject(
new Error(
`Execution timeout after 30 seconds for cell ${cellId}`,
),
);
}, 30000);
// Poll execution status
const pollInterval = setInterval(() => {
const executionEntry = store.query(
tables.executionQueue.select().where({ id: queueId }),
)[0];
if (!executionEntry) return;
if (
executionEntry.status === "completed" ||
executionEntry.status === "failed"
) {
cleanup();
if (executionEntry.status === "failed") {
reject(new Error(`Execution failed for cell ${cellId}`));
return;
}
// Get cell outputs after execution
const outputs = store.query(
tables.outputs.select().where({ cellId }).orderBy(
"position",
"asc",
),
);
// Format outputs for AI consumption
let outputSummary = `Cell ${cellId} executed successfully`;
if (outputs.length > 0) {
const outputTexts: string[] = [];
for (const output of outputs) {
if (output.outputType === "terminal" && output.data) {
outputTexts.push(
`Output: ${String(output.data).trim()}`,
);
} else if (
output.outputType === "multimedia_result"
) {
// Try to get text representation from representations or fallback to data
// Prioritize markdown for AI context, then plain text
let resultText = "";
let usedFormat = "";
logger.debug(
"Processing multimedia_result for tool response",
{
cellId,
hasRepresentations: !!output.representations,
representationKeys: output.representations
? Object.keys(output.representations)
: [],
hasData: !!output.data,
},
);
if (
output.representations &&
output.representations["text/markdown"]
) {
const container = output.representations["text/markdown"];
if (container.type === "inline") {
resultText = String(container.data || "");
usedFormat = "text/markdown";
}
} else if (
output.representations &&
output.representations["text/plain"]
) {
const container = output.representations["text/plain"];
if (container.type === "inline") {
resultText = String(container.data || "");
usedFormat = "text/plain";
}
} else if (output.data) {
resultText = String(output.data);
usedFormat = "raw_data";
}
logger.debug("Tool result content extracted", {
cellId,
usedFormat,
contentLength: resultText.length,
fullContent: resultText,
});
if (resultText) {
outputTexts.push(`Result: ${resultText.trim()}`);
}
} else if (output.outputType === "error" && output.data) {
try {
const errorData = typeof output.data === "string"
? JSON.parse(output.data)
: output.data;
outputTexts.push(
`Error: ${errorData.ename}: ${errorData.evalue}`,
);
} catch {
outputTexts.push(`Error: ${String(output.data)}`);
}
}
}
if (outputTexts.length > 0) {
outputSummary += `. ${outputTexts.join(". ")}`;
}
}
resolve(outputSummary);
}
}, 500); // Poll every 500ms
},
);
// Request execution for the cell
store.commit(
events.executionRequested({
queueId,
cellId,
executionCount: (existingCell.executionCount || 0) + 1,
requestedBy: `ai-assistant-${sessionId}`,
}),
);
logger.info(
"Execution requested for cell, waiting for completion",
{ cellId, queueId },
);
// Wait for execution to complete and return the result
return await executionCompletePromise;
}
case "query_documents": {
const query = String(args.query || "");
if (!query) {
logger.error("query_documents: query is required");
throw new Error("query_documents: query is required");
}
logger.info("Querying vector store", {
query,
queryLength: query.length,
});
try {
// Import vector store here to avoid circular dependencies
const { getVectorStore } = await import("./vector-store.ts");
const vectorStore = getVectorStore();
// Check vector store status
const status = vectorStore.getStatus();
if (status.isIngesting && !status.ingestionComplete) {
logger.info(
"Vector store ingestion in progress, waiting for completion",
);
}
// Query the vector store (will wait for ingestion if needed)
const result = await vectorStore.query(query);
logger.info("Vector store query completed successfully", {
resultLength: result.length,
});
return result;
} catch (error) {
logger.error("Vector store query failed", {
query,
error: String(error),
});
if (
error instanceof Error && error.message.includes("not initialized")
) {
return "No documents have been mounted to search. Use the --mount flag when starting the runtime to add documents to the vector store.";
}
throw new Error(
`Document search failed: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
case "list_indexed_files": {
logger.info("Listing all indexed file paths");
try {
// Import vector store here to avoid circular dependencies
const { getVectorStore } = await import("./vector-store.ts");
const vectorStore = getVectorStore();
// Check vector store status
const status = vectorStore.getStatus();
if (status.isIngesting && !status.ingestionComplete) {
logger.info(
"Vector store ingestion in progress, waiting for completion",
);
}
// Get all indexed file paths
const response = vectorStore.getAllIndexedFilePaths();
logger.info("Retrieved all indexed file paths successfully");
return response;
} catch (error) {
logger.error("Failed to list indexed files", {
error: String(error),
});
if (
error instanceof Error && error.message.includes("not initialized")
) {
return "No files have been mounted and indexed. Use the --mount flag when starting the runtime to add files to the vector store.";
}
throw new Error(
`Failed to list indexed files: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
default:
// Handle unknown tools via Python worker if available
if (sendWorkerMessage) {
logger.info("Calling registered Python tool via worker", {
toolName: name,
argsKeys: Object.keys(args),
});
try {
const result = await sendWorkerMessage("run_registered_tool", {
toolName: name,
args: args,
});
logger.info("Python tool executed successfully", {
toolName: name,
result,
});
return `Tool ${name} executed successfully: ${String(result)}`;
} catch (error) {
logger.error("Python tool execution failed", {
toolName: name,
error: String(error),
});
throw new Error(`Failed to execute tool ${name}: ${String(error)}`);
}
} else {
logger.warn("Unknown AI tool and no worker available", {
toolName: name,
});
throw new Error(`Unknown tool: ${name}`);
}
}
}