@frontmcp/plugin-codecall 0.0.1 → 0.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 (62) hide show
  1. package/codecall.plugin.d.ts +42 -0
  2. package/codecall.plugin.d.ts.map +1 -0
  3. package/codecall.symbol.d.ts +107 -0
  4. package/codecall.symbol.d.ts.map +1 -0
  5. package/codecall.types.d.ts +353 -0
  6. package/codecall.types.d.ts.map +1 -0
  7. package/errors/index.d.ts +2 -0
  8. package/errors/index.d.ts.map +1 -0
  9. package/errors/tool-call.errors.d.ts +80 -0
  10. package/errors/tool-call.errors.d.ts.map +1 -0
  11. package/esm/index.mjs +2625 -0
  12. package/esm/package.json +59 -0
  13. package/index.d.ts +3 -0
  14. package/index.d.ts.map +1 -0
  15. package/index.js +2668 -0
  16. package/package.json +1 -1
  17. package/providers/code-call.config.d.ts +30 -0
  18. package/providers/code-call.config.d.ts.map +1 -0
  19. package/security/index.d.ts +3 -0
  20. package/security/index.d.ts.map +1 -0
  21. package/security/self-reference-guard.d.ts +33 -0
  22. package/security/self-reference-guard.d.ts.map +1 -0
  23. package/security/tool-access-control.service.d.ts +105 -0
  24. package/security/tool-access-control.service.d.ts.map +1 -0
  25. package/services/audit-logger.service.d.ts +187 -0
  26. package/services/audit-logger.service.d.ts.map +1 -0
  27. package/services/enclave.service.d.ts +63 -0
  28. package/services/enclave.service.d.ts.map +1 -0
  29. package/services/error-enrichment.service.d.ts +95 -0
  30. package/services/error-enrichment.service.d.ts.map +1 -0
  31. package/services/index.d.ts +7 -0
  32. package/services/index.d.ts.map +1 -0
  33. package/services/output-sanitizer.d.ts +87 -0
  34. package/services/output-sanitizer.d.ts.map +1 -0
  35. package/services/synonym-expansion.service.d.ts +67 -0
  36. package/services/synonym-expansion.service.d.ts.map +1 -0
  37. package/services/tool-search.service.d.ts +196 -0
  38. package/services/tool-search.service.d.ts.map +1 -0
  39. package/tools/describe.schema.d.ts +29 -0
  40. package/tools/describe.schema.d.ts.map +1 -0
  41. package/tools/describe.tool.d.ts +36 -0
  42. package/tools/describe.tool.d.ts.map +1 -0
  43. package/tools/execute.schema.d.ts +116 -0
  44. package/tools/execute.schema.d.ts.map +1 -0
  45. package/tools/execute.tool.d.ts +6 -0
  46. package/tools/execute.tool.d.ts.map +1 -0
  47. package/tools/index.d.ts +5 -0
  48. package/tools/index.d.ts.map +1 -0
  49. package/tools/invoke.schema.d.ts +105 -0
  50. package/tools/invoke.schema.d.ts.map +1 -0
  51. package/tools/invoke.tool.d.ts +14 -0
  52. package/tools/invoke.tool.d.ts.map +1 -0
  53. package/tools/search.schema.d.ts +31 -0
  54. package/tools/search.schema.d.ts.map +1 -0
  55. package/tools/search.tool.d.ts +6 -0
  56. package/tools/search.tool.d.ts.map +1 -0
  57. package/utils/describe.utils.d.ts +87 -0
  58. package/utils/describe.utils.d.ts.map +1 -0
  59. package/utils/index.d.ts +3 -0
  60. package/utils/index.d.ts.map +1 -0
  61. package/utils/mcp-result.d.ts +7 -0
  62. package/utils/mcp-result.d.ts.map +1 -0
