skyloom 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/ci.yml +36 -0
- package/CONVERSION_PLAN.md +191 -0
- package/README.md +67 -0
- package/dist/agents/dew.d.ts +15 -0
- package/dist/agents/dew.d.ts.map +1 -0
- package/dist/agents/dew.js +74 -0
- package/dist/agents/dew.js.map +1 -0
- package/dist/agents/fair.d.ts +15 -0
- package/dist/agents/fair.d.ts.map +1 -0
- package/dist/agents/fair.js +106 -0
- package/dist/agents/fair.js.map +1 -0
- package/dist/agents/fog.d.ts +15 -0
- package/dist/agents/fog.d.ts.map +1 -0
- package/dist/agents/fog.js +52 -0
- package/dist/agents/fog.js.map +1 -0
- package/dist/agents/frost.d.ts +15 -0
- package/dist/agents/frost.d.ts.map +1 -0
- package/dist/agents/frost.js +54 -0
- package/dist/agents/frost.js.map +1 -0
- package/dist/agents/rain.d.ts +15 -0
- package/dist/agents/rain.d.ts.map +1 -0
- package/dist/agents/rain.js +54 -0
- package/dist/agents/rain.js.map +1 -0
- package/dist/agents/snow.d.ts +27 -0
- package/dist/agents/snow.d.ts.map +1 -0
- package/dist/agents/snow.js +226 -0
- package/dist/agents/snow.js.map +1 -0
- package/dist/cli/main.d.ts +7 -0
- package/dist/cli/main.d.ts.map +1 -0
- package/dist/cli/main.js +402 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/cli/mode.d.ts +17 -0
- package/dist/cli/mode.d.ts.map +1 -0
- package/dist/cli/mode.js +56 -0
- package/dist/cli/mode.js.map +1 -0
- package/dist/core/agent.d.ts +174 -0
- package/dist/core/agent.d.ts.map +1 -0
- package/dist/core/agent.js +1332 -0
- package/dist/core/agent.js.map +1 -0
- package/dist/core/agent_helpers.d.ts +51 -0
- package/dist/core/agent_helpers.d.ts.map +1 -0
- package/dist/core/agent_helpers.js +477 -0
- package/dist/core/agent_helpers.js.map +1 -0
- package/dist/core/bus.d.ts +99 -0
- package/dist/core/bus.d.ts.map +1 -0
- package/dist/core/bus.js +191 -0
- package/dist/core/bus.js.map +1 -0
- package/dist/core/cache.d.ts +63 -0
- package/dist/core/cache.d.ts.map +1 -0
- package/dist/core/cache.js +121 -0
- package/dist/core/cache.js.map +1 -0
- package/dist/core/checkpoint.d.ts +19 -0
- package/dist/core/checkpoint.d.ts.map +1 -0
- package/dist/core/checkpoint.js +120 -0
- package/dist/core/checkpoint.js.map +1 -0
- package/dist/core/circuit_breaker.d.ts +46 -0
- package/dist/core/circuit_breaker.d.ts.map +1 -0
- package/dist/core/circuit_breaker.js +99 -0
- package/dist/core/circuit_breaker.js.map +1 -0
- package/dist/core/config.d.ts +97 -0
- package/dist/core/config.d.ts.map +1 -0
- package/dist/core/config.js +281 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/constants.d.ts +78 -0
- package/dist/core/constants.d.ts.map +1 -0
- package/dist/core/constants.js +84 -0
- package/dist/core/constants.js.map +1 -0
- package/dist/core/factory.d.ts +63 -0
- package/dist/core/factory.d.ts.map +1 -0
- package/dist/core/factory.js +537 -0
- package/dist/core/factory.js.map +1 -0
- package/dist/core/icons.d.ts +28 -0
- package/dist/core/icons.d.ts.map +1 -0
- package/dist/core/icons.js +86 -0
- package/dist/core/icons.js.map +1 -0
- package/dist/core/index.d.ts +29 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +54 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/llm.d.ts +121 -0
- package/dist/core/llm.d.ts.map +1 -0
- package/dist/core/llm.js +532 -0
- package/dist/core/llm.js.map +1 -0
- package/dist/core/logger.d.ts +57 -0
- package/dist/core/logger.d.ts.map +1 -0
- package/dist/core/logger.js +122 -0
- package/dist/core/logger.js.map +1 -0
- package/dist/core/mcp.d.ts +190 -0
- package/dist/core/mcp.d.ts.map +1 -0
- package/dist/core/mcp.js +822 -0
- package/dist/core/mcp.js.map +1 -0
- package/dist/core/mcp_server.d.ts +26 -0
- package/dist/core/mcp_server.d.ts.map +1 -0
- package/dist/core/mcp_server.js +211 -0
- package/dist/core/mcp_server.js.map +1 -0
- package/dist/core/memory.d.ts +190 -0
- package/dist/core/memory.d.ts.map +1 -0
- package/dist/core/memory.js +988 -0
- package/dist/core/memory.js.map +1 -0
- package/dist/core/middleware.d.ts +114 -0
- package/dist/core/middleware.d.ts.map +1 -0
- package/dist/core/middleware.js +248 -0
- package/dist/core/middleware.js.map +1 -0
- package/dist/core/pipelines.d.ts +87 -0
- package/dist/core/pipelines.d.ts.map +1 -0
- package/dist/core/pipelines.js +301 -0
- package/dist/core/pipelines.js.map +1 -0
- package/dist/core/profile.d.ts +23 -0
- package/dist/core/profile.d.ts.map +1 -0
- package/dist/core/profile.js +289 -0
- package/dist/core/profile.js.map +1 -0
- package/dist/core/router.d.ts +24 -0
- package/dist/core/router.d.ts.map +1 -0
- package/dist/core/router.js +111 -0
- package/dist/core/router.js.map +1 -0
- package/dist/core/schemas.d.ts +82 -0
- package/dist/core/schemas.d.ts.map +1 -0
- package/dist/core/schemas.js +200 -0
- package/dist/core/schemas.js.map +1 -0
- package/dist/core/semantic.d.ts +92 -0
- package/dist/core/semantic.d.ts.map +1 -0
- package/dist/core/semantic.js +175 -0
- package/dist/core/semantic.js.map +1 -0
- package/dist/core/skill.d.ts +68 -0
- package/dist/core/skill.d.ts.map +1 -0
- package/dist/core/skill.js +350 -0
- package/dist/core/skill.js.map +1 -0
- package/dist/core/tool.d.ts +99 -0
- package/dist/core/tool.d.ts.map +1 -0
- package/dist/core/tool.js +341 -0
- package/dist/core/tool.js.map +1 -0
- package/dist/core/tool_router.d.ts +29 -0
- package/dist/core/tool_router.d.ts.map +1 -0
- package/dist/core/tool_router.js +172 -0
- package/dist/core/tool_router.js.map +1 -0
- package/dist/core/workspace.d.ts +48 -0
- package/dist/core/workspace.d.ts.map +1 -0
- package/dist/core/workspace.js +179 -0
- package/dist/core/workspace.js.map +1 -0
- package/dist/plugins/loader.d.ts +17 -0
- package/dist/plugins/loader.d.ts.map +1 -0
- package/dist/plugins/loader.js +96 -0
- package/dist/plugins/loader.js.map +1 -0
- package/dist/skills/loader.d.ts +9 -0
- package/dist/skills/loader.d.ts.map +1 -0
- package/dist/skills/loader.js +78 -0
- package/dist/skills/loader.js.map +1 -0
- package/dist/tools/builtin.d.ts +10 -0
- package/dist/tools/builtin.d.ts.map +1 -0
- package/dist/tools/builtin.js +414 -0
- package/dist/tools/builtin.js.map +1 -0
- package/dist/tools/computer.d.ts +12 -0
- package/dist/tools/computer.d.ts.map +1 -0
- package/dist/tools/computer.js +326 -0
- package/dist/tools/computer.js.map +1 -0
- package/dist/tools/delegate.d.ts +10 -0
- package/dist/tools/delegate.d.ts.map +1 -0
- package/dist/tools/delegate.js +45 -0
- package/dist/tools/delegate.js.map +1 -0
- package/dist/web/server.d.ts +5 -0
- package/dist/web/server.d.ts.map +1 -0
- package/dist/web/server.js +647 -0
- package/dist/web/server.js.map +1 -0
- package/dist/web/tts.d.ts +33 -0
- package/dist/web/tts.d.ts.map +1 -0
- package/dist/web/tts.js +69 -0
- package/dist/web/tts.js.map +1 -0
- package/package.json +60 -0
- package/scripts/install.js +48 -0
- package/scripts/link.js +10 -0
- package/setup.bat +79 -0
- package/skill-test-ty2fOA/test.md +10 -0
- package/src/agents/dew.ts +70 -0
- package/src/agents/fair.ts +102 -0
- package/src/agents/fog.ts +48 -0
- package/src/agents/frost.ts +50 -0
- package/src/agents/rain.ts +50 -0
- package/src/agents/snow.ts +239 -0
- package/src/cli/main.ts +405 -0
- package/src/cli/mode.ts +58 -0
- package/src/core/agent.ts +1506 -0
- package/src/core/agent_helpers.ts +461 -0
- package/src/core/bus.ts +221 -0
- package/src/core/cache.ts +153 -0
- package/src/core/checkpoint.ts +94 -0
- package/src/core/circuit_breaker.ts +119 -0
- package/src/core/config.ts +341 -0
- package/src/core/constants.ts +95 -0
- package/src/core/factory.ts +627 -0
- package/src/core/icons.ts +53 -0
- package/src/core/index.ts +31 -0
- package/src/core/llm.ts +724 -0
- package/src/core/logger.ts +144 -0
- package/src/core/mcp.ts +953 -0
- package/src/core/mcp_server.ts +176 -0
- package/src/core/memory.ts +1169 -0
- package/src/core/middleware.ts +350 -0
- package/src/core/pipelines.ts +424 -0
- package/src/core/profile.ts +255 -0
- package/src/core/router.ts +124 -0
- package/src/core/schemas.ts +282 -0
- package/src/core/semantic.ts +211 -0
- package/src/core/skill.ts +342 -0
- package/src/core/tool.ts +427 -0
- package/src/core/tool_router.ts +193 -0
- package/src/core/workspace.ts +150 -0
- package/src/plugins/loader.ts +66 -0
- package/src/skills/loader.ts +46 -0
- package/src/sql.js.d.ts +29 -0
- package/src/tools/builtin.ts +382 -0
- package/src/tools/computer.ts +269 -0
- package/src/tools/delegate.ts +49 -0
- package/src/web/server.ts +634 -0
- package/src/web/tts.ts +93 -0
- package/tests/bus.test.ts +121 -0
- package/tests/icons.test.ts +45 -0
- package/tests/router.test.ts +86 -0
- package/tests/schemas.test.ts +51 -0
- package/tests/semantic.test.ts +83 -0
- package/tests/setup.ts +10 -0
- package/tests/skill.test.ts +172 -0
- package/tests/tool.test.ts +108 -0
- package/tests/tool_router.test.ts +71 -0
- package/tsconfig.json +37 -0
- package/vitest.config.ts +17 -0
package/src/core/tool.ts
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool registration and execution framework with retry support
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { EventEmitter } from "events";
|
|
6
|
+
import { getLogger } from "./logger";
|
|
7
|
+
import { CircuitBreaker } from "./circuit_breaker";
|
|
8
|
+
|
|
9
|
+
const log = getLogger("tool");
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Tool parameter definition
|
|
13
|
+
*/
|
|
14
|
+
export interface ToolParameter {
|
|
15
|
+
name: string;
|
|
16
|
+
type: "string" | "number" | "boolean" | "array" | "object";
|
|
17
|
+
description: string;
|
|
18
|
+
required?: boolean;
|
|
19
|
+
default?: unknown;
|
|
20
|
+
enum?: string[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Tool handler function
|
|
25
|
+
*/
|
|
26
|
+
export type ToolHandler = (params: Record<string, unknown>) => Promise<string>;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Tool definition
|
|
30
|
+
*/
|
|
31
|
+
export interface ToolDefinition {
|
|
32
|
+
name: string;
|
|
33
|
+
description: string;
|
|
34
|
+
parameters?: ToolParameter[];
|
|
35
|
+
handler?: ToolHandler;
|
|
36
|
+
maxRetries?: number;
|
|
37
|
+
retryDelay?: number;
|
|
38
|
+
dangerous?: boolean;
|
|
39
|
+
cacheable?: boolean;
|
|
40
|
+
timeout?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Tool execution result
|
|
45
|
+
*/
|
|
46
|
+
export interface ToolResult {
|
|
47
|
+
success: boolean;
|
|
48
|
+
result: string;
|
|
49
|
+
error?: string;
|
|
50
|
+
retries?: number;
|
|
51
|
+
duration?: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const CACHE_MAXSIZE = 128;
|
|
55
|
+
const DEFAULT_TIMEOUT = 30000; // 30 seconds
|
|
56
|
+
const DEFAULT_RETRIES = 2;
|
|
57
|
+
const DEFAULT_RETRY_DELAY = 0.5; // seconds
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Tool result cache
|
|
61
|
+
*/
|
|
62
|
+
class ToolResultStore {
|
|
63
|
+
private store: Map<string, Map<string, string>> = new Map();
|
|
64
|
+
|
|
65
|
+
get(toolName: string, key: string): string | undefined {
|
|
66
|
+
const bucket = this.store.get(toolName);
|
|
67
|
+
if (!bucket) return undefined;
|
|
68
|
+
|
|
69
|
+
const value = bucket.get(key);
|
|
70
|
+
if (value) {
|
|
71
|
+
// Move to end (LRU)
|
|
72
|
+
bucket.delete(key);
|
|
73
|
+
bucket.set(key, value);
|
|
74
|
+
}
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
set(toolName: string, key: string, value: string): void {
|
|
79
|
+
let bucket = this.store.get(toolName);
|
|
80
|
+
if (!bucket) {
|
|
81
|
+
bucket = new Map();
|
|
82
|
+
this.store.set(toolName, bucket);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
bucket.set(key, value);
|
|
86
|
+
|
|
87
|
+
// Evict oldest if over limit
|
|
88
|
+
if (bucket.size > CACHE_MAXSIZE) {
|
|
89
|
+
const firstKey = bucket.keys().next().value;
|
|
90
|
+
if (firstKey !== undefined) bucket.delete(firstKey);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
clear(toolName?: string): void {
|
|
95
|
+
if (toolName) {
|
|
96
|
+
this.store.delete(toolName);
|
|
97
|
+
} else {
|
|
98
|
+
this.store.clear();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const resultStore = new ToolResultStore();
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Type coercion for tool parameters
|
|
107
|
+
*/
|
|
108
|
+
function coerceValue(value: unknown, targetType: string): [boolean, unknown] {
|
|
109
|
+
if (value === null || value === undefined) {
|
|
110
|
+
return [true, value];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Already correct type
|
|
114
|
+
if (targetType === "string" && typeof value === "string") {
|
|
115
|
+
return [true, value];
|
|
116
|
+
}
|
|
117
|
+
if (targetType === "number" && typeof value === "number") {
|
|
118
|
+
return [true, value];
|
|
119
|
+
}
|
|
120
|
+
if (targetType === "boolean" && typeof value === "boolean") {
|
|
121
|
+
return [true, value];
|
|
122
|
+
}
|
|
123
|
+
if (targetType === "array" && Array.isArray(value)) {
|
|
124
|
+
return [true, value];
|
|
125
|
+
}
|
|
126
|
+
if (targetType === "object" && typeof value === "object") {
|
|
127
|
+
return [true, value];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Lenient coercion from string
|
|
131
|
+
if (typeof value === "string") {
|
|
132
|
+
const stripped = value.trim();
|
|
133
|
+
|
|
134
|
+
if (targetType === "integer" || targetType === "number") {
|
|
135
|
+
const num = parseInt(stripped, 10);
|
|
136
|
+
if (!isNaN(num)) return [true, num];
|
|
137
|
+
const float = parseFloat(stripped);
|
|
138
|
+
if (!isNaN(float)) return [true, float];
|
|
139
|
+
return [false, value];
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (targetType === "boolean") {
|
|
143
|
+
const lower = stripped.toLowerCase();
|
|
144
|
+
if (["true", "1", "yes", "y"].includes(lower)) return [true, true];
|
|
145
|
+
if (["false", "0", "no", "n"].includes(lower)) return [true, false];
|
|
146
|
+
return [false, value];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (targetType === "array") {
|
|
150
|
+
if (stripped.includes(",")) {
|
|
151
|
+
return [true, stripped.split(",").map((s) => s.trim())];
|
|
152
|
+
}
|
|
153
|
+
return [true, [value]];
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return [false, value];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Tool registry and executor
|
|
162
|
+
*/
|
|
163
|
+
export class ToolRegistry extends EventEmitter {
|
|
164
|
+
private tools: Map<string, ToolDefinition> = new Map();
|
|
165
|
+
private breakers: Map<string, CircuitBreaker> = new Map();
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Register a tool
|
|
169
|
+
*/
|
|
170
|
+
register(def: ToolDefinition): void {
|
|
171
|
+
if (!def.name || !def.description) {
|
|
172
|
+
throw new Error("Tool must have name and description");
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
this.tools.set(def.name, def);
|
|
176
|
+
|
|
177
|
+
// Create circuit breaker for the tool
|
|
178
|
+
if (!this.breakers.has(def.name)) {
|
|
179
|
+
this.breakers.set(
|
|
180
|
+
def.name,
|
|
181
|
+
new CircuitBreaker({
|
|
182
|
+
name: `tool_${def.name}`,
|
|
183
|
+
failureThreshold: 5,
|
|
184
|
+
resetTimeout: 60000,
|
|
185
|
+
})
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
log.info("Tool registered", { tool: def.name });
|
|
190
|
+
this.emit("registered", def.name);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Unregister a tool
|
|
195
|
+
*/
|
|
196
|
+
unregister(toolName: string): void {
|
|
197
|
+
this.tools.delete(toolName);
|
|
198
|
+
this.emit("unregistered", toolName);
|
|
199
|
+
log.info("Tool unregistered", { tool: toolName });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Get a tool definition
|
|
204
|
+
*/
|
|
205
|
+
get(toolName: string): ToolDefinition | undefined {
|
|
206
|
+
return this.tools.get(toolName);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* List all registered tools
|
|
211
|
+
*/
|
|
212
|
+
list(): ToolDefinition[] {
|
|
213
|
+
return Array.from(this.tools.values());
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Check if tool is registered
|
|
218
|
+
*/
|
|
219
|
+
has(toolName: string): boolean {
|
|
220
|
+
return this.tools.has(toolName);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Validate tool parameters
|
|
225
|
+
*/
|
|
226
|
+
validateParameters(toolName: string, params: Record<string, unknown>): [boolean, string] {
|
|
227
|
+
const tool = this.tools.get(toolName);
|
|
228
|
+
if (!tool) {
|
|
229
|
+
return [false, `Tool ${toolName} not found`];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (!tool.parameters) {
|
|
233
|
+
return [true, ""];
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
for (const param of tool.parameters) {
|
|
237
|
+
if (param.required && !(param.name in params)) {
|
|
238
|
+
return [false, `Missing required parameter: ${param.name}`];
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (param.name in params) {
|
|
242
|
+
const [valid] = coerceValue(params[param.name], param.type);
|
|
243
|
+
if (!valid) {
|
|
244
|
+
return [false, `Invalid type for parameter ${param.name}: expected ${param.type}`];
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return [true, ""];
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Execute a tool with retry support
|
|
254
|
+
*/
|
|
255
|
+
async execute(toolName: string, params: Record<string, unknown>): Promise<ToolResult> {
|
|
256
|
+
const tool = this.tools.get(toolName);
|
|
257
|
+
if (!tool) {
|
|
258
|
+
return {
|
|
259
|
+
success: false,
|
|
260
|
+
result: "",
|
|
261
|
+
error: `Tool ${toolName} not found`,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Check circuit breaker
|
|
266
|
+
const breaker = this.breakers.get(toolName);
|
|
267
|
+
if (breaker && !breaker.canExecute()) {
|
|
268
|
+
return {
|
|
269
|
+
success: false,
|
|
270
|
+
result: "",
|
|
271
|
+
error: `Tool ${toolName} is temporarily unavailable (circuit breaker open)`,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Check cache
|
|
276
|
+
if (tool.cacheable) {
|
|
277
|
+
const cacheKey = JSON.stringify(params);
|
|
278
|
+
const cached = resultStore.get(toolName, cacheKey);
|
|
279
|
+
if (cached) {
|
|
280
|
+
log.debug("Tool cache hit", { tool: toolName });
|
|
281
|
+
return {
|
|
282
|
+
success: true,
|
|
283
|
+
result: cached,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Validate parameters
|
|
289
|
+
const [valid, error] = this.validateParameters(toolName, params);
|
|
290
|
+
if (!valid) {
|
|
291
|
+
return {
|
|
292
|
+
success: false,
|
|
293
|
+
result: "",
|
|
294
|
+
error,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Execute with retries
|
|
299
|
+
const maxRetries = tool.maxRetries ?? DEFAULT_RETRIES;
|
|
300
|
+
const retryDelay = (tool.retryDelay ?? DEFAULT_RETRY_DELAY) * 1000;
|
|
301
|
+
const timeout = tool.timeout ?? DEFAULT_TIMEOUT;
|
|
302
|
+
|
|
303
|
+
let lastError: Error | null = null;
|
|
304
|
+
let retries = 0;
|
|
305
|
+
|
|
306
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
307
|
+
try {
|
|
308
|
+
if (attempt > 0) {
|
|
309
|
+
await new Promise((resolve) => setTimeout(resolve, retryDelay * attempt));
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (!tool.handler) {
|
|
313
|
+
throw new Error(`No handler for tool ${toolName}`);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const startTime = Date.now();
|
|
317
|
+
|
|
318
|
+
// Execute with timeout
|
|
319
|
+
const promise = tool.handler(params);
|
|
320
|
+
const timeoutPromise = new Promise<string>((_, reject) =>
|
|
321
|
+
setTimeout(() => reject(new Error("Tool execution timeout")), timeout)
|
|
322
|
+
);
|
|
323
|
+
|
|
324
|
+
const result = await Promise.race([promise, timeoutPromise]);
|
|
325
|
+
|
|
326
|
+
const duration = Date.now() - startTime;
|
|
327
|
+
|
|
328
|
+
// Cache result
|
|
329
|
+
if (tool.cacheable) {
|
|
330
|
+
const cacheKey = JSON.stringify(params);
|
|
331
|
+
resultStore.set(toolName, cacheKey, result);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
breaker?.recordSuccess();
|
|
335
|
+
|
|
336
|
+
log.info("Tool executed successfully", {
|
|
337
|
+
tool: toolName,
|
|
338
|
+
duration,
|
|
339
|
+
retries: attempt,
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
return {
|
|
343
|
+
success: true,
|
|
344
|
+
result,
|
|
345
|
+
duration,
|
|
346
|
+
retries: attempt,
|
|
347
|
+
};
|
|
348
|
+
} catch (error) {
|
|
349
|
+
lastError = error as Error;
|
|
350
|
+
retries = attempt;
|
|
351
|
+
|
|
352
|
+
if (attempt < maxRetries) {
|
|
353
|
+
log.warn("Tool execution failed, retrying", {
|
|
354
|
+
tool: toolName,
|
|
355
|
+
attempt: attempt + 1,
|
|
356
|
+
error: lastError.message,
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
breaker?.recordFailure();
|
|
363
|
+
|
|
364
|
+
log.error("Tool execution failed after retries", {
|
|
365
|
+
tool: toolName,
|
|
366
|
+
retries,
|
|
367
|
+
error: lastError?.message,
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
return {
|
|
371
|
+
success: false,
|
|
372
|
+
result: "",
|
|
373
|
+
error: lastError?.message || "Tool execution failed",
|
|
374
|
+
retries,
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Get all tools (alias for list, used by agent code)
|
|
380
|
+
*/
|
|
381
|
+
getTools(): ToolDefinition[] {
|
|
382
|
+
return this.list();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* List all registered tool names
|
|
387
|
+
*/
|
|
388
|
+
listNames(): string[] {
|
|
389
|
+
return Array.from(this.tools.keys());
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Merge tools from another registry into this one.
|
|
394
|
+
*/
|
|
395
|
+
merge(other: ToolRegistry): void {
|
|
396
|
+
for (const tool of other.list()) {
|
|
397
|
+
this.tools.set(tool.name, tool);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Clear result cache for a tool or all tools
|
|
403
|
+
*/
|
|
404
|
+
clearCache(toolName?: string): void {
|
|
405
|
+
resultStore.clear(toolName);
|
|
406
|
+
if (toolName) {
|
|
407
|
+
log.info("Tool cache cleared", { tool: toolName });
|
|
408
|
+
} else {
|
|
409
|
+
log.info("All tool caches cleared");
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Global tool registry
|
|
416
|
+
*/
|
|
417
|
+
let globalRegistry: ToolRegistry | null = null;
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Get the global tool registry
|
|
421
|
+
*/
|
|
422
|
+
export function getToolRegistry(): ToolRegistry {
|
|
423
|
+
if (!globalRegistry) {
|
|
424
|
+
globalRegistry = new ToolRegistry();
|
|
425
|
+
}
|
|
426
|
+
return globalRegistry;
|
|
427
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool-subset selection for LLM calls.
|
|
3
|
+
*
|
|
4
|
+
* Without filtering, every chat turn ships ~50 tool schemas (built-ins + MCP +
|
|
5
|
+
* skill-required + delegation) to the model. That dilutes attention (the LLM
|
|
6
|
+
* picks plausible-but-wrong tools more often) and burns 8-15k input tokens per
|
|
7
|
+
* turn. This module narrows the active tool set to ~12 by lightweight scoring
|
|
8
|
+
* against the user's latest message.
|
|
9
|
+
*
|
|
10
|
+
* The router intentionally avoids embeddings / LLM calls — it must run in <1ms
|
|
11
|
+
* on every turn, before the real LLM call. A coarse keyword/substring score is
|
|
12
|
+
* good enough to keep the right tools in and bad enough to be cheap.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { ToolDefinition, ToolRegistry } from './tool';
|
|
16
|
+
|
|
17
|
+
// Infrastructure tools that are useful on most turns.
|
|
18
|
+
const INFRA_TOOLS: ReadonlySet<string> = new Set([
|
|
19
|
+
'delegate_to',
|
|
20
|
+
'list_skills',
|
|
21
|
+
'use_skill',
|
|
22
|
+
'recall_facts',
|
|
23
|
+
'remember_fact',
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
const MUTATING_TOOLS: ReadonlySet<string> = new Set([
|
|
27
|
+
'write_file',
|
|
28
|
+
'edit_file',
|
|
29
|
+
'move_file',
|
|
30
|
+
'copy_file',
|
|
31
|
+
'delete_file',
|
|
32
|
+
'git_add',
|
|
33
|
+
'git_commit',
|
|
34
|
+
'git_checkout',
|
|
35
|
+
'shell_exec',
|
|
36
|
+
'http_post',
|
|
37
|
+
'mcp_add_server',
|
|
38
|
+
'mcp_remove_server',
|
|
39
|
+
'mcp_scaffold_server',
|
|
40
|
+
'kill_process',
|
|
41
|
+
'package_manager',
|
|
42
|
+
'service_control',
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
const TOKEN_RE = /[A-Za-z][A-Za-z0-9_]*|[一-鿿]+/g;
|
|
46
|
+
|
|
47
|
+
const STOPWORDS: ReadonlySet<string> = new Set([
|
|
48
|
+
'a', 'an', 'the', 'is', 'are', 'was', 'were', 'and', 'or', 'but',
|
|
49
|
+
'to', 'for', 'of', 'in', 'on', 'at', 'with', 'by', 'do', 'did',
|
|
50
|
+
'does', 'i', 'me', 'my', 'you', 'your', 'it', 'this', 'that',
|
|
51
|
+
'what', 'how', 'can', 'could', 'would', 'should', 'please',
|
|
52
|
+
'tell', 'show', 'help', 'ok', 'yes', 'no',
|
|
53
|
+
'好', '的', '是', '我', '你', '他', '她', '它', '这', '那',
|
|
54
|
+
'什么', '怎么', '请', '帮', '麻烦',
|
|
55
|
+
]);
|
|
56
|
+
|
|
57
|
+
function tokenize(text: string): Set<string> {
|
|
58
|
+
const tokens = new Set<string>();
|
|
59
|
+
const matches = text?.toLowerCase().match(TOKEN_RE) || [];
|
|
60
|
+
for (const t of matches) {
|
|
61
|
+
if (t.length >= 2 && !STOPWORDS.has(t)) {
|
|
62
|
+
tokens.add(t);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return tokens;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function scoreTool(tool: ToolDefinition, queryTokens: Set<string>, queryLc: string): number {
|
|
69
|
+
if (queryTokens.size === 0) return 0;
|
|
70
|
+
let score = 0;
|
|
71
|
+
|
|
72
|
+
// Tool name tokens carry the strongest signal
|
|
73
|
+
const nameTokens = tokenize(tool.name.replace(/_/g, ' '));
|
|
74
|
+
for (const qt of queryTokens) {
|
|
75
|
+
if (nameTokens.has(qt)) {
|
|
76
|
+
score += 5;
|
|
77
|
+
} else if (tool.name.toLowerCase().includes(qt)) {
|
|
78
|
+
score += 3;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Description tokens are weaker
|
|
83
|
+
const descTokens = tokenize(tool.description);
|
|
84
|
+
for (const qt of queryTokens) {
|
|
85
|
+
if (descTokens.has(qt)) {
|
|
86
|
+
score += 1;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Intent boosts for common Chinese/English tasks
|
|
91
|
+
const name = tool.name;
|
|
92
|
+
if (['read_file', 'list_directory', 'tree', 'file_search', 'code_search', 'grep'].includes(name) &&
|
|
93
|
+
['read', 'file', 'inspect', 'search', 'grep', '看', '读', '查', '搜索', '文件', '代码'].some(k => queryLc.includes(k))) {
|
|
94
|
+
score += 4;
|
|
95
|
+
}
|
|
96
|
+
if (['write_file', 'edit_file', 'move_file', 'copy_file', 'delete_file'].includes(name) &&
|
|
97
|
+
['write', 'edit', 'modify', 'fix', 'save', '生成', '写', '改', '修复', '保存', '删除'].some(k => queryLc.includes(k))) {
|
|
98
|
+
score += 4;
|
|
99
|
+
}
|
|
100
|
+
if (name.startsWith('git_') &&
|
|
101
|
+
['git', 'commit', 'diff', 'branch', '提交', '分支', '差异'].some(k => queryLc.includes(k))) {
|
|
102
|
+
score += 4;
|
|
103
|
+
}
|
|
104
|
+
if (['web_search', 'fetch_page', 'http_get'].includes(name) &&
|
|
105
|
+
['web', 'url', 'http', 'research', '搜索', '网页', '联网', '资料'].some(k => queryLc.includes(k))) {
|
|
106
|
+
score += 4;
|
|
107
|
+
}
|
|
108
|
+
if (['list_skills', 'use_skill'].includes(name) &&
|
|
109
|
+
['skill', '能力', '技能', 'ppt', 'pdf', 'excel', 'xlsx', 'docx'].some(k => queryLc.includes(k))) {
|
|
110
|
+
score += 4;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return score;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Return up to ~topK tool names ordered by relevance to the query.
|
|
118
|
+
*
|
|
119
|
+
* Always-included infrastructure tools and mustInclude (e.g. active
|
|
120
|
+
* skill required_tools) are appended regardless of score. When the candidate
|
|
121
|
+
* set is already small (<= topK + |mustInclude|), no filtering is applied.
|
|
122
|
+
*
|
|
123
|
+
* A short or empty query means we have no signal to filter — returning the
|
|
124
|
+
* full candidate set is correct in that case.
|
|
125
|
+
*/
|
|
126
|
+
export function selectRelevantTools(
|
|
127
|
+
registry: ToolRegistry,
|
|
128
|
+
candidateNames: string[],
|
|
129
|
+
query: string,
|
|
130
|
+
options?: {
|
|
131
|
+
topK?: number;
|
|
132
|
+
mustInclude?: Set<string>;
|
|
133
|
+
}
|
|
134
|
+
): string[] {
|
|
135
|
+
const topK = options?.topK ?? 12;
|
|
136
|
+
const explicitMust = new Set(options?.mustInclude ?? []);
|
|
137
|
+
|
|
138
|
+
const infraPresent = candidateNames.filter(n => INFRA_TOOLS.has(n) && !explicitMust.has(n));
|
|
139
|
+
const mustPresent = candidateNames.filter(n => explicitMust.has(n));
|
|
140
|
+
const remaining = candidateNames.filter(n => !explicitMust.has(n) && !INFRA_TOOLS.has(n));
|
|
141
|
+
|
|
142
|
+
const queryTokens = tokenize(query);
|
|
143
|
+
const queryLc = (query || '').toLowerCase();
|
|
144
|
+
const smallSurface = candidateNames.length <= topK + mustPresent.length + infraPresent.length;
|
|
145
|
+
const lowSignal = queryTokens.size < 2 && queryLc.length < 8;
|
|
146
|
+
|
|
147
|
+
// No filtering when the set is already small or the query is too short
|
|
148
|
+
if (smallSurface || lowSignal) {
|
|
149
|
+
return [...mustPresent, ...infraPresent, ...remaining];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const scored: Array<{ name: string; score: number; penalty: number }> = [];
|
|
153
|
+
const allScoredNames = [...infraPresent, ...remaining];
|
|
154
|
+
|
|
155
|
+
for (const name of allScoredNames) {
|
|
156
|
+
const tool = registry.get(name);
|
|
157
|
+
if (!tool) continue;
|
|
158
|
+
const score = scoreTool(tool, queryTokens, queryLc);
|
|
159
|
+
const penalty = MUTATING_TOOLS.has(name) && score === 0 ? 1 : 0;
|
|
160
|
+
scored.push({ name, score, penalty });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Stable sort by descending score; zero-score tools only fill spare slots
|
|
164
|
+
scored.sort((a, b) => {
|
|
165
|
+
if (a.score !== b.score) return b.score - a.score;
|
|
166
|
+
return a.penalty - b.penalty;
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const budget = Math.max(0, topK - mustPresent.length);
|
|
170
|
+
const picked: string[] = [];
|
|
171
|
+
const pickedSet = new Set<string>();
|
|
172
|
+
|
|
173
|
+
for (const item of scored) {
|
|
174
|
+
if (picked.length >= budget) break;
|
|
175
|
+
if (item.score > 0) {
|
|
176
|
+
picked.push(item.name);
|
|
177
|
+
pickedSet.add(item.name);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Fill remaining slots with zero-score tools
|
|
182
|
+
if (picked.length < budget) {
|
|
183
|
+
for (const item of scored) {
|
|
184
|
+
if (picked.length >= budget) break;
|
|
185
|
+
if (!pickedSet.has(item.name)) {
|
|
186
|
+
picked.push(item.name);
|
|
187
|
+
pickedSet.add(item.name);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return [...mustPresent, ...picked];
|
|
193
|
+
}
|