sdkwork-browser-agent 1.0.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 (146) hide show
  1. package/README.md +228 -0
  2. package/README.zh.md +228 -0
  3. package/dist/agent-Bpxmkz8W.d.ts +197 -0
  4. package/dist/agent-kexkkI13.d.cts +197 -0
  5. package/dist/browser/agent-Bpxmkz8W.d.ts +197 -0
  6. package/dist/browser/chunk-7W2JJCSS.js +276 -0
  7. package/dist/browser/chunk-7W2JJCSS.js.map +1 -0
  8. package/dist/browser/chunk-BHRFRGR7.js +144 -0
  9. package/dist/browser/chunk-BHRFRGR7.js.map +1 -0
  10. package/dist/browser/chunk-CLP6UNSV.js +285 -0
  11. package/dist/browser/chunk-CLP6UNSV.js.map +1 -0
  12. package/dist/browser/chunk-HXLRBB7S.js +1569 -0
  13. package/dist/browser/chunk-HXLRBB7S.js.map +1 -0
  14. package/dist/browser/chunk-VJEFLRZT.js +1720 -0
  15. package/dist/browser/chunk-VJEFLRZT.js.map +1 -0
  16. package/dist/browser/index.d.ts +842 -0
  17. package/dist/browser/index.js +3293 -0
  18. package/dist/browser/index.js.map +1 -0
  19. package/dist/browser/llm/index.d.ts +235 -0
  20. package/dist/browser/llm/index.js +29 -0
  21. package/dist/browser/llm/index.js.map +1 -0
  22. package/dist/browser/mcp/index.d.ts +63 -0
  23. package/dist/browser/mcp/index.js +9 -0
  24. package/dist/browser/mcp/index.js.map +1 -0
  25. package/dist/browser/provider-Dna36xA-.d.ts +105 -0
  26. package/dist/browser/skills/index.d.ts +401 -0
  27. package/dist/browser/skills/index.js +31 -0
  28. package/dist/browser/skills/index.js.map +1 -0
  29. package/dist/browser/storage/index.d.ts +64 -0
  30. package/dist/browser/storage/index.js +15 -0
  31. package/dist/browser/storage/index.js.map +1 -0
  32. package/dist/browser/tools/index.d.ts +45 -0
  33. package/dist/browser/tools/index.js +15 -0
  34. package/dist/browser/tools/index.js.map +1 -0
  35. package/dist/browser/types-CG5I-byI.d.ts +30 -0
  36. package/dist/chunk-56J3IBXZ.js +144 -0
  37. package/dist/chunk-56J3IBXZ.js.map +1 -0
  38. package/dist/chunk-5XTVS5MB.js +1720 -0
  39. package/dist/chunk-5XTVS5MB.js.map +1 -0
  40. package/dist/chunk-6AYIRBGI.js +166 -0
  41. package/dist/chunk-6AYIRBGI.js.map +1 -0
  42. package/dist/chunk-C2EYJHXW.cjs +276 -0
  43. package/dist/chunk-C2EYJHXW.cjs.map +1 -0
  44. package/dist/chunk-HOZQ445W.cjs +166 -0
  45. package/dist/chunk-HOZQ445W.cjs.map +1 -0
  46. package/dist/chunk-KZNZ6CGD.cjs +144 -0
  47. package/dist/chunk-KZNZ6CGD.cjs.map +1 -0
  48. package/dist/chunk-XFMT5ZA4.js +276 -0
  49. package/dist/chunk-XFMT5ZA4.js.map +1 -0
  50. package/dist/chunk-XPGICLEJ.cjs +1720 -0
  51. package/dist/chunk-XPGICLEJ.cjs.map +1 -0
  52. package/dist/index.cjs +1311 -0
  53. package/dist/index.cjs.map +1 -0
  54. package/dist/index.d.cts +395 -0
  55. package/dist/index.d.ts +395 -0
  56. package/dist/index.js +1311 -0
  57. package/dist/index.js.map +1 -0
  58. package/dist/llm/index.cjs +29 -0
  59. package/dist/llm/index.cjs.map +1 -0
  60. package/dist/llm/index.d.cts +235 -0
  61. package/dist/llm/index.d.ts +235 -0
  62. package/dist/llm/index.js +29 -0
  63. package/dist/llm/index.js.map +1 -0
  64. package/dist/mcp/index.cjs +9 -0
  65. package/dist/mcp/index.cjs.map +1 -0
  66. package/dist/mcp/index.d.cts +63 -0
  67. package/dist/mcp/index.d.ts +63 -0
  68. package/dist/mcp/index.js +9 -0
  69. package/dist/mcp/index.js.map +1 -0
  70. package/dist/node/agent-Bpxmkz8W.d.ts +197 -0
  71. package/dist/node/agent-kexkkI13.d.cts +197 -0
  72. package/dist/node/chunk-7W2JJCSS.js +276 -0
  73. package/dist/node/chunk-7W2JJCSS.js.map +1 -0
  74. package/dist/node/chunk-BHRFRGR7.js +144 -0
  75. package/dist/node/chunk-BHRFRGR7.js.map +1 -0
  76. package/dist/node/chunk-CLP6UNSV.js +285 -0
  77. package/dist/node/chunk-CLP6UNSV.js.map +1 -0
  78. package/dist/node/chunk-HXLRBB7S.js +1569 -0
  79. package/dist/node/chunk-HXLRBB7S.js.map +1 -0
  80. package/dist/node/chunk-IYG37UN3.cjs +144 -0
  81. package/dist/node/chunk-IYG37UN3.cjs.map +1 -0
  82. package/dist/node/chunk-JF33ZOMB.cjs +285 -0
  83. package/dist/node/chunk-JF33ZOMB.cjs.map +1 -0
  84. package/dist/node/chunk-KXXS33G3.cjs +276 -0
  85. package/dist/node/chunk-KXXS33G3.cjs.map +1 -0
  86. package/dist/node/chunk-MTFOABGC.cjs +1720 -0
  87. package/dist/node/chunk-MTFOABGC.cjs.map +1 -0
  88. package/dist/node/chunk-VJEFLRZT.js +1720 -0
  89. package/dist/node/chunk-VJEFLRZT.js.map +1 -0
  90. package/dist/node/chunk-YDHQCPSN.cjs +1569 -0
  91. package/dist/node/chunk-YDHQCPSN.cjs.map +1 -0
  92. package/dist/node/index.cjs +3293 -0
  93. package/dist/node/index.cjs.map +1 -0
  94. package/dist/node/index.d.cts +842 -0
  95. package/dist/node/index.d.ts +842 -0
  96. package/dist/node/index.js +3293 -0
  97. package/dist/node/index.js.map +1 -0
  98. package/dist/node/llm/index.cjs +29 -0
  99. package/dist/node/llm/index.cjs.map +1 -0
  100. package/dist/node/llm/index.d.cts +235 -0
  101. package/dist/node/llm/index.d.ts +235 -0
  102. package/dist/node/llm/index.js +29 -0
  103. package/dist/node/llm/index.js.map +1 -0
  104. package/dist/node/mcp/index.cjs +9 -0
  105. package/dist/node/mcp/index.cjs.map +1 -0
  106. package/dist/node/mcp/index.d.cts +63 -0
  107. package/dist/node/mcp/index.d.ts +63 -0
  108. package/dist/node/mcp/index.js +9 -0
  109. package/dist/node/mcp/index.js.map +1 -0
  110. package/dist/node/provider-Dna36xA-.d.cts +105 -0
  111. package/dist/node/provider-Dna36xA-.d.ts +105 -0
  112. package/dist/node/skills/index.cjs +31 -0
  113. package/dist/node/skills/index.cjs.map +1 -0
  114. package/dist/node/skills/index.d.cts +401 -0
  115. package/dist/node/skills/index.d.ts +401 -0
  116. package/dist/node/skills/index.js +31 -0
  117. package/dist/node/skills/index.js.map +1 -0
  118. package/dist/node/storage/index.cjs +15 -0
  119. package/dist/node/storage/index.cjs.map +1 -0
  120. package/dist/node/storage/index.d.cts +64 -0
  121. package/dist/node/storage/index.d.ts +64 -0
  122. package/dist/node/storage/index.js +15 -0
  123. package/dist/node/storage/index.js.map +1 -0
  124. package/dist/node/tools/index.cjs +15 -0
  125. package/dist/node/tools/index.cjs.map +1 -0
  126. package/dist/node/tools/index.d.cts +45 -0
  127. package/dist/node/tools/index.d.ts +45 -0
  128. package/dist/node/tools/index.js +15 -0
  129. package/dist/node/tools/index.js.map +1 -0
  130. package/dist/node/types-CG5I-byI.d.cts +30 -0
  131. package/dist/node/types-CG5I-byI.d.ts +30 -0
  132. package/dist/provider-Dna36xA-.d.cts +105 -0
  133. package/dist/provider-Dna36xA-.d.ts +105 -0
  134. package/dist/skills/index.cjs +15 -0
  135. package/dist/skills/index.cjs.map +1 -0
  136. package/dist/skills/index.d.cts +43 -0
  137. package/dist/skills/index.d.ts +43 -0
  138. package/dist/skills/index.js +15 -0
  139. package/dist/skills/index.js.map +1 -0
  140. package/dist/tools/index.cjs +15 -0
  141. package/dist/tools/index.cjs.map +1 -0
  142. package/dist/tools/index.d.cts +45 -0
  143. package/dist/tools/index.d.ts +45 -0
  144. package/dist/tools/index.js +15 -0
  145. package/dist/tools/index.js.map +1 -0
  146. package/package.json +150 -0
