@shareai-lab/kode-sdk 1.0.0-beta.9 → 2.7.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 (193) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +115 -273
  3. package/README.zh-CN.md +114 -0
  4. package/dist/core/agent/breakpoint-manager.d.ts +16 -0
  5. package/dist/core/agent/breakpoint-manager.js +36 -0
  6. package/dist/core/agent/message-queue.d.ts +26 -0
  7. package/dist/core/agent/message-queue.js +57 -0
  8. package/dist/core/agent/permission-manager.d.ts +9 -0
  9. package/dist/core/agent/permission-manager.js +32 -0
  10. package/dist/core/agent/todo-manager.d.ts +26 -0
  11. package/dist/core/agent/todo-manager.js +91 -0
  12. package/dist/core/agent/tool-runner.d.ts +9 -0
  13. package/dist/core/agent/tool-runner.js +45 -0
  14. package/dist/core/agent.d.ts +228 -62
  15. package/dist/core/agent.js +1890 -615
  16. package/dist/core/config.d.ts +10 -0
  17. package/dist/core/config.js +2 -0
  18. package/dist/core/context-manager.d.ts +82 -0
  19. package/dist/core/context-manager.js +241 -0
  20. package/dist/core/errors.d.ts +22 -0
  21. package/dist/core/errors.js +49 -0
  22. package/dist/core/events.d.ts +41 -10
  23. package/dist/core/events.js +270 -68
  24. package/dist/core/file-pool.d.ts +41 -0
  25. package/dist/core/file-pool.js +102 -0
  26. package/dist/core/hooks.d.ts +3 -3
  27. package/dist/core/hooks.js +1 -1
  28. package/dist/core/permission-modes.d.ts +31 -0
  29. package/dist/core/permission-modes.js +61 -0
  30. package/dist/core/pool.d.ts +56 -13
  31. package/dist/core/pool.js +244 -34
  32. package/dist/core/room.d.ts +2 -2
  33. package/dist/core/room.js +10 -10
  34. package/dist/core/scheduler.d.ts +30 -23
  35. package/dist/core/scheduler.js +42 -168
  36. package/dist/core/skills/index.d.ts +10 -0
  37. package/dist/core/skills/index.js +20 -0
  38. package/dist/core/skills/management-manager.d.ts +130 -0
  39. package/dist/core/skills/management-manager.js +557 -0
  40. package/dist/core/skills/manager.d.ts +47 -0
  41. package/dist/core/skills/manager.js +243 -0
  42. package/dist/core/skills/operation-queue.d.ts +87 -0
  43. package/dist/core/skills/operation-queue.js +113 -0
  44. package/dist/core/skills/sandbox-file-manager.d.ts +82 -0
  45. package/dist/core/skills/sandbox-file-manager.js +183 -0
  46. package/dist/core/skills/types.d.ts +120 -0
  47. package/dist/core/skills/types.js +9 -0
  48. package/dist/core/skills/xml-generator.d.ts +13 -0
  49. package/dist/core/skills/xml-generator.js +70 -0
  50. package/dist/core/template.d.ts +57 -0
  51. package/dist/core/template.js +35 -0
  52. package/dist/core/time-bridge.d.ts +18 -0
  53. package/dist/core/time-bridge.js +100 -0
  54. package/dist/core/todo.d.ts +34 -0
  55. package/dist/core/todo.js +89 -0
  56. package/dist/core/types.d.ts +311 -114
  57. package/dist/core/types.js +1 -12
  58. package/dist/index.d.ts +47 -9
  59. package/dist/index.js +108 -15
  60. package/dist/infra/db/postgres/postgres-store.d.ts +97 -0
  61. package/dist/infra/db/postgres/postgres-store.js +1073 -0
  62. package/dist/infra/db/sqlite/sqlite-store.d.ts +84 -0
  63. package/dist/infra/db/sqlite/sqlite-store.js +800 -0
  64. package/dist/infra/e2b/e2b-fs.d.ts +29 -0
  65. package/dist/infra/e2b/e2b-fs.js +128 -0
  66. package/dist/infra/e2b/e2b-sandbox.d.ts +37 -0
  67. package/dist/infra/e2b/e2b-sandbox.js +156 -0
  68. package/dist/infra/e2b/e2b-template.d.ts +24 -0
  69. package/dist/infra/e2b/e2b-template.js +105 -0
  70. package/dist/infra/e2b/index.d.ts +4 -0
  71. package/dist/infra/e2b/index.js +9 -0
  72. package/dist/infra/e2b/types.d.ts +46 -0
  73. package/dist/infra/e2b/types.js +2 -0
  74. package/dist/infra/provider.d.ts +17 -58
  75. package/dist/infra/provider.js +65 -116
  76. package/dist/infra/providers/anthropic.d.ts +42 -0
  77. package/dist/infra/providers/anthropic.js +308 -0
  78. package/dist/infra/providers/core/errors.d.ts +230 -0
  79. package/dist/infra/providers/core/errors.js +353 -0
  80. package/dist/infra/providers/core/fork.d.ts +106 -0
  81. package/dist/infra/providers/core/fork.js +418 -0
  82. package/dist/infra/providers/core/index.d.ts +10 -0
  83. package/dist/infra/providers/core/index.js +76 -0
  84. package/dist/infra/providers/core/logger.d.ts +186 -0
  85. package/dist/infra/providers/core/logger.js +191 -0
  86. package/dist/infra/providers/core/retry.d.ts +62 -0
  87. package/dist/infra/providers/core/retry.js +189 -0
  88. package/dist/infra/providers/core/usage.d.ts +151 -0
  89. package/dist/infra/providers/core/usage.js +376 -0
  90. package/dist/infra/providers/gemini.d.ts +49 -0
  91. package/dist/infra/providers/gemini.js +493 -0
  92. package/dist/infra/providers/index.d.ts +25 -0
  93. package/dist/infra/providers/index.js +83 -0
  94. package/dist/infra/providers/openai.d.ts +123 -0
  95. package/dist/infra/providers/openai.js +662 -0
  96. package/dist/infra/providers/types.d.ts +334 -0
  97. package/dist/infra/providers/types.js +20 -0
  98. package/dist/infra/providers/utils.d.ts +53 -0
  99. package/dist/infra/providers/utils.js +400 -0
  100. package/dist/infra/sandbox-factory.d.ts +13 -0
  101. package/dist/infra/sandbox-factory.js +30 -0
  102. package/dist/infra/sandbox.d.ts +35 -6
  103. package/dist/infra/sandbox.js +174 -8
  104. package/dist/infra/store/factory.d.ts +45 -0
  105. package/dist/infra/store/factory.js +80 -0
  106. package/dist/infra/store/index.d.ts +3 -0
  107. package/dist/infra/store/index.js +26 -0
  108. package/dist/infra/store/json-store.d.ts +67 -0
  109. package/dist/infra/store/json-store.js +606 -0
  110. package/dist/infra/store/types.d.ts +342 -0
  111. package/dist/infra/store/types.js +2 -0
  112. package/dist/infra/store.d.ts +12 -32
  113. package/dist/infra/store.js +27 -130
  114. package/dist/tools/bash_kill/index.d.ts +1 -0
  115. package/dist/tools/bash_kill/index.js +35 -0
  116. package/dist/tools/bash_kill/prompt.d.ts +2 -0
  117. package/dist/tools/bash_kill/prompt.js +14 -0
  118. package/dist/tools/bash_logs/index.d.ts +1 -0
  119. package/dist/tools/bash_logs/index.js +40 -0
  120. package/dist/tools/bash_logs/prompt.d.ts +2 -0
  121. package/dist/tools/bash_logs/prompt.js +14 -0
  122. package/dist/tools/bash_run/index.d.ts +16 -0
  123. package/dist/tools/bash_run/index.js +61 -0
  124. package/dist/tools/bash_run/prompt.d.ts +2 -0
  125. package/dist/tools/bash_run/prompt.js +18 -0
  126. package/dist/tools/builtin.d.ts +7 -13
  127. package/dist/tools/builtin.js +19 -90
  128. package/dist/tools/define.d.ts +101 -0
  129. package/dist/tools/define.js +214 -0
  130. package/dist/tools/fs_edit/index.d.ts +1 -0
  131. package/dist/tools/fs_edit/index.js +62 -0
  132. package/dist/tools/fs_edit/prompt.d.ts +2 -0
  133. package/dist/tools/fs_edit/prompt.js +15 -0
  134. package/dist/tools/fs_glob/index.d.ts +1 -0
  135. package/dist/tools/fs_glob/index.js +40 -0
  136. package/dist/tools/fs_glob/prompt.d.ts +2 -0
  137. package/dist/tools/fs_glob/prompt.js +15 -0
  138. package/dist/tools/fs_grep/index.d.ts +1 -0
  139. package/dist/tools/fs_grep/index.js +66 -0
  140. package/dist/tools/fs_grep/prompt.d.ts +2 -0
  141. package/dist/tools/fs_grep/prompt.js +16 -0
  142. package/dist/tools/fs_multi_edit/index.d.ts +1 -0
  143. package/dist/tools/fs_multi_edit/index.js +106 -0
  144. package/dist/tools/fs_multi_edit/prompt.d.ts +2 -0
  145. package/dist/tools/fs_multi_edit/prompt.js +16 -0
  146. package/dist/tools/fs_read/index.d.ts +1 -0
  147. package/dist/tools/fs_read/index.js +40 -0
  148. package/dist/tools/fs_read/prompt.d.ts +2 -0
  149. package/dist/tools/fs_read/prompt.js +16 -0
  150. package/dist/tools/fs_write/index.d.ts +1 -0
  151. package/dist/tools/fs_write/index.js +40 -0
  152. package/dist/tools/fs_write/prompt.d.ts +2 -0
  153. package/dist/tools/fs_write/prompt.js +15 -0
  154. package/dist/tools/index.d.ts +11 -0
  155. package/dist/tools/index.js +61 -0
  156. package/dist/tools/mcp.d.ts +69 -0
  157. package/dist/tools/mcp.js +185 -0
  158. package/dist/tools/registry.d.ts +29 -0
  159. package/dist/tools/registry.js +26 -0
  160. package/dist/tools/scripts.d.ts +22 -0
  161. package/dist/tools/scripts.js +205 -0
  162. package/dist/tools/skills.d.ts +20 -0
  163. package/dist/tools/skills.js +115 -0
  164. package/dist/tools/task_run/index.d.ts +7 -0
  165. package/dist/tools/task_run/index.js +58 -0
  166. package/dist/tools/task_run/prompt.d.ts +5 -0
  167. package/dist/tools/task_run/prompt.js +25 -0
  168. package/dist/tools/todo_read/index.d.ts +1 -0
  169. package/dist/tools/todo_read/index.js +29 -0
  170. package/dist/tools/todo_read/prompt.d.ts +2 -0
  171. package/dist/tools/todo_read/prompt.js +18 -0
  172. package/dist/tools/todo_write/index.d.ts +1 -0
  173. package/dist/tools/todo_write/index.js +42 -0
  174. package/dist/tools/todo_write/prompt.d.ts +2 -0
  175. package/dist/tools/todo_write/prompt.js +23 -0
  176. package/dist/tools/tool.d.ts +43 -0
  177. package/dist/tools/tool.js +211 -0
  178. package/dist/tools/toolkit.d.ts +69 -0
  179. package/dist/tools/toolkit.js +98 -0
  180. package/dist/tools/type-inference.d.ts +127 -0
  181. package/dist/tools/type-inference.js +207 -0
  182. package/dist/utils/agent-id.d.ts +1 -0
  183. package/dist/utils/agent-id.js +28 -0
  184. package/dist/utils/logger.d.ts +15 -0
  185. package/dist/utils/logger.js +44 -0
  186. package/dist/utils/session-id.js +16 -16
  187. package/package.json +35 -11
  188. package/dist/tools/bash.d.ts +0 -63
  189. package/dist/tools/bash.js +0 -92
  190. package/dist/tools/fs.d.ts +0 -96
  191. package/dist/tools/fs.js +0 -100
  192. package/dist/tools/task.d.ts +0 -38
  193. package/dist/tools/task.js +0 -45
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DESCRIPTION = void 0;
4
+ exports.generatePrompt = generatePrompt;
5
+ exports.DESCRIPTION = 'Delegate a task to a specialized sub-agent';
6
+ function generatePrompt(templates) {
7
+ const templateList = templates
8
+ .map((tpl) => `- agentTemplateId: ${tpl.id}\n whenToUse: ${tpl.whenToUse || 'General purpose tasks'}`)
9
+ .join('\n');
10
+ return `Delegate complex, multi-step work to specialized sub-agents.
11
+
12
+ Instructions:
13
+ - Always provide a concise "description" (3-5 words) and a detailed "prompt" outlining deliverables.
14
+ - REQUIRED: Set "agentTemplateId" to one of the available template IDs below.
15
+ - Optionally supply "context" for extra background information.
16
+ - The tool returns the sub-agent's final text and any pending permissions.
17
+
18
+ Available agent templates:
19
+ ${templateList}
20
+
21
+ Safety/Limitations:
22
+ - Sub-agents inherit the same sandbox and tool restrictions.
23
+ - Task delegation depth may be limited to prevent infinite recursion.
24
+ - Sub-agents cannot access parent agent state or context directly.`;
25
+ }
@@ -0,0 +1 @@
1
+ export declare const TodoRead: import("..").ToolInstance;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TodoRead = void 0;
4
+ const tool_1 = require("../tool");
5
+ const zod_1 = require("zod");
6
+ const prompt_1 = require("./prompt");
7
+ exports.TodoRead = (0, tool_1.tool)({
8
+ name: 'todo_read',
9
+ description: prompt_1.DESCRIPTION,
10
+ parameters: zod_1.z.object({}),
11
+ async execute(_args, ctx) {
12
+ if (ctx.agent?.getTodos) {
13
+ return { todos: ctx.agent.getTodos() };
14
+ }
15
+ const service = ctx.services?.todo;
16
+ if (!service) {
17
+ return {
18
+ todos: [],
19
+ note: 'Todo service not enabled for this agent'
20
+ };
21
+ }
22
+ return { todos: service.list() };
23
+ },
24
+ metadata: {
25
+ readonly: true,
26
+ version: '1.0',
27
+ },
28
+ });
29
+ exports.TodoRead.prompt = prompt_1.PROMPT;
@@ -0,0 +1,2 @@
1
+ export declare const DESCRIPTION = "Read the current todo list managed by the agent";
2
+ export declare const PROMPT = "Retrieve the canonical list of todos that this agent maintains.\n\nGuidelines:\n- Use this before planning or reprioritizing work\n- The returned list reflects the current state of all tracked tasks\n- Each todo includes: id, title, status, and optional assignee/notes\n\nTodo Status Values:\n- pending: Not yet started\n- in_progress: Currently being worked on\n- completed: Finished\n\nLimitations:\n- Returns empty list if todo service is not enabled for this agent";
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROMPT = exports.DESCRIPTION = void 0;
4
+ exports.DESCRIPTION = 'Read the current todo list managed by the agent';
5
+ exports.PROMPT = `Retrieve the canonical list of todos that this agent maintains.
6
+
7
+ Guidelines:
8
+ - Use this before planning or reprioritizing work
9
+ - The returned list reflects the current state of all tracked tasks
10
+ - Each todo includes: id, title, status, and optional assignee/notes
11
+
12
+ Todo Status Values:
13
+ - pending: Not yet started
14
+ - in_progress: Currently being worked on
15
+ - completed: Finished
16
+
17
+ Limitations:
18
+ - Returns empty list if todo service is not enabled for this agent`;
@@ -0,0 +1 @@
1
+ export declare const TodoWrite: import("..").ToolInstance;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TodoWrite = void 0;
4
+ const tool_1 = require("../tool");
5
+ const zod_1 = require("zod");
6
+ const prompt_1 = require("./prompt");
7
+ const todoItemSchema = zod_1.z.object({
8
+ id: zod_1.z.string().describe('Unique identifier for the todo'),
9
+ title: zod_1.z.string().describe('Clear description of the task'),
10
+ status: zod_1.z.enum(['pending', 'in_progress', 'completed']).describe('Current status'),
11
+ assignee: zod_1.z.string().optional().describe('Who is responsible'),
12
+ notes: zod_1.z.string().optional().describe('Additional context'),
13
+ });
14
+ exports.TodoWrite = (0, tool_1.tool)({
15
+ name: 'todo_write',
16
+ description: prompt_1.DESCRIPTION,
17
+ parameters: zod_1.z.object({
18
+ todos: zod_1.z.array(todoItemSchema).describe('Array of todo items'),
19
+ }),
20
+ async execute(args, ctx) {
21
+ const { todos } = args;
22
+ const inProgressCount = todos.filter((t) => t.status === 'in_progress').length;
23
+ if (inProgressCount > 1) {
24
+ throw new Error(`Only one todo can be "in_progress" at a time. Found ${inProgressCount} in_progress todos.`);
25
+ }
26
+ if (!ctx.agent?.setTodos) {
27
+ const service = ctx.services?.todo;
28
+ if (!service) {
29
+ throw new Error('Todo service not enabled for this agent');
30
+ }
31
+ await service.setTodos(todos);
32
+ return { ok: true, count: todos.length };
33
+ }
34
+ await ctx.agent.setTodos(todos);
35
+ return { ok: true, count: todos.length };
36
+ },
37
+ metadata: {
38
+ readonly: false,
39
+ version: '1.0',
40
+ },
41
+ });
42
+ exports.TodoWrite.prompt = prompt_1.PROMPT;
@@ -0,0 +1,2 @@
1
+ export declare const DESCRIPTION = "Replace the todo list managed by the agent";
2
+ export declare const PROMPT = "Replace the agent-managed todo list with a new array of todos.\n\nGuidelines:\n- Always provide structured IDs, titles, and statuses\n- Only ONE item may have \"in_progress\" status at any time\n- IDs should be unique and descriptive\n- Titles should be clear and actionable\n\nTodo Structure:\n- id (required): Unique identifier for the todo\n- title (required): Clear description of the task\n- status (required): \"pending\" | \"in_progress\" | \"completed\"\n- assignee (optional): Who is responsible\n- notes (optional): Additional context or details\n\nSafety/Limitations:\n- This operation replaces the entire todo list\n- Previous todos not included in the new list will be removed\n- Returns error if todo service is not enabled";
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROMPT = exports.DESCRIPTION = void 0;
4
+ exports.DESCRIPTION = 'Replace the todo list managed by the agent';
5
+ exports.PROMPT = `Replace the agent-managed todo list with a new array of todos.
6
+
7
+ Guidelines:
8
+ - Always provide structured IDs, titles, and statuses
9
+ - Only ONE item may have "in_progress" status at any time
10
+ - IDs should be unique and descriptive
11
+ - Titles should be clear and actionable
12
+
13
+ Todo Structure:
14
+ - id (required): Unique identifier for the todo
15
+ - title (required): Clear description of the task
16
+ - status (required): "pending" | "in_progress" | "completed"
17
+ - assignee (optional): Who is responsible
18
+ - notes (optional): Additional context or details
19
+
20
+ Safety/Limitations:
21
+ - This operation replaces the entire todo list
22
+ - Previous todos not included in the new list will be removed
23
+ - Returns error if todo service is not enabled`;
@@ -0,0 +1,43 @@
1
+ import { ZodType } from 'zod';
2
+ import { ToolInstance } from './registry';
3
+ import { ToolContext } from '../core/types';
4
+ import { Hooks } from '../core/hooks';
5
+ /**
6
+ * 工具定义接口
7
+ */
8
+ export interface ToolDefinition<TArgs = any, TResult = any> {
9
+ name: string;
10
+ description?: string;
11
+ parameters?: ZodType<TArgs>;
12
+ execute: (args: TArgs, ctx: EnhancedToolContext) => Promise<TResult> | TResult;
13
+ metadata?: {
14
+ version?: string;
15
+ tags?: string[];
16
+ cacheable?: boolean;
17
+ cacheTTL?: number;
18
+ timeout?: number;
19
+ concurrent?: boolean;
20
+ readonly?: boolean;
21
+ };
22
+ hooks?: Hooks;
23
+ }
24
+ /**
25
+ * 工具上下文增强接口
26
+ */
27
+ export interface EnhancedToolContext extends ToolContext {
28
+ emit(eventType: string, data?: any): void;
29
+ }
30
+ /**
31
+ * 重载 1: tool(name, executeFn)
32
+ * 零配置模式,自动推断类型
33
+ */
34
+ export declare function tool<TArgs = any, TResult = any>(name: string, executeFn: (args: TArgs, ctx?: EnhancedToolContext) => Promise<TResult> | TResult): ToolInstance;
35
+ /**
36
+ * 重载 2: tool(definition)
37
+ * 完整配置模式
38
+ */
39
+ export declare function tool<TArgs = any, TResult = any>(definition: ToolDefinition<TArgs, TResult>): ToolInstance;
40
+ /**
41
+ * 批量定义工具
42
+ */
43
+ export declare function tools(definitions: ToolDefinition[]): ToolInstance[];
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tool = tool;
4
+ exports.tools = tools;
5
+ const zod_1 = require("zod");
6
+ const registry_1 = require("./registry");
7
+ /**
8
+ * 实现
9
+ */
10
+ function tool(nameOrDef, executeFn) {
11
+ // 解析参数
12
+ const def = typeof nameOrDef === 'string'
13
+ ? {
14
+ name: nameOrDef,
15
+ description: `Execute ${nameOrDef}`,
16
+ parameters: zod_1.z.any(),
17
+ execute: executeFn,
18
+ }
19
+ : nameOrDef;
20
+ // 生成 JSON Schema (使用 Zod v4 原生方法)
21
+ let input_schema;
22
+ if (def.parameters) {
23
+ // Zod v4: 使用 zodToJsonSchema 的替代方案
24
+ // 由于 zod-to-json-schema 已被弃用,我们需要手动转换 Zod schema 为 JSON Schema
25
+ input_schema = zodToJsonSchemaManual(def.parameters);
26
+ }
27
+ else {
28
+ input_schema = { type: 'object', properties: {} };
29
+ }
30
+ // 创建工具实例
31
+ const toolInstance = {
32
+ name: def.name,
33
+ description: def.description || `Execute ${def.name}`,
34
+ input_schema,
35
+ hooks: def.hooks,
36
+ async exec(args, ctx) {
37
+ try {
38
+ // 参数验证
39
+ if (def.parameters) {
40
+ const parseResult = def.parameters.safeParse(args);
41
+ if (!parseResult.success) {
42
+ return {
43
+ ok: false,
44
+ error: `Invalid parameters: ${parseResult.error.message}`,
45
+ _validationError: true,
46
+ };
47
+ }
48
+ args = parseResult.data;
49
+ }
50
+ // 增强上下文
51
+ const enhancedCtx = {
52
+ ...ctx,
53
+ emit(eventType, data) {
54
+ ctx.agent?.events?.emitMonitor({
55
+ type: 'tool_custom_event',
56
+ toolName: def.name,
57
+ eventType,
58
+ data,
59
+ timestamp: Date.now(),
60
+ });
61
+ },
62
+ };
63
+ // 执行工具
64
+ const result = await def.execute(args, enhancedCtx);
65
+ // 如果工具返回 {ok: false},保持原样
66
+ if (result && typeof result === 'object' && 'ok' in result && result.ok === false) {
67
+ return result;
68
+ }
69
+ // 正常结果
70
+ return result;
71
+ }
72
+ catch (error) {
73
+ // 捕获工具执行中的所有错误,统一返回格式
74
+ return {
75
+ ok: false,
76
+ error: error?.message || String(error),
77
+ _thrownError: true,
78
+ };
79
+ }
80
+ },
81
+ toDescriptor() {
82
+ return {
83
+ source: 'registered',
84
+ name: def.name,
85
+ registryId: def.name,
86
+ metadata: {
87
+ version: def.metadata?.version,
88
+ tags: def.metadata?.tags,
89
+ cacheable: def.metadata?.cacheable,
90
+ cacheTTL: def.metadata?.cacheTTL,
91
+ timeout: def.metadata?.timeout,
92
+ concurrent: def.metadata?.concurrent,
93
+ access: def.metadata?.readonly ? 'read' : 'write',
94
+ mutates: !def.metadata?.readonly,
95
+ },
96
+ };
97
+ },
98
+ };
99
+ // 自动注册到全局 registry
100
+ registry_1.globalToolRegistry.register(def.name, () => toolInstance);
101
+ return toolInstance;
102
+ }
103
+ /**
104
+ * 批量定义工具
105
+ */
106
+ function tools(definitions) {
107
+ return definitions.map((def) => tool(def));
108
+ }
109
+ /**
110
+ * 手动转换 Zod Schema 为 JSON Schema (替代已弃用的 zod-to-json-schema)
111
+ *
112
+ * 设计原则:
113
+ * - 简洁:只处理工具定义中常用的 Zod 类型
114
+ * - 健壮:对于不支持的类型,返回默认的 object schema
115
+ * - 可扩展:可以根据需要添加更多类型的支持
116
+ */
117
+ function zodToJsonSchemaManual(zodType) {
118
+ // 处理 ZodEffects 类型(经过 .transform()、.refine() 等转换的 schema)
119
+ const typeName = zodType._def?.typeName;
120
+ if (typeName === 'ZodEffects' || (typeof typeName === 'string' && typeName.includes('ZodEffects'))) {
121
+ const innerSchema = zodType._def.schema;
122
+ if (innerSchema) {
123
+ return zodToJsonSchemaManual(innerSchema);
124
+ }
125
+ return { type: 'object', properties: {}, required: [] };
126
+ }
127
+ // 如果是 ZodObject
128
+ if (zodType instanceof zod_1.z.ZodObject) {
129
+ // Zod v4: shape 是属性而非方法
130
+ const shape = zodType.shape || zodType._def.shape;
131
+ const properties = {};
132
+ const required = [];
133
+ for (const [key, value] of Object.entries(shape)) {
134
+ const fieldSchema = convertZodType(value);
135
+ properties[key] = fieldSchema;
136
+ // 检查是否可选
137
+ const isOptional = isZodTypeOptional(value);
138
+ if (!isOptional) {
139
+ required.push(key);
140
+ }
141
+ }
142
+ return {
143
+ type: 'object',
144
+ properties,
145
+ required,
146
+ };
147
+ }
148
+ // 默认返回空对象
149
+ return {
150
+ type: 'object',
151
+ properties: {},
152
+ required: [],
153
+ };
154
+ }
155
+ /**
156
+ * 转换 Zod 类型为 JSON Schema 类型
157
+ */
158
+ function convertZodType(zodType) {
159
+ // 处理可选类型
160
+ if (zodType instanceof zod_1.z.ZodOptional) {
161
+ const innerType = zodType._def.innerType;
162
+ return convertZodType(innerType);
163
+ }
164
+ // 处理默认值类型
165
+ if (zodType instanceof zod_1.z.ZodDefault) {
166
+ const innerType = zodType._def.innerType;
167
+ return convertZodType(innerType);
168
+ }
169
+ // 基本类型映射
170
+ if (zodType instanceof zod_1.z.ZodString) {
171
+ return { type: 'string' };
172
+ }
173
+ if (zodType instanceof zod_1.z.ZodNumber) {
174
+ return { type: 'number' };
175
+ }
176
+ if (zodType instanceof zod_1.z.ZodBoolean) {
177
+ return { type: 'boolean' };
178
+ }
179
+ if (zodType instanceof zod_1.z.ZodArray) {
180
+ const elementType = zodType._def.type;
181
+ return {
182
+ type: 'array',
183
+ items: convertZodType(elementType),
184
+ };
185
+ }
186
+ if (zodType instanceof zod_1.z.ZodObject) {
187
+ return zodToJsonSchemaManual(zodType);
188
+ }
189
+ if (zodType instanceof zod_1.z.ZodEnum) {
190
+ return {
191
+ type: 'string',
192
+ enum: zodType._def.values,
193
+ };
194
+ }
195
+ if (zodType instanceof zod_1.z.ZodLiteral) {
196
+ return {
197
+ type: typeof zodType._def.value,
198
+ const: zodType._def.value,
199
+ };
200
+ }
201
+ // 未知类型,默认为 object(避免意外返回 string)
202
+ return { type: 'object', properties: {}, required: [] };
203
+ }
204
+ /**
205
+ * 检查 Zod 类型是否可选
206
+ */
207
+ function isZodTypeOptional(zodType) {
208
+ return (zodType instanceof zod_1.z.ZodOptional ||
209
+ zodType instanceof zod_1.z.ZodDefault ||
210
+ zodType.isNullable?.() === true);
211
+ }
@@ -0,0 +1,69 @@
1
+ import { ZodType } from 'zod';
2
+ import type { ToolInstance } from '../index';
3
+ /**
4
+ * ToolKit 装饰器元数据
5
+ */
6
+ interface ToolMethodMetadata {
7
+ description?: string;
8
+ parameters?: ZodType;
9
+ metadata?: any;
10
+ }
11
+ /**
12
+ * 工具方法装饰器
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * class WeatherKit extends ToolKit {
17
+ * @toolMethod({ description: 'Get current weather' })
18
+ * async getWeather(args: { city: string }, ctx: ToolContext) {
19
+ * return { temperature: 25, city: args.city };
20
+ * }
21
+ * }
22
+ * ```
23
+ */
24
+ export declare function toolMethod(metadata?: ToolMethodMetadata): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
25
+ /**
26
+ * ToolKit 基类
27
+ *
28
+ * 提供组织化的工具定义方式
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * class DatabaseKit extends ToolKit {
33
+ * constructor(private db: Database) {
34
+ * super('db');
35
+ * }
36
+ *
37
+ * @toolMethod({
38
+ * description: 'Query database',
39
+ * parameters: z.object({ query: z.string() })
40
+ * })
41
+ * async query(args: { query: string }, ctx: ToolContext) {
42
+ * return await this.db.query(args.query);
43
+ * }
44
+ *
45
+ * @toolMethod({ description: 'Insert record' })
46
+ * async insert(args: { table: string; data: any }, ctx: ToolContext) {
47
+ * return await this.db.insert(args.table, args.data);
48
+ * }
49
+ * }
50
+ *
51
+ * // 使用
52
+ * const dbKit = new DatabaseKit(myDatabase);
53
+ * const tools = dbKit.getTools();
54
+ * // 返回: [db__query, db__insert]
55
+ * ```
56
+ */
57
+ export declare class ToolKit {
58
+ private readonly namespace?;
59
+ constructor(namespace?: string | undefined);
60
+ /**
61
+ * 获取所有工具实例
62
+ */
63
+ getTools(): ToolInstance[];
64
+ /**
65
+ * 获取工具名称列表
66
+ */
67
+ getToolNames(): string[];
68
+ }
69
+ export {};
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ToolKit = void 0;
4
+ exports.toolMethod = toolMethod;
5
+ const zod_1 = require("zod");
6
+ const tool_1 = require("./tool");
7
+ /**
8
+ * 工具方法装饰器
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * class WeatherKit extends ToolKit {
13
+ * @toolMethod({ description: 'Get current weather' })
14
+ * async getWeather(args: { city: string }, ctx: ToolContext) {
15
+ * return { temperature: 25, city: args.city };
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ function toolMethod(metadata = {}) {
21
+ return function (target, propertyKey, descriptor) {
22
+ // 存储元数据到类的原型
23
+ if (!target.constructor._toolMethods) {
24
+ target.constructor._toolMethods = new Map();
25
+ }
26
+ target.constructor._toolMethods.set(propertyKey, {
27
+ ...metadata,
28
+ method: descriptor.value,
29
+ });
30
+ };
31
+ }
32
+ /**
33
+ * ToolKit 基类
34
+ *
35
+ * 提供组织化的工具定义方式
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * class DatabaseKit extends ToolKit {
40
+ * constructor(private db: Database) {
41
+ * super('db');
42
+ * }
43
+ *
44
+ * @toolMethod({
45
+ * description: 'Query database',
46
+ * parameters: z.object({ query: z.string() })
47
+ * })
48
+ * async query(args: { query: string }, ctx: ToolContext) {
49
+ * return await this.db.query(args.query);
50
+ * }
51
+ *
52
+ * @toolMethod({ description: 'Insert record' })
53
+ * async insert(args: { table: string; data: any }, ctx: ToolContext) {
54
+ * return await this.db.insert(args.table, args.data);
55
+ * }
56
+ * }
57
+ *
58
+ * // 使用
59
+ * const dbKit = new DatabaseKit(myDatabase);
60
+ * const tools = dbKit.getTools();
61
+ * // 返回: [db__query, db__insert]
62
+ * ```
63
+ */
64
+ class ToolKit {
65
+ constructor(namespace) {
66
+ this.namespace = namespace;
67
+ }
68
+ /**
69
+ * 获取所有工具实例
70
+ */
71
+ getTools() {
72
+ const constructor = this.constructor;
73
+ const toolMethods = constructor._toolMethods;
74
+ if (!toolMethods) {
75
+ return [];
76
+ }
77
+ const tools = [];
78
+ for (const [methodName, metadata] of toolMethods) {
79
+ const toolName = this.namespace ? `${this.namespace}__${methodName}` : methodName;
80
+ const def = {
81
+ name: toolName,
82
+ description: metadata.description || `Execute ${methodName}`,
83
+ parameters: metadata.parameters || zod_1.z.any(),
84
+ execute: metadata.method.bind(this),
85
+ metadata: metadata.metadata,
86
+ };
87
+ tools.push((0, tool_1.tool)(def));
88
+ }
89
+ return tools;
90
+ }
91
+ /**
92
+ * 获取工具名称列表
93
+ */
94
+ getToolNames() {
95
+ return this.getTools().map((t) => t.name);
96
+ }
97
+ }
98
+ exports.ToolKit = ToolKit;