package/index.js ADDED
@@ -0,0 +1,2668 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var __decorateClass = (decorators, target, key, kind) => {
30
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
31
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
32
+ if (decorator = decorators[i])
33
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
34
+ if (kind && result) __defProp(target, key, result);
35
+ return result;
36
+ };
37
+
38
+ // plugins/plugin-codecall/src/index.ts
39
+ var index_exports = {};
40
+ __export(index_exports, {
41
+ CodeCallPlugin: () => CodeCallPlugin,
42
+ codeCallDirectCallsOptionsSchema: () => codeCallDirectCallsOptionsSchema,
43
+ codeCallEmbeddingOptionsSchema: () => codeCallEmbeddingOptionsSchema,
44
+ codeCallModeSchema: () => codeCallModeSchema,
45
+ codeCallPluginOptionsSchema: () => codeCallPluginOptionsSchema,
46
+ codeCallSidecarOptionsSchema: () => codeCallSidecarOptionsSchema,
47
+ codeCallVmOptionsSchema: () => codeCallVmOptionsSchema,
48
+ codeCallVmPresetSchema: () => codeCallVmPresetSchema,
49
+ default: () => CodeCallPlugin,
50
+ embeddingStrategySchema: () => embeddingStrategySchema,
51
+ synonymExpansionConfigSchema: () => synonymExpansionConfigSchema
52
+ });
53
+ module.exports = __toCommonJS(index_exports);
54
+
55
+ // plugins/plugin-codecall/src/codecall.plugin.ts
56
+ var import_sdk7 = require("@frontmcp/sdk");
57
+
58
+ // plugins/plugin-codecall/src/codecall.types.ts
59
+ var import_zod = require("zod");
60
+ var directCallsFilterSchema = import_zod.z.custom((val) => typeof val === "function", {
61
+ message: "filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"
62
+ });
63
+ var includeToolsFilterSchema = import_zod.z.custom((val) => typeof val === "function", {
64
+ message: "includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"
65
+ });
66
+ var codeCallModeSchema = import_zod.z.enum(["codecall_only", "codecall_opt_in", "metadata_driven"]).default("codecall_only");
67
+ var codeCallVmPresetSchema = import_zod.z.enum(["locked_down", "secure", "balanced", "experimental"]).default("secure");
68
+ var DEFAULT_VM_OPTIONS = {
69
+ preset: "secure"
70
+ };
71
+ var codeCallVmOptionsSchema = import_zod.z.object({
72
+ /**
73
+ * CSP-like preset; see README.
74
+ * @default 'secure'
75
+ */
76
+ preset: codeCallVmPresetSchema,
77
+ /**
78
+ * Timeout for script execution in milliseconds
79
+ * Defaults vary by preset
80
+ */
81
+ timeoutMs: import_zod.z.number().positive().optional(),
82
+ /**
83
+ * Allow loop constructs (for, while, do-while)
84
+ * Defaults vary by preset
85
+ */
86
+ allowLoops: import_zod.z.boolean().optional(),
87
+ /**
88
+ * Maximum number of steps (if applicable)
89
+ * Defaults vary by preset
90
+ */
91
+ maxSteps: import_zod.z.number().positive().optional(),
92
+ /**
93
+ * List of disabled builtin functions
94
+ * Defaults vary by preset
95
+ */
96
+ disabledBuiltins: import_zod.z.array(import_zod.z.string()).optional(),
97
+ /**
98
+ * List of disabled global variables
99
+ * Defaults vary by preset
100
+ */
101
+ disabledGlobals: import_zod.z.array(import_zod.z.string()).optional(),
102
+ /**
103
+ * Allow console.log/warn/error
104
+ * Defaults vary by preset
105
+ */
106
+ allowConsole: import_zod.z.boolean().optional()
107
+ }).default(() => DEFAULT_VM_OPTIONS);
108
+ var codeCallDirectCallsOptionsSchema = import_zod.z.object({
109
+ /**
110
+ * Enable/disable the `codecall.invoke` meta-tool.
111
+ */
112
+ enabled: import_zod.z.boolean(),
113
+ /**
114
+ * Optional allowlist of tool names.
115
+ */
116
+ allowedTools: import_zod.z.array(import_zod.z.string()).optional(),
117
+ /**
118
+ * Optional advanced filter function.
119
+ * Signature: (tool: DirectCallsFilterToolInfo) => boolean
120
+ */
121
+ filter: directCallsFilterSchema.optional()
122
+ });
123
+ var embeddingStrategySchema = import_zod.z.enum(["tfidf", "ml"]).default("tfidf");
124
+ var synonymExpansionConfigSchema = import_zod.z.object({
125
+ /**
126
+ * Enable/disable synonym expansion for TF-IDF search.
127
+ * When enabled, queries are expanded with synonyms to improve relevance.
128
+ * For example, "add user" will also match tools containing "create user".
129
+ * @default true
130
+ */
131
+ enabled: import_zod.z.boolean().default(true),
132
+ /**
133
+ * Additional synonym groups beyond the defaults.
134
+ * Each group is an array of related terms that should be treated as equivalent.
135
+ * @example [['customer', 'client', 'buyer'], ['order', 'purchase', 'transaction']]
136
+ */
137
+ additionalSynonyms: import_zod.z.array(import_zod.z.array(import_zod.z.string())).optional(),
138
+ /**
139
+ * Replace default synonyms entirely with additionalSynonyms.
140
+ * @default false
141
+ */
142
+ replaceDefaults: import_zod.z.boolean().default(false),
143
+ /**
144
+ * Maximum number of synonym expansions per term.
145
+ * Prevents query explosion for terms with many synonyms.
146
+ * @default 5
147
+ */
148
+ maxExpansionsPerTerm: import_zod.z.number().positive().default(5)
149
+ }).default({ enabled: true, replaceDefaults: false, maxExpansionsPerTerm: 5 });
150
+ var DEFAULT_EMBEDDING_OPTIONS = {
151
+ strategy: "tfidf",
152
+ modelName: "Xenova/all-MiniLM-L6-v2",
153
+ cacheDir: "./.cache/transformers",
154
+ useHNSW: false,
155
+ synonymExpansion: { enabled: true, replaceDefaults: false, maxExpansionsPerTerm: 5 }
156
+ };
157
+ var codeCallEmbeddingOptionsSchema = import_zod.z.object({
158
+ /**
159
+ * Embedding strategy to use for tool search
160
+ * - 'tfidf': Lightweight, synchronous TF-IDF based search (no ML models required)
161
+ * - 'ml': ML-based semantic search using transformers.js (better quality, requires model download)
162
+ * @default 'tfidf'
163
+ */
164
+ strategy: embeddingStrategySchema.optional(),
165
+ /**
166
+ * Model name for ML-based embeddings (only used when strategy='ml')
167
+ * @default 'Xenova/all-MiniLM-L6-v2'
168
+ */
169
+ modelName: import_zod.z.string().optional(),
170
+ /**
171
+ * Cache directory for ML models (only used when strategy='ml')
172
+ * @default './.cache/transformers'
173
+ */
174
+ cacheDir: import_zod.z.string().optional(),
175
+ /**
176
+ * Enable HNSW index for faster search (only used when strategy='ml')
177
+ * When enabled, provides O(log n) search instead of O(n) brute-force
178
+ * @default false
179
+ */
180
+ useHNSW: import_zod.z.boolean().optional(),
181
+ /**
182
+ * Synonym expansion configuration for TF-IDF search.
183
+ * When enabled, queries like "add user" will match tools for "create user".
184
+ * Only applies when strategy is 'tfidf' (ML already handles semantic similarity).
185
+ * Set to false to disable, or provide a config object to customize.
186
+ * @default { enabled: true }
187
+ */
188
+ synonymExpansion: import_zod.z.union([import_zod.z.literal(false), synonymExpansionConfigSchema]).optional()
189
+ }).optional().transform((opts) => ({
190
+ strategy: opts?.strategy ?? DEFAULT_EMBEDDING_OPTIONS.strategy,
191
+ modelName: opts?.modelName ?? DEFAULT_EMBEDDING_OPTIONS.modelName,
192
+ cacheDir: opts?.cacheDir ?? DEFAULT_EMBEDDING_OPTIONS.cacheDir,
193
+ useHNSW: opts?.useHNSW ?? DEFAULT_EMBEDDING_OPTIONS.useHNSW,
194
+ synonymExpansion: opts?.synonymExpansion ?? DEFAULT_EMBEDDING_OPTIONS.synonymExpansion
195
+ }));
196
+ var codeCallSidecarOptionsSchema = import_zod.z.object({
197
+ /**
198
+ * Enable pass-by-reference support via sidecar
199
+ * When enabled, large strings are automatically lifted to a sidecar
200
+ * and resolved at the callTool boundary
201
+ * @default false
202
+ */
203
+ enabled: import_zod.z.boolean().default(false),
204
+ /**
205
+ * Maximum total size of all stored references in bytes
206
+ * @default 16MB (from security level)
207
+ */
208
+ maxTotalSize: import_zod.z.number().positive().optional(),
209
+ /**
210
+ * Maximum size of a single reference in bytes
211
+ * @default 4MB (from security level)
212
+ */
213
+ maxReferenceSize: import_zod.z.number().positive().optional(),
214
+ /**
215
+ * Threshold in bytes to trigger extraction from source code
216
+ * Strings larger than this are lifted to the sidecar
217
+ * @default 64KB (from security level)
218
+ */
219
+ extractionThreshold: import_zod.z.number().positive().optional(),
220
+ /**
221
+ * Maximum expanded size when resolving references for tool calls
222
+ * @default 8MB (from security level)
223
+ */
224
+ maxResolvedSize: import_zod.z.number().positive().optional(),
225
+ /**
226
+ * Whether to allow composite handles from string concatenation
227
+ * If false, concatenating references throws an error
228
+ * @default false (strict mode)
229
+ */
230
+ allowComposites: import_zod.z.boolean().optional(),
231
+ /**
232
+ * Maximum script length (in characters) when sidecar is disabled
233
+ * Prevents large inline data from being embedded in script
234
+ * If null, no limit is enforced
235
+ * @default 64KB
236
+ */
237
+ maxScriptLengthWhenDisabled: import_zod.z.number().positive().nullable().default(64 * 1024)
238
+ }).default(() => ({
239
+ enabled: false,
240
+ maxScriptLengthWhenDisabled: 64 * 1024
241
+ }));
242
+ var codeCallPluginOptionsObjectSchema = import_zod.z.object({
243
+ /**
244
+ * CodeCall mode
245
+ * @default 'codecall_only'
246
+ */
247
+ mode: codeCallModeSchema,
248
+ /**
249
+ * Default number of tools to return in search results
250
+ * @default 8
251
+ */
252
+ topK: import_zod.z.number().positive().default(8),
253
+ /**
254
+ * Maximum number of tool definitions to include
255
+ * @default 8
256
+ */
257
+ maxDefinitions: import_zod.z.number().positive().default(8),
258
+ /**
259
+ * Optional filter function for including tools.
260
+ * Signature: (tool: IncludeToolsFilterToolInfo) => boolean
261
+ */
262
+ includeTools: includeToolsFilterSchema.optional(),
263
+ /**
264
+ * Direct calls configuration
265
+ */
266
+ directCalls: codeCallDirectCallsOptionsSchema.optional(),
267
+ /**
268
+ * VM execution options
269
+ */
270
+ vm: codeCallVmOptionsSchema,
271
+ /**
272
+ * Embedding configuration for tool search
273
+ */
274
+ embedding: codeCallEmbeddingOptionsSchema,
275
+ /**
276
+ * Sidecar (pass-by-reference) configuration
277
+ * When enabled, large data is stored outside the sandbox and resolved at callTool boundary
278
+ */
279
+ sidecar: codeCallSidecarOptionsSchema
280
+ });
281
+ var DEFAULT_PLUGIN_OPTIONS = {
282
+ mode: "codecall_only",
283
+ topK: 8,
284
+ maxDefinitions: 8,
285
+ vm: DEFAULT_VM_OPTIONS,
286
+ embedding: DEFAULT_EMBEDDING_OPTIONS,
287
+ sidecar: {
288
+ enabled: false,
289
+ maxScriptLengthWhenDisabled: 64 * 1024
290
+ }
291
+ };
292
+ var codeCallPluginOptionsSchema = codeCallPluginOptionsObjectSchema.prefault(DEFAULT_PLUGIN_OPTIONS);
293
+
294
+ // plugins/plugin-codecall/src/services/tool-search.service.ts
295
+ var import_vectoriadb = require("vectoriadb");
296
+
297
+ // plugins/plugin-codecall/src/services/synonym-expansion.service.ts
298
+ var DEFAULT_SYNONYM_GROUPS = [
299
+ // ===========================================================================
300
+ // 1. CORE DATA OPERATIONS (CRUD+)
301
+ // ===========================================================================
302
+ // Creation / Instantiation
303
+ [
304
+ "create",
305
+ "add",
306
+ "new",
307
+ "insert",
308
+ "make",
309
+ "append",
310
+ "register",
311
+ "generate",
312
+ "produce",
313
+ "build",
314
+ "construct",
315
+ "provision",
316
+ "instantiate",
317
+ "define",
318
+ "compose",
319
+ "draft"
320
+ ],
321
+ // Destructive Removal
322
+ [
323
+ "delete",
324
+ "remove",
325
+ "destroy",
326
+ "drop",
327
+ "erase",
328
+ "clear",
329
+ "purge",
330
+ "discard",
331
+ "eliminate",
332
+ "nuke",
333
+ "unbind",
334
+ "unregister"
335
+ ],
336
+ // Retrieval / Access
337
+ ["get", "fetch", "retrieve", "read", "obtain", "load", "pull", "access", "grab", "snag", "receive"],
338
+ // Modification
339
+ [
340
+ "update",
341
+ "edit",
342
+ "modify",
343
+ "change",
344
+ "patch",
345
+ "alter",
346
+ "revise",
347
+ "refresh",
348
+ "correct",
349
+ "amend",
350
+ "adjust",
351
+ "tweak",
352
+ "rectify",
353
+ "refine"
354
+ ],
355
+ // Viewing / Listing
356
+ [
357
+ "list",
358
+ "show",
359
+ "display",
360
+ "enumerate",
361
+ "browse",
362
+ "view",
363
+ "peek",
364
+ "index",
365
+ "catalog",
366
+ "survey",
367
+ "inspect",
368
+ "ls",
369
+ "dir"
370
+ ],
371
+ // Searching / Discovery
372
+ [
373
+ "find",
374
+ "search",
375
+ "lookup",
376
+ "query",
377
+ "locate",
378
+ "filter",
379
+ "scan",
380
+ "explore",
381
+ "investigate",
382
+ "detect",
383
+ "scout",
384
+ "seek"
385
+ ],
386
+ // Soft Delete / Archival
387
+ ["archive", "shelve", "retire", "hide", "suppress", "mute"],
388
+ ["unarchive", "restore", "recover", "undelete", "unhide"],
389
+ // ===========================================================================
390
+ // 2. STATE & LIFECYCLE
391
+ // ===========================================================================
392
+ // Activation
393
+ [
394
+ "enable",
395
+ "activate",
396
+ "start",
397
+ "turn on",
398
+ "switch on",
399
+ "boot",
400
+ "init",
401
+ "initialize",
402
+ "setup",
403
+ "spin up",
404
+ "resume",
405
+ "unpause"
406
+ ],
407
+ // Deactivation
408
+ [
409
+ "disable",
410
+ "deactivate",
411
+ "stop",
412
+ "turn off",
413
+ "switch off",
414
+ "shutdown",
415
+ "halt",
416
+ "kill",
417
+ "terminate",
418
+ "suspend",
419
+ "pause",
420
+ "cease"
421
+ ],
422
+ // Execution
423
+ ["run", "execute", "invoke", "trigger", "launch", "call", "perform", "operate", "handle", "process", "fire"],
424
+ // Reset cycles
425
+ ["restart", "reboot", "reset", "reload", "bounce", "recycle", "refresh"],
426
+ // Validation & Check
427
+ ["validate", "verify", "check", "confirm", "assert", "test", "audit", "assess", "healthcheck", "ping"],
428
+ // Analysis & Math
429
+ [
430
+ "analyze",
431
+ "interpret",
432
+ "diagnose",
433
+ "evaluate",
434
+ "review",
435
+ "summarize",
436
+ "count",
437
+ "calculate",
438
+ "compute",
439
+ "measure",
440
+ "aggregate",
441
+ "summarise"
442
+ ],
443
+ // ===========================================================================
444
+ // 3. TRANSFER, IO & MANIPULATION
445
+ // ===========================================================================
446
+ // Duplication
447
+ ["copy", "duplicate", "clone", "replicate", "mirror", "fork", "repro"],
448
+ // Movement
449
+ ["move", "transfer", "migrate", "relocate", "rename", "shift", "mv", "slide"],
450
+ // Persistence
451
+ ["save", "store", "write", "persist", "commit", "stash", "record", "log"],
452
+ // Synchronization
453
+ ["sync", "synchronize", "resync", "reconcile", "align", "pair"],
454
+ // Import/Export
455
+ ["import", "ingest", "upload", "push", "feed"],
456
+ ["export", "download", "dump", "backup", "extract"],
457
+ // Connection
458
+ ["connect", "link", "bind", "attach", "join", "bridge", "associate", "mount", "map"],
459
+ ["disconnect", "unlink", "unbind", "detach", "leave", "dissociate", "unmount", "unmap"],
460
+ // ===========================================================================
461
+ // 4. DEVOPS, SECURITY & TECHNICAL
462
+ // ===========================================================================
463
+ // Auth
464
+ ["login", "log in", "sign in", "authenticate", "auth"],
465
+ ["logout", "log out", "sign out", "disconnect"],
466
+ // Permissions
467
+ ["approve", "authorize", "grant", "permit", "allow", "sanction", "whitelist"],
468
+ ["deny", "reject", "revoke", "forbid", "block", "ban", "blacklist"],
469
+ // Encryption
470
+ ["encrypt", "secure", "lock", "seal", "protect", "scramble", "hash"],
471
+ ["decrypt", "unlock", "unseal", "reveal", "decode"],
472
+ // Deployment
473
+ ["deploy", "release", "ship", "publish", "roll out", "promote", "distribute", "install"],
474
+ // Development
475
+ ["debug", "troubleshoot", "fix", "repair", "resolve", "trace"],
476
+ ["compile", "transpile", "build", "assemble", "package", "bundle", "minify"],
477
+ // ===========================================================================
478
+ // 5. COMMERCE & BUSINESS LOGIC
479
+ // ===========================================================================
480
+ // Financial Transactions
481
+ ["buy", "purchase", "order", "pay", "checkout", "spend"],
482
+ ["sell", "refund", "reimburse", "charge", "invoice", "bill"],
483
+ ["subscribe", "upgrade", "upsell"],
484
+ ["unsubscribe", "cancel", "downgrade"],
485
+ // Scheduling
486
+ ["schedule", "book", "appoint", "reserve", "plan", "calendar"],
487
+ ["reschedule", "postpone", "delay", "defer"],
488
+ // ===========================================================================
489
+ // 6. COMMUNICATION & SOCIAL
490
+ // ===========================================================================
491
+ // Outbound
492
+ [
493
+ "send",
494
+ "dispatch",
495
+ "deliver",
496
+ "transmit",
497
+ "post",
498
+ "broadcast",
499
+ "notify",
500
+ "alert",
501
+ "email",
502
+ "text",
503
+ "message",
504
+ "chat"
505
+ ],
506
+ // Social Interactions
507
+ ["reply", "respond", "answer", "retort"],
508
+ ["share", "forward", "retweet", "repost"],
509
+ ["like", "favorite", "star", "upvote", "heart"],
510
+ ["dislike", "downvote"],
511
+ ["follow", "watch", "track"],
512
+ ["unfollow", "ignore", "mute"],
513
+ // ===========================================================================
514
+ // 7. COMMON ENTITIES (NOUNS)
515
+ // ===========================================================================
516
+ // Users & Roles
517
+ [
518
+ "user",
519
+ "account",
520
+ "member",
521
+ "profile",
522
+ "identity",
523
+ "customer",
524
+ "principal",
525
+ "admin",
526
+ "operator",
527
+ "client",
528
+ "employee",
529
+ "staff"
530
+ ],
531
+ ["role", "group", "team", "squad", "unit", "department"],
532
+ // Data Artifacts
533
+ ["file", "document", "attachment", "blob", "asset", "object", "resource", "content", "media"],
534
+ ["image", "picture", "photo", "screenshot"],
535
+ ["video", "clip", "recording", "footage"],
536
+ // System Artifacts
537
+ ["message", "notification", "alert", "event", "signal", "webhook", "ping"],
538
+ ["log", "trace", "metric", "telemetry", "audit trail", "history"],
539
+ ["settings", "config", "configuration", "preferences", "options", "params", "env", "environment", "variables"],
540
+ ["permission", "privilege", "access right", "policy", "rule", "scope"],
541
+ // Business Artifacts
542
+ ["organization", "company", "tenant", "workspace", "org", "project", "repo", "repository"],
543
+ ["product", "item", "sku", "inventory", "stock"],
544
+ ["task", "ticket", "issue", "bug", "story", "epic", "todo", "job", "workitem"],
545
+ // Identification
546
+ ["id", "identifier", "key", "uuid", "guid", "token", "hash", "fingerprint"]
547
+ ];
548
+ var SynonymExpansionService = class {
549
+ synonymMap;
550
+ maxExpansions;
551
+ constructor(config = {}) {
552
+ this.maxExpansions = config.maxExpansionsPerTerm ?? 5;
553
+ const groups = config.replaceDefaults ? config.additionalSynonyms || [] : [...DEFAULT_SYNONYM_GROUPS, ...config.additionalSynonyms || []];
554
+ this.synonymMap = this.buildSynonymMap(groups);
555
+ }
556
+ /**
557
+ * Build a bidirectional synonym map from groups.
558
+ * Each term maps to all other terms in its group(s).
559
+ */
560
+ buildSynonymMap(groups) {
561
+ const map = /* @__PURE__ */ new Map();
562
+ for (const group of groups) {
563
+ const normalizedGroup = group.map((term) => term.toLowerCase());
564
+ for (const term of normalizedGroup) {
565
+ if (!map.has(term)) {
566
+ map.set(term, /* @__PURE__ */ new Set());
567
+ }
568
+ const synonyms = map.get(term);
569
+ for (const synonym of normalizedGroup) {
570
+ if (synonym !== term) {
571
+ synonyms.add(synonym);
572
+ }
573
+ }
574
+ }
575
+ }
576
+ return map;
577
+ }
578
+ /**
579
+ * Get synonyms for a single term.
580
+ * Returns empty array if no synonyms found.
581
+ *
582
+ * @example
583
+ * getSynonyms('add') // ['create', 'new', 'insert', 'make']
584
+ */
585
+ getSynonyms(term) {
586
+ const normalized = term.toLowerCase();
587
+ const synonyms = this.synonymMap.get(normalized);
588
+ if (!synonyms) {
589
+ return [];
590
+ }
591
+ return Array.from(synonyms).slice(0, this.maxExpansions);
592
+ }
593
+ /**
594
+ * Expand a query string by adding synonyms for each term.
595
+ * Returns the expanded query string with original terms and their synonyms.
596
+ *
597
+ * @example
598
+ * expandQuery('add user') // 'add create new insert make user account member profile'
599
+ */
600
+ expandQuery(query) {
601
+ const terms = query.toLowerCase().split(/\s+/).filter((term) => term.length > 1);
602
+ const expandedTerms = [];
603
+ for (const term of terms) {
604
+ expandedTerms.push(term);
605
+ const synonyms = this.getSynonyms(term);
606
+ expandedTerms.push(...synonyms);
607
+ }
608
+ return expandedTerms.join(" ");
609
+ }
610
+ /**
611
+ * Check if synonym expansion is available for any term in the query.
612
+ */
613
+ hasExpansions(query) {
614
+ const terms = query.toLowerCase().split(/\s+/);
615
+ return terms.some((term) => this.synonymMap.has(term));
616
+ }
617
+ /**
618
+ * Get statistics about the synonym dictionary.
619
+ */
620
+ getStats() {
621
+ const termCount = this.synonymMap.size;
622
+ let totalSynonyms = 0;
623
+ for (const synonyms of this.synonymMap.values()) {
624
+ totalSynonyms += synonyms.size;
625
+ }
626
+ return {
627
+ termCount,
628
+ avgSynonymsPerTerm: termCount > 0 ? totalSynonyms / termCount : 0
629
+ };
630
+ }
631
+ };
632
+
633
+ // plugins/plugin-codecall/src/services/tool-search.service.ts
634
+ var STOP_WORDS = /* @__PURE__ */ new Set([
635
+ // Articles & Determiners
636
+ "the",
637
+ "a",
638
+ "an",
639
+ "this",
640
+ "that",
641
+ "these",
642
+ "those",
643
+ // Prepositions
644
+ "in",
645
+ "on",
646
+ "at",
647
+ "to",
648
+ "for",
649
+ "of",
650
+ "with",
651
+ "by",
652
+ "from",
653
+ "into",
654
+ "over",
655
+ "after",
656
+ "before",
657
+ "between",
658
+ "under",
659
+ "about",
660
+ "against",
661
+ "during",
662
+ "through",
663
+ // Conjunctions
664
+ "and",
665
+ "or",
666
+ "but",
667
+ "nor",
668
+ "so",
669
+ "yet",
670
+ "as",
671
+ "than",
672
+ "if",
673
+ "because",
674
+ "while",
675
+ "when",
676
+ "where",
677
+ "unless",
678
+ // Pronouns (Subject/Object/Possessive)
679
+ "i",
680
+ "me",
681
+ "my",
682
+ "mine",
683
+ "myself",
684
+ "you",
685
+ "your",
686
+ "yours",
687
+ "yourself",
688
+ "he",
689
+ "him",
690
+ "his",
691
+ "himself",
692
+ "she",
693
+ "her",
694
+ "hers",
695
+ "herself",
696
+ "it",
697
+ "its",
698
+ "itself",
699
+ "we",
700
+ "us",
701
+ "our",
702
+ "ours",
703
+ "ourselves",
704
+ "they",
705
+ "them",
706
+ "their",
707
+ "theirs",
708
+ "themselves",
709
+ "who",
710
+ "whom",
711
+ "whose",
712
+ "which",
713
+ "what",
714
+ // Auxiliary/Linking Verbs (State of being is usually noise, Action is signal)
715
+ "is",
716
+ "was",
717
+ "are",
718
+ "were",
719
+ "been",
720
+ "be",
721
+ "being",
722
+ "have",
723
+ "has",
724
+ "had",
725
+ "having",
726
+ "do",
727
+ "does",
728
+ "did",
729
+ "doing",
730
+ // "do" is usually auxiliary ("do you have..."). "run" or "execute" is better.
731
+ "will",
732
+ "would",
733
+ "shall",
734
+ "should",
735
+ "can",
736
+ "could",
737
+ "may",
738
+ "might",
739
+ "must",
740
+ // Quantifiers / Adverbs of degree
741
+ "all",
742
+ "any",
743
+ "both",
744
+ "each",
745
+ "few",
746
+ "more",
747
+ "most",
748
+ "other",
749
+ "some",
750
+ "such",
751
+ "no",
752
+ "nor",
753
+ "not",
754
+ "only",
755
+ "own",
756
+ "same",
757
+ "too",
758
+ "very",
759
+ "just",
760
+ "even",
761
+ // Conversational / Chat Fillers (Common in LLM prompts)
762
+ "please",
763
+ "pls",
764
+ "plz",
765
+ "thanks",
766
+ "thank",
767
+ "thx",
768
+ "hello",
769
+ "hi",
770
+ "hey",
771
+ "ok",
772
+ "okay",
773
+ "yes",
774
+ "no",
775
+ "actually",
776
+ "basically",
777
+ "literally",
778
+ "maybe",
779
+ "perhaps",
780
+ "now",
781
+ "then",
782
+ "here",
783
+ "there",
784
+ "again",
785
+ "once",
786
+ "back",
787
+ // "back" can be tricky, but usually implies direction not action
788
+ // Meta/Structural words
789
+ "example",
790
+ "context",
791
+ "optionally",
792
+ "optional",
793
+ // Users rarely search for "optional", they search for the thing itself.
794
+ "etc",
795
+ "ie",
796
+ "eg"
797
+ ]);
798
+ var ToolSearchService = class _ToolSearchService {
799
+ static MAX_SUBSCRIPTION_RETRIES = 100;
800
+ static INITIAL_RETRY_DELAY_MS = 10;
801
+ static MAX_RETRY_DELAY_MS = 1e3;
802
+ vectorDB;
803
+ strategy;
804
+ initialized = false;
805
+ mlInitialized = false;
806
+ config;
807
+ scope;
808
+ unsubscribe;
809
+ synonymService = null;
810
+ // Subscription tracking for async initialization
811
+ subscriptionPromise;
812
+ subscriptionResolved = false;
813
+ subscriptionResolve = null;
814
+ subscriptionReject = null;
815
+ retryTimeoutId = null;
816
+ disposed = false;
817
+ constructor(config = {}, scope) {
818
+ this.scope = scope;
819
+ const embeddingOptions = config.embeddingOptions || {
820
+ strategy: "tfidf",
821
+ modelName: "Xenova/all-MiniLM-L6-v2",
822
+ cacheDir: "./.cache/transformers",
823
+ useHNSW: false,
824
+ synonymExpansion: { enabled: true, replaceDefaults: false, maxExpansionsPerTerm: 5 }
825
+ };
826
+ this.strategy = config.strategy || embeddingOptions.strategy || "tfidf";
827
+ this.config = {
828
+ strategy: this.strategy,
829
+ embeddingOptions,
830
+ defaultTopK: config.defaultTopK ?? 8,
831
+ defaultSimilarityThreshold: config.defaultSimilarityThreshold ?? 0,
832
+ mode: config.mode ?? "codecall_only",
833
+ includeTools: config.includeTools
834
+ };
835
+ const validModes = ["codecall_only", "codecall_opt_in", "metadata_driven"];
836
+ if (!validModes.includes(this.config.mode)) {
837
+ throw new Error(`Invalid CodeCall mode: ${this.config.mode}. Valid modes: ${validModes.join(", ")}`);
838
+ }
839
+ if (this.strategy === "ml") {
840
+ this.vectorDB = new import_vectoriadb.VectoriaDB({
841
+ modelName: embeddingOptions.modelName || "Xenova/all-MiniLM-L6-v2",
842
+ cacheDir: embeddingOptions.cacheDir || "./.cache/transformers",
843
+ defaultTopK: this.config.defaultTopK,
844
+ defaultSimilarityThreshold: this.config.defaultSimilarityThreshold,
845
+ useHNSW: embeddingOptions.useHNSW || false
846
+ });
847
+ } else {
848
+ this.vectorDB = new import_vectoriadb.TFIDFVectoria({
849
+ defaultTopK: this.config.defaultTopK,
850
+ defaultSimilarityThreshold: this.config.defaultSimilarityThreshold
851
+ });
852
+ }
853
+ if (config.synonymExpansion === false) {
854
+ this.synonymService = null;
855
+ } else if (this.strategy === "tfidf") {
856
+ const synonymConfig = typeof config.synonymExpansion === "object" ? config.synonymExpansion : {};
857
+ if (synonymConfig.enabled !== false) {
858
+ this.synonymService = new SynonymExpansionService(synonymConfig);
859
+ }
860
+ }
861
+ this.subscriptionPromise = new Promise((resolve, reject) => {
862
+ this.subscriptionResolve = resolve;
863
+ this.subscriptionReject = reject;
864
+ });
865
+ this.setupSubscription();
866
+ }
867
+ /**
868
+ * Ensures the service is subscribed to tool changes before proceeding.
869
+ * Public methods should call this before accessing tools.
870
+ */
871
+ async ensureSubscribed() {
872
+ if (this.subscriptionResolved) {
873
+ return;
874
+ }
875
+ await this.subscriptionPromise;
876
+ }
877
+ /**
878
+ * Sets up subscription to tool changes with exponential backoff retry.
879
+ * Handles the case where scope.tools may not be available yet during plugin initialization.
880
+ */
881
+ setupSubscription(retryCount = 0, delayMs = _ToolSearchService.INITIAL_RETRY_DELAY_MS) {
882
+ if (this.scope.tools) {
883
+ this.subscribeToToolChanges();
884
+ return;
885
+ }
886
+ if (retryCount >= _ToolSearchService.MAX_SUBSCRIPTION_RETRIES) {
887
+ this.scope.logger.warn(
888
+ "ToolSearchService: scope.tools not available after max retries. Tool search will return incomplete results until tools are registered."
889
+ );
890
+ this.markSubscribed();
891
+ return;
892
+ }
893
+ const nextDelay = Math.min(delayMs * 2, _ToolSearchService.MAX_RETRY_DELAY_MS);
894
+ this.retryTimeoutId = setTimeout(() => {
895
+ this.retryTimeoutId = null;
896
+ if (this.disposed) {
897
+ return;
898
+ }
899
+ this.setupSubscription(retryCount + 1, nextDelay);
900
+ }, delayMs);
901
+ }
902
+ /**
903
+ * Subscribes to tool changes once scope.tools is available.
904
+ */
905
+ subscribeToToolChanges() {
906
+ this.unsubscribe = this.scope.tools.subscribe({ immediate: true }, (event) => {
907
+ this.handleToolChange(event.snapshot);
908
+ });
909
+ this.markSubscribed();
910
+ }
911
+ /**
912
+ * Marks the subscription as resolved, allowing pending operations to proceed.
913
+ */
914
+ markSubscribed() {
915
+ this.subscriptionResolved = true;
916
+ if (this.subscriptionResolve) {
917
+ this.subscriptionResolve();
918
+ this.subscriptionResolve = null;
919
+ }
920
+ }
921
+ /**
922
+ * Handles tool change events by reindexing all tools from the snapshot
923
+ */
924
+ async handleToolChange(tools) {
925
+ this.vectorDB.clear();
926
+ if (tools.length === 0) {
927
+ this.initialized = true;
928
+ return;
929
+ }
930
+ if (!this.mlInitialized && this.strategy === "ml" && this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
931
+ await this.vectorDB.initialize();
932
+ this.mlInitialized = true;
933
+ }
934
+ const filteredTools = tools.filter((tool) => this.shouldIndexTool(tool));
935
+ if (filteredTools.length === 0) {
936
+ this.initialized = true;
937
+ return;
938
+ }
939
+ const documents = filteredTools.map((tool) => {
940
+ const searchableText = this.extractSearchableText(tool);
941
+ const appId = this.extractAppId(tool);
942
+ const toolName = tool.name;
943
+ const qualifiedName = tool.fullName || toolName;
944
+ return {
945
+ id: toolName,
946
+ text: searchableText,
947
+ metadata: {
948
+ id: toolName,
949
+ toolName,
950
+ qualifiedName,
951
+ appId,
952
+ toolInstance: tool
953
+ }
954
+ };
955
+ });
956
+ if (this.strategy === "ml" && this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
957
+ await this.vectorDB.addMany(documents);
958
+ } else if (this.vectorDB instanceof import_vectoriadb.TFIDFVectoria) {
959
+ this.vectorDB.addDocuments(documents);
960
+ this.vectorDB.reindex();
961
+ }
962
+ this.initialized = true;
963
+ }
964
+ /**
965
+ * Determines if a tool should be indexed in the search database.
966
+ * Filters based on:
967
+ * - Excludes codecall:* meta-tools (they should not be searchable)
968
+ * - Mode-based filtering (codecall_only, codecall_opt_in, metadata_driven)
969
+ * - Per-tool metadata.codecall.enabledInCodeCall
970
+ * - Custom includeTools filter function
971
+ */
972
+ shouldIndexTool(tool) {
973
+ const toolName = tool.name || tool.fullName;
974
+ if (toolName.startsWith("codecall:")) {
975
+ return false;
976
+ }
977
+ const codecallMeta = this.getCodeCallMetadata(tool);
978
+ switch (this.config.mode) {
979
+ case "codecall_only":
980
+ if (codecallMeta?.enabledInCodeCall === false) {
981
+ return false;
982
+ }
983
+ break;
984
+ case "codecall_opt_in":
985
+ if (codecallMeta?.enabledInCodeCall !== true) {
986
+ return false;
987
+ }
988
+ break;
989
+ case "metadata_driven":
990
+ if (codecallMeta?.enabledInCodeCall === false) {
991
+ return false;
992
+ }
993
+ break;
994
+ default:
995
+ throw new Error(`Unknown CodeCall mode: ${this.config.mode}`);
996
+ }
997
+ if (this.config.includeTools) {
998
+ const appId = this.extractAppId(tool);
999
+ const filterInfo = {
1000
+ name: toolName,
1001
+ appId,
1002
+ source: codecallMeta?.source,
1003
+ description: tool.metadata.description,
1004
+ tags: codecallMeta?.tags || tool.metadata.tags
1005
+ };
1006
+ if (!this.config.includeTools(filterInfo)) {
1007
+ return false;
1008
+ }
1009
+ }
1010
+ return true;
1011
+ }
1012
+ /**
1013
+ * Extract CodeCall-specific metadata from a tool.
1014
+ */
1015
+ getCodeCallMetadata(tool) {
1016
+ return tool.metadata?.codecall;
1017
+ }
1018
+ /**
1019
+ * Initializes the search service by indexing all tools from the registry.
1020
+ * NOTE: This method is now a no-op. Initialization is handled reactively
1021
+ * via subscription to tool change events in the constructor.
1022
+ * This method exists for interface compatibility.
1023
+ */
1024
+ async initialize() {
1025
+ }
1026
+ /**
1027
+ * Cleanup subscription and pending retries when service is destroyed
1028
+ */
1029
+ dispose() {
1030
+ this.disposed = true;
1031
+ if (this.retryTimeoutId) {
1032
+ clearTimeout(this.retryTimeoutId);
1033
+ this.retryTimeoutId = null;
1034
+ }
1035
+ if (this.subscriptionReject) {
1036
+ this.subscriptionReject(new Error("ToolSearchService disposed before subscription completed"));
1037
+ this.subscriptionReject = null;
1038
+ this.subscriptionResolve = null;
1039
+ }
1040
+ if (this.unsubscribe) {
1041
+ this.unsubscribe();
1042
+ this.unsubscribe = void 0;
1043
+ }
1044
+ }
1045
+ /**
1046
+ * Extracts searchable text from a tool instance.
1047
+ * Uses term weighting to improve relevance:
1048
+ * - Description terms are heavily weighted (most important for semantic matching)
1049
+ * - Tool name parts are tokenized and weighted
1050
+ * - Tags provide additional context
1051
+ */
1052
+ extractSearchableText(tool) {
1053
+ const parts = [];
1054
+ if (tool.name) {
1055
+ const nameParts = tool.name.split(/[:\-_.]/).filter(Boolean);
1056
+ for (const part of nameParts) {
1057
+ parts.push(part, part);
1058
+ }
1059
+ }
1060
+ if (tool.metadata.description) {
1061
+ const description = tool.metadata.description;
1062
+ parts.push(description, description, description);
1063
+ const keyTerms = description.toLowerCase().split(/\s+/).filter((word) => word.length >= 4 && !this.isStopWord(word));
1064
+ parts.push(...keyTerms);
1065
+ }
1066
+ if (tool.metadata.tags && tool.metadata.tags.length > 0) {
1067
+ for (const tag of tool.metadata.tags) {
1068
+ parts.push(tag, tag);
1069
+ }
1070
+ }
1071
+ if (tool.rawInputSchema && typeof tool.rawInputSchema === "object") {
1072
+ const schema = tool.rawInputSchema;
1073
+ if (schema.properties) {
1074
+ parts.push(...Object.keys(schema.properties));
1075
+ }
1076
+ }
1077
+ const examples = tool.metadata?.examples;
1078
+ if (examples && Array.isArray(examples)) {
1079
+ for (const ex of examples) {
1080
+ if (ex.description) {
1081
+ parts.push(ex.description, ex.description);
1082
+ }
1083
+ if (ex.input && typeof ex.input === "object") {
1084
+ for (const [key, value] of Object.entries(ex.input)) {
1085
+ parts.push(key);
1086
+ if (typeof value === "string") {
1087
+ parts.push(value);
1088
+ }
1089
+ }
1090
+ }
1091
+ }
1092
+ }
1093
+ return parts.join(" ");
1094
+ }
1095
+ /**
1096
+ * Checks if a word is a common stop word that should not receive extra weighting.
1097
+ * Uses module-level STOP_WORDS constant to avoid recreating the Set on each call.
1098
+ */
1099
+ isStopWord(word) {
1100
+ return STOP_WORDS.has(word);
1101
+ }
1102
+ /**
1103
+ * Extracts app ID from tool's owner lineage
1104
+ */
1105
+ extractAppId(tool) {
1106
+ if (!tool.owner) return void 0;
1107
+ if (tool.owner.kind === "app") {
1108
+ return tool.owner.id;
1109
+ }
1110
+ return void 0;
1111
+ }
1112
+ /**
1113
+ * Searches for tools matching the query
1114
+ * Implements the ToolSearch interface
1115
+ */
1116
+ async search(query, options = {}) {
1117
+ await this.ensureSubscribed();
1118
+ const { topK = this.config.defaultTopK, appIds, excludeToolNames = [] } = options;
1119
+ const minScore = this.config.defaultSimilarityThreshold;
1120
+ const filter = (metadata) => {
1121
+ if (excludeToolNames.includes(metadata.toolName)) {
1122
+ return false;
1123
+ }
1124
+ if (appIds && appIds.length > 0) {
1125
+ if (!metadata.appId || !appIds.includes(metadata.appId)) {
1126
+ return false;
1127
+ }
1128
+ }
1129
+ return true;
1130
+ };
1131
+ const effectiveQuery = this.synonymService ? this.synonymService.expandQuery(query) : query;
1132
+ const results = await this.vectorDB.search(effectiveQuery, {
1133
+ topK,
1134
+ threshold: minScore,
1135
+ filter
1136
+ });
1137
+ return results.map((result) => ({
1138
+ toolName: result.metadata.toolName,
1139
+ appId: result.metadata.appId,
1140
+ description: result.metadata.toolInstance.metadata.description || "",
1141
+ relevanceScore: result.score
1142
+ }));
1143
+ }
1144
+ /**
1145
+ * Gets all indexed tool names
1146
+ */
1147
+ getAllToolNames() {
1148
+ if (this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
1149
+ return this.vectorDB.getAll().map((doc) => doc.id);
1150
+ } else {
1151
+ return this.vectorDB.getAllDocumentIds();
1152
+ }
1153
+ }
1154
+ /**
1155
+ * Gets the total number of indexed tools
1156
+ */
1157
+ getTotalCount() {
1158
+ if (this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
1159
+ return this.vectorDB.size();
1160
+ } else {
1161
+ return this.vectorDB.getDocumentCount();
1162
+ }
1163
+ }
1164
+ /**
1165
+ * Checks if a tool exists in the index
1166
+ */
1167
+ hasTool(toolName) {
1168
+ if (this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
1169
+ return this.vectorDB.has(toolName);
1170
+ } else {
1171
+ return this.vectorDB.hasDocument(toolName);
1172
+ }
1173
+ }
1174
+ /**
1175
+ * Clears the entire index
1176
+ */
1177
+ clear() {
1178
+ this.vectorDB.clear();
1179
+ this.initialized = false;
1180
+ }
1181
+ /**
1182
+ * Get the current embedding strategy
1183
+ */
1184
+ getStrategy() {
1185
+ return this.strategy;
1186
+ }
1187
+ /**
1188
+ * Check if the service is initialized
1189
+ */
1190
+ isInitialized() {
1191
+ return this.initialized;
1192
+ }
1193
+ };
1194
+
1195
+ // plugins/plugin-codecall/src/services/enclave.service.ts
1196
+ var import_sdk = require("@frontmcp/sdk");
1197
+ var import_enclave_vm = require("enclave-vm");
1198
+ var ScriptTooLargeError = class extends Error {
1199
+ code = "SCRIPT_TOO_LARGE";
1200
+ scriptLength;
1201
+ maxLength;
1202
+ constructor(scriptLength, maxLength) {
1203
+ super(
1204
+ `Script length (${scriptLength} characters) exceeds maximum allowed length (${maxLength} characters). Enable sidecar to handle large data, or reduce script size.`
1205
+ );
1206
+ this.name = "ScriptTooLargeError";
1207
+ this.scriptLength = scriptLength;
1208
+ this.maxLength = maxLength;
1209
+ }
1210
+ };
1211
+ var EnclaveService = class {
1212
+ vmOptions;
1213
+ sidecarOptions;
1214
+ constructor(config) {
1215
+ const all = config.getAll();
1216
+ this.vmOptions = all.resolvedVm;
1217
+ this.sidecarOptions = all.sidecar;
1218
+ }
1219
+ /**
1220
+ * Execute AgentScript code in the enclave
1221
+ *
1222
+ * @param code - The AgentScript code to execute (raw, not transformed)
1223
+ * @param environment - The VM environment with callTool, getTool, etc.
1224
+ * @returns Execution result with success/error and logs
1225
+ * @throws ScriptTooLargeError if script exceeds max length and sidecar is disabled
1226
+ */
1227
+ async execute(code, environment) {
1228
+ const logs = [];
1229
+ if (!this.sidecarOptions.enabled && this.sidecarOptions.maxScriptLengthWhenDisabled !== null) {
1230
+ const maxLength = this.sidecarOptions.maxScriptLengthWhenDisabled;
1231
+ if (code.length > maxLength) {
1232
+ throw new ScriptTooLargeError(code.length, maxLength);
1233
+ }
1234
+ }
1235
+ const toolHandler = async (toolName, args) => {
1236
+ return environment.callTool(toolName, args);
1237
+ };
1238
+ const sidecar = this.sidecarOptions.enabled ? {
1239
+ enabled: true,
1240
+ maxTotalSize: this.sidecarOptions.maxTotalSize,
1241
+ maxReferenceSize: this.sidecarOptions.maxReferenceSize,
1242
+ extractionThreshold: this.sidecarOptions.extractionThreshold,
1243
+ maxResolvedSize: this.sidecarOptions.maxResolvedSize,
1244
+ allowComposites: this.sidecarOptions.allowComposites
1245
+ } : void 0;
1246
+ const enclave = new import_enclave_vm.Enclave({
1247
+ timeout: this.vmOptions.timeoutMs,
1248
+ maxToolCalls: this.vmOptions.maxSteps || 100,
1249
+ maxIterations: 1e4,
1250
+ toolHandler,
1251
+ validate: true,
1252
+ transform: true,
1253
+ sidecar,
1254
+ // Allow functions in globals since we intentionally provide getTool, mcpLog, mcpNotify, and console
1255
+ allowFunctionsInGlobals: true,
1256
+ globals: {
1257
+ // Provide getTool as a custom global
1258
+ getTool: environment.getTool,
1259
+ // Provide logging functions if available
1260
+ ...environment.mcpLog ? {
1261
+ mcpLog: (level, message, metadata) => {
1262
+ environment.mcpLog(level, message, metadata);
1263
+ logs.push(`[mcp:${level}] ${message}`);
1264
+ }
1265
+ } : {},
1266
+ ...environment.mcpNotify ? {
1267
+ mcpNotify: (event, payload) => {
1268
+ environment.mcpNotify(event, payload);
1269
+ logs.push(`[notify] ${event}`);
1270
+ }
1271
+ } : {}
1272
+ // Note: enclave-vm v2.0.0+ provides its own __safe_console internally with rate limiting
1273
+ // and output size limits. Passing console in globals causes "Cannot redefine property"
1274
+ // errors due to Double VM architecture. Console output from user scripts goes to stdout
1275
+ // via enclave's internal console, not to this logs array. Only mcpLog/mcpNotify are captured.
1276
+ }
1277
+ });
1278
+ try {
1279
+ const result = await enclave.run(code);
1280
+ return this.mapEnclaveResult(result, logs);
1281
+ } finally {
1282
+ enclave.dispose();
1283
+ }
1284
+ }
1285
+ /**
1286
+ * Map Enclave ExecutionResult to EnclaveExecutionResult
1287
+ */
1288
+ mapEnclaveResult(result, logs) {
1289
+ if (result.success) {
1290
+ return {
1291
+ success: true,
1292
+ result: result.value,
1293
+ logs,
1294
+ timedOut: false,
1295
+ stats: {
1296
+ duration: result.stats.duration,
1297
+ toolCallCount: result.stats.toolCallCount,
1298
+ iterationCount: result.stats.iterationCount
1299
+ }
1300
+ };
1301
+ }
1302
+ const error = result.error;
1303
+ const timedOut = error.message?.includes("timed out") || error.code === "TIMEOUT";
1304
+ if (error.code === "VALIDATION_ERROR") {
1305
+ return {
1306
+ success: false,
1307
+ error: {
1308
+ message: error.message,
1309
+ name: "ValidationError",
1310
+ code: error.code
1311
+ },
1312
+ logs,
1313
+ timedOut: false
1314
+ };
1315
+ }
1316
+ const errorData = error.data;
1317
+ const toolName = errorData?.["toolName"];
1318
+ if (toolName) {
1319
+ return {
1320
+ success: false,
1321
+ error: {
1322
+ message: error.message,
1323
+ name: error.name,
1324
+ stack: error.stack,
1325
+ code: error.code,
1326
+ toolName,
1327
+ toolInput: errorData?.["toolInput"],
1328
+ details: errorData?.["details"]
1329
+ },
1330
+ logs,
1331
+ timedOut
1332
+ };
1333
+ }
1334
+ return {
1335
+ success: false,
1336
+ error: {
1337
+ message: error.message,
1338
+ name: error.name,
1339
+ stack: error.stack,
1340
+ code: error.code
1341
+ },
1342
+ logs,
1343
+ timedOut,
1344
+ stats: {
1345
+ duration: result.stats.duration,
1346
+ toolCallCount: result.stats.toolCallCount,
1347
+ iterationCount: result.stats.iterationCount
1348
+ }
1349
+ };
1350
+ }
1351
+ };
1352
+ EnclaveService = __decorateClass([
1353
+ (0, import_sdk.Provider)({
1354
+ name: "codecall:enclave",
1355
+ description: "Executes AgentScript code in a secure enclave",
1356
+ scope: import_sdk.ProviderScope.GLOBAL
1357
+ })
1358
+ ], EnclaveService);
1359
+
1360
+ // plugins/plugin-codecall/src/tools/search.tool.ts
1361
+ var import_sdk2 = require("@frontmcp/sdk");
1362
+
1363
+ // plugins/plugin-codecall/src/tools/search.schema.ts
1364
+ var import_zod2 = require("zod");
1365
+ var searchToolDescription = `Find tools by splitting user request into atomic actions.
1366
+
1367
+ DECOMPOSE: "delete users and send email" \u2192 queries: ["delete user", "send email"]
1368
+ DECOMPOSE: "get order and refund" \u2192 queries: ["get order", "calculate refund"]
1369
+
1370
+ AVOID RE-SEARCHING: Use excludeToolNames for already-discovered tools.
1371
+ RE-SEARCH WHEN: describe fails (typo?) OR execute returns tool_not_found.
1372
+
1373
+ INPUT:
1374
+ - queries: string[] (required) - atomic action phrases, max 10
1375
+ - appIds?: string[] - filter by app
1376
+ - excludeToolNames?: string[] - skip known tools
1377
+ - topK?: number (default 5) - results per query
1378
+ - minRelevanceScore?: number (default 0.3) - minimum match threshold
1379
+
1380
+ OUTPUT: Flat deduplicated tool list. relevanceScore: 0.5+=good, 0.7+=strong match.
1381
+
1382
+ FLOW: search \u2192 describe \u2192 execute/invoke`;
1383
+ var searchToolInputSchema = import_zod2.z.object({
1384
+ queries: import_zod2.z.array(import_zod2.z.string().min(2).max(256)).min(1).max(10).describe("Atomic action queries. Split complex requests into simple actions."),
1385
+ appIds: import_zod2.z.array(import_zod2.z.string()).max(10).optional().describe("Filter by app IDs"),
1386
+ excludeToolNames: import_zod2.z.array(import_zod2.z.string()).max(50).optional().describe("Skip already-known tool names"),
1387
+ topK: import_zod2.z.number().int().positive().max(50).optional().default(10).describe("Results per query (default 10)"),
1388
+ minRelevanceScore: import_zod2.z.number().min(0).max(1).optional().default(0.1).describe("Minimum relevance threshold (default 0.1)")
1389
+ });
1390
+ var searchToolOutputSchema = import_zod2.z.object({
1391
+ tools: import_zod2.z.array(
1392
+ import_zod2.z.object({
1393
+ name: import_zod2.z.string().describe('Tool name (e.g., "users:list")'),
1394
+ appId: import_zod2.z.string().optional().describe("App ID"),
1395
+ description: import_zod2.z.string().describe("What this tool does"),
1396
+ relevanceScore: import_zod2.z.number().min(0).max(1).describe("Match score (0-1)"),
1397
+ matchedQueries: import_zod2.z.array(import_zod2.z.string()).describe("Which queries matched this tool")
1398
+ })
1399
+ ).describe("Deduplicated tools sorted by relevance"),
1400
+ warnings: import_zod2.z.array(
1401
+ import_zod2.z.object({
1402
+ type: import_zod2.z.enum(["excluded_tool_not_found", "no_results", "low_relevance"]).describe("Warning type"),
1403
+ message: import_zod2.z.string().describe("Warning message"),
1404
+ affectedTools: import_zod2.z.array(import_zod2.z.string()).optional().describe("Affected tool names")
1405
+ })
1406
+ ).describe("Search warnings"),
1407
+ totalAvailableTools: import_zod2.z.number().int().nonnegative().describe("Total tools in index")
1408
+ });
1409
+
1410
+ // plugins/plugin-codecall/src/tools/search.tool.ts
1411
+ var SearchTool = class extends import_sdk2.ToolContext {
1412
+ async execute(input) {
1413
+ const { queries, appIds, excludeToolNames = [], topK = 5, minRelevanceScore = 0.3 } = input;
1414
+ const searchService = this.get(ToolSearchService);
1415
+ const warnings = [];
1416
+ const nonExistentExcludedTools = excludeToolNames.filter((toolName) => !searchService.hasTool(toolName));
1417
+ if (nonExistentExcludedTools.length > 0) {
1418
+ warnings.push({
1419
+ type: "excluded_tool_not_found",
1420
+ message: `Excluded tools not found: ${nonExistentExcludedTools.join(", ")}`,
1421
+ affectedTools: nonExistentExcludedTools
1422
+ });
1423
+ }
1424
+ const toolMap = /* @__PURE__ */ new Map();
1425
+ let lowRelevanceCount = 0;
1426
+ for (const query of queries) {
1427
+ const searchResults = await searchService.search(query, {
1428
+ topK,
1429
+ appIds,
1430
+ excludeToolNames
1431
+ });
1432
+ for (const result of searchResults) {
1433
+ if (result.relevanceScore < minRelevanceScore) {
1434
+ lowRelevanceCount++;
1435
+ continue;
1436
+ }
1437
+ const existing = toolMap.get(result.toolName);
1438
+ if (existing) {
1439
+ existing.matchedQueries.push(query);
1440
+ existing.relevanceScore = Math.max(existing.relevanceScore, result.relevanceScore);
1441
+ } else {
1442
+ toolMap.set(result.toolName, {
1443
+ name: result.toolName,
1444
+ appId: result.appId,
1445
+ description: result.description,
1446
+ relevanceScore: result.relevanceScore,
1447
+ matchedQueries: [query]
1448
+ });
1449
+ }
1450
+ }
1451
+ }
1452
+ const tools = Array.from(toolMap.values()).sort((a, b) => b.relevanceScore - a.relevanceScore).map((tool) => ({
1453
+ name: tool.name,
1454
+ appId: tool.appId,
1455
+ description: tool.description,
1456
+ relevanceScore: tool.relevanceScore,
1457
+ matchedQueries: tool.matchedQueries
1458
+ }));
1459
+ if (tools.length === 0) {
1460
+ warnings.push({
1461
+ type: "no_results",
1462
+ message: `No tools found for queries: ${queries.join(", ")}${appIds?.length ? ` in apps: ${appIds.join(", ")}` : ""}`
1463
+ });
1464
+ }
1465
+ if (lowRelevanceCount > 0 && tools.length > 0) {
1466
+ warnings.push({
1467
+ type: "low_relevance",
1468
+ message: `${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`
1469
+ });
1470
+ }
1471
+ return {
1472
+ tools,
1473
+ warnings,
1474
+ totalAvailableTools: searchService.getTotalCount()
1475
+ };
1476
+ }
1477
+ };
1478
+ SearchTool = __decorateClass([
1479
+ (0, import_sdk2.Tool)({
1480
+ name: "codecall:search",
1481
+ cache: {
1482
+ ttl: 60,
1483
+ // 1 minute
1484
+ slideWindow: false
1485
+ },
1486
+ codecall: {
1487
+ enabledInCodeCall: false,
1488
+ visibleInListTools: true
1489
+ },
1490
+ description: searchToolDescription,
1491
+ inputSchema: searchToolInputSchema,
1492
+ outputSchema: searchToolOutputSchema,
1493
+ annotations: {
1494
+ readOnlyHint: true,
1495
+ openWorldHint: true
1496
+ }
1497
+ })
1498
+ ], SearchTool);
1499
+
1500
+ // plugins/plugin-codecall/src/tools/describe.tool.ts
1501
+ var import_sdk3 = require("@frontmcp/sdk");
1502
+ var import_v4 = require("zod/v4");
1503
+ var import_zod4 = require("zod");
1504
+
1505
+ // plugins/plugin-codecall/src/tools/describe.schema.ts
1506
+ var import_zod3 = require("zod");
1507
+ var import_types = require("@modelcontextprotocol/sdk/types.js");
1508
+ var describeToolDescription = `Get input/output schemas for tools from search results.
1509
+
1510
+ INPUT: toolNames: string[] - tool names from search
1511
+ OUTPUT per tool: inputSchema (JSON Schema), outputSchema (JSON Schema), usageExamples (up to 5 callTool examples)
1512
+
1513
+ IMPORTANT: If notFound array is non-empty \u2192 re-search with corrected queries.
1514
+ FLOW: search \u2192 describe \u2192 execute/invoke`;
1515
+ var describeToolInputSchema = import_zod3.z.object({
1516
+ toolNames: import_zod3.z.array(import_zod3.z.string()).min(1).superRefine((toolNames, ctx) => {
1517
+ const seen = /* @__PURE__ */ new Set();
1518
+ const duplicates = /* @__PURE__ */ new Set();
1519
+ for (const name of toolNames) {
1520
+ if (seen.has(name)) {
1521
+ duplicates.add(name);
1522
+ }
1523
+ seen.add(name);
1524
+ }
1525
+ if (duplicates.size > 0) {
1526
+ ctx.addIssue({
1527
+ code: import_zod3.z.ZodIssueCode.custom,
1528
+ message: `Duplicate tool names are not allowed: ${Array.from(duplicates).join(", ")}`
1529
+ });
1530
+ }
1531
+ }).describe(
1532
+ 'Array of unique tool names (from codecall:search results) to fetch their detailed schemas and usage examples. Example: ["users:list", "billing:getInvoice"]'
1533
+ )
1534
+ });
1535
+ var describeToolOutputSchema = import_zod3.z.object({
1536
+ tools: import_zod3.z.array(
1537
+ import_zod3.z.object({
1538
+ name: import_zod3.z.string().describe("Tool name to be used in callTool() within codecall:execute scripts"),
1539
+ appId: import_zod3.z.string().describe("The app ID this tool belongs to"),
1540
+ description: import_zod3.z.string().describe("Detailed description of what this tool does"),
1541
+ inputSchema: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).nullable().describe("JSON Schema object describing the tool input parameters"),
1542
+ outputSchema: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).nullable().describe("JSON Schema object describing the tool output structure"),
1543
+ annotations: import_types.ToolAnnotationsSchema.optional().describe("MCP tool annotations (metadata)"),
1544
+ usageExamples: import_zod3.z.array(
1545
+ import_zod3.z.object({
1546
+ description: import_zod3.z.string().describe("Description of what this example demonstrates"),
1547
+ code: import_zod3.z.string().describe(
1548
+ 'JavaScript code example showing how to call this tool using callTool(). Format: const result = await callTool("tool:name", { ...params });'
1549
+ )
1550
+ })
1551
+ ).max(5).describe("Up to 5 practical examples of how to use this tool in a codecall:execute script")
1552
+ })
1553
+ ).describe("Array of tool descriptions with schemas and usage examples"),
1554
+ notFound: import_zod3.z.array(import_zod3.z.string()).optional().describe("Tool names that were requested but not found in the index. Check these for typos.")
1555
+ });
1556
+
1557
+ // plugins/plugin-codecall/src/utils/describe.utils.ts
1558
+ var INTENT_PATTERNS = {
1559
+ create: /^(create|add|new|insert|make|append|register|generate|produce|build|construct|provision|instantiate|define|compose|draft)/i,
1560
+ delete: /^(delete|remove|destroy|drop|erase|clear|purge|discard|eliminate|unbind|unregister)/i,
1561
+ get: /^(get|fetch|retrieve|read|obtain|load|pull|access|grab|receive)/i,
1562
+ update: /^(update|edit|modify|change|patch|set|alter|revise|adjust|amend|correct|fix|refresh|sync|upgrade|downgrade)/i,
1563
+ list: /^(list|all|index|enumerate|show|display|view|browse|scan|inventory)/i,
1564
+ search: /^(search|find|query|lookup|locate|discover|explore|seek|match|filter)/i
1565
+ };
1566
+ function detectToolIntent(toolName, description) {
1567
+ const parts = toolName.split(":");
1568
+ const actionPart = parts.length > 1 ? parts[parts.length - 1] : toolName;
1569
+ for (const [intent, pattern] of Object.entries(INTENT_PATTERNS)) {
1570
+ if (pattern.test(actionPart)) {
1571
+ return intent;
1572
+ }
1573
+ }
1574
+ if (description) {
1575
+ const descLower = description.toLowerCase();
1576
+ if (/creates?\s|adding\s|inserts?/i.test(descLower)) return "create";
1577
+ if (/deletes?\s|removes?\s|destroys?/i.test(descLower)) return "delete";
1578
+ if (/gets?\s|fetche?s?\s|retrieves?/i.test(descLower)) return "get";
1579
+ if (/updates?\s|modif(?:y|ies)\s|edits?/i.test(descLower)) return "update";
1580
+ if (/lists?\s|shows?\s|displays?/i.test(descLower)) return "list";
1581
+ if (/search(?:es)?\s|find(?:s)?\s|quer(?:y|ies)/i.test(descLower)) return "search";
1582
+ }
1583
+ return "unknown";
1584
+ }
1585
+ function generateBasicExample(toolName, inputSchema) {
1586
+ const params = generateSampleParams(inputSchema);
1587
+ const paramsStr = params ? JSON.stringify(params, null, 2) : "{}";
1588
+ return {
1589
+ description: `Basic usage of ${toolName}`,
1590
+ code: `const result = await callTool('${toolName}', ${paramsStr});
1591
+ return result;`
1592
+ };
1593
+ }
1594
+ function generateSampleParams(schema) {
1595
+ if (!schema || schema.type !== "object" || !schema.properties) {
1596
+ return null;
1597
+ }
1598
+ const params = {};
1599
+ const required = new Set(schema.required || []);
1600
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
1601
+ if (typeof propSchema === "boolean") continue;
1602
+ if (!required.has(key)) continue;
1603
+ params[key] = getSampleValue(propSchema, key);
1604
+ }
1605
+ return Object.keys(params).length > 0 ? params : null;
1606
+ }
1607
+ function getSampleValue(schema, key) {
1608
+ if (schema.default !== void 0) {
1609
+ return schema.default;
1610
+ }
1611
+ if (schema.enum && schema.enum.length > 0) {
1612
+ return schema.enum[0];
1613
+ }
1614
+ if (schema.const !== void 0) {
1615
+ return schema.const;
1616
+ }
1617
+ const type = Array.isArray(schema.type) ? schema.type[0] : schema.type;
1618
+ switch (type) {
1619
+ case "string":
1620
+ if (key.toLowerCase().includes("id")) return "abc123";
1621
+ if (key.toLowerCase().includes("email")) return "user@example.com";
1622
+ if (key.toLowerCase().includes("name")) return "Example";
1623
+ if (key.toLowerCase().includes("url")) return "https://example.com";
1624
+ return "string";
1625
+ case "number":
1626
+ case "integer":
1627
+ if (key.toLowerCase().includes("limit")) return 10;
1628
+ if (key.toLowerCase().includes("offset")) return 0;
1629
+ if (key.toLowerCase().includes("page")) return 1;
1630
+ return 0;
1631
+ case "boolean":
1632
+ return true;
1633
+ case "array":
1634
+ return [];
1635
+ case "object":
1636
+ return {};
1637
+ default:
1638
+ return null;
1639
+ }
1640
+ }
1641
+ function hasPaginationParams(schema) {
1642
+ if (!schema || schema.type !== "object" || !schema.properties) {
1643
+ return false;
1644
+ }
1645
+ const props = Object.keys(schema.properties);
1646
+ return props.some((p) => ["limit", "offset", "page", "pageSize", "cursor"].includes(p.toLowerCase()));
1647
+ }
1648
+ function generatePaginationExample(toolName) {
1649
+ return {
1650
+ description: `Pagination example for ${toolName}`,
1651
+ code: `// Fetch first page
1652
+ const page1 = await callTool('${toolName}', { limit: 10, offset: 0 });
1653
+
1654
+ // Fetch second page
1655
+ const page2 = await callTool('${toolName}', { limit: 10, offset: 10 });
1656
+
1657
+ // Combine results
1658
+ return [...page1.items, ...page2.items];`
1659
+ };
1660
+ }
1661
+ function extractEntityName(toolName) {
1662
+ const parts = toolName.split(":");
1663
+ const entity = parts.length > 1 ? parts[0] : toolName;
1664
+ return entity.endsWith("s") && !entity.endsWith("ss") ? entity.slice(0, -1) : entity;
1665
+ }
1666
+ function generateCreateExample(toolName, inputSchema) {
1667
+ const entity = extractEntityName(toolName);
1668
+ const params = generateSampleParams(inputSchema);
1669
+ const paramsStr = params ? JSON.stringify(params, null, 2) : "{ /* required fields */ }";
1670
+ return {
1671
+ description: `Create a new ${entity}`,
1672
+ code: `const result = await callTool('${toolName}', ${paramsStr});
1673
+ return result;`
1674
+ };
1675
+ }
1676
+ function generateGetExample(toolName, inputSchema) {
1677
+ const entity = extractEntityName(toolName);
1678
+ const idParam = findIdParameter(inputSchema);
1679
+ if (idParam) {
1680
+ return {
1681
+ description: `Get ${entity} by ${idParam}`,
1682
+ code: `const ${entity} = await callTool('${toolName}', { ${idParam}: 'abc123' });
1683
+ return ${entity};`
1684
+ };
1685
+ }
1686
+ const params = generateSampleParams(inputSchema);
1687
+ const paramsStr = params ? JSON.stringify(params, null, 2) : "{}";
1688
+ return {
1689
+ description: `Get ${entity} details`,
1690
+ code: `const ${entity} = await callTool('${toolName}', ${paramsStr});
1691
+ return ${entity};`
1692
+ };
1693
+ }
1694
+ function generateListExample(toolName, inputSchema) {
1695
+ const entity = extractEntityName(toolName);
1696
+ return {
1697
+ description: `List all ${entity}s`,
1698
+ code: `const result = await callTool('${toolName}', {});
1699
+ return result.items || result;`
1700
+ };
1701
+ }
1702
+ function generateUpdateExample(toolName, inputSchema) {
1703
+ const entity = extractEntityName(toolName);
1704
+ const idParam = findIdParameter(inputSchema);
1705
+ const updateFields = generateUpdateFields(inputSchema);
1706
+ const fieldsStr = updateFields ? JSON.stringify(updateFields, null, 2).replace(/\n/g, "\n ") : "{ /* fields to update */ }";
1707
+ if (idParam) {
1708
+ return {
1709
+ description: `Update ${entity} by ${idParam}`,
1710
+ code: `const updated = await callTool('${toolName}', {
1711
+ ${idParam}: 'abc123',
1712
+ ...${fieldsStr}
1713
+ });
1714
+ return updated;`
1715
+ };
1716
+ }
1717
+ return {
1718
+ description: `Update ${entity}`,
1719
+ code: `const updated = await callTool('${toolName}', ${fieldsStr});
1720
+ return updated;`
1721
+ };
1722
+ }
1723
+ function generateDeleteExample(toolName, inputSchema) {
1724
+ const entity = extractEntityName(toolName);
1725
+ const idParam = findIdParameter(inputSchema);
1726
+ if (idParam) {
1727
+ return {
1728
+ description: `Delete ${entity} by ${idParam}`,
1729
+ code: `const result = await callTool('${toolName}', { ${idParam}: 'abc123' });
1730
+ return result;`
1731
+ };
1732
+ }
1733
+ const params = generateSampleParams(inputSchema);
1734
+ const paramsStr = params ? JSON.stringify(params, null, 2) : "{ /* identifier */ }";
1735
+ return {
1736
+ description: `Delete ${entity}`,
1737
+ code: `const result = await callTool('${toolName}', ${paramsStr});
1738
+ return result;`
1739
+ };
1740
+ }
1741
+ function generateSearchExample(toolName, inputSchema) {
1742
+ const entity = extractEntityName(toolName);
1743
+ const queryParam = findQueryParameter(inputSchema);
1744
+ if (queryParam) {
1745
+ return {
1746
+ description: `Search for ${entity}s`,
1747
+ code: `const results = await callTool('${toolName}', { ${queryParam}: 'search term' });
1748
+ return results.items || results;`
1749
+ };
1750
+ }
1751
+ return {
1752
+ description: `Search for ${entity}s`,
1753
+ code: `const results = await callTool('${toolName}', { query: 'search term' });
1754
+ return results.items || results;`
1755
+ };
1756
+ }
1757
+ function findIdParameter(schema) {
1758
+ if (!schema || schema.type !== "object" || !schema.properties) {
1759
+ return null;
1760
+ }
1761
+ const props = Object.keys(schema.properties);
1762
+ const required = new Set(schema.required || []);
1763
+ const idPatterns = ["id", "Id", "ID", "_id", "uuid", "key"];
1764
+ for (const pattern of idPatterns) {
1765
+ const found = props.find((p) => (p === pattern || p.endsWith(pattern)) && required.has(p));
1766
+ if (found) return found;
1767
+ }
1768
+ for (const pattern of idPatterns) {
1769
+ const found = props.find((p) => p === pattern || p.endsWith(pattern));
1770
+ if (found) return found;
1771
+ }
1772
+ return null;
1773
+ }
1774
+ function findQueryParameter(schema) {
1775
+ if (!schema || schema.type !== "object" || !schema.properties) {
1776
+ return null;
1777
+ }
1778
+ const props = Object.keys(schema.properties);
1779
+ const queryPatterns = ["query", "search", "q", "term", "keyword", "filter"];
1780
+ for (const pattern of queryPatterns) {
1781
+ const found = props.find((p) => p.toLowerCase() === pattern || p.toLowerCase().includes(pattern));
1782
+ if (found) return found;
1783
+ }
1784
+ return null;
1785
+ }
1786
+ function generateUpdateFields(schema) {
1787
+ if (!schema || schema.type !== "object" || !schema.properties) {
1788
+ return null;
1789
+ }
1790
+ const fields = {};
1791
+ const idPatterns = ["id", "Id", "ID", "_id", "uuid", "key"];
1792
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
1793
+ if (typeof propSchema === "boolean") continue;
1794
+ const isIdField = idPatterns.some((p) => key === p || key.endsWith(p));
1795
+ if (isIdField) continue;
1796
+ if (Object.keys(fields).length < 2) {
1797
+ fields[key] = getSampleValue(propSchema, key);
1798
+ }
1799
+ }
1800
+ return Object.keys(fields).length > 0 ? fields : null;
1801
+ }
1802
+ function generateSmartExample(toolName, inputSchema, description) {
1803
+ const intent = detectToolIntent(toolName, description);
1804
+ switch (intent) {
1805
+ case "create":
1806
+ return generateCreateExample(toolName, inputSchema);
1807
+ case "get":
1808
+ return generateGetExample(toolName, inputSchema);
1809
+ case "list":
1810
+ return hasPaginationParams(inputSchema) ? generatePaginationExample(toolName) : generateListExample(toolName, inputSchema);
1811
+ case "update":
1812
+ return generateUpdateExample(toolName, inputSchema);
1813
+ case "delete":
1814
+ return generateDeleteExample(toolName, inputSchema);
1815
+ case "search":
1816
+ return generateSearchExample(toolName, inputSchema);
1817
+ default:
1818
+ return generateBasicExample(toolName, inputSchema);
1819
+ }
1820
+ }
1821
+
1822
+ // plugins/plugin-codecall/src/utils/mcp-result.ts
1823
+ function extractResultFromCallToolResult(mcpResult) {
1824
+ if (mcpResult.isError) {
1825
+ const errorContent = mcpResult.content?.[0];
1826
+ if (errorContent && "text" in errorContent) {
1827
+ throw new Error(errorContent.text);
1828
+ }
1829
+ throw new Error("Tool execution failed");
1830
+ }
1831
+ const content = mcpResult.content;
1832
+ if (!content || content.length === 0) {
1833
+ return void 0;
1834
+ }
1835
+ if (content.length === 1 && content[0].type === "text") {
1836
+ try {
1837
+ return JSON.parse(content[0].text);
1838
+ } catch {
1839
+ return content[0].text;
1840
+ }
1841
+ }
1842
+ return content;
1843
+ }
1844
+
1845
+ // plugins/plugin-codecall/src/errors/tool-call.errors.ts
1846
+ var TOOL_CALL_ERROR_CODES = {
1847
+ NOT_FOUND: "NOT_FOUND",
1848
+ VALIDATION: "VALIDATION",
1849
+ EXECUTION: "EXECUTION",
1850
+ TIMEOUT: "TIMEOUT",
1851
+ ACCESS_DENIED: "ACCESS_DENIED",
1852
+ SELF_REFERENCE: "SELF_REFERENCE"
1853
+ };
1854
+ function createToolCallError(code, toolName, rawMessage) {
1855
+ const sanitizedMessage = getSanitizedMessage(code, toolName, rawMessage);
1856
+ return Object.freeze({
1857
+ code,
1858
+ message: sanitizedMessage,
1859
+ toolName
1860
+ });
1861
+ }
1862
+ function getSanitizedMessage(code, toolName, rawMessage) {
1863
+ switch (code) {
1864
+ case TOOL_CALL_ERROR_CODES.NOT_FOUND:
1865
+ return `Tool "${toolName}" was not found`;
1866
+ case TOOL_CALL_ERROR_CODES.VALIDATION:
1867
+ return rawMessage ? sanitizeValidationMessage(rawMessage) : `Input validation failed for tool "${toolName}"`;
1868
+ case TOOL_CALL_ERROR_CODES.EXECUTION:
1869
+ return `Tool "${toolName}" execution failed`;
1870
+ case TOOL_CALL_ERROR_CODES.TIMEOUT:
1871
+ return `Tool "${toolName}" execution timed out`;
1872
+ case TOOL_CALL_ERROR_CODES.ACCESS_DENIED:
1873
+ return `Access denied for tool "${toolName}"`;
1874
+ case TOOL_CALL_ERROR_CODES.SELF_REFERENCE:
1875
+ return `Cannot call CodeCall tools from within AgentScript`;
1876
+ default:
1877
+ return `An error occurred while calling "${toolName}"`;
1878
+ }
1879
+ }
1880
+ function sanitizeValidationMessage(message) {
1881
+ let sanitized = message.replace(/(?:\/[\w.-]+)+|(?:[A-Za-z]:\\[\w\\.-]+)+/g, "[path]");
1882
+ sanitized = sanitized.replace(/\bat line \d+/gi, "");
1883
+ sanitized = sanitized.replace(/\bline \d+/gi, "");
1884
+ sanitized = sanitized.replace(/:\d+:\d+/g, "");
1885
+ sanitized = sanitized.replace(/\n\s*at .*/g, "");
1886
+ if (sanitized.length > 200) {
1887
+ sanitized = sanitized.substring(0, 200) + "...";
1888
+ }
1889
+ return sanitized.trim();
1890
+ }
1891
+ var SelfReferenceError = class extends Error {
1892
+ code = TOOL_CALL_ERROR_CODES.SELF_REFERENCE;
1893
+ toolName;
1894
+ constructor(toolName) {
1895
+ super(`Self-reference attack: Attempted to call CodeCall tool "${toolName}" from within AgentScript`);
1896
+ this.name = "SelfReferenceError";
1897
+ this.toolName = toolName;
1898
+ Object.freeze(this);
1899
+ }
1900
+ };
1901
+
1902
+ // plugins/plugin-codecall/src/security/self-reference-guard.ts
1903
+ var CODECALL_TOOL_PREFIX = "codecall:";
1904
+ var BLOCKED_CODECALL_TOOLS = Object.freeze(
1905
+ /* @__PURE__ */ new Set(["codecall:search", "codecall:describe", "codecall:execute", "codecall:invoke"])
1906
+ );
1907
+ function isBlockedSelfReference(toolName) {
1908
+ const normalizedName = toolName.toLowerCase().trim();
1909
+ if (normalizedName.startsWith(CODECALL_TOOL_PREFIX)) {
1910
+ return true;
1911
+ }
1912
+ if (BLOCKED_CODECALL_TOOLS.has(toolName)) {
1913
+ return true;
1914
+ }
1915
+ return false;
1916
+ }
1917
+ function assertNotSelfReference(toolName) {
1918
+ if (isBlockedSelfReference(toolName)) {
1919
+ throw new SelfReferenceError(toolName);
1920
+ }
1921
+ }
1922
+
1923
+ // plugins/plugin-codecall/src/tools/describe.tool.ts
1924
+ var DescribeTool = class extends import_sdk3.ToolContext {
1925
+ async execute(input) {
1926
+ const { toolNames } = input;
1927
+ const tools = [];
1928
+ const notFound = [];
1929
+ const allTools = this.scope.tools.getTools(true);
1930
+ const toolMap = new Map(allTools.map((t) => [t.name, t]));
1931
+ const fullNameMap = new Map(allTools.map((t) => [t.fullName, t]));
1932
+ for (const toolName of toolNames) {
1933
+ if (isBlockedSelfReference(toolName)) {
1934
+ notFound.push(toolName);
1935
+ continue;
1936
+ }
1937
+ const tool = toolMap.get(toolName) || fullNameMap.get(toolName);
1938
+ if (!tool) {
1939
+ notFound.push(toolName);
1940
+ continue;
1941
+ }
1942
+ const appId = this.extractAppId(tool);
1943
+ const inputSchema = this.getInputSchema(tool);
1944
+ const outputSchema = this.toJsonSchema(tool.outputSchema);
1945
+ const usageExamples = this.generateExamples(tool, inputSchema ?? void 0);
1946
+ tools.push({
1947
+ name: tool.name,
1948
+ appId,
1949
+ description: tool.metadata?.description || `Tool: ${tool.name}`,
1950
+ inputSchema: inputSchema || null,
1951
+ outputSchema: outputSchema || null,
1952
+ annotations: tool.metadata?.annotations,
1953
+ usageExamples
1954
+ });
1955
+ }
1956
+ return {
1957
+ tools,
1958
+ notFound: notFound.length > 0 ? notFound : void 0
1959
+ };
1960
+ }
1961
+ /**
1962
+ * Get the input schema for a tool, converting from Zod to JSON Schema.
1963
+ * This ensures that property descriptions from .describe() are included.
1964
+ *
1965
+ * Priority:
1966
+ * 1. Convert from tool.inputSchema (Zod) to get descriptions
1967
+ * 2. Fall back to rawInputSchema if conversion fails
1968
+ * 3. Return null if no schema available
1969
+ */
1970
+ getInputSchema(tool) {
1971
+ if (tool.inputSchema && typeof tool.inputSchema === "object" && Object.keys(tool.inputSchema).length > 0) {
1972
+ try {
1973
+ const firstValue = Object.values(tool.inputSchema)[0];
1974
+ if (firstValue instanceof import_zod4.ZodType) {
1975
+ return (0, import_v4.toJSONSchema)(import_zod4.z.object(tool.inputSchema));
1976
+ }
1977
+ } catch {
1978
+ }
1979
+ }
1980
+ if (tool.rawInputSchema) {
1981
+ return tool.rawInputSchema;
1982
+ }
1983
+ return null;
1984
+ }
1985
+ /**
1986
+ * Convert a schema to JSON Schema format.
1987
+ * Handles Zod schemas, raw shapes, and already-JSON-Schema objects.
1988
+ *
1989
+ * Uses Zod v4's built-in z.toJSONSchema() for conversion.
1990
+ */
1991
+ toJsonSchema(schema) {
1992
+ if (!schema) {
1993
+ return null;
1994
+ }
1995
+ if (schema instanceof import_zod4.ZodType) {
1996
+ try {
1997
+ return (0, import_v4.toJSONSchema)(schema);
1998
+ } catch {
1999
+ return null;
2000
+ }
2001
+ }
2002
+ if (typeof schema === "object" && schema !== null && !Array.isArray(schema)) {
2003
+ const obj = schema;
2004
+ const firstValue = Object.values(obj)[0];
2005
+ if (firstValue instanceof import_zod4.ZodType) {
2006
+ try {
2007
+ return (0, import_v4.toJSONSchema)(import_zod4.z.object(obj));
2008
+ } catch {
2009
+ return null;
2010
+ }
2011
+ }
2012
+ if ("type" in obj || "properties" in obj || "$schema" in obj) {
2013
+ return schema;
2014
+ }
2015
+ }
2016
+ if (typeof schema === "string") {
2017
+ return null;
2018
+ }
2019
+ if (Array.isArray(schema)) {
2020
+ return null;
2021
+ }
2022
+ return null;
2023
+ }
2024
+ /**
2025
+ * Extract app ID from tool metadata or owner.
2026
+ */
2027
+ extractAppId(tool) {
2028
+ if (tool.metadata?.codecall?.appId) {
2029
+ return tool.metadata.codecall.appId;
2030
+ }
2031
+ if (tool.metadata?.source) {
2032
+ return tool.metadata.source;
2033
+ }
2034
+ if (tool.owner?.id) {
2035
+ return tool.owner.id;
2036
+ }
2037
+ const nameParts = tool.name?.split(":");
2038
+ if (nameParts && nameParts.length > 1) {
2039
+ return nameParts[0];
2040
+ }
2041
+ return "unknown";
2042
+ }
2043
+ /**
2044
+ * Generate up to 5 usage examples for a tool.
2045
+ *
2046
+ * Priority:
2047
+ * 1. User-provided examples from @Tool decorator metadata (up to 5)
2048
+ * 2. Smart intent-based generation to fill remaining slots
2049
+ * 3. Returns at least 1 example
2050
+ */
2051
+ generateExamples(tool, inputSchema) {
2052
+ const result = [];
2053
+ const examples = tool.metadata?.examples;
2054
+ if (examples && Array.isArray(examples)) {
2055
+ for (const ex of examples.slice(0, 5)) {
2056
+ result.push({
2057
+ description: ex.description || "Example usage",
2058
+ code: `const result = await callTool('${tool.name}', ${JSON.stringify(ex.input, null, 2)});
2059
+ return result;`
2060
+ });
2061
+ }
2062
+ }
2063
+ if (result.length < 5) {
2064
+ result.push(generateSmartExample(tool.name, inputSchema, tool.metadata?.description));
2065
+ }
2066
+ return result.slice(0, 5);
2067
+ }
2068
+ };
2069
+ DescribeTool = __decorateClass([
2070
+ (0, import_sdk3.Tool)({
2071
+ name: "codecall:describe",
2072
+ cache: {
2073
+ ttl: 60,
2074
+ // 1 minute
2075
+ slideWindow: false
2076
+ },
2077
+ codecall: {
2078
+ enabledInCodeCall: false,
2079
+ visibleInListTools: true
2080
+ },
2081
+ description: describeToolDescription,
2082
+ inputSchema: describeToolInputSchema,
2083
+ outputSchema: describeToolOutputSchema,
2084
+ annotations: {
2085
+ readOnlyHint: true,
2086
+ openWorldHint: true
2087
+ }
2088
+ })
2089
+ ], DescribeTool);
2090
+
2091
+ // plugins/plugin-codecall/src/tools/execute.tool.ts
2092
+ var import_sdk5 = require("@frontmcp/sdk");
2093
+
2094
+ // plugins/plugin-codecall/src/tools/execute.schema.ts
2095
+ var import_zod5 = require("zod");
2096
+ var MIN_EXECUTE_SCRIPT_LENGTH = 'return callTool("a",{})'.length;
2097
+ var executeToolDescription = `Execute AgentScript (safe JS subset) for multi-tool orchestration.
2098
+
2099
+ API: await callTool(name, args, opts?)
2100
+ - Default: throws on error
2101
+ - Safe mode: { throwOnError: false } \u2192 returns { success, data?, error? }
2102
+
2103
+ EXAMPLE:
2104
+ const users = await callTool('users:list', { active: true });
2105
+ const results = [];
2106
+ for (const u of users.items) {
2107
+ const orders = await callTool('orders:list', { userId: u.id });
2108
+ results.push({ id: u.id, total: orders.items.reduce((s,o) => s + o.amount, 0) });
2109
+ }
2110
+ return results;
2111
+
2112
+ ALLOWED: for, for-of, arrow fn, map/filter/reduce/find, Math.*, JSON.*, if/else, destructuring, spread, template literals
2113
+ BLOCKED: while, do-while, function decl, eval, require, fetch, setTimeout, process, globalThis
2114
+
2115
+ ERRORS: NOT_FOUND | VALIDATION | EXECUTION | TIMEOUT | ACCESS_DENIED
2116
+ STATUS: ok | syntax_error | illegal_access | runtime_error | tool_error | timeout
2117
+ LIMITS: 10K iter/loop, 30s timeout, 100 calls max`;
2118
+ var executeToolInputSchema = import_zod5.z.object({
2119
+ script: import_zod5.z.string().min(MIN_EXECUTE_SCRIPT_LENGTH).max(100 * 1024).describe(
2120
+ "JavaScript code to execute in the sandbox. Must return a value (implicitly or via explicit return). Use callTool(name, input) to invoke tools."
2121
+ ),
2122
+ allowedTools: import_zod5.z.array(import_zod5.z.string()).optional().describe(
2123
+ 'Optional whitelist of tool names that can be called from this script. If not provided, all indexed tools are available. Example: ["users:list", "billing:getInvoice"]'
2124
+ )
2125
+ });
2126
+ var syntaxErrorPayloadSchema = import_zod5.z.object({
2127
+ message: import_zod5.z.string(),
2128
+ location: import_zod5.z.object({
2129
+ line: import_zod5.z.number(),
2130
+ column: import_zod5.z.number()
2131
+ }).optional()
2132
+ });
2133
+ var illegalAccessErrorPayloadSchema = import_zod5.z.object({
2134
+ message: import_zod5.z.string(),
2135
+ kind: import_zod5.z.union([
2136
+ import_zod5.z.literal("IllegalBuiltinAccess"),
2137
+ import_zod5.z.literal("DisallowedGlobal"),
2138
+ import_zod5.z.string()
2139
+ // same as your original type: 'A' | 'B' | string
2140
+ ])
2141
+ });
2142
+ var runtimeErrorPayloadSchema = import_zod5.z.object({
2143
+ source: import_zod5.z.literal("script"),
2144
+ message: import_zod5.z.string(),
2145
+ name: import_zod5.z.string().optional(),
2146
+ stack: import_zod5.z.string().optional()
2147
+ });
2148
+ var toolErrorPayloadSchema = import_zod5.z.object({
2149
+ source: import_zod5.z.literal("tool"),
2150
+ toolName: import_zod5.z.string(),
2151
+ toolInput: import_zod5.z.unknown(),
2152
+ message: import_zod5.z.string(),
2153
+ code: import_zod5.z.string().optional(),
2154
+ details: import_zod5.z.unknown().optional()
2155
+ });
2156
+ var timeoutErrorPayloadSchema = import_zod5.z.object({
2157
+ message: import_zod5.z.string()
2158
+ });
2159
+ var codeCallOkResultSchema = import_zod5.z.object({
2160
+ status: import_zod5.z.literal("ok"),
2161
+ result: import_zod5.z.unknown(),
2162
+ logs: import_zod5.z.array(import_zod5.z.string()).optional()
2163
+ });
2164
+ var codeCallSyntaxErrorResultSchema = import_zod5.z.object({
2165
+ status: import_zod5.z.literal("syntax_error"),
2166
+ error: syntaxErrorPayloadSchema
2167
+ });
2168
+ var codeCallIllegalAccessResultSchema = import_zod5.z.object({
2169
+ status: import_zod5.z.literal("illegal_access"),
2170
+ error: illegalAccessErrorPayloadSchema
2171
+ });
2172
+ var codeCallRuntimeErrorResultSchema = import_zod5.z.object({
2173
+ status: import_zod5.z.literal("runtime_error"),
2174
+ error: runtimeErrorPayloadSchema
2175
+ });
2176
+ var codeCallToolErrorResultSchema = import_zod5.z.object({
2177
+ status: import_zod5.z.literal("tool_error"),
2178
+ error: toolErrorPayloadSchema
2179
+ });
2180
+ var codeCallTimeoutResultSchema = import_zod5.z.object({
2181
+ status: import_zod5.z.literal("timeout"),
2182
+ error: timeoutErrorPayloadSchema
2183
+ });
2184
+ var executeToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2185
+ codeCallOkResultSchema,
2186
+ codeCallSyntaxErrorResultSchema,
2187
+ codeCallIllegalAccessResultSchema,
2188
+ codeCallRuntimeErrorResultSchema,
2189
+ codeCallToolErrorResultSchema,
2190
+ codeCallTimeoutResultSchema
2191
+ ]);
2192
+
2193
+ // plugins/plugin-codecall/src/providers/code-call.config.ts
2194
+ var import_sdk4 = require("@frontmcp/sdk");
2195
+ var CodeCallConfig = class extends import_sdk4.BaseConfig {
2196
+ constructor(options = {}) {
2197
+ const parsedConfig = codeCallPluginOptionsSchema.parse(options);
2198
+ const resolvedVm = resolveVmOptions(parsedConfig.vm);
2199
+ super({ ...parsedConfig, resolvedVm });
2200
+ }
2201
+ };
2202
+ CodeCallConfig = __decorateClass([
2203
+ (0, import_sdk4.Provider)({
2204
+ name: "codecall:config",
2205
+ description: "CodeCall plugin configuration with validated defaults",
2206
+ scope: import_sdk4.ProviderScope.GLOBAL
2207
+ })
2208
+ ], CodeCallConfig);
2209
+ function resolveVmOptions(vmOptions) {
2210
+ const preset = vmOptions?.preset ?? "secure";
2211
+ const base = presetDefaults(preset);
2212
+ return {
2213
+ ...base,
2214
+ ...vmOptions,
2215
+ disabledBuiltins: vmOptions?.disabledBuiltins ?? base.disabledBuiltins,
2216
+ disabledGlobals: vmOptions?.disabledGlobals ?? base.disabledGlobals
2217
+ };
2218
+ }
2219
+ function presetDefaults(preset) {
2220
+ switch (preset) {
2221
+ case "locked_down":
2222
+ return {
2223
+ preset,
2224
+ timeoutMs: 2e3,
2225
+ allowLoops: false,
2226
+ allowConsole: false,
2227
+ maxSteps: 2e3,
2228
+ disabledBuiltins: ["eval", "Function", "AsyncFunction"],
2229
+ disabledGlobals: [
2230
+ "require",
2231
+ "process",
2232
+ "fetch",
2233
+ "setTimeout",
2234
+ "setInterval",
2235
+ "setImmediate",
2236
+ "global",
2237
+ "globalThis"
2238
+ ]
2239
+ };
2240
+ case "balanced":
2241
+ return {
2242
+ preset,
2243
+ timeoutMs: 5e3,
2244
+ allowLoops: true,
2245
+ allowConsole: true,
2246
+ maxSteps: 1e4,
2247
+ disabledBuiltins: ["eval", "Function", "AsyncFunction"],
2248
+ disabledGlobals: ["require", "process", "fetch"]
2249
+ };
2250
+ case "experimental":
2251
+ return {
2252
+ preset,
2253
+ timeoutMs: 1e4,
2254
+ allowLoops: true,
2255
+ allowConsole: true,
2256
+ maxSteps: 2e4,
2257
+ disabledBuiltins: ["eval", "Function", "AsyncFunction"],
2258
+ disabledGlobals: ["require", "process"]
2259
+ };
2260
+ case "secure":
2261
+ default:
2262
+ return {
2263
+ preset: "secure",
2264
+ timeoutMs: 3500,
2265
+ allowLoops: false,
2266
+ allowConsole: true,
2267
+ maxSteps: 5e3,
2268
+ disabledBuiltins: ["eval", "Function", "AsyncFunction"],
2269
+ disabledGlobals: [
2270
+ "require",
2271
+ "process",
2272
+ "fetch",
2273
+ "setTimeout",
2274
+ "setInterval",
2275
+ "setImmediate",
2276
+ "global",
2277
+ "globalThis"
2278
+ ]
2279
+ };
2280
+ }
2281
+ }
2282
+
2283
+ // plugins/plugin-codecall/src/tools/execute.tool.ts
2284
+ function getErrorCode(error) {
2285
+ if (!(error instanceof Error)) {
2286
+ return TOOL_CALL_ERROR_CODES.EXECUTION;
2287
+ }
2288
+ if (error.name === "ZodError" || error.message?.includes("validation")) {
2289
+ return TOOL_CALL_ERROR_CODES.VALIDATION;
2290
+ }
2291
+ if (error.message?.includes("timeout") || error.message?.includes("timed out")) {
2292
+ return TOOL_CALL_ERROR_CODES.TIMEOUT;
2293
+ }
2294
+ if (error.name === "ToolNotFoundError" || error.message?.includes("not found")) {
2295
+ return TOOL_CALL_ERROR_CODES.NOT_FOUND;
2296
+ }
2297
+ return TOOL_CALL_ERROR_CODES.EXECUTION;
2298
+ }
2299
+ var ExecuteTool = class extends import_sdk5.ToolContext {
2300
+ async execute(input) {
2301
+ const { script, allowedTools } = input;
2302
+ const allowedToolSet = allowedTools ? new Set(allowedTools) : null;
2303
+ const environment = {
2304
+ callTool: async (name, toolInput, options) => {
2305
+ const throwOnError = options?.throwOnError !== false;
2306
+ assertNotSelfReference(name);
2307
+ if (allowedToolSet && !allowedToolSet.has(name)) {
2308
+ const error = createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED, name);
2309
+ if (throwOnError) {
2310
+ throw error;
2311
+ }
2312
+ return { success: false, error };
2313
+ }
2314
+ try {
2315
+ const request = {
2316
+ method: "tools/call",
2317
+ params: {
2318
+ name,
2319
+ arguments: toolInput
2320
+ }
2321
+ };
2322
+ const ctx = {
2323
+ authInfo: this.authInfo
2324
+ };
2325
+ const mcpResult = await this.scope.runFlow("tools:call-tool", { request, ctx });
2326
+ if (!mcpResult) {
2327
+ const error = createToolCallError(TOOL_CALL_ERROR_CODES.EXECUTION, name, "Flow returned no result");
2328
+ if (throwOnError) {
2329
+ throw error;
2330
+ }
2331
+ return { success: false, error };
2332
+ }
2333
+ const result = extractResultFromCallToolResult(mcpResult);
2334
+ if (throwOnError) {
2335
+ return result;
2336
+ }
2337
+ return { success: true, data: result };
2338
+ } catch (error) {
2339
+ const errorCode = getErrorCode(error);
2340
+ const rawMessage = error instanceof Error ? error.message : void 0;
2341
+ const sanitizedError = createToolCallError(errorCode, name, rawMessage);
2342
+ if (throwOnError) {
2343
+ throw sanitizedError;
2344
+ }
2345
+ return { success: false, error: sanitizedError };
2346
+ }
2347
+ },
2348
+ getTool: (name) => {
2349
+ try {
2350
+ const tools = this.scope.tools.getTools(true);
2351
+ const tool = tools.find((t) => t.name === name || t.fullName === name);
2352
+ if (!tool) return void 0;
2353
+ return {
2354
+ name: tool.name,
2355
+ description: tool.metadata?.description,
2356
+ inputSchema: tool.rawInputSchema,
2357
+ outputSchema: tool.outputSchema
2358
+ };
2359
+ } catch {
2360
+ return void 0;
2361
+ }
2362
+ },
2363
+ console: this.get(CodeCallConfig).get("resolvedVm.allowConsole") ? console : void 0,
2364
+ mcpLog: (level, message, metadata) => {
2365
+ this.logger?.[level](message, metadata);
2366
+ },
2367
+ mcpNotify: (event, payload) => {
2368
+ this.logger?.debug("Notification sent", { event, payload });
2369
+ }
2370
+ };
2371
+ const enclaveService = this.get(EnclaveService);
2372
+ const config = this.get(CodeCallConfig);
2373
+ try {
2374
+ const executionResult = await enclaveService.execute(script, environment);
2375
+ if (executionResult.timedOut) {
2376
+ return {
2377
+ status: "timeout",
2378
+ error: {
2379
+ message: `Script execution timed out after ${config.getAll().resolvedVm.timeoutMs}ms`
2380
+ }
2381
+ };
2382
+ }
2383
+ if (!executionResult.success) {
2384
+ const error = executionResult.error;
2385
+ if (error.code === "VALIDATION_ERROR" || error.name === "ValidationError") {
2386
+ return {
2387
+ status: "illegal_access",
2388
+ error: {
2389
+ kind: "IllegalBuiltinAccess",
2390
+ message: error.message
2391
+ }
2392
+ };
2393
+ }
2394
+ if (error.toolName) {
2395
+ return {
2396
+ status: "tool_error",
2397
+ error: {
2398
+ source: "tool",
2399
+ toolName: error.toolName,
2400
+ toolInput: error.toolInput,
2401
+ message: error.message,
2402
+ code: error.code,
2403
+ details: error.details
2404
+ }
2405
+ };
2406
+ }
2407
+ return {
2408
+ status: "runtime_error",
2409
+ error: {
2410
+ source: "script",
2411
+ message: error.message,
2412
+ name: error.name,
2413
+ stack: error.stack
2414
+ }
2415
+ };
2416
+ }
2417
+ return {
2418
+ status: "ok",
2419
+ result: executionResult.result,
2420
+ logs: executionResult.logs.length > 0 ? executionResult.logs : void 0
2421
+ };
2422
+ } catch (error) {
2423
+ const errorName = error instanceof Error ? error.name : "Error";
2424
+ const errorMessage = error instanceof Error ? error.message : String(error);
2425
+ const errorStack = error instanceof Error ? error.stack : void 0;
2426
+ const errorLoc = error.loc;
2427
+ if (errorName === "SyntaxError" || errorMessage?.includes("syntax")) {
2428
+ return {
2429
+ status: "syntax_error",
2430
+ error: {
2431
+ message: errorMessage || "Syntax error in script",
2432
+ location: errorLoc ? { line: errorLoc.line, column: errorLoc.column } : void 0
2433
+ }
2434
+ };
2435
+ }
2436
+ return {
2437
+ status: "runtime_error",
2438
+ error: {
2439
+ source: "script",
2440
+ message: errorMessage || "An unexpected error occurred during script execution",
2441
+ name: errorName,
2442
+ stack: errorStack
2443
+ }
2444
+ };
2445
+ }
2446
+ }
2447
+ };
2448
+ ExecuteTool = __decorateClass([
2449
+ (0, import_sdk5.Tool)({
2450
+ name: "codecall:execute",
2451
+ cache: {
2452
+ ttl: 0,
2453
+ // No caching - each execution is unique
2454
+ slideWindow: false
2455
+ },
2456
+ codecall: {
2457
+ enabledInCodeCall: false,
2458
+ visibleInListTools: true
2459
+ },
2460
+ description: executeToolDescription,
2461
+ inputSchema: executeToolInputSchema,
2462
+ outputSchema: executeToolOutputSchema
2463
+ })
2464
+ ], ExecuteTool);
2465
+
2466
+ // plugins/plugin-codecall/src/tools/invoke.tool.ts
2467
+ var import_sdk6 = require("@frontmcp/sdk");
2468
+
2469
+ // plugins/plugin-codecall/src/tools/invoke.schema.ts
2470
+ var import_zod6 = require("zod");
2471
+ var import_types2 = require("@modelcontextprotocol/sdk/types.js");
2472
+ var invokeToolDescription = `Call ONE tool directly. Returns standard MCP CallToolResult.
2473
+
2474
+ USE invoke: single tool, no transformation
2475
+ USE execute: multiple tools, loops, filtering, joining
2476
+
2477
+ INPUT: tool (string), input (object matching tool schema)
2478
+ OUTPUT: MCP CallToolResult (same as standard tool call)
2479
+ ERRORS: tool_not_found (\u2192 re-search) | validation_error | execution_error | permission_denied
2480
+
2481
+ FLOW: search \u2192 describe \u2192 invoke`;
2482
+ var invokeToolInputSchema = import_zod6.z.object({
2483
+ tool: import_zod6.z.string().describe(
2484
+ 'The name of the tool to invoke (e.g., "users:getById", "billing:getInvoice"). Must be a tool you discovered via codecall:search.'
2485
+ ),
2486
+ input: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.unknown()).describe(
2487
+ "The input parameters for the tool. Structure must match the tool's input schema (check codecall:describe for schema details)."
2488
+ )
2489
+ });
2490
+ var invokeToolOutputSchema = import_types2.CallToolResultSchema;
2491
+
2492
+ // plugins/plugin-codecall/src/tools/invoke.tool.ts
2493
+ function buildErrorResult(message) {
2494
+ return {
2495
+ content: [{ type: "text", text: message }],
2496
+ isError: true
2497
+ };
2498
+ }
2499
+ var InvokeTool = class extends import_sdk6.ToolContext {
2500
+ async execute(input) {
2501
+ const { tool: toolName, input: toolInput } = input;
2502
+ if (isBlockedSelfReference(toolName)) {
2503
+ return buildErrorResult(
2504
+ `Tool "${toolName}" cannot be invoked directly. CodeCall tools are internal and not accessible via codecall:invoke.`
2505
+ );
2506
+ }
2507
+ const request = {
2508
+ method: "tools/call",
2509
+ params: {
2510
+ name: toolName,
2511
+ arguments: toolInput
2512
+ }
2513
+ };
2514
+ const ctx = {
2515
+ authInfo: this.authInfo
2516
+ };
2517
+ const result = await this.scope.runFlow("tools:call-tool", { request, ctx });
2518
+ if (!result) {
2519
+ return buildErrorResult(`Tool "${toolName}" not found. Use codecall:search to discover available tools.`);
2520
+ }
2521
+ return result;
2522
+ }
2523
+ };
2524
+ InvokeTool = __decorateClass([
2525
+ (0, import_sdk6.Tool)({
2526
+ name: "codecall:invoke",
2527
+ cache: {
2528
+ ttl: 0,
2529
+ // No caching - each invocation is unique
2530
+ slideWindow: false
2531
+ },
2532
+ codecall: {
2533
+ enabledInCodeCall: false,
2534
+ visibleInListTools: true
2535
+ },
2536
+ description: invokeToolDescription,
2537
+ inputSchema: invokeToolInputSchema,
2538
+ outputSchema: invokeToolOutputSchema
2539
+ })
2540
+ ], InvokeTool);
2541
+
2542
+ // plugins/plugin-codecall/src/codecall.plugin.ts
2543
+ var import_plugin_cache = __toESM(require("@frontmcp/plugin-cache"));
2544
+ var CodeCallPlugin = class extends import_sdk7.DynamicPlugin {
2545
+ options;
2546
+ constructor(options = {}) {
2547
+ super();
2548
+ this.options = codeCallPluginOptionsSchema.parse(options);
2549
+ console.log("[CodeCall] Plugin initialized with mode:", this.options.mode);
2550
+ }
2551
+ /**
2552
+ * Dynamic providers allow you to configure the plugin with custom options
2553
+ * without touching the plugin decorator.
2554
+ */
2555
+ static dynamicProviders(options) {
2556
+ const parsedOptions = codeCallPluginOptionsSchema.parse(options);
2557
+ const config = new CodeCallConfig(parsedOptions);
2558
+ return [
2559
+ {
2560
+ name: "codecall:config",
2561
+ provide: CodeCallConfig,
2562
+ useValue: config
2563
+ },
2564
+ {
2565
+ name: "codecall:enclave",
2566
+ provide: EnclaveService,
2567
+ inject: () => [CodeCallConfig],
2568
+ useFactory: async (cfg) => {
2569
+ return new EnclaveService(cfg);
2570
+ }
2571
+ },
2572
+ {
2573
+ name: "codecall:tool-search",
2574
+ provide: ToolSearchService,
2575
+ inject: () => [import_sdk7.ScopeEntry],
2576
+ useFactory: async (scope) => {
2577
+ return new ToolSearchService(
2578
+ {
2579
+ embeddingOptions: parsedOptions.embedding,
2580
+ mode: parsedOptions.mode,
2581
+ includeTools: parsedOptions["includeTools"]
2582
+ },
2583
+ scope
2584
+ );
2585
+ }
2586
+ }
2587
+ ];
2588
+ }
2589
+ async adjustListTools(flowCtx) {
2590
+ const { resolvedTools } = flowCtx.state;
2591
+ console.log("[CodeCall] adjustListTools hook called, mode:", this.options.mode);
2592
+ console.log("[CodeCall] Tools before filter:", resolvedTools?.length ?? 0);
2593
+ if (!resolvedTools || resolvedTools.length === 0) {
2594
+ console.log("[CodeCall] No tools to filter, returning early");
2595
+ return;
2596
+ }
2597
+ const filteredTools = resolvedTools.filter(({ tool }) => {
2598
+ return this.shouldShowInListTools(tool, this.options.mode);
2599
+ });
2600
+ console.log("[CodeCall] Tools after filter:", filteredTools.length);
2601
+ flowCtx.state.set("resolvedTools", filteredTools);
2602
+ }
2603
+ /**
2604
+ * Determine if a tool should be visible in list_tools based on mode.
2605
+ *
2606
+ * @param tool - The tool entry to check
2607
+ * @param mode - The current CodeCall mode
2608
+ * @returns true if tool should be visible
2609
+ */
2610
+ shouldShowInListTools(tool, mode) {
2611
+ if (this.isCodeCallTool(tool)) {
2612
+ return true;
2613
+ }
2614
+ const codecallMeta = this.getCodeCallMetadata(tool);
2615
+ switch (mode) {
2616
+ case "codecall_only":
2617
+ return codecallMeta?.visibleInListTools === true;
2618
+ case "codecall_opt_in":
2619
+ return true;
2620
+ case "metadata_driven":
2621
+ if (codecallMeta?.visibleInListTools === false) {
2622
+ return false;
2623
+ }
2624
+ return true;
2625
+ default:
2626
+ return true;
2627
+ }
2628
+ }
2629
+ /**
2630
+ * Check if a tool is a CodeCall meta-tool.
2631
+ * CodeCall meta-tools always remain visible.
2632
+ */
2633
+ isCodeCallTool(tool) {
2634
+ const name = tool.name || tool.fullName;
2635
+ return name.startsWith("codecall:");
2636
+ }
2637
+ /**
2638
+ * Extract CodeCall-specific metadata from a tool.
2639
+ */
2640
+ getCodeCallMetadata(tool) {
2641
+ return tool.metadata?.codecall;
2642
+ }
2643
+ };
2644
+ __decorateClass([
2645
+ import_sdk7.ListToolsHook.Did("resolveConflicts", { priority: 1e3 })
2646
+ ], CodeCallPlugin.prototype, "adjustListTools", 1);
2647
+ CodeCallPlugin = __decorateClass([
2648
+ (0, import_sdk7.Plugin)({
2649
+ name: "codecall",
2650
+ description: "CodeCall plugin: AgentScript-based meta-tools for orchestrating MCP tools",
2651
+ providers: [],
2652
+ plugins: [import_plugin_cache.default],
2653
+ tools: [SearchTool, DescribeTool, ExecuteTool, InvokeTool]
2654
+ })
2655
+ ], CodeCallPlugin);
2656
+ // Annotate the CommonJS export names for ESM import in node:
2657
+ 0 && (module.exports = {
2658
+ CodeCallPlugin,
2659
+ codeCallDirectCallsOptionsSchema,
2660
+ codeCallEmbeddingOptionsSchema,
2661
+ codeCallModeSchema,
2662
+ codeCallPluginOptionsSchema,
2663
+ codeCallSidecarOptionsSchema,
2664
+ codeCallVmOptionsSchema,
2665
+ codeCallVmPresetSchema,
2666
+ embeddingStrategySchema,
2667
+ synonymExpansionConfigSchema
2668
+ });