package/dist/index.js ADDED
@@ -0,0 +1,1311 @@
1
+ import {
2
+ AnthropicProvider,
3
+ DeepSeekProvider,
4
+ DoubaoProvider,
5
+ GeminiProvider,
6
+ LLMManager,
7
+ LLMProviderRegistry,
8
+ MiniMaxProvider,
9
+ MoonshotProvider,
10
+ OpenAIProvider,
11
+ QwenProvider,
12
+ ZhipuProvider,
13
+ globalProviderRegistry
14
+ } from "./chunk-5XTVS5MB.js";
15
+ import {
16
+ SkillRegistry,
17
+ builtInSkills,
18
+ echoSkill,
19
+ listSkillsSkill,
20
+ mathSkill
21
+ } from "./chunk-6AYIRBGI.js";
22
+ import {
23
+ ToolRegistry,
24
+ builtInTools,
25
+ fileReadTool,
26
+ fileWriteTool,
27
+ httpRequestTool
28
+ } from "./chunk-XFMT5ZA4.js";
29
+ import {
30
+ MCPClient,
31
+ MCPServer
32
+ } from "./chunk-56J3IBXZ.js";
33
+
34
+ // src/core/agent.ts
35
+ var Agent = class {
36
+ constructor(config) {
37
+ this.config = config;
38
+ this.name = config.name;
39
+ this.description = config.description;
40
+ this.version = config.version;
41
+ this.llmProvider = config.llmProvider;
42
+ this.systemPrompt = config.systemPrompt;
43
+ this.maxIterations = config.maxIterations || 10;
44
+ this.hooks = config.hooks;
45
+ this._middlewares = config.middlewares || [];
46
+ }
47
+ _skills = /* @__PURE__ */ new Map();
48
+ _tools = /* @__PURE__ */ new Map();
49
+ _plugins = /* @__PURE__ */ new Map();
50
+ _mcpResources = /* @__PURE__ */ new Map();
51
+ _mcpTools = /* @__PURE__ */ new Map();
52
+ _middlewares = [];
53
+ _initialized = false;
54
+ name;
55
+ description;
56
+ version;
57
+ llmProvider;
58
+ systemPrompt;
59
+ maxIterations;
60
+ hooks;
61
+ async initialize() {
62
+ if (this._initialized) return;
63
+ this.config.skills?.forEach((skill) => this.registerSkill(skill));
64
+ this.config.tools?.forEach((tool) => this.registerTool(tool));
65
+ this.config.mcpResources?.forEach((resource) => this.registerMCPResource(resource));
66
+ this.config.mcpTools?.forEach((tool) => this.registerMCPTool(tool));
67
+ const pluginContext = {
68
+ agent: this,
69
+ registerSkill: (skill) => this.registerSkill(skill),
70
+ registerTool: (tool) => this.registerTool(tool),
71
+ registerMCPResource: (resource) => this.registerMCPResource(resource),
72
+ registerMCPTool: (tool) => this.registerMCPTool(tool),
73
+ getLLMProvider: () => this.llmProvider,
74
+ config: {}
75
+ };
76
+ for (const plugin of this.config.plugins || []) {
77
+ await plugin.initialize(pluginContext);
78
+ this._plugins.set(plugin.name, plugin);
79
+ }
80
+ this._initialized = true;
81
+ }
82
+ // ============================================
83
+ // Registration Methods
84
+ // ============================================
85
+ registerSkill(skill) {
86
+ if (this._skills.has(skill.name)) {
87
+ console.warn(`Skill '${skill.name}' is already registered. Overwriting.`);
88
+ }
89
+ this._skills.set(skill.name, skill);
90
+ }
91
+ registerTool(tool) {
92
+ if (this._tools.has(tool.name)) {
93
+ console.warn(`Tool '${tool.name}' is already registered. Overwriting.`);
94
+ }
95
+ this._tools.set(tool.name, tool);
96
+ }
97
+ registerMCPResource(resource) {
98
+ if (this._mcpResources.has(resource.uri)) {
99
+ console.warn(`MCP Resource '${resource.uri}' is already registered. Overwriting.`);
100
+ }
101
+ this._mcpResources.set(resource.uri, resource);
102
+ }
103
+ registerMCPTool(tool) {
104
+ if (this._mcpTools.has(tool.name)) {
105
+ console.warn(`MCP Tool '${tool.name}' is already registered. Overwriting.`);
106
+ }
107
+ this._mcpTools.set(tool.name, tool);
108
+ }
109
+ use(middleware) {
110
+ this._middlewares.push(middleware);
111
+ }
112
+ // ============================================
113
+ // Execution Methods
114
+ // ============================================
115
+ async executeSkill(name, params = {}) {
116
+ const skill = this._skills.get(name);
117
+ if (!skill) {
118
+ return { success: false, error: `Skill '${name}' not found` };
119
+ }
120
+ const context = {
121
+ agent: this,
122
+ skillName: name,
123
+ timestamp: /* @__PURE__ */ new Date()
124
+ };
125
+ await this.hooks?.beforeSkillExecution?.(name, params);
126
+ const execute = async () => {
127
+ try {
128
+ const result = await skill.handler(params, context);
129
+ await this.hooks?.afterSkillExecution?.(name, result);
130
+ return result;
131
+ } catch (error) {
132
+ const err = error instanceof Error ? error : new Error(String(error));
133
+ await this.hooks?.onError?.(err, context);
134
+ return { success: false, error: err.message };
135
+ }
136
+ };
137
+ const chain = this._middlewares.reduceRight(
138
+ (next, middleware) => () => middleware(context, next),
139
+ execute
140
+ );
141
+ return chain();
142
+ }
143
+ async executeTool(name, input) {
144
+ const tool = this._tools.get(name);
145
+ if (!tool) {
146
+ return {
147
+ content: [{ type: "error", text: `Tool '${name}' not found` }],
148
+ isError: true
149
+ };
150
+ }
151
+ const context = {
152
+ agent: this,
153
+ skillName: name,
154
+ timestamp: /* @__PURE__ */ new Date()
155
+ };
156
+ try {
157
+ await this.hooks?.onToolCall?.(name, input);
158
+ return await tool.execute(input, context);
159
+ } catch (error) {
160
+ const message = error instanceof Error ? error.message : String(error);
161
+ return {
162
+ content: [{ type: "error", text: message }],
163
+ isError: true
164
+ };
165
+ }
166
+ }
167
+ async readMCPResource(uri) {
168
+ const resource = this._mcpResources.get(uri);
169
+ if (!resource) return null;
170
+ return resource.read();
171
+ }
172
+ async executeMCPTool(name, args) {
173
+ const tool = this._mcpTools.get(name);
174
+ if (!tool) {
175
+ return {
176
+ content: [{ type: "error", text: `MCP Tool '${name}' not found` }],
177
+ isError: true
178
+ };
179
+ }
180
+ const context = {
181
+ agent: this,
182
+ skillName: name,
183
+ timestamp: /* @__PURE__ */ new Date()
184
+ };
185
+ try {
186
+ return await tool.execute(args, context);
187
+ } catch (error) {
188
+ const message = error instanceof Error ? error.message : String(error);
189
+ return {
190
+ content: [{ type: "error", text: message }],
191
+ isError: true
192
+ };
193
+ }
194
+ }
195
+ // ============================================
196
+ // LLM Integration
197
+ // ============================================
198
+ async chat(messages, options) {
199
+ if (!this.llmProvider) {
200
+ throw new Error("No LLM provider configured");
201
+ }
202
+ const request = {
203
+ messages: this.systemPrompt ? [{ role: "system", content: this.systemPrompt }, ...messages] : messages,
204
+ ...options
205
+ };
206
+ return this.llmProvider.complete(request);
207
+ }
208
+ async *streamChat(messages, options) {
209
+ if (!this.llmProvider) {
210
+ throw new Error("No LLM provider configured");
211
+ }
212
+ const request = {
213
+ messages: this.systemPrompt ? [{ role: "system", content: this.systemPrompt }, ...messages] : messages,
214
+ stream: true,
215
+ ...options
216
+ };
217
+ yield* this.llmProvider.stream(request);
218
+ }
219
+ async executeWithTools(messages, tools) {
220
+ if (!this.llmProvider) {
221
+ throw new Error("No LLM provider configured");
222
+ }
223
+ const request = {
224
+ messages: this.systemPrompt ? [{ role: "system", content: this.systemPrompt }, ...messages] : messages,
225
+ tools,
226
+ tool_choice: "auto"
227
+ };
228
+ return this.llmProvider.complete(request);
229
+ }
230
+ // ============================================
231
+ // Query Methods
232
+ // ============================================
233
+ getSkill(name) {
234
+ return this._skills.get(name);
235
+ }
236
+ getTool(name) {
237
+ return this._tools.get(name);
238
+ }
239
+ getMCPResource(uri) {
240
+ return this._mcpResources.get(uri);
241
+ }
242
+ getMCPTool(name) {
243
+ return this._mcpTools.get(name);
244
+ }
245
+ getPlugin(name) {
246
+ return this._plugins.get(name);
247
+ }
248
+ getSkillNames() {
249
+ return Array.from(this._skills.keys());
250
+ }
251
+ getToolNames() {
252
+ return Array.from(this._tools.keys());
253
+ }
254
+ getMCPResourceURIs() {
255
+ return Array.from(this._mcpResources.keys());
256
+ }
257
+ getMCPToolNames() {
258
+ return Array.from(this._mcpTools.keys());
259
+ }
260
+ getPluginNames() {
261
+ return Array.from(this._plugins.keys());
262
+ }
263
+ getAllSkills() {
264
+ return Array.from(this._skills.values());
265
+ }
266
+ getAllTools() {
267
+ return Array.from(this._tools.values());
268
+ }
269
+ // ============================================
270
+ // Lifecycle Methods
271
+ // ============================================
272
+ async destroy() {
273
+ for (const plugin of this._plugins.values()) {
274
+ await plugin.destroy?.();
275
+ }
276
+ this._skills.clear();
277
+ this._tools.clear();
278
+ this._plugins.clear();
279
+ this._mcpResources.clear();
280
+ this._mcpTools.clear();
281
+ this._middlewares = [];
282
+ this._initialized = false;
283
+ }
284
+ };
285
+
286
+ // src/core/decision-engine.ts
287
+ var SimpleEmbeddingProvider = class {
288
+ vocabulary = /* @__PURE__ */ new Map();
289
+ vocabSize = 0;
290
+ maxVocabSize = 1e3;
291
+ async embed(text) {
292
+ const tokens = this.tokenize(text);
293
+ const embedding = new Array(this.maxVocabSize).fill(0);
294
+ for (const token of tokens) {
295
+ if (!this.vocabulary.has(token)) {
296
+ if (this.vocabSize < this.maxVocabSize) {
297
+ this.vocabulary.set(token, this.vocabSize++);
298
+ }
299
+ }
300
+ const idx = this.vocabulary.get(token);
301
+ if (idx !== void 0) {
302
+ embedding[idx] += 1;
303
+ }
304
+ }
305
+ const magnitude = Math.sqrt(embedding.reduce((sum, val) => sum + val * val, 0));
306
+ if (magnitude > 0) {
307
+ return embedding.map((val) => val / magnitude);
308
+ }
309
+ return embedding;
310
+ }
311
+ similarity(a, b) {
312
+ let dotProduct = 0;
313
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
314
+ dotProduct += a[i] * b[i];
315
+ }
316
+ return dotProduct;
317
+ }
318
+ tokenize(text) {
319
+ return text.toLowerCase().replace(/[^\w\s]/g, " ").split(/\s+/).filter((t) => t.length > 2);
320
+ }
321
+ };
322
+ var DecisionEngine = class {
323
+ skillEmbeddings = /* @__PURE__ */ new Map();
324
+ embeddingProvider;
325
+ decisionCache = /* @__PURE__ */ new Map();
326
+ config;
327
+ constructor(config = {}, embeddingProvider) {
328
+ this.config = {
329
+ threshold: config.threshold ?? 0.6,
330
+ maxSkills: config.maxSkills ?? 3,
331
+ enableEmbeddings: config.enableEmbeddings ?? true,
332
+ enableCaching: config.enableCaching ?? true,
333
+ similarityThreshold: config.similarityThreshold ?? 0.5
334
+ };
335
+ this.embeddingProvider = embeddingProvider ?? new SimpleEmbeddingProvider();
336
+ }
337
+ /**
338
+ * Index skills for fast retrieval
339
+ */
340
+ async indexSkill(skill) {
341
+ if (!this.config.enableEmbeddings) return;
342
+ const text = `${skill.name} ${skill.description} ${this.extractKeywords(skill)}`;
343
+ const embedding = await this.embeddingProvider.embed(text);
344
+ this.skillEmbeddings.set(skill.name, embedding);
345
+ }
346
+ /**
347
+ * Make decision based on input
348
+ */
349
+ async decide(context) {
350
+ const cacheKey = this.generateCacheKey(context);
351
+ if (this.config.enableCaching) {
352
+ const cached = this.decisionCache.get(cacheKey);
353
+ if (cached) return cached;
354
+ }
355
+ const relevantSkills = await this.findRelevantSkills(context);
356
+ const relevantTools = this.findRelevantTools(context);
357
+ let decision;
358
+ if (relevantSkills.length === 0 && relevantTools.length === 0) {
359
+ decision = {
360
+ type: "llm",
361
+ confidence: 1,
362
+ reasoning: "No relevant skills found, using LLM directly"
363
+ };
364
+ } else if (relevantSkills.length === 1 && relevantTools.length === 0) {
365
+ decision = {
366
+ type: "skill",
367
+ skills: [relevantSkills[0].name],
368
+ confidence: relevantSkills[0].confidence,
369
+ reasoning: `Single skill match: ${relevantSkills[0].name}`
370
+ };
371
+ } else if (relevantTools.length === 1 && relevantSkills.length === 0) {
372
+ decision = {
373
+ type: "tool",
374
+ tools: [relevantTools[0].name],
375
+ confidence: relevantTools[0].confidence,
376
+ reasoning: `Single tool match: ${relevantTools[0].name}`
377
+ };
378
+ } else {
379
+ const topSkills = relevantSkills.slice(0, this.config.maxSkills);
380
+ const topTools = relevantTools.slice(0, 2);
381
+ decision = {
382
+ type: "multi",
383
+ skills: topSkills.map((s) => s.name),
384
+ tools: topTools.map((t) => t.name),
385
+ confidence: Math.max(topSkills[0]?.confidence ?? 0, topTools[0]?.confidence ?? 0),
386
+ reasoning: `Multiple matches: ${topSkills.map((s) => s.name).join(", ")}`,
387
+ fallback: "llm"
388
+ };
389
+ }
390
+ if (this.config.enableCaching) {
391
+ this.decisionCache.set(cacheKey, decision);
392
+ if (this.decisionCache.size > 1e3) {
393
+ const firstKey = this.decisionCache.keys().next().value;
394
+ if (firstKey !== void 0) {
395
+ this.decisionCache.delete(firstKey);
396
+ }
397
+ }
398
+ }
399
+ return decision;
400
+ }
401
+ /**
402
+ * Find relevant skills using similarity matching
403
+ */
404
+ async findRelevantSkills(context) {
405
+ if (!this.config.enableEmbeddings || this.skillEmbeddings.size === 0) {
406
+ return this.fallbackSkillMatching(context);
407
+ }
408
+ const inputEmbedding = await this.embeddingProvider.embed(context.input);
409
+ const results = [];
410
+ for (const [skillName, skillEmbedding] of this.skillEmbeddings) {
411
+ const similarity = this.embeddingProvider.similarity(inputEmbedding, skillEmbedding);
412
+ if (similarity >= this.config.similarityThreshold) {
413
+ results.push({ name: skillName, confidence: similarity });
414
+ }
415
+ }
416
+ results.sort((a, b) => b.confidence - a.confidence);
417
+ return results;
418
+ }
419
+ /**
420
+ * Fallback matching using keyword extraction
421
+ */
422
+ fallbackSkillMatching(context) {
423
+ const inputKeywords = this.extractKeywordsFromText(context.input);
424
+ const results = [];
425
+ for (const skillName of context.availableSkills) {
426
+ const skillKeywords = skillName.toLowerCase().split(/[_-]/);
427
+ const matches = inputKeywords.filter(
428
+ (kw) => skillKeywords.some((sk) => sk.includes(kw) || kw.includes(sk))
429
+ );
430
+ if (matches.length > 0) {
431
+ const confidence = matches.length / Math.max(inputKeywords.length, skillKeywords.length);
432
+ if (confidence >= this.config.threshold) {
433
+ results.push({ name: skillName, confidence });
434
+ }
435
+ }
436
+ }
437
+ results.sort((a, b) => b.confidence - a.confidence);
438
+ return results;
439
+ }
440
+ /**
441
+ * Find relevant tools
442
+ */
443
+ findRelevantTools(context) {
444
+ const inputKeywords = this.extractKeywordsFromText(context.input);
445
+ const results = [];
446
+ for (const toolName of context.availableTools) {
447
+ const toolKeywords = toolName.toLowerCase().split(/[_-]/);
448
+ const matches = inputKeywords.filter(
449
+ (kw) => toolKeywords.some((tk) => tk.includes(kw) || kw.includes(tk))
450
+ );
451
+ if (matches.length > 0) {
452
+ const confidence = matches.length / Math.max(inputKeywords.length, toolKeywords.length);
453
+ if (confidence >= this.config.threshold) {
454
+ results.push({ name: toolName, confidence });
455
+ }
456
+ }
457
+ }
458
+ results.sort((a, b) => b.confidence - a.confidence);
459
+ return results;
460
+ }
461
+ /**
462
+ * Extract keywords from skill
463
+ */
464
+ extractKeywords(skill) {
465
+ const keywords = [
466
+ skill.name,
467
+ skill.description,
468
+ ...skill.metadata?.tags ?? [],
469
+ skill.metadata?.category ?? ""
470
+ ];
471
+ for (const [key, prop] of Object.entries(skill.parameters.properties)) {
472
+ keywords.push(key, prop.description);
473
+ }
474
+ return keywords.join(" ");
475
+ }
476
+ /**
477
+ * Extract keywords from text
478
+ */
479
+ extractKeywordsFromText(text) {
480
+ return text.toLowerCase().replace(/[^\w\s]/g, " ").split(/\s+/).filter((t) => t.length > 2);
481
+ }
482
+ /**
483
+ * Generate cache key
484
+ */
485
+ generateCacheKey(context) {
486
+ return `${context.input}:${context.availableSkills.join(",")}:${context.availableTools.join(",")}`;
487
+ }
488
+ /**
489
+ * Clear cache
490
+ */
491
+ clearCache() {
492
+ this.decisionCache.clear();
493
+ }
494
+ /**
495
+ * Get cache stats
496
+ */
497
+ getCacheStats() {
498
+ return { size: this.decisionCache.size };
499
+ }
500
+ };
501
+
502
+ // src/core/skill-loader.ts
503
+ var DynamicSkillLoader = class {
504
+ loadedSkills = /* @__PURE__ */ new Map();
505
+ skillCache = /* @__PURE__ */ new Map();
506
+ skillSources = /* @__PURE__ */ new Map();
507
+ config;
508
+ constructor(config = {}) {
509
+ this.config = {
510
+ skillDirectory: config.skillDirectory ?? "./skills",
511
+ enableLazyLoading: config.enableLazyLoading ?? true,
512
+ enableCaching: config.enableCaching ?? true,
513
+ cacheSize: config.cacheSize ?? 100,
514
+ hotReload: config.hotReload ?? false
515
+ };
516
+ }
517
+ /**
518
+ * Register a skill source for lazy loading
519
+ */
520
+ registerSource(source) {
521
+ this.skillSources.set(source.name, source);
522
+ }
523
+ /**
524
+ * Load a skill dynamically
525
+ */
526
+ async load(name) {
527
+ if (this.config.enableCaching) {
528
+ const cached = this.skillCache.get(name);
529
+ if (cached) return cached;
530
+ }
531
+ const loaded = this.loadedSkills.get(name);
532
+ if (loaded) {
533
+ return loaded;
534
+ }
535
+ const source = this.skillSources.get(name);
536
+ if (!source) {
537
+ return null;
538
+ }
539
+ let skill = null;
540
+ switch (source.type) {
541
+ case "builtin":
542
+ skill = await this.loadBuiltin(source);
543
+ break;
544
+ case "file":
545
+ skill = await this.loadFromFile(source);
546
+ break;
547
+ case "url":
548
+ skill = await this.loadFromUrl(source);
549
+ break;
550
+ case "module":
551
+ skill = await this.loadFromModule(source);
552
+ break;
553
+ }
554
+ if (skill) {
555
+ if (this.config.enableCaching) {
556
+ this.skillCache.set(name, skill);
557
+ this.enforceCacheLimit();
558
+ }
559
+ const loadedSkill = {
560
+ ...skill,
561
+ loadedAt: /* @__PURE__ */ new Date(),
562
+ source,
563
+ size: JSON.stringify(skill).length
564
+ };
565
+ this.loadedSkills.set(name, loadedSkill);
566
+ }
567
+ return skill;
568
+ }
569
+ /**
570
+ * Load multiple skills
571
+ */
572
+ async loadMultiple(names) {
573
+ const results = /* @__PURE__ */ new Map();
574
+ await Promise.all(
575
+ names.map(async (name) => {
576
+ const skill = await this.load(name);
577
+ if (skill) {
578
+ results.set(name, skill);
579
+ }
580
+ })
581
+ );
582
+ return results;
583
+ }
584
+ /**
585
+ * Unload a skill
586
+ */
587
+ unload(name) {
588
+ this.skillCache.delete(name);
589
+ return this.loadedSkills.delete(name);
590
+ }
591
+ /**
592
+ * Check if skill is loaded
593
+ */
594
+ isLoaded(name) {
595
+ return this.loadedSkills.has(name) || this.skillCache.has(name);
596
+ }
597
+ /**
598
+ * Get loaded skill info
599
+ */
600
+ getLoadedSkill(name) {
601
+ return this.loadedSkills.get(name);
602
+ }
603
+ /**
604
+ * List all loaded skills
605
+ */
606
+ listLoaded() {
607
+ return Array.from(this.loadedSkills.values());
608
+ }
609
+ /**
610
+ * List available skill sources
611
+ */
612
+ listSources() {
613
+ return Array.from(this.skillSources.values());
614
+ }
615
+ /**
616
+ * Preload skills (eager loading)
617
+ */
618
+ async preload(names) {
619
+ await this.loadMultiple(names);
620
+ }
621
+ /**
622
+ * Get memory usage stats
623
+ */
624
+ getStats() {
625
+ const loaded = this.listLoaded();
626
+ return {
627
+ loaded: loaded.length,
628
+ cached: this.skillCache.size,
629
+ sources: this.skillSources.size,
630
+ totalSize: loaded.reduce((sum, s) => sum + (s.size ?? 0), 0)
631
+ };
632
+ }
633
+ /**
634
+ * Clear cache
635
+ */
636
+ clearCache() {
637
+ this.skillCache.clear();
638
+ }
639
+ /**
640
+ * Clear all loaded skills
641
+ */
642
+ clear() {
643
+ this.loadedSkills.clear();
644
+ this.skillCache.clear();
645
+ }
646
+ // Private loading methods
647
+ async loadBuiltin(_source) {
648
+ return null;
649
+ }
650
+ async loadFromFile(source) {
651
+ if (typeof window !== "undefined") {
652
+ console.warn("File loading not supported in browser");
653
+ return null;
654
+ }
655
+ try {
656
+ const fs = await import("fs/promises");
657
+ const content = await fs.readFile(source.source, "utf-8");
658
+ const module = JSON.parse(content);
659
+ return this.validateSkill(module);
660
+ } catch (error) {
661
+ console.error(`Failed to load skill from file: ${source.source}`, error);
662
+ return null;
663
+ }
664
+ }
665
+ async loadFromUrl(source) {
666
+ try {
667
+ const response = await fetch(source.source);
668
+ if (!response.ok) {
669
+ throw new Error(`HTTP ${response.status}`);
670
+ }
671
+ const module = await response.json();
672
+ return this.validateSkill(module);
673
+ } catch (error) {
674
+ console.error(`Failed to load skill from URL: ${source.source}`, error);
675
+ return null;
676
+ }
677
+ }
678
+ async loadFromModule(source) {
679
+ try {
680
+ const module = await import(source.source);
681
+ const skill = module.default || module.skill || module;
682
+ return this.validateSkill(skill);
683
+ } catch (error) {
684
+ console.error(`Failed to load skill from module: ${source.source}`, error);
685
+ return null;
686
+ }
687
+ }
688
+ validateSkill(obj) {
689
+ if (typeof obj !== "object" || obj === null) return null;
690
+ const skill = obj;
691
+ if (typeof skill.name === "string" && typeof skill.description === "string" && typeof skill.parameters === "object" && typeof skill.handler === "function") {
692
+ return skill;
693
+ }
694
+ return null;
695
+ }
696
+ enforceCacheLimit() {
697
+ while (this.skillCache.size > this.config.cacheSize) {
698
+ const firstKey = this.skillCache.keys().next().value;
699
+ if (firstKey !== void 0) {
700
+ this.skillCache.delete(firstKey);
701
+ }
702
+ }
703
+ }
704
+ };
705
+
706
+ // src/core/token-optimizer.ts
707
+ var TokenOptimizer = class {
708
+ config;
709
+ constructor(config = {}) {
710
+ this.config = {
711
+ maxContextTokens: config.maxContextTokens ?? 4e3,
712
+ maxSkillDescriptionLength: config.maxSkillDescriptionLength ?? 200,
713
+ enableCompression: config.enableCompression ?? true,
714
+ preserveSystemPrompt: config.preserveSystemPrompt ?? true
715
+ };
716
+ }
717
+ /**
718
+ * Optimize skills for minimal token usage
719
+ */
720
+ optimizeSkills(skills, forQuery) {
721
+ if (!this.config.enableCompression) return skills;
722
+ return skills.map((skill) => this.compressSkill(skill, forQuery));
723
+ }
724
+ /**
725
+ * Compress a single skill
726
+ */
727
+ compressSkill(skill, forQuery) {
728
+ const compressed = {
729
+ ...skill,
730
+ description: this.truncateDescription(skill.description),
731
+ parameters: this.compressParameters(skill.parameters)
732
+ };
733
+ if (forQuery && skill.metadata) {
734
+ const relevant = this.isMetadataRelevant(skill.metadata, forQuery);
735
+ if (!relevant) {
736
+ delete compressed.metadata;
737
+ }
738
+ }
739
+ return compressed;
740
+ }
741
+ /**
742
+ * Optimize tools for minimal token usage
743
+ */
744
+ optimizeTools(tools) {
745
+ if (!this.config.enableCompression) return tools;
746
+ return tools.map((tool) => ({
747
+ ...tool,
748
+ description: this.truncateDescription(tool.description),
749
+ parameters: tool.parameters ? this.compressParameters(tool.parameters) : void 0
750
+ }));
751
+ }
752
+ /**
753
+ * Optimize messages for context window
754
+ */
755
+ optimizeMessages(messages, maxTokens) {
756
+ const limit = maxTokens ?? this.config.maxContextTokens;
757
+ let totalTokens = this.estimateMessagesTokens(messages);
758
+ if (totalTokens <= limit) return messages;
759
+ const optimized = [];
760
+ let systemMessage = null;
761
+ if (this.config.preserveSystemPrompt) {
762
+ systemMessage = messages.find((m) => m.role === "system") || null;
763
+ if (systemMessage) {
764
+ optimized.push(systemMessage);
765
+ totalTokens -= this.estimateTokens(systemMessage.content);
766
+ }
767
+ }
768
+ const recentMessages = messages.filter((m) => m.role !== "system").reverse();
769
+ for (const message of recentMessages) {
770
+ const messageTokens = this.estimateTokens(message.content);
771
+ if (totalTokens + messageTokens <= limit) {
772
+ optimized.unshift(message);
773
+ totalTokens += messageTokens;
774
+ } else {
775
+ break;
776
+ }
777
+ }
778
+ return optimized;
779
+ }
780
+ /**
781
+ * Build optimized prompt with skills
782
+ */
783
+ buildOptimizedPrompt(userInput, availableSkills, context) {
784
+ const parts = [];
785
+ if (context) {
786
+ parts.push(`Context: ${this.truncateDescription(context, 500)}`);
787
+ }
788
+ parts.push(`User: ${userInput}`);
789
+ if (availableSkills.length > 0) {
790
+ const skillDescriptions = availableSkills.map((skill) => this.formatSkillForPrompt(skill));
791
+ parts.push(`
792
+ Available skills:
793
+ ${skillDescriptions.join("\n")}`);
794
+ }
795
+ return parts.join("\n\n");
796
+ }
797
+ /**
798
+ * Estimate tokens for text
799
+ */
800
+ estimateTokens(text) {
801
+ return Math.ceil(text.length / 4);
802
+ }
803
+ /**
804
+ * Estimate tokens for messages
805
+ */
806
+ estimateMessagesTokens(messages) {
807
+ return messages.reduce((total, msg) => {
808
+ const baseTokens = 4;
809
+ return total + baseTokens + this.estimateTokens(msg.content);
810
+ }, 0);
811
+ }
812
+ /**
813
+ * Estimate tokens for skills
814
+ */
815
+ estimateSkillsTokens(skills) {
816
+ return skills.reduce((total, skill) => {
817
+ return total + this.estimateTokens(skill.name) + this.estimateTokens(skill.description) + this.estimateTokens(JSON.stringify(skill.parameters));
818
+ }, 0);
819
+ }
820
+ /**
821
+ * Get optimization stats
822
+ */
823
+ getOptimizationStats(original, optimized) {
824
+ const originalTokens = this.estimateSkillsTokens(original);
825
+ const optimizedTokens = this.estimateSkillsTokens(optimized);
826
+ const savings = originalTokens - optimizedTokens;
827
+ return {
828
+ originalTokens,
829
+ optimizedTokens,
830
+ savings,
831
+ savingsPercent: originalTokens > 0 ? savings / originalTokens * 100 : 0
832
+ };
833
+ }
834
+ // Private helper methods
835
+ truncateDescription(description, maxLength) {
836
+ const limit = maxLength ?? this.config.maxSkillDescriptionLength;
837
+ if (description.length <= limit) return description;
838
+ return description.substring(0, limit - 3) + "...";
839
+ }
840
+ compressParameters(parameters) {
841
+ const compressed = {
842
+ type: parameters.type,
843
+ properties: {}
844
+ };
845
+ if (parameters.required) {
846
+ compressed.required = parameters.required;
847
+ }
848
+ for (const [key, prop] of Object.entries(parameters.properties)) {
849
+ compressed.properties[key] = {
850
+ type: prop.type,
851
+ description: this.truncateDescription(prop.description, 100),
852
+ ...prop.enum && { enum: prop.enum },
853
+ ...prop.default !== void 0 && { default: prop.default }
854
+ };
855
+ }
856
+ return compressed;
857
+ }
858
+ isMetadataRelevant(metadata, query) {
859
+ if (!metadata) return false;
860
+ const queryLower = query.toLowerCase();
861
+ const metadataStr = JSON.stringify(metadata).toLowerCase();
862
+ return metadataStr.includes(queryLower);
863
+ }
864
+ formatSkillForPrompt(skill) {
865
+ const params = Object.keys(skill.parameters.properties).join(", ");
866
+ return `- ${skill.name}(${params}): ${skill.description}`;
867
+ }
868
+ };
869
+
870
+ // src/core/smart-agent.ts
871
+ var SmartAgent = class extends Agent {
872
+ decisionEngine;
873
+ skillLoader;
874
+ tokenOptimizer;
875
+ executionHistory = [];
876
+ constructor(config) {
877
+ super(config);
878
+ this.decisionEngine = new DecisionEngine(config.decisionEngine);
879
+ this.skillLoader = new DynamicSkillLoader(config.skillLoader);
880
+ this.tokenOptimizer = new TokenOptimizer(config.tokenOptimizer);
881
+ void config.autoDecide;
882
+ void config.maxAutoIterations;
883
+ void config.enableStreaming;
884
+ }
885
+ /**
886
+ * Initialize the smart agent
887
+ */
888
+ async initialize() {
889
+ await super.initialize();
890
+ for (const skill of this.getAllSkills()) {
891
+ await this.decisionEngine.indexSkill(skill);
892
+ }
893
+ }
894
+ /**
895
+ * Auto-process user input with smart decision making
896
+ */
897
+ async process(input, context) {
898
+ const startTime = Date.now();
899
+ let tokensUsed = 0;
900
+ const decision = await this.makeDecision(input, context);
901
+ const loadedSkills = [];
902
+ if (decision.skills) {
903
+ for (const skillName of decision.skills) {
904
+ if (!this.getSkill(skillName)) {
905
+ const skill = await this.skillLoader.load(skillName);
906
+ if (skill) {
907
+ this.registerSkill(skill);
908
+ await this.decisionEngine.indexSkill(skill);
909
+ loadedSkills.push(skillName);
910
+ }
911
+ }
912
+ }
913
+ }
914
+ let result;
915
+ switch (decision.type) {
916
+ case "skill":
917
+ if (decision.skills?.length === 1) {
918
+ const skillName = decision.skills[0];
919
+ const params = await this.extractParameters(input, skillName);
920
+ const skillResult = await this.executeSkill(skillName, params);
921
+ result = skillResult.success ? String(skillResult.data ?? "Success") : String(skillResult.error ?? "Error");
922
+ } else {
923
+ result = await this.coordinateSkills(input, decision.skills || []);
924
+ }
925
+ break;
926
+ case "tool":
927
+ if (decision.tools?.length === 1) {
928
+ const toolName = decision.tools[0];
929
+ const toolResult = await this.executeTool(toolName, input);
930
+ result = toolResult.isError ? String(toolResult.content[0]?.text ?? "Error") : String(toolResult.content[0]?.text ?? "Success");
931
+ } else {
932
+ result = await this.coordinateTools(input, decision.tools || []);
933
+ }
934
+ break;
935
+ case "multi":
936
+ result = await this.executeMixed(input, decision);
937
+ break;
938
+ case "llm":
939
+ default:
940
+ result = await this.directLLMResponse(input, context);
941
+ break;
942
+ }
943
+ this.executionHistory.push({
944
+ input,
945
+ decision,
946
+ timestamp: /* @__PURE__ */ new Date()
947
+ });
948
+ const executionTime = Date.now() - startTime;
949
+ return {
950
+ decision,
951
+ result,
952
+ tokensUsed,
953
+ executionTime,
954
+ skillsLoaded: loadedSkills.length > 0 ? loadedSkills : void 0
955
+ };
956
+ }
957
+ /**
958
+ * Stream process user input
959
+ */
960
+ async *streamProcess(input, context) {
961
+ const decision = await this.makeDecision(input, context);
962
+ yield { type: "decision", data: decision };
963
+ switch (decision.type) {
964
+ case "skill":
965
+ for (const skillName of decision.skills || []) {
966
+ yield { type: "skill", data: { name: skillName, status: "executing" } };
967
+ const params = await this.extractParameters(input, skillName);
968
+ const result = await this.executeSkill(skillName, params);
969
+ yield { type: "skill", data: { name: skillName, result } };
970
+ }
971
+ break;
972
+ case "tool":
973
+ for (const toolName of decision.tools || []) {
974
+ yield { type: "tool", data: { name: toolName, status: "executing" } };
975
+ const result = await this.executeTool(toolName, input);
976
+ yield { type: "tool", data: { name: toolName, result } };
977
+ }
978
+ break;
979
+ case "llm":
980
+ yield { type: "llm", data: { status: "generating" } };
981
+ const messages = [{ role: "user", content: input }];
982
+ let fullResponse = "";
983
+ for await (const chunk of this.streamChat(messages)) {
984
+ if (chunk.delta.content) {
985
+ fullResponse += chunk.delta.content;
986
+ yield { type: "llm", data: { chunk: chunk.delta.content } };
987
+ }
988
+ }
989
+ break;
990
+ }
991
+ yield { type: "complete" };
992
+ }
993
+ /**
994
+ * Make decision based on input
995
+ */
996
+ async makeDecision(input, context) {
997
+ const decisionContext = {
998
+ input,
999
+ history: this.executionHistory.slice(-5).map((h) => h.input),
1000
+ availableSkills: this.getSkillNames(),
1001
+ availableTools: this.getToolNames(),
1002
+ metadata: context ? { context } : void 0
1003
+ };
1004
+ return this.decisionEngine.decide(decisionContext);
1005
+ }
1006
+ /**
1007
+ * Extract parameters from input for a skill
1008
+ */
1009
+ async extractParameters(input, skillName) {
1010
+ const skill = this.getSkill(skillName);
1011
+ if (!skill) return {};
1012
+ if (this.llmProvider) {
1013
+ const prompt = this.buildParameterExtractionPrompt(input, skill);
1014
+ const response = await this.chat([{ role: "user", content: prompt }]);
1015
+ try {
1016
+ const params = JSON.parse(response.content);
1017
+ return params;
1018
+ } catch {
1019
+ return {};
1020
+ }
1021
+ }
1022
+ return this.simpleParameterExtraction(input, skill);
1023
+ }
1024
+ /**
1025
+ * Coordinate multiple skills
1026
+ */
1027
+ async coordinateSkills(input, skillNames) {
1028
+ const skills = skillNames.map((name) => this.getSkill(name)).filter((s) => s !== void 0);
1029
+ const optimizedSkills = this.tokenOptimizer.optimizeSkills(skills, input);
1030
+ if (!this.llmProvider) {
1031
+ const results = [];
1032
+ for (const skill of optimizedSkills) {
1033
+ const params = await this.extractParameters(input, skill.name);
1034
+ const result = await this.executeSkill(skill.name, params);
1035
+ results.push(`${skill.name}: ${result.success ? result.data : result.error}`);
1036
+ }
1037
+ return results.join("\n");
1038
+ }
1039
+ const prompt = this.tokenOptimizer.buildOptimizedPrompt(
1040
+ input,
1041
+ optimizedSkills,
1042
+ "Coordinate the following skills to answer the user query."
1043
+ );
1044
+ const response = await this.chat([{ role: "user", content: prompt }]);
1045
+ return response.content;
1046
+ }
1047
+ /**
1048
+ * Coordinate multiple tools
1049
+ */
1050
+ async coordinateTools(input, toolNames) {
1051
+ const tools = toolNames.map((name) => this.getTool(name)).filter((t) => t !== void 0);
1052
+ const results = [];
1053
+ for (const tool of tools) {
1054
+ const result = await this.executeTool(tool.name, input);
1055
+ results.push(`${tool.name}: ${result.content[0]?.text ?? "No output"}`);
1056
+ }
1057
+ return results.join("\n");
1058
+ }
1059
+ /**
1060
+ * Execute mixed skills and tools
1061
+ */
1062
+ async executeMixed(input, decision) {
1063
+ const results = [];
1064
+ if (decision.skills) {
1065
+ for (const skillName of decision.skills) {
1066
+ const params = await this.extractParameters(input, skillName);
1067
+ const result = await this.executeSkill(skillName, params);
1068
+ results.push(`Skill ${skillName}: ${result.success ? result.data : result.error}`);
1069
+ }
1070
+ }
1071
+ if (decision.tools) {
1072
+ for (const toolName of decision.tools) {
1073
+ const result = await this.executeTool(toolName, input);
1074
+ results.push(`Tool ${toolName}: ${result.content[0]?.text ?? "No output"}`);
1075
+ }
1076
+ }
1077
+ return results.join("\n");
1078
+ }
1079
+ /**
1080
+ * Direct LLM response
1081
+ */
1082
+ async directLLMResponse(input, context) {
1083
+ if (!this.llmProvider) {
1084
+ return "No LLM provider configured";
1085
+ }
1086
+ const messages = [];
1087
+ if (context) {
1088
+ messages.push({
1089
+ role: "system",
1090
+ content: `Context: ${context}`
1091
+ });
1092
+ }
1093
+ messages.push({ role: "user", content: input });
1094
+ const response = await this.chat(messages);
1095
+ return response.content;
1096
+ }
1097
+ /**
1098
+ * Build parameter extraction prompt
1099
+ */
1100
+ buildParameterExtractionPrompt(input, skill) {
1101
+ const params = Object.entries(skill.parameters.properties).map(([key, prop]) => {
1102
+ const required = skill.parameters.required?.includes(key) ? " (required)" : "";
1103
+ return `- ${key}: ${prop.description}${required}`;
1104
+ }).join("\n");
1105
+ return `Extract parameters for skill "${skill.name}" from the following input.
1106
+
1107
+ Skill description: ${skill.description}
1108
+
1109
+ Parameters:
1110
+ ${params}
1111
+
1112
+ Input: "${input}"
1113
+
1114
+ Return only a JSON object with the parameter names and values. If a parameter cannot be determined, use null or omit it.`;
1115
+ }
1116
+ /**
1117
+ * Simple parameter extraction without LLM
1118
+ */
1119
+ simpleParameterExtraction(input, skill) {
1120
+ const params = {};
1121
+ for (const [key, prop] of Object.entries(skill.parameters.properties)) {
1122
+ const patterns = [
1123
+ new RegExp(`${key}[:=]\\s*([^,\\s]+)`, "i"),
1124
+ new RegExp(`${key}\\s+is\\s+([^,\\s]+)`, "i"),
1125
+ new RegExp(`${key}\\s+([^,\\s]+)`, "i")
1126
+ ];
1127
+ for (const pattern of patterns) {
1128
+ const match = input.match(pattern);
1129
+ if (match) {
1130
+ let value = match[1];
1131
+ if (prop.type === "number") {
1132
+ value = parseFloat(value);
1133
+ } else if (prop.type === "boolean") {
1134
+ value = ["true", "yes", "1"].includes(value.toLowerCase());
1135
+ }
1136
+ params[key] = value;
1137
+ break;
1138
+ }
1139
+ }
1140
+ if (!(key in params) && prop.default !== void 0) {
1141
+ params[key] = prop.default;
1142
+ }
1143
+ }
1144
+ return params;
1145
+ }
1146
+ /**
1147
+ * Register a skill source for dynamic loading
1148
+ */
1149
+ registerSkillSource(name, source, type) {
1150
+ this.skillLoader.registerSource({
1151
+ name,
1152
+ type,
1153
+ source
1154
+ });
1155
+ }
1156
+ /**
1157
+ * Get execution history
1158
+ */
1159
+ getExecutionHistory() {
1160
+ return [...this.executionHistory];
1161
+ }
1162
+ /**
1163
+ * Get decision engine stats
1164
+ */
1165
+ getDecisionStats() {
1166
+ return {
1167
+ cacheSize: this.decisionEngine.getCacheStats().size,
1168
+ loadedSkills: this.skillLoader.getStats().loaded,
1169
+ historySize: this.executionHistory.length
1170
+ };
1171
+ }
1172
+ /**
1173
+ * Clear execution history
1174
+ */
1175
+ clearHistory() {
1176
+ this.executionHistory = [];
1177
+ this.decisionEngine.clearCache();
1178
+ }
1179
+ };
1180
+
1181
+ // src/plugins/manager.ts
1182
+ var PluginManager = class {
1183
+ constructor(agent, config = {}) {
1184
+ this.agent = agent;
1185
+ this.config = config;
1186
+ }
1187
+ plugins = /* @__PURE__ */ new Map();
1188
+ contexts = /* @__PURE__ */ new Map();
1189
+ async load(plugin, config = {}) {
1190
+ if (this.config.allowedPlugins && !this.config.allowedPlugins.includes(plugin.name)) {
1191
+ throw new Error(`Plugin '${plugin.name}' is not in the allowed list`);
1192
+ }
1193
+ const context = {
1194
+ agent: this.agent,
1195
+ registerSkill: (skill) => this.agent.registerSkill(skill),
1196
+ registerTool: (tool) => this.agent.registerTool(tool),
1197
+ registerMCPResource: (resource) => this.agent.registerMCPResource(resource),
1198
+ registerMCPTool: (tool) => this.agent.registerMCPTool(tool),
1199
+ getLLMProvider: () => this.agent.llmProvider,
1200
+ config
1201
+ };
1202
+ await plugin.initialize(context);
1203
+ this.plugins.set(plugin.name, plugin);
1204
+ this.contexts.set(plugin.name, context);
1205
+ }
1206
+ async unload(name) {
1207
+ const plugin = this.plugins.get(name);
1208
+ if (!plugin) {
1209
+ throw new Error(`Plugin '${name}' not found`);
1210
+ }
1211
+ await plugin.destroy?.();
1212
+ this.plugins.delete(name);
1213
+ this.contexts.delete(name);
1214
+ }
1215
+ get(name) {
1216
+ return this.plugins.get(name);
1217
+ }
1218
+ getContext(name) {
1219
+ return this.contexts.get(name);
1220
+ }
1221
+ list() {
1222
+ return Array.from(this.plugins.values());
1223
+ }
1224
+ listNames() {
1225
+ return Array.from(this.plugins.keys());
1226
+ }
1227
+ isLoaded(name) {
1228
+ return this.plugins.has(name);
1229
+ }
1230
+ async reload(name) {
1231
+ const plugin = this.plugins.get(name);
1232
+ if (!plugin) {
1233
+ throw new Error(`Plugin '${name}' not found`);
1234
+ }
1235
+ const context = this.contexts.get(name);
1236
+ if (!context) {
1237
+ throw new Error(`Context for plugin '${name}' not found`);
1238
+ }
1239
+ await plugin.destroy?.();
1240
+ await plugin.initialize(context);
1241
+ }
1242
+ async unloadAll() {
1243
+ for (const [name] of this.plugins) {
1244
+ await this.unload(name);
1245
+ }
1246
+ }
1247
+ getStats() {
1248
+ return {
1249
+ total: this.plugins.size,
1250
+ withDestroy: this.list().filter((p) => p.destroy !== void 0).length
1251
+ };
1252
+ }
1253
+ };
1254
+ var PluginLoader = class {
1255
+ factories = /* @__PURE__ */ new Map();
1256
+ registerFactory(type, factory) {
1257
+ this.factories.set(type, factory);
1258
+ }
1259
+ async loadFromSource(type, source, config = {}) {
1260
+ const factory = this.factories.get(type);
1261
+ if (!factory) {
1262
+ throw new Error(`Unknown plugin type: ${type}`);
1263
+ }
1264
+ const pluginConfig = await this.loadConfig(source);
1265
+ return factory.create({ ...pluginConfig, ...config });
1266
+ }
1267
+ async loadConfig(source) {
1268
+ if (source.startsWith("http")) {
1269
+ const response = await fetch(source);
1270
+ return response.json();
1271
+ }
1272
+ throw new Error(
1273
+ "Loading config from file path is not supported. Use a URL (http/https) or pass config object directly."
1274
+ );
1275
+ }
1276
+ };
1277
+ export {
1278
+ Agent,
1279
+ AnthropicProvider,
1280
+ DecisionEngine,
1281
+ DeepSeekProvider,
1282
+ DoubaoProvider,
1283
+ DynamicSkillLoader,
1284
+ GeminiProvider,
1285
+ LLMManager,
1286
+ LLMProviderRegistry,
1287
+ MCPClient,
1288
+ MCPServer,
1289
+ MiniMaxProvider,
1290
+ MoonshotProvider,
1291
+ OpenAIProvider,
1292
+ PluginLoader,
1293
+ PluginManager,
1294
+ QwenProvider,
1295
+ SimpleEmbeddingProvider,
1296
+ SkillRegistry,
1297
+ SmartAgent,
1298
+ TokenOptimizer,
1299
+ ToolRegistry,
1300
+ ZhipuProvider,
1301
+ builtInSkills,
1302
+ builtInTools,
1303
+ echoSkill,
1304
+ fileReadTool,
1305
+ fileWriteTool,
1306
+ globalProviderRegistry,
1307
+ httpRequestTool,
1308
+ listSkillsSkill,
1309
+ mathSkill
1310
+ };
1311
+ //# sourceMappingURL=index.js